blob: 7fe2e19e7781e8cae294fd6393770d302fae974f [file] [log] [blame]
Mike Lockwood94afecf2012-10-24 10:45:23 -07001/*
2** Copyright 2008, The Android Open Source Project
3**
Dave Allisond9370732014-01-30 14:19:23 -08004** Licensed under the Apache License, Version 2.0 (the "License");
5** you may not use this file except in compliance with the License.
6** You may obtain a copy of the License at
Mike Lockwood94afecf2012-10-24 10:45:23 -07007**
Dave Allisond9370732014-01-30 14:19:23 -08008** http://www.apache.org/licenses/LICENSE-2.0
Mike Lockwood94afecf2012-10-24 10:45:23 -07009**
Dave Allisond9370732014-01-30 14:19:23 -080010** Unless required by applicable law or agreed to in writing, software
11** distributed under the License is distributed on an "AS IS" BASIS,
12** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13** See the License for the specific language governing permissions and
Mike Lockwood94afecf2012-10-24 10:45:23 -070014** limitations under the License.
15*/
16
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070017#include "InstalldNativeService.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080018
19#include <errno.h>
20#include <inttypes.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070021#include <fstream>
22#include <fts.h>
Andreas Gamped089ca12016-06-27 14:25:30 -070023#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080024#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070025#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026#include <sys/capability.h>
27#include <sys/file.h>
28#include <sys/resource.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070029#include <sys/quota.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080030#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070031#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070032#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000033#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070034#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070036
Andreas Gampe6fb5a012016-06-03 16:09:32 -070037#include <android-base/logging.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080038#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070039#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010040#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080041#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070042#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070043#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070044#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070045#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080046#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070047#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080048#include <system/thread_defs.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070049
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070050#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070051#include "globals.h"
52#include "installd_deps.h"
53#include "otapreopt_utils.h"
54#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070055
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070056#include "MatchExtensionGen.h"
57
Andreas Gampe02d0de52015-11-11 20:43:16 -080058#ifndef LOG_TAG
59#define LOG_TAG "installd"
60#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070061
62using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070063
Andreas Gampe02d0de52015-11-11 20:43:16 -080064namespace android {
65namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070066
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070067static constexpr const char* kCpPath = "/system/bin/cp";
68static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070069
Andreas Gamped089ca12016-06-27 14:25:30 -070070static constexpr const char* PKG_LIB_POSTFIX = "/lib";
71static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
72static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
73
74static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
75static constexpr const char* IDMAP_SUFFIX = "@idmap";
76
77// NOTE: keep in sync with StorageManager
78static constexpr int FLAG_STORAGE_DE = 1 << 0;
79static constexpr int FLAG_STORAGE_CE = 1 << 1;
80
81// NOTE: keep in sync with Installer
82static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
83static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070084static constexpr int FLAG_USE_QUOTA = 1 << 12;
Andreas Gamped089ca12016-06-27 14:25:30 -070085
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000086#define MIN_RESTRICTED_HOME_SDK_VERSION 24 // > M
Jeff Sharkey0274c972016-12-06 09:32:04 -070087namespace {
88
89constexpr const char* kDump = "android.permission.DUMP";
90
Jeff Sharkey423e7462016-12-09 18:18:43 -070091static binder::Status ok() {
92 return binder::Status::ok();
93}
94
95static binder::Status exception(uint32_t code, const std::string& msg) {
96 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
97}
98
99static binder::Status error() {
100 return binder::Status::fromServiceSpecificError(errno);
101}
102
103static binder::Status error(const std::string& msg) {
104 PLOG(ERROR) << msg;
105 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
106}
107
108static binder::Status error(uint32_t code, const std::string& msg) {
109 LOG(ERROR) << msg << " (" << code << ")";
110 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
111}
112
Jeff Sharkey0274c972016-12-06 09:32:04 -0700113binder::Status checkPermission(const char* permission) {
114 pid_t pid;
115 uid_t uid;
116
117 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
118 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700119 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700120 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700121 return exception(binder::Status::EX_SECURITY,
122 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700123 }
124}
125
126binder::Status checkUid(uid_t expectedUid) {
127 uid_t uid = IPCThreadState::self()->getCallingUid();
128 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700129 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700130 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700131 return exception(binder::Status::EX_SECURITY,
132 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
133 }
134}
135
136binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
137 if (!uuid || is_valid_filename(*uuid)) {
138 return ok();
139 } else {
140 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
141 StringPrintf("UUID %s is malformed", uuid->c_str()));
142 }
143}
144
145binder::Status checkArgumentPackageName(const std::string& packageName) {
146 if (is_valid_package_name(packageName.c_str())) {
147 return ok();
148 } else {
149 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
150 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700151 }
152}
153
154#define ENFORCE_UID(uid) { \
155 binder::Status status = checkUid((uid)); \
156 if (!status.isOk()) { \
157 return status; \
158 } \
159}
160
Jeff Sharkey423e7462016-12-09 18:18:43 -0700161#define CHECK_ARGUMENT_UUID(uuid) { \
162 binder::Status status = checkArgumentUuid((uuid)); \
163 if (!status.isOk()) { \
164 return status; \
165 } \
166}
167
168#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
169 binder::Status status = \
170 checkArgumentPackageName((packageName)); \
171 if (!status.isOk()) { \
172 return status; \
173 } \
174}
175
Jeff Sharkey0274c972016-12-06 09:32:04 -0700176} // namespace
177
178status_t InstalldNativeService::start() {
179 IPCThreadState::self()->disableBackgroundScheduling(true);
180 status_t ret = BinderService<InstalldNativeService>::publish();
181 if (ret != android::OK) {
182 return ret;
183 }
184 sp<ProcessState> ps(ProcessState::self());
185 ps->startThreadPool();
186 ps->giveThreadPoolName();
187 return android::OK;
188}
189
190status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
191 const binder::Status dump_permission = checkPermission(kDump);
192 if (!dump_permission.isOk()) {
193 const String8 msg(dump_permission.toString8());
194 write(fd, msg.string(), msg.size());
195 return PERMISSION_DENIED;
196 }
197
198 std::string msg = "installd is happy\n";
199 write(fd, msg.c_str(), strlen(msg.c_str()));
200 return NO_ERROR;
201}
202
Jeff Sharkey7db60412016-09-20 18:21:42 -0600203/**
204 * Perform restorecon of the given path, but only perform recursive restorecon
205 * if the label of that top-level file actually changed. This can save us
206 * significant time by avoiding no-op traversals of large filesystem trees.
207 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700208static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
209 bool existing) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600210 int res = 0;
211 char* before = nullptr;
212 char* after = nullptr;
213
214 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
215 // libselinux. Not needed here.
216
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600217 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600218 PLOG(ERROR) << "Failed before getfilecon for " << path;
219 goto fail;
220 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700221 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600222 PLOG(ERROR) << "Failed top-level restorecon for " << path;
223 goto fail;
224 }
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600225 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey7db60412016-09-20 18:21:42 -0600226 PLOG(ERROR) << "Failed after getfilecon for " << path;
227 goto fail;
228 }
229
230 // If the initial top-level restorecon above changed the label, then go
231 // back and restorecon everything recursively
232 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700233 if (existing) {
234 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
235 << path << "; running recursive restorecon";
236 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700237 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey7db60412016-09-20 18:21:42 -0600238 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
239 PLOG(ERROR) << "Failed recursive restorecon for " << path;
240 goto fail;
241 }
242 }
243
244 goto done;
245fail:
246 res = -1;
247done:
248 free(before);
249 free(after);
250 return res;
251}
252
Jeff Sharkey0274c972016-12-06 09:32:04 -0700253static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700254 const std::string& seInfo, uid_t uid, bool existing) {
255 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
256 existing);
Jeff Sharkey95d9ac62016-10-31 11:22:19 -0600257}
258
Jeff Sharkey7db60412016-09-20 18:21:42 -0600259static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600260 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
261 PLOG(ERROR) << "Failed to prepare " << path;
262 return -1;
263 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600264 return 0;
265}
266
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700267/**
268 * Prepare an app cache directory, which offers to fix-up the GID and
269 * directory mode flags during a platform upgrade.
270 */
271static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
272 uid_t uid, gid_t gid) {
273 auto path = StringPrintf("%s/%s", parent.c_str(), name);
274 struct stat st;
275 if (stat(path.c_str(), &st) != 0) {
276 if (errno == ENOENT) {
277 // This is fine, just create it
278 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
279 PLOG(ERROR) << "Failed to prepare " << path;
280 return -1;
281 } else {
282 return 0;
283 }
284 } else {
285 PLOG(ERROR) << "Failed to stat " << path;
286 return -1;
287 }
288 }
289
290 if (st.st_uid != uid) {
291 // Mismatched UID is real trouble; we can't recover
292 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
293 << " but expected " << uid;
294 return -1;
295 } else if (st.st_gid == gid && st.st_mode == target_mode) {
296 // Everything looks good!
297 return 0;
298 }
299
300 // Directory is owned correctly, but GID or mode mismatch means it's
301 // probably a platform upgrade so we need to fix them
302 FTS *fts;
303 FTSENT *p;
304 char *argv[] = { (char*) path.c_str(), nullptr };
305 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
306 PLOG(ERROR) << "Failed to fts_open " << path;
307 return -1;
308 }
309 while ((p = fts_read(fts)) != NULL) {
310 switch (p->fts_info) {
311 case FTS_DP:
312 if (chmod(p->fts_accpath, target_mode) != 0) {
313 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
314 }
315 // Intentional fall through to also set GID
316 case FTS_F:
317 if (chown(p->fts_accpath, -1, gid) != 0) {
318 PLOG(WARNING) << "Failed to chown " << p->fts_path;
319 }
320 break;
321 case FTS_SL:
322 case FTS_SLNONE:
323 if (lchown(p->fts_accpath, -1, gid) != 0) {
324 PLOG(WARNING) << "Failed to chown " << p->fts_path;
325 }
326 break;
327 }
328 }
329 fts_close(fts);
330 return 0;
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600331}
332
Jeff Sharkey0274c972016-12-06 09:32:04 -0700333binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
334 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700335 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700336 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700337 CHECK_ARGUMENT_UUID(uuid);
338 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700339
340 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
341 const char* pkgname = packageName.c_str();
342
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700343 // Assume invalid inode unless filled in below
344 if (_aidl_return != nullptr) *_aidl_return = -1;
345
Jeff Sharkey0274c972016-12-06 09:32:04 -0700346 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700347 gid_t cacheGid = multiuser_get_cache_gid(userId, appId);
348 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
349
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700350 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700351 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700352 bool existing = (access(path.c_str(), F_OK) == 0);
353
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700354 if (prepare_app_dir(path, targetMode, uid) ||
355 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
356 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700357 return error("Failed to prepare " + path);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600358 }
359
360 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700361 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
362 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
363 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700364 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700365 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600366
367 // Remember inode numbers of cache directories so that we can clear
368 // contents while CE storage is locked
369 if (write_path_inode(path, "cache", kXattrInodeCache) ||
370 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700371 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700372 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700373
374 // And return the CE inode of the top-level data directory so we can
375 // clear contents while CE storage is locked
376 if ((_aidl_return != nullptr)
377 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
378 return error("Failed to get_path_inode for " + path);
379 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700380 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700381 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700382 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700383 bool existing = (access(path.c_str(), F_OK) == 0);
384
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700385 if (prepare_app_dir(path, targetMode, uid) ||
386 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
387 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700388 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700389 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000390
Jeff Sharkey7db60412016-09-20 18:21:42 -0600391 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700392 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700393 return error("Failed to restorecon " + path);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600394 }
395
Jeff Sharkey90aff262016-12-12 14:28:24 -0700396 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700397 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000398 // read-write-execute only for the app user.
399 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700400 return error("Failed to prepare " + profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000401 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100402 std::string profile_file = create_primary_profile(profile_path);
403 // read-write only for the app user.
404 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700405 return error("Failed to prepare " + profile_path);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100406 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000407 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
408 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
409 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700410 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700411 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000412 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700413 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000414 }
415 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700416 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700417 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700418}
419
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700420binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
421 const std::string& packageName, int32_t userId, int32_t flags) {
422 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700423 CHECK_ARGUMENT_UUID(uuid);
424 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
425
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700426 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
427 const char* pkgname = packageName.c_str();
428
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700429 // This method only exists to upgrade system apps that have requested
430 // forceDeviceEncrypted, so their default storage always lives in a
431 // consistent location. This only works on non-FBE devices, since we
432 // never want to risk exposing data on a device with real CE/DE storage.
433
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700434 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
435 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700436
437 // If neither directory is marked as default, assume CE is default
438 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
439 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
440 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700441 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700442 }
443 }
444
445 // Migrate default data location if needed
446 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
447 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
448
449 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
450 LOG(WARNING) << "Requested default storage " << target
451 << " is not active; migrating from " << source;
452 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700453 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700454 }
455 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700456 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700457 }
458 }
459
Jeff Sharkey423e7462016-12-09 18:18:43 -0700460 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700461}
462
Calin Juravle6a1648e2016-02-01 12:12:16 +0000463
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700464binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
465 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700466 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
467
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700468 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700469 binder::Status res = ok();
470 if (!clear_reference_profile(pkgname)) {
471 res = error("Failed to clear reference profile for " + packageName);
472 }
473 if (!clear_current_profiles(pkgname)) {
474 res = error("Failed to clear current profiles for " + packageName);
475 }
476 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000477}
478
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700479binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
480 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
481 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700482 CHECK_ARGUMENT_UUID(uuid);
483 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
484
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700485 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
486 const char* pkgname = packageName.c_str();
487
Jeff Sharkey423e7462016-12-09 18:18:43 -0700488 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700489 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700490 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600491 if (flags & FLAG_CLEAR_CACHE_ONLY) {
492 path = read_path_inode(path, "cache", kXattrInodeCache);
493 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
494 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
495 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700496 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700497 if (delete_dir_contents(path) != 0) {
498 res = error("Failed to delete contents of " + path);
499 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700500 }
501 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700502 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600503 std::string suffix = "";
504 bool only_cache = false;
505 if (flags & FLAG_CLEAR_CACHE_ONLY) {
506 suffix = CACHE_DIR_POSTFIX;
507 only_cache = true;
508 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
509 suffix = CODE_CACHE_DIR_POSTFIX;
510 only_cache = true;
511 }
512
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700513 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700514 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700515 if (delete_dir_contents(path) != 0) {
516 res = error("Failed to delete contents of " + path);
517 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700518 }
Calin Juravleedae6692016-03-23 13:55:31 +0000519 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700520 if (!clear_current_profile(pkgname, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700521 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000522 }
523 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700524 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700525 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700526}
527
Calin Juravle7535e8e2016-03-29 16:05:40 +0100528static int destroy_app_reference_profile(const char *pkgname) {
529 return delete_dir_contents_and_dir(
530 create_data_ref_profile_package_path(pkgname),
531 /*ignore_if_missing*/ true);
532}
533
Calin Juravleedae6692016-03-23 13:55:31 +0000534static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100535 return delete_dir_contents_and_dir(
536 create_data_user_profile_package_path(userid, pkgname),
537 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000538}
539
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700540binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
541 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700542 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
543
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700544 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700545 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000546 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
547 for (auto user : users) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700548 if (destroy_app_current_profiles(pkgname, user) != 0) {
549 res = error("Failed to destroy current profiles for " + packageName);
550 }
Calin Juravleedae6692016-03-23 13:55:31 +0000551 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700552 if (destroy_app_reference_profile(pkgname) != 0) {
553 res = error("Failed to destroy reference profile for " + packageName);
554 }
555 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000556}
557
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700558binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
559 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
560 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700561 CHECK_ARGUMENT_UUID(uuid);
562 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
563
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700564 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
565 const char* pkgname = packageName.c_str();
566
Jeff Sharkey423e7462016-12-09 18:18:43 -0700567 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700568 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700569 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
570 if (delete_dir_contents_and_dir(path) != 0) {
571 res = error("Failed to delete " + path);
572 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700573 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700574 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700575 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
576 if (delete_dir_contents_and_dir(path) != 0) {
577 res = error("Failed to delete " + path);
578 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700579 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100580 // TODO(calin): If the package is still installed by other users it's probably
581 // beneficial to keep the reference profile around.
582 // Verify if it's ok to do that.
583 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700584 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700585 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700586}
587
Jeff Sharkey0274c972016-12-06 09:32:04 -0700588binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
589 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
590 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
591 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700592 ENFORCE_UID(AID_SYSTEM);
593 CHECK_ARGUMENT_UUID(fromUuid);
594 CHECK_ARGUMENT_UUID(toUuid);
595 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700596
597 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
598 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
599 const char* package_name = packageName.c_str();
600 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700601
Jeff Sharkey423e7462016-12-09 18:18:43 -0700602 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700603 std::vector<userid_t> users = get_known_users(from_uuid);
604
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700605 // Copy app
606 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600607 auto from = create_data_app_package_path(from_uuid, data_app_name);
608 auto to = create_data_app_package_path(to_uuid, data_app_name);
609 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700610
611 char *argv[] = {
612 (char*) kCpPath,
613 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
614 (char*) "-p", /* preserve timestamps, ownership, and permissions */
615 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
616 (char*) "-P", /* Do not follow symlinks [default] */
617 (char*) "-d", /* don't dereference symlinks */
618 (char*) from.c_str(),
619 (char*) to_parent.c_str()
620 };
621
622 LOG(DEBUG) << "Copying " << from << " to " << to;
623 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700624 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700625 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700626 goto fail;
627 }
628
629 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700630 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700631 goto fail;
632 }
633 }
634
635 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700636 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700637
638 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600639 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
640 if (access(from_ce.c_str(), F_OK) != 0) {
641 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700642 continue;
643 }
644
Jeff Sharkey0274c972016-12-06 09:32:04 -0700645 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700646 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700647 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700648 goto fail;
649 }
650
651 char *argv[] = {
652 (char*) kCpPath,
653 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
654 (char*) "-p", /* preserve timestamps, ownership, and permissions */
655 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
656 (char*) "-P", /* Do not follow symlinks [default] */
657 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600658 nullptr,
659 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700660 };
661
Jeff Sharkey51c94492016-05-10 17:46:39 -0600662 {
663 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
664 auto to = create_data_user_de_path(to_uuid, user);
665 argv[6] = (char*) from.c_str();
666 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700667
Jeff Sharkey51c94492016-05-10 17:46:39 -0600668 LOG(DEBUG) << "Copying " << from << " to " << to;
669 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
670 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700671 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600672 goto fail;
673 }
674 }
675 {
676 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
677 auto to = create_data_user_ce_path(to_uuid, user);
678 argv[6] = (char*) from.c_str();
679 argv[7] = (char*) to.c_str();
680
681 LOG(DEBUG) << "Copying " << from << " to " << to;
682 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
683 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700684 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600685 goto fail;
686 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700687 }
688
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700689 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
690 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700691 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700692 goto fail;
693 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700694 }
695
Jeff Sharkey31f08982015-07-07 13:31:37 -0700696 // We let the framework scan the new location and persist that before
697 // deleting the data in the old location; this ordering ensures that
698 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700699 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700700
701fail:
702 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700703 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600704 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700705 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
706 LOG(WARNING) << "Failed to rollback " << to;
707 }
708 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700709 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600710 {
711 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
712 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
713 LOG(WARNING) << "Failed to rollback " << to;
714 }
715 }
716 {
717 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
718 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
719 LOG(WARNING) << "Failed to rollback " << to;
720 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700721 }
722 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700723 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700724}
725
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700726binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
727 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
728 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700729 CHECK_ARGUMENT_UUID(uuid);
730
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700731 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600732 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700733 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700734 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700735 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700736 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700737 }
738 }
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700739 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700740}
741
742binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
743 int32_t userId, int32_t flags) {
744 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700745 CHECK_ARGUMENT_UUID(uuid);
746
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700747 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700748 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700749 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700750 auto path = create_data_user_de_path(uuid_, userId);
751 if (delete_dir_contents_and_dir(path, true) != 0) {
752 res = error("Failed to delete " + path);
753 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700754 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700755 path = create_data_misc_legacy_path(userId);
756 if (delete_dir_contents_and_dir(path, true) != 0) {
757 res = error("Failed to delete " + path);
758 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700759 path = create_data_user_profile_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700760 if (delete_dir_contents_and_dir(path, true) != 0) {
761 res = error("Failed to delete " + path);
762 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700763 }
Robin Lee095c7632014-04-25 15:05:19 +0100764 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600765 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700766 auto path = create_data_user_ce_path(uuid_, userId);
767 if (delete_dir_contents_and_dir(path, true) != 0) {
768 res = error("Failed to delete " + path);
769 }
770 path = create_data_media_path(uuid_, userId);
771 if (delete_dir_contents_and_dir(path, true) != 0) {
772 res = error("Failed to delete " + path);
773 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600774 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700775 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100776}
777
Mike Lockwood94afecf2012-10-24 10:45:23 -0700778/* Try to ensure free_size bytes of storage are available.
779 * Returns 0 on success.
780 * This is rather simple-minded because doing a full LRU would
781 * be potentially memory-intensive, and without atime it would
782 * also require that apps constantly modify file metadata even
783 * when just reading from the cache, which is pretty awful.
784 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700785binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
786 int64_t freeStorageSize) {
787 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700788 CHECK_ARGUMENT_UUID(uuid);
789
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700790 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700791 cache_t* cache;
792 int64_t avail;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700793
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700794 auto data_path = create_data_path(uuid_);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700795
796 avail = data_disk_free(data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700797 if (avail < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700798 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700799 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700800
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700801 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
802 if (avail >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700803 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700804 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700805
806 cache = start_cache_collection();
807
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700808 auto users = get_known_users(uuid_);
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600809 for (auto user : users) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700810 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
811 add_cache_files(cache, create_data_user_de_path(uuid_, user));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600812 add_cache_files(cache,
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700813 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700814 }
815
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700816 clear_cache_files(data_path, cache, freeStorageSize);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700817 finish_cache_collection(cache);
818
Jeff Sharkey423e7462016-12-09 18:18:43 -0700819 avail = data_disk_free(data_path);
820 if (avail >= freeStorageSize) {
821 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700822 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700823 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
824 freeStorageSize, data_path.c_str(), avail));
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700825 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700826}
827
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700828binder::Status InstalldNativeService::rmdex(const std::string& codePath,
829 const std::string& instructionSet) {
830 ENFORCE_UID(AID_SYSTEM);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700831 char dex_path[PKG_PATH_MAX];
832
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700833 const char* path = codePath.c_str();
834 const char* instruction_set = instructionSet.c_str();
835
Jeff Sharkey770180a2014-09-08 17:14:26 -0700836 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700837 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700838 }
839
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700840 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700841 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700842 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700843
844 ALOGV("unlink %s\n", dex_path);
845 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700846 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700847 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700848 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700849 }
850}
851
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700852struct stats {
853 int64_t codeSize;
854 int64_t dataSize;
855 int64_t cacheSize;
856};
857
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700858#if MEASURE_DEBUG
859static std::string toString(std::vector<int64_t> values) {
860 std::stringstream res;
861 res << "[";
862 for (size_t i = 0; i < values.size(); i++) {
863 res << values[i];
864 if (i < values.size() - 1) {
865 res << ",";
866 }
867 }
868 res << "]";
869 return res.str();
870}
871#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700872
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700873static std::string findDeviceForUuid(const std::unique_ptr<std::string>& uuid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700874 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700875 std::ifstream in("/proc/mounts");
876 if (!in.is_open()) {
877 PLOG(ERROR) << "Failed to read mounts";
878 return "";
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700879 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700880 std::string source;
881 std::string target;
882 while (!in.eof()) {
883 std::getline(in, source, ' ');
884 std::getline(in, target, ' ');
885 if (target == path) {
886 return source;
887 }
888 // Skip to next line
889 std::getline(in, source);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700890 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700891 PLOG(ERROR) << "Failed to resolve block device for " << path;
892 return "";
893}
894
895static void collectQuotaStats(const std::string& device, int32_t userId,
896 int32_t appId, struct stats* stats, struct stats* extStats ATTRIBUTE_UNUSED) {
897 if (device.empty()) return;
898
899 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700900
901 uid_t uid = multiuser_get_uid(userId, appId);
902 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
903 reinterpret_cast<char*>(&dq)) != 0) {
904 if (errno != ESRCH) {
905 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
906 }
907 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700908#if MEASURE_DEBUG
909 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
910#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700911 stats->dataSize += dq.dqb_curspace;
912 }
913
914 int cacheGid = multiuser_get_cache_gid(userId, appId);
915 if (cacheGid != -1) {
916 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
917 reinterpret_cast<char*>(&dq)) != 0) {
918 if (errno != ESRCH) {
919 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
920 }
921 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700922#if MEASURE_DEBUG
923 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
924#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700925 stats->cacheSize += dq.dqb_curspace;
926 }
927 }
928
929 int sharedGid = multiuser_get_shared_app_gid(uid);
930 if (sharedGid != -1) {
931 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
932 reinterpret_cast<char*>(&dq)) != 0) {
933 if (errno != ESRCH) {
934 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
935 }
936 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700937#if MEASURE_DEBUG
938 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
939#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700940 stats->codeSize += dq.dqb_curspace;
941 }
942 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700943
944#if MEASURE_EXTERNAL
945 // TODO: measure using external GIDs
946#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700947}
948
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700949static void collectQuotaStats(const std::unique_ptr<std::string>& uuid, int32_t userId,
950 int32_t appId, struct stats* stats, struct stats* extStats) {
951 collectQuotaStats(findDeviceForUuid(uuid), userId, appId, stats, extStats);
952}
953
954static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700955 DIR *d;
956 int dfd;
957 struct dirent *de;
958 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700959
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600960 d = opendir(path.c_str());
961 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700962 if (errno != ENOENT) {
963 PLOG(WARNING) << "Failed to open " << path;
964 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600965 return;
966 }
967 dfd = dirfd(d);
968 while ((de = readdir(d))) {
969 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700970
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700971 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600972 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700973 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600974 }
975
976 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700977 if (!strcmp(name, ".")) {
978 // Don't recurse, but still count node size
979 } else if (!strcmp(name, "..")) {
980 // Don't recurse or count node size
981 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700982 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700983 // Measure all children nodes
984 size = 0;
985 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700986 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700987
988 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
989 stats->cacheSize += size;
990 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700991 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700992
993 // Legacy symlink isn't owned by app
994 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
995 continue;
996 }
997
998 // Everything found inside is considered data
999 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001000 }
1001 closedir(d);
1002}
1003
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001004static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1005 bool exclude_apps = false) {
1006 DIR *d;
1007 int dfd;
1008 struct dirent *de;
1009 struct stat s;
1010
1011 d = opendir(path.c_str());
1012 if (d == nullptr) {
1013 if (errno != ENOENT) {
1014 PLOG(WARNING) << "Failed to open " << path;
1015 }
1016 return;
1017 }
1018 dfd = dirfd(d);
1019 while ((de = readdir(d))) {
1020 if (de->d_type == DT_DIR) {
1021 const char *name = de->d_name;
1022 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1023 continue;
1024 }
1025 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1026 continue;
1027 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1028 continue;
1029 } else {
1030 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1031 }
1032 }
1033 }
1034 closedir(d);
1035}
1036
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001037binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001038 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1039 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1040 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001041 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001042 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001043 for (auto packageName : packageNames) {
1044 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1045 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001046
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001047 // When modifying this logic, always verify using tests:
1048 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1049
1050#if MEASURE_DEBUG
1051 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1052#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001053
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001054 // Here's a summary of the common storage locations across the platform,
1055 // and how they're each tagged:
1056 //
1057 // /data/app/com.example UID system
1058 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001059 // /data/user/0/com.example UID u0_a10 GID u0_a10
1060 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1061 // /data/media/0/foo.txt UID u0_media_rw
1062 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1063 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1064 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1065 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001066
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001067 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001068 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001069 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001070 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001071
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001072 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001073
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001074 for (auto packageName : packageNames) {
1075 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1076 calculate_tree_size(obbCodePath, &extStats.codeSize);
1077 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001078
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001079 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
1080 for (auto codePath : codePaths) {
1081 calculate_tree_size(codePath, &stats.codeSize, -1,
1082 multiuser_get_shared_gid(userId, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001083 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001084
1085 collectQuotaStats(uuid, userId, appId, &stats, &extStats);
1086
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001087 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001088 for (auto codePath : codePaths) {
1089 calculate_tree_size(codePath, &stats.codeSize);
1090 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001091
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001092 for (size_t i = 0; i < packageNames.size(); i++) {
1093 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001094
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001095 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1096 collectManualStats(cePath, &stats);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001097
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001098 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1099 collectManualStats(dePath, &stats);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001100
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001101 auto userProfilePath = create_data_user_profile_package_path(userId, pkgname);
1102 calculate_tree_size(userProfilePath, &stats.dataSize);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001103
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001104 auto refProfilePath = create_data_ref_profile_package_path(pkgname);
1105 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001106
1107#if MEASURE_EXTERNAL
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001108 auto extPath = create_data_media_package_path(uuid_, userId, pkgname, "data");
1109 collectManualStats(extPath, &extStats);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001110
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001111 auto mediaPath = create_data_media_package_path(uuid_, userId, pkgname, "media");
1112 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001113#endif
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001114 }
1115
1116 int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1117 if (sharedGid != -1) {
1118 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1119 sharedGid, -1);
1120 }
1121
1122 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1123 multiuser_get_uid(userId, appId), -1);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001124 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001125
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001126 std::vector<int64_t> ret;
1127 ret.push_back(stats.codeSize);
1128 ret.push_back(stats.dataSize);
1129 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001130 ret.push_back(extStats.codeSize);
1131 ret.push_back(extStats.dataSize);
1132 ret.push_back(extStats.cacheSize);
1133#if MEASURE_DEBUG
1134 LOG(DEBUG) << "Final result " << toString(ret);
1135#endif
1136 *_aidl_return = ret;
1137 return ok();
1138}
1139
1140binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1141 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1142 std::vector<int64_t>* _aidl_return) {
1143 ENFORCE_UID(AID_SYSTEM);
1144 CHECK_ARGUMENT_UUID(uuid);
1145
1146 // When modifying this logic, always verify using tests:
1147 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1148
1149#if MEASURE_DEBUG
1150 LOG(INFO) << "Measuring user " << userId;
1151#endif
1152
1153 struct stats stats;
1154 struct stats extStats;
1155 memset(&stats, 0, sizeof(stats));
1156 memset(&extStats, 0, sizeof(extStats));
1157
1158 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1159
1160 auto obbPath = create_data_path(uuid_) + "/media/obb";
1161 calculate_tree_size(obbPath, &extStats.codeSize);
1162
1163 if (flags & FLAG_USE_QUOTA) {
1164 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
1165
1166 auto cePath = create_data_user_ce_path(uuid_, userId);
1167 collectManualStatsForUser(cePath, &stats, true);
1168
1169 auto dePath = create_data_user_de_path(uuid_, userId);
1170 collectManualStatsForUser(dePath, &stats, true);
1171
1172 auto userProfilePath = create_data_user_profile_path(userId);
1173 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1174
1175 auto refProfilePath = create_data_ref_profile_path();
1176 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1177
1178#if MEASURE_EXTERNAL
1179 // TODO: measure external storage paths
1180#endif
1181
1182 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1183 -1, -1, true);
1184
1185 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1186 -1, -1, true);
1187
1188 auto device = findDeviceForUuid(uuid);
1189 for (auto appId : appIds) {
1190 if (appId >= AID_APP_START) {
1191 collectQuotaStats(device, userId, appId, &stats, &extStats);
1192#if MEASURE_DEBUG
1193 // Sleep to make sure we don't lose logs
1194 usleep(1);
1195#endif
1196 }
1197 }
1198 } else {
1199 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
1200
1201 auto cePath = create_data_user_ce_path(uuid_, userId);
1202 collectManualStatsForUser(cePath, &stats);
1203
1204 auto dePath = create_data_user_de_path(uuid_, userId);
1205 collectManualStatsForUser(dePath, &stats);
1206
1207 auto userProfilePath = create_data_user_profile_path(userId);
1208 calculate_tree_size(userProfilePath, &stats.dataSize);
1209
1210 auto refProfilePath = create_data_ref_profile_path();
1211 calculate_tree_size(refProfilePath, &stats.codeSize);
1212
1213#if MEASURE_EXTERNAL
1214 // TODO: measure external storage paths
1215#endif
1216
1217 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1218
1219 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize);
1220 }
1221
1222 std::vector<int64_t> ret;
1223 ret.push_back(stats.codeSize);
1224 ret.push_back(stats.dataSize);
1225 ret.push_back(stats.cacheSize);
1226 ret.push_back(extStats.codeSize);
1227 ret.push_back(extStats.dataSize);
1228 ret.push_back(extStats.cacheSize);
1229#if MEASURE_DEBUG
1230 LOG(DEBUG) << "Final result " << toString(ret);
1231#endif
1232 *_aidl_return = ret;
1233 return ok();
1234}
1235
1236binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1237 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1238 ENFORCE_UID(AID_SYSTEM);
1239 CHECK_ARGUMENT_UUID(uuid);
1240
1241 // When modifying this logic, always verify using tests:
1242 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1243
1244#if MEASURE_DEBUG
1245 LOG(INFO) << "Measuring external " << userId;
1246#endif
1247
1248 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1249
1250 int64_t totalSize = 0;
1251 int64_t audioSize = 0;
1252 int64_t videoSize = 0;
1253 int64_t imageSize = 0;
1254
1255 if (flags & FLAG_USE_QUOTA) {
1256 struct dqblk dq;
1257
1258 auto device = findDeviceForUuid(uuid);
1259
1260 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1261 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1262 reinterpret_cast<char*>(&dq)) != 0) {
1263 if (errno != ESRCH) {
1264 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1265 }
1266 } else {
1267#if MEASURE_DEBUG
1268 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1269#endif
1270 totalSize = dq.dqb_curspace;
1271 }
1272
1273 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1274 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1275 reinterpret_cast<char*>(&dq)) == 0) {
1276#if MEASURE_DEBUG
1277 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1278#endif
1279 audioSize = dq.dqb_curspace;
1280 }
1281 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1282 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1283 reinterpret_cast<char*>(&dq)) == 0) {
1284#if MEASURE_DEBUG
1285 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1286#endif
1287 videoSize = dq.dqb_curspace;
1288 }
1289 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1290 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1291 reinterpret_cast<char*>(&dq)) == 0) {
1292#if MEASURE_DEBUG
1293 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1294#endif
1295 imageSize = dq.dqb_curspace;
1296 }
1297 } else {
1298 FTS *fts;
1299 FTSENT *p;
1300 auto path = create_data_media_path(uuid_, userId);
1301 char *argv[] = { (char*) path.c_str(), nullptr };
1302 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1303 return error("Failed to fts_open " + path);
1304 }
1305 while ((p = fts_read(fts)) != NULL) {
1306 char* ext;
1307 int64_t size = (p->fts_statp->st_blocks * 512);
1308 switch (p->fts_info) {
1309 case FTS_F:
1310 // Only categorize files not belonging to apps
1311 if (p->fts_statp->st_gid < AID_APP_START) {
1312 ext = strrchr(p->fts_name, '.');
1313 if (ext != nullptr) {
1314 switch (MatchExtension(++ext)) {
1315 case AID_MEDIA_AUDIO: audioSize += size; break;
1316 case AID_MEDIA_VIDEO: videoSize += size; break;
1317 case AID_MEDIA_IMAGE: imageSize += size; break;
1318 }
1319 }
1320 }
1321 // Fall through to always count against total
1322 case FTS_D:
1323 case FTS_DEFAULT:
1324 case FTS_SL:
1325 case FTS_SLNONE:
1326 totalSize += size;
1327 break;
1328 }
1329 }
1330 fts_close(fts);
1331 }
1332
1333 std::vector<int64_t> ret;
1334 ret.push_back(totalSize);
1335 ret.push_back(audioSize);
1336 ret.push_back(videoSize);
1337 ret.push_back(imageSize);
1338#if MEASURE_DEBUG
1339 LOG(DEBUG) << "Final result " << toString(ret);
1340#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001341 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001342 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001343}
1344
David Sehr6727c2d2016-05-17 16:06:22 -07001345// Dumps the contents of a profile file, using pkgname's dex files for pretty
1346// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001347binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1348 const std::string& codePaths, bool* _aidl_return) {
1349 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001350 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001351
1352 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001353 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001354
Jeff Sharkey90aff262016-12-12 14:28:24 -07001355 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001356 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001357}
1358
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001359// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001360binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001361 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001362 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001363 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1364
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001365 const char* pkgname = packageName.c_str();
1366 *_aidl_return = analyse_profiles(uid, pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001367 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001368}
1369
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001370binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1371 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1372 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1373 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1374 const std::unique_ptr<std::string>& sharedLibraries) {
1375 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001376 CHECK_ARGUMENT_UUID(uuid);
1377 if (packageName && *packageName != "*") {
1378 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1379 }
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001380
1381 const char* apk_path = apkPath.c_str();
1382 const char* pkgname = packageName ? packageName->c_str() : "*";
1383 const char* instruction_set = instructionSet.c_str();
1384 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1385 const char* compiler_filter = compilerFilter.c_str();
1386 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1387 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1388
1389 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1390 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001391 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001392}
1393
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001394binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1395 ENFORCE_UID(AID_SYSTEM);
1396 const char* instruction_set = instructionSet.c_str();
1397
1398 char boot_marker_path[PKG_PATH_MAX];
1399 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001400 "%s/%s/%s/.booting",
1401 android_data_dir.path,
1402 DALVIK_CACHE,
1403 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001404
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001405 ALOGV("mark_boot_complete : %s", boot_marker_path);
1406 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001407 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001408 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001409 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001410}
1411
Mike Lockwood94afecf2012-10-24 10:45:23 -07001412void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1413 struct stat* statbuf)
1414{
1415 while (path[basepos] != 0) {
1416 if (path[basepos] == '/') {
1417 path[basepos] = 0;
1418 if (lstat(path, statbuf) < 0) {
1419 ALOGV("Making directory: %s\n", path);
1420 if (mkdir(path, mode) == 0) {
1421 chown(path, uid, gid);
1422 } else {
1423 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1424 }
1425 }
1426 path[basepos] = '/';
1427 basepos++;
1428 }
1429 basepos++;
1430 }
1431}
1432
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001433binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1434 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1435 const std::string& nativeLibPath32, int32_t userId) {
1436 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001437 CHECK_ARGUMENT_UUID(uuid);
1438 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1439
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001440 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1441 const char* pkgname = packageName.c_str();
1442 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001443 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001444 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001445
Jeff Sharkey423e7462016-12-09 18:18:43 -07001446 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1447 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001448
1449 const char* pkgdir = _pkgdir.c_str();
1450 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001451
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001452 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001453 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001454 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001455
1456 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001457 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001458 }
1459
1460 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001461 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001462 goto out;
1463 }
1464
1465 if (lstat(libsymlink, &libStat) < 0) {
1466 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001467 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001468 goto out;
1469 }
1470 } else {
1471 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001472 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001473 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001474 goto out;
1475 }
1476 } else if (S_ISLNK(libStat.st_mode)) {
1477 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001478 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001479 goto out;
1480 }
1481 }
1482 }
1483
1484 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001485 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001486 goto out;
1487 }
1488
1489out:
1490 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001491 auto msg = "Failed to cleanup chmod " + _pkgdir;
1492 if (res.isOk()) {
1493 res = error(msg);
1494 } else {
1495 PLOG(ERROR) << msg;
1496 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001497 }
1498
1499 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001500 auto msg = "Failed to cleanup chown " + _pkgdir;
1501 if (res.isOk()) {
1502 res = error(msg);
1503 } else {
1504 PLOG(ERROR) << msg;
1505 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001506 }
1507
Jeff Sharkey423e7462016-12-09 18:18:43 -07001508 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001509}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001510
1511static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1512{
1513 static const char *IDMAP_BIN = "/system/bin/idmap";
1514 static const size_t MAX_INT_LEN = 32;
1515 char idmap_str[MAX_INT_LEN];
1516
1517 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1518
1519 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1520 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1521}
1522
1523// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1524// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1525static int flatten_path(const char *prefix, const char *suffix,
1526 const char *overlay_path, char *idmap_path, size_t N)
1527{
1528 if (overlay_path == NULL || idmap_path == NULL) {
1529 return -1;
1530 }
1531 const size_t len_overlay_path = strlen(overlay_path);
1532 // will access overlay_path + 1 further below; requires absolute path
1533 if (len_overlay_path < 2 || *overlay_path != '/') {
1534 return -1;
1535 }
1536 const size_t len_idmap_root = strlen(prefix);
1537 const size_t len_suffix = strlen(suffix);
1538 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1539 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1540 // additions below would cause overflow
1541 return -1;
1542 }
1543 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1544 return -1;
1545 }
1546 memset(idmap_path, 0, N);
1547 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1548 char *ch = idmap_path + len_idmap_root;
1549 while (*ch != '\0') {
1550 if (*ch == '/') {
1551 *ch = '@';
1552 }
1553 ++ch;
1554 }
1555 return 0;
1556}
1557
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001558binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1559 const std::string& overlayApkPath, int32_t uid) {
1560 ENFORCE_UID(AID_SYSTEM);
1561 const char* target_apk = targetApkPath.c_str();
1562 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001563 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1564
1565 int idmap_fd = -1;
1566 char idmap_path[PATH_MAX];
1567
1568 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1569 idmap_path, sizeof(idmap_path)) == -1) {
1570 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1571 goto fail;
1572 }
1573
1574 unlink(idmap_path);
1575 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1576 if (idmap_fd < 0) {
1577 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1578 goto fail;
1579 }
1580 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1581 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1582 goto fail;
1583 }
1584 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1585 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1586 goto fail;
1587 }
1588
1589 pid_t pid;
1590 pid = fork();
1591 if (pid == 0) {
1592 /* child -- drop privileges before continuing */
1593 if (setgid(uid) != 0) {
1594 ALOGE("setgid(%d) failed during idmap\n", uid);
1595 exit(1);
1596 }
1597 if (setuid(uid) != 0) {
1598 ALOGE("setuid(%d) failed during idmap\n", uid);
1599 exit(1);
1600 }
1601 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1602 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1603 exit(1);
1604 }
1605
1606 run_idmap(target_apk, overlay_apk, idmap_fd);
1607 exit(1); /* only if exec call to idmap failed */
1608 } else {
1609 int status = wait_child(pid);
1610 if (status != 0) {
1611 ALOGE("idmap failed, status=0x%04x\n", status);
1612 goto fail;
1613 }
1614 }
1615
1616 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001617 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001618fail:
1619 if (idmap_fd >= 0) {
1620 close(idmap_fd);
1621 unlink(idmap_path);
1622 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001623 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001624}
Robert Craige9887e42014-02-20 10:25:56 -05001625
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001626binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1627 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1628 const std::string& seInfo) {
1629 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001630 CHECK_ARGUMENT_UUID(uuid);
1631 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1632
1633 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05001634
Robert Craigda30dc72014-03-27 10:21:12 -04001635 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001636 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001637 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1638 const char* pkgName = packageName.c_str();
1639 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04001640
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001641 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001642 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001643 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001644 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001645 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001646 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001647 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001648 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001649 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001650 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001651 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001652 }
Robert Craige9887e42014-02-20 10:25:56 -05001653 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001654 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001655}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001656
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001657binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1658 const std::string& instructionSet) {
1659 ENFORCE_UID(AID_SYSTEM);
1660 const char* oat_dir = oatDir.c_str();
1661 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001662 char oat_instr_dir[PKG_PATH_MAX];
1663
1664 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001665 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001666 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001667 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001668 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001669 }
1670 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001671 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001672 }
1673 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001674 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001675 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001676 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001677 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001678}
1679
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001680binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1681 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001682 if (validate_apk_path(packageDir.c_str())) {
1683 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001684 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001685 if (delete_dir_contents_and_dir(packageDir) != 0) {
1686 return error("Failed to delete " + packageDir);
1687 }
1688 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001689}
1690
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001691binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1692 const std::string& fromBase, const std::string& toBase) {
1693 ENFORCE_UID(AID_SYSTEM);
1694 const char* relative_path = relativePath.c_str();
1695 const char* from_base = fromBase.c_str();
1696 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01001697 char from_path[PKG_PATH_MAX];
1698 char to_path[PKG_PATH_MAX];
1699 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1700 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1701
1702 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001703 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001704 }
1705
1706 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001707 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001708 }
1709
Jeff Sharkey423e7462016-12-09 18:18:43 -07001710 if (link(from_path, to_path) < 0) {
1711 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001712 }
1713
Jeff Sharkey423e7462016-12-09 18:18:43 -07001714 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01001715}
1716
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001717binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1718 const std::string& instructionSet, const std::string& outputPath) {
1719 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001720
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001721 const char* apk_path = apkPath.c_str();
1722 const char* instruction_set = instructionSet.c_str();
1723 const char* oat_dir = outputPath.c_str();
Andreas Gamped089ca12016-06-27 14:25:30 -07001724
Jeff Sharkey90aff262016-12-12 14:28:24 -07001725 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001726 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08001727}
1728
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001729binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
1730 const std::string& instructionSet, const std::string& outputPath) {
1731 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001732
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001733 const char* apk_path = apkPath.c_str();
1734 const char* instruction_set = instructionSet.c_str();
1735 const char* oat_dir = outputPath.c_str();
1736
Jeff Sharkey90aff262016-12-12 14:28:24 -07001737 bool res = delete_odex(apk_path, instruction_set, oat_dir);
1738 return res ? ok() : error();
Andreas Gampeb31206b2016-09-09 17:07:04 -07001739}
1740
Andreas Gampe02d0de52015-11-11 20:43:16 -08001741} // namespace installd
1742} // namespace android