blob: 102359d44287981b877cf119483881f390c30105 [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
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700290 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700291 if (st.st_uid != uid) {
292 // Mismatched UID is real trouble; we can't recover
293 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
294 << " but expected " << uid;
295 return -1;
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700296 } else if (st.st_gid == gid && actual_mode == target_mode) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700297 // Everything looks good!
298 return 0;
299 }
300
301 // Directory is owned correctly, but GID or mode mismatch means it's
302 // probably a platform upgrade so we need to fix them
303 FTS *fts;
304 FTSENT *p;
305 char *argv[] = { (char*) path.c_str(), nullptr };
306 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
307 PLOG(ERROR) << "Failed to fts_open " << path;
308 return -1;
309 }
310 while ((p = fts_read(fts)) != NULL) {
311 switch (p->fts_info) {
312 case FTS_DP:
313 if (chmod(p->fts_accpath, target_mode) != 0) {
314 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
315 }
316 // Intentional fall through to also set GID
317 case FTS_F:
318 if (chown(p->fts_accpath, -1, gid) != 0) {
319 PLOG(WARNING) << "Failed to chown " << p->fts_path;
320 }
321 break;
322 case FTS_SL:
323 case FTS_SLNONE:
324 if (lchown(p->fts_accpath, -1, gid) != 0) {
325 PLOG(WARNING) << "Failed to chown " << p->fts_path;
326 }
327 break;
328 }
329 }
330 fts_close(fts);
331 return 0;
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600332}
333
Jeff Sharkey0274c972016-12-06 09:32:04 -0700334binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
335 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700336 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700337 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700338 CHECK_ARGUMENT_UUID(uuid);
339 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700340 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700341
342 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
343 const char* pkgname = packageName.c_str();
344
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700345 // Assume invalid inode unless filled in below
346 if (_aidl_return != nullptr) *_aidl_return = -1;
347
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700348 int32_t uid = multiuser_get_uid(userId, appId);
349 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700350 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
351
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700352 // If UID doesn't have a specific cache GID, use UID value
353 if (cacheGid == -1) {
354 cacheGid = uid;
355 }
356
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700357 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700358 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700359 bool existing = (access(path.c_str(), F_OK) == 0);
360
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700361 if (prepare_app_dir(path, targetMode, uid) ||
362 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
363 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700364 return error("Failed to prepare " + path);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600365 }
366
367 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700368 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
369 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
370 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700371 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700372 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600373
374 // Remember inode numbers of cache directories so that we can clear
375 // contents while CE storage is locked
376 if (write_path_inode(path, "cache", kXattrInodeCache) ||
377 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700378 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700379 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700380
381 // And return the CE inode of the top-level data directory so we can
382 // clear contents while CE storage is locked
383 if ((_aidl_return != nullptr)
384 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
385 return error("Failed to get_path_inode for " + path);
386 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700387 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700388 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700389 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700390 bool existing = (access(path.c_str(), F_OK) == 0);
391
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700392 if (prepare_app_dir(path, targetMode, uid) ||
393 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
394 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700395 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700396 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000397
Jeff Sharkey7db60412016-09-20 18:21:42 -0600398 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700399 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700400 return error("Failed to restorecon " + path);
Jeff Sharkey7db60412016-09-20 18:21:42 -0600401 }
402
Jeff Sharkey90aff262016-12-12 14:28:24 -0700403 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700404 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000405 // read-write-execute only for the app user.
406 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700407 return error("Failed to prepare " + profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000408 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100409 std::string profile_file = create_primary_profile(profile_path);
410 // read-write only for the app user.
411 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700412 return error("Failed to prepare " + profile_path);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100413 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000414 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
415 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
416 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700417 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700418 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000419 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700420 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000421 }
422 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700423 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700424 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700425}
426
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700427binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
428 const std::string& packageName, int32_t userId, int32_t flags) {
429 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700430 CHECK_ARGUMENT_UUID(uuid);
431 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700432 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700433
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700434 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
435 const char* pkgname = packageName.c_str();
436
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700437 // This method only exists to upgrade system apps that have requested
438 // forceDeviceEncrypted, so their default storage always lives in a
439 // consistent location. This only works on non-FBE devices, since we
440 // never want to risk exposing data on a device with real CE/DE storage.
441
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700442 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
443 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700444
445 // If neither directory is marked as default, assume CE is default
446 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
447 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
448 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700449 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700450 }
451 }
452
453 // Migrate default data location if needed
454 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
455 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
456
457 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
458 LOG(WARNING) << "Requested default storage " << target
459 << " is not active; migrating from " << source;
460 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700461 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700462 }
463 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700464 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700465 }
466 }
467
Jeff Sharkey423e7462016-12-09 18:18:43 -0700468 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700469}
470
Calin Juravle6a1648e2016-02-01 12:12:16 +0000471
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700472binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
473 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700474 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700475 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700476
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700477 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700478 binder::Status res = ok();
479 if (!clear_reference_profile(pkgname)) {
480 res = error("Failed to clear reference profile for " + packageName);
481 }
482 if (!clear_current_profiles(pkgname)) {
483 res = error("Failed to clear current profiles for " + packageName);
484 }
485 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000486}
487
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700488binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
489 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
490 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700491 CHECK_ARGUMENT_UUID(uuid);
492 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700493 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700494
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700495 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
496 const char* pkgname = packageName.c_str();
497
Jeff Sharkey423e7462016-12-09 18:18:43 -0700498 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700499 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700500 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600501 if (flags & FLAG_CLEAR_CACHE_ONLY) {
502 path = read_path_inode(path, "cache", kXattrInodeCache);
503 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
504 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
505 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700506 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700507 if (delete_dir_contents(path) != 0) {
508 res = error("Failed to delete contents of " + path);
509 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700510 }
511 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700512 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600513 std::string suffix = "";
514 bool only_cache = false;
515 if (flags & FLAG_CLEAR_CACHE_ONLY) {
516 suffix = CACHE_DIR_POSTFIX;
517 only_cache = true;
518 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
519 suffix = CODE_CACHE_DIR_POSTFIX;
520 only_cache = true;
521 }
522
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700523 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700524 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700525 if (delete_dir_contents(path) != 0) {
526 res = error("Failed to delete contents of " + path);
527 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700528 }
Calin Juravleedae6692016-03-23 13:55:31 +0000529 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700530 if (!clear_current_profile(pkgname, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700531 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000532 }
533 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700534 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700535 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700536}
537
Calin Juravle7535e8e2016-03-29 16:05:40 +0100538static int destroy_app_reference_profile(const char *pkgname) {
539 return delete_dir_contents_and_dir(
540 create_data_ref_profile_package_path(pkgname),
541 /*ignore_if_missing*/ true);
542}
543
Calin Juravleedae6692016-03-23 13:55:31 +0000544static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100545 return delete_dir_contents_and_dir(
546 create_data_user_profile_package_path(userid, pkgname),
547 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000548}
549
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700550binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
551 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700552 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700553 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700554
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700555 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700556 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000557 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
558 for (auto user : users) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700559 if (destroy_app_current_profiles(pkgname, user) != 0) {
560 res = error("Failed to destroy current profiles for " + packageName);
561 }
Calin Juravleedae6692016-03-23 13:55:31 +0000562 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700563 if (destroy_app_reference_profile(pkgname) != 0) {
564 res = error("Failed to destroy reference profile for " + packageName);
565 }
566 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000567}
568
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700569binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
570 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
571 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700572 CHECK_ARGUMENT_UUID(uuid);
573 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700574 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700575
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700576 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
577 const char* pkgname = packageName.c_str();
578
Jeff Sharkey423e7462016-12-09 18:18:43 -0700579 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700580 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700581 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
582 if (delete_dir_contents_and_dir(path) != 0) {
583 res = error("Failed to delete " + path);
584 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700585 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700586 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700587 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
588 if (delete_dir_contents_and_dir(path) != 0) {
589 res = error("Failed to delete " + path);
590 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700591 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100592 // TODO(calin): If the package is still installed by other users it's probably
593 // beneficial to keep the reference profile around.
594 // Verify if it's ok to do that.
595 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700596 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700597 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700598}
599
Jeff Sharkey0274c972016-12-06 09:32:04 -0700600binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
601 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
602 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
603 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700604 ENFORCE_UID(AID_SYSTEM);
605 CHECK_ARGUMENT_UUID(fromUuid);
606 CHECK_ARGUMENT_UUID(toUuid);
607 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700608 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700609
610 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
611 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
612 const char* package_name = packageName.c_str();
613 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700614
Jeff Sharkey423e7462016-12-09 18:18:43 -0700615 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700616 std::vector<userid_t> users = get_known_users(from_uuid);
617
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700618 // Copy app
619 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600620 auto from = create_data_app_package_path(from_uuid, data_app_name);
621 auto to = create_data_app_package_path(to_uuid, data_app_name);
622 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700623
624 char *argv[] = {
625 (char*) kCpPath,
626 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
627 (char*) "-p", /* preserve timestamps, ownership, and permissions */
628 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
629 (char*) "-P", /* Do not follow symlinks [default] */
630 (char*) "-d", /* don't dereference symlinks */
631 (char*) from.c_str(),
632 (char*) to_parent.c_str()
633 };
634
635 LOG(DEBUG) << "Copying " << from << " to " << to;
636 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700637 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700638 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700639 goto fail;
640 }
641
642 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700643 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700644 goto fail;
645 }
646 }
647
648 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700649 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700650
651 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600652 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
653 if (access(from_ce.c_str(), F_OK) != 0) {
654 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700655 continue;
656 }
657
Jeff Sharkey0274c972016-12-06 09:32:04 -0700658 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700659 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700660 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700661 goto fail;
662 }
663
664 char *argv[] = {
665 (char*) kCpPath,
666 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
667 (char*) "-p", /* preserve timestamps, ownership, and permissions */
668 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
669 (char*) "-P", /* Do not follow symlinks [default] */
670 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600671 nullptr,
672 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700673 };
674
Jeff Sharkey51c94492016-05-10 17:46:39 -0600675 {
676 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
677 auto to = create_data_user_de_path(to_uuid, user);
678 argv[6] = (char*) from.c_str();
679 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700680
Jeff Sharkey51c94492016-05-10 17:46:39 -0600681 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 }
687 }
688 {
689 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
690 auto to = create_data_user_ce_path(to_uuid, user);
691 argv[6] = (char*) from.c_str();
692 argv[7] = (char*) to.c_str();
693
694 LOG(DEBUG) << "Copying " << from << " to " << to;
695 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
696 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700697 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600698 goto fail;
699 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700700 }
701
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700702 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
703 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700704 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700705 goto fail;
706 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700707 }
708
Jeff Sharkey31f08982015-07-07 13:31:37 -0700709 // We let the framework scan the new location and persist that before
710 // deleting the data in the old location; this ordering ensures that
711 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700712 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700713
714fail:
715 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700716 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600717 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700718 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
719 LOG(WARNING) << "Failed to rollback " << to;
720 }
721 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700722 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600723 {
724 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
725 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
726 LOG(WARNING) << "Failed to rollback " << to;
727 }
728 }
729 {
730 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
731 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
732 LOG(WARNING) << "Failed to rollback " << to;
733 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700734 }
735 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700736 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700737}
738
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700739binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
740 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
741 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700742 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700743 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700744
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700745 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600746 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700747 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700748 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700749 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700750 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700751 }
752 }
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700753 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700754}
755
756binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
757 int32_t userId, int32_t flags) {
758 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700759 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700760 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700761
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700762 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700763 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700764 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700765 auto path = create_data_user_de_path(uuid_, userId);
766 if (delete_dir_contents_and_dir(path, true) != 0) {
767 res = error("Failed to delete " + path);
768 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700769 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700770 path = create_data_misc_legacy_path(userId);
771 if (delete_dir_contents_and_dir(path, true) != 0) {
772 res = error("Failed to delete " + path);
773 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700774 path = create_data_user_profile_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700775 if (delete_dir_contents_and_dir(path, true) != 0) {
776 res = error("Failed to delete " + path);
777 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700778 }
Robin Lee095c7632014-04-25 15:05:19 +0100779 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600780 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700781 auto path = create_data_user_ce_path(uuid_, userId);
782 if (delete_dir_contents_and_dir(path, true) != 0) {
783 res = error("Failed to delete " + path);
784 }
785 path = create_data_media_path(uuid_, userId);
786 if (delete_dir_contents_and_dir(path, true) != 0) {
787 res = error("Failed to delete " + path);
788 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600789 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700790 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100791}
792
Mike Lockwood94afecf2012-10-24 10:45:23 -0700793/* Try to ensure free_size bytes of storage are available.
794 * Returns 0 on success.
795 * This is rather simple-minded because doing a full LRU would
796 * be potentially memory-intensive, and without atime it would
797 * also require that apps constantly modify file metadata even
798 * when just reading from the cache, which is pretty awful.
799 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700800binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
801 int64_t freeStorageSize) {
802 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700803 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700804 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700805
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700806 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700807 cache_t* cache;
808 int64_t avail;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700809
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700810 auto data_path = create_data_path(uuid_);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700811
812 avail = data_disk_free(data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700813 if (avail < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700814 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700815 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700816
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700817 ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
818 if (avail >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700819 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700820 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700821
822 cache = start_cache_collection();
823
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700824 auto users = get_known_users(uuid_);
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600825 for (auto user : users) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700826 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
827 add_cache_files(cache, create_data_user_de_path(uuid_, user));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600828 add_cache_files(cache,
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700829 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700830 }
831
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700832 clear_cache_files(data_path, cache, freeStorageSize);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700833 finish_cache_collection(cache);
834
Jeff Sharkey423e7462016-12-09 18:18:43 -0700835 avail = data_disk_free(data_path);
836 if (avail >= freeStorageSize) {
837 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700838 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700839 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
840 freeStorageSize, data_path.c_str(), avail));
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700841 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700842}
843
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700844binder::Status InstalldNativeService::rmdex(const std::string& codePath,
845 const std::string& instructionSet) {
846 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700847 std::lock_guard<std::recursive_mutex> lock(mLock);
848
Mike Lockwood94afecf2012-10-24 10:45:23 -0700849 char dex_path[PKG_PATH_MAX];
850
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700851 const char* path = codePath.c_str();
852 const char* instruction_set = instructionSet.c_str();
853
Jeff Sharkey770180a2014-09-08 17:14:26 -0700854 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700855 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700856 }
857
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700858 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700859 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700860 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700861
862 ALOGV("unlink %s\n", dex_path);
863 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700864 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700865 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700866 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700867 }
868}
869
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700870struct stats {
871 int64_t codeSize;
872 int64_t dataSize;
873 int64_t cacheSize;
874};
875
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700876#if MEASURE_DEBUG
877static std::string toString(std::vector<int64_t> values) {
878 std::stringstream res;
879 res << "[";
880 for (size_t i = 0; i < values.size(); i++) {
881 res << values[i];
882 if (i < values.size() - 1) {
883 res << ",";
884 }
885 }
886 res << "]";
887 return res.str();
888}
889#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700890
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700891static std::string findDeviceForUuid(const std::unique_ptr<std::string>& uuid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700892 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700893 std::ifstream in("/proc/mounts");
894 if (!in.is_open()) {
895 PLOG(ERROR) << "Failed to read mounts";
896 return "";
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700897 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700898 std::string source;
899 std::string target;
900 while (!in.eof()) {
901 std::getline(in, source, ' ');
902 std::getline(in, target, ' ');
903 if (target == path) {
904 return source;
905 }
906 // Skip to next line
907 std::getline(in, source);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700908 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700909 PLOG(ERROR) << "Failed to resolve block device for " << path;
910 return "";
911}
912
913static void collectQuotaStats(const std::string& device, int32_t userId,
914 int32_t appId, struct stats* stats, struct stats* extStats ATTRIBUTE_UNUSED) {
915 if (device.empty()) return;
916
917 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700918
919 uid_t uid = multiuser_get_uid(userId, appId);
920 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
921 reinterpret_cast<char*>(&dq)) != 0) {
922 if (errno != ESRCH) {
923 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
924 }
925 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700926#if MEASURE_DEBUG
927 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
928#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700929 stats->dataSize += dq.dqb_curspace;
930 }
931
932 int cacheGid = multiuser_get_cache_gid(userId, appId);
933 if (cacheGid != -1) {
934 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
935 reinterpret_cast<char*>(&dq)) != 0) {
936 if (errno != ESRCH) {
937 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
938 }
939 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700940#if MEASURE_DEBUG
941 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
942#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700943 stats->cacheSize += dq.dqb_curspace;
944 }
945 }
946
947 int sharedGid = multiuser_get_shared_app_gid(uid);
948 if (sharedGid != -1) {
949 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
950 reinterpret_cast<char*>(&dq)) != 0) {
951 if (errno != ESRCH) {
952 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
953 }
954 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700955#if MEASURE_DEBUG
956 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
957#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700958 stats->codeSize += dq.dqb_curspace;
959 }
960 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700961
962#if MEASURE_EXTERNAL
963 // TODO: measure using external GIDs
964#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700965}
966
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700967static void collectQuotaStats(const std::unique_ptr<std::string>& uuid, int32_t userId,
968 int32_t appId, struct stats* stats, struct stats* extStats) {
969 collectQuotaStats(findDeviceForUuid(uuid), userId, appId, stats, extStats);
970}
971
972static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700973 DIR *d;
974 int dfd;
975 struct dirent *de;
976 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700977
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600978 d = opendir(path.c_str());
979 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700980 if (errno != ENOENT) {
981 PLOG(WARNING) << "Failed to open " << path;
982 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600983 return;
984 }
985 dfd = dirfd(d);
986 while ((de = readdir(d))) {
987 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700988
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700989 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600990 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700991 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600992 }
993
994 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700995 if (!strcmp(name, ".")) {
996 // Don't recurse, but still count node size
997 } else if (!strcmp(name, "..")) {
998 // Don't recurse or count node size
999 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001000 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001001 // Measure all children nodes
1002 size = 0;
1003 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001004 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001005
1006 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1007 stats->cacheSize += size;
1008 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001009 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001010
1011 // Legacy symlink isn't owned by app
1012 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1013 continue;
1014 }
1015
1016 // Everything found inside is considered data
1017 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001018 }
1019 closedir(d);
1020}
1021
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001022static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1023 bool exclude_apps = false) {
1024 DIR *d;
1025 int dfd;
1026 struct dirent *de;
1027 struct stat s;
1028
1029 d = opendir(path.c_str());
1030 if (d == nullptr) {
1031 if (errno != ENOENT) {
1032 PLOG(WARNING) << "Failed to open " << path;
1033 }
1034 return;
1035 }
1036 dfd = dirfd(d);
1037 while ((de = readdir(d))) {
1038 if (de->d_type == DT_DIR) {
1039 const char *name = de->d_name;
1040 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1041 continue;
1042 }
1043 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1044 continue;
1045 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1046 continue;
1047 } else {
1048 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1049 }
1050 }
1051 }
1052 closedir(d);
1053}
1054
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001055binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001056 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1057 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1058 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001059 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001060 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001061 for (auto packageName : packageNames) {
1062 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1063 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001064 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001065
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001066 // When modifying this logic, always verify using tests:
1067 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1068
1069#if MEASURE_DEBUG
1070 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1071#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001072
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001073 // Here's a summary of the common storage locations across the platform,
1074 // and how they're each tagged:
1075 //
1076 // /data/app/com.example UID system
1077 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001078 // /data/user/0/com.example UID u0_a10 GID u0_a10
1079 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1080 // /data/media/0/foo.txt UID u0_media_rw
1081 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1082 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1083 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1084 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001085
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001086 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001087 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001088 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001089 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001090
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001091 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001092
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001093 for (auto packageName : packageNames) {
1094 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1095 calculate_tree_size(obbCodePath, &extStats.codeSize);
1096 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001097
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001098 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
1099 for (auto codePath : codePaths) {
1100 calculate_tree_size(codePath, &stats.codeSize, -1,
1101 multiuser_get_shared_gid(userId, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001102 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001103
1104 collectQuotaStats(uuid, userId, appId, &stats, &extStats);
1105
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001106 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001107 for (auto codePath : codePaths) {
1108 calculate_tree_size(codePath, &stats.codeSize);
1109 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001110
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001111 for (size_t i = 0; i < packageNames.size(); i++) {
1112 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001113
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001114 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1115 collectManualStats(cePath, &stats);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001116
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001117 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1118 collectManualStats(dePath, &stats);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001119
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001120 auto userProfilePath = create_data_user_profile_package_path(userId, pkgname);
1121 calculate_tree_size(userProfilePath, &stats.dataSize);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001122
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001123 auto refProfilePath = create_data_ref_profile_package_path(pkgname);
1124 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001125
1126#if MEASURE_EXTERNAL
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001127 auto extPath = create_data_media_package_path(uuid_, userId, pkgname, "data");
1128 collectManualStats(extPath, &extStats);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001129
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001130 auto mediaPath = create_data_media_package_path(uuid_, userId, pkgname, "media");
1131 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001132#endif
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001133 }
1134
1135 int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1136 if (sharedGid != -1) {
1137 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1138 sharedGid, -1);
1139 }
1140
1141 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1142 multiuser_get_uid(userId, appId), -1);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001143 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001144
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001145 std::vector<int64_t> ret;
1146 ret.push_back(stats.codeSize);
1147 ret.push_back(stats.dataSize);
1148 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001149 ret.push_back(extStats.codeSize);
1150 ret.push_back(extStats.dataSize);
1151 ret.push_back(extStats.cacheSize);
1152#if MEASURE_DEBUG
1153 LOG(DEBUG) << "Final result " << toString(ret);
1154#endif
1155 *_aidl_return = ret;
1156 return ok();
1157}
1158
1159binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1160 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1161 std::vector<int64_t>* _aidl_return) {
1162 ENFORCE_UID(AID_SYSTEM);
1163 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001164 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001165
1166 // When modifying this logic, always verify using tests:
1167 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1168
1169#if MEASURE_DEBUG
1170 LOG(INFO) << "Measuring user " << userId;
1171#endif
1172
1173 struct stats stats;
1174 struct stats extStats;
1175 memset(&stats, 0, sizeof(stats));
1176 memset(&extStats, 0, sizeof(extStats));
1177
1178 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1179
1180 auto obbPath = create_data_path(uuid_) + "/media/obb";
1181 calculate_tree_size(obbPath, &extStats.codeSize);
1182
1183 if (flags & FLAG_USE_QUOTA) {
1184 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
1185
1186 auto cePath = create_data_user_ce_path(uuid_, userId);
1187 collectManualStatsForUser(cePath, &stats, true);
1188
1189 auto dePath = create_data_user_de_path(uuid_, userId);
1190 collectManualStatsForUser(dePath, &stats, true);
1191
1192 auto userProfilePath = create_data_user_profile_path(userId);
1193 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1194
1195 auto refProfilePath = create_data_ref_profile_path();
1196 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1197
1198#if MEASURE_EXTERNAL
1199 // TODO: measure external storage paths
1200#endif
1201
1202 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1203 -1, -1, true);
1204
1205 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1206 -1, -1, true);
1207
1208 auto device = findDeviceForUuid(uuid);
1209 for (auto appId : appIds) {
1210 if (appId >= AID_APP_START) {
1211 collectQuotaStats(device, userId, appId, &stats, &extStats);
1212#if MEASURE_DEBUG
1213 // Sleep to make sure we don't lose logs
1214 usleep(1);
1215#endif
1216 }
1217 }
1218 } else {
1219 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
1220
1221 auto cePath = create_data_user_ce_path(uuid_, userId);
1222 collectManualStatsForUser(cePath, &stats);
1223
1224 auto dePath = create_data_user_de_path(uuid_, userId);
1225 collectManualStatsForUser(dePath, &stats);
1226
1227 auto userProfilePath = create_data_user_profile_path(userId);
1228 calculate_tree_size(userProfilePath, &stats.dataSize);
1229
1230 auto refProfilePath = create_data_ref_profile_path();
1231 calculate_tree_size(refProfilePath, &stats.codeSize);
1232
1233#if MEASURE_EXTERNAL
1234 // TODO: measure external storage paths
1235#endif
1236
1237 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1238
1239 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize);
1240 }
1241
1242 std::vector<int64_t> ret;
1243 ret.push_back(stats.codeSize);
1244 ret.push_back(stats.dataSize);
1245 ret.push_back(stats.cacheSize);
1246 ret.push_back(extStats.codeSize);
1247 ret.push_back(extStats.dataSize);
1248 ret.push_back(extStats.cacheSize);
1249#if MEASURE_DEBUG
1250 LOG(DEBUG) << "Final result " << toString(ret);
1251#endif
1252 *_aidl_return = ret;
1253 return ok();
1254}
1255
1256binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1257 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1258 ENFORCE_UID(AID_SYSTEM);
1259 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001260 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001261
1262 // When modifying this logic, always verify using tests:
1263 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1264
1265#if MEASURE_DEBUG
1266 LOG(INFO) << "Measuring external " << userId;
1267#endif
1268
1269 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1270
1271 int64_t totalSize = 0;
1272 int64_t audioSize = 0;
1273 int64_t videoSize = 0;
1274 int64_t imageSize = 0;
1275
1276 if (flags & FLAG_USE_QUOTA) {
1277 struct dqblk dq;
1278
1279 auto device = findDeviceForUuid(uuid);
1280
1281 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1282 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1283 reinterpret_cast<char*>(&dq)) != 0) {
1284 if (errno != ESRCH) {
1285 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1286 }
1287 } else {
1288#if MEASURE_DEBUG
1289 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1290#endif
1291 totalSize = dq.dqb_curspace;
1292 }
1293
1294 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1295 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1296 reinterpret_cast<char*>(&dq)) == 0) {
1297#if MEASURE_DEBUG
1298 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1299#endif
1300 audioSize = dq.dqb_curspace;
1301 }
1302 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1303 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1304 reinterpret_cast<char*>(&dq)) == 0) {
1305#if MEASURE_DEBUG
1306 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1307#endif
1308 videoSize = dq.dqb_curspace;
1309 }
1310 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1311 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1312 reinterpret_cast<char*>(&dq)) == 0) {
1313#if MEASURE_DEBUG
1314 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1315#endif
1316 imageSize = dq.dqb_curspace;
1317 }
1318 } else {
1319 FTS *fts;
1320 FTSENT *p;
1321 auto path = create_data_media_path(uuid_, userId);
1322 char *argv[] = { (char*) path.c_str(), nullptr };
1323 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1324 return error("Failed to fts_open " + path);
1325 }
1326 while ((p = fts_read(fts)) != NULL) {
1327 char* ext;
1328 int64_t size = (p->fts_statp->st_blocks * 512);
1329 switch (p->fts_info) {
1330 case FTS_F:
1331 // Only categorize files not belonging to apps
1332 if (p->fts_statp->st_gid < AID_APP_START) {
1333 ext = strrchr(p->fts_name, '.');
1334 if (ext != nullptr) {
1335 switch (MatchExtension(++ext)) {
1336 case AID_MEDIA_AUDIO: audioSize += size; break;
1337 case AID_MEDIA_VIDEO: videoSize += size; break;
1338 case AID_MEDIA_IMAGE: imageSize += size; break;
1339 }
1340 }
1341 }
1342 // Fall through to always count against total
1343 case FTS_D:
1344 case FTS_DEFAULT:
1345 case FTS_SL:
1346 case FTS_SLNONE:
1347 totalSize += size;
1348 break;
1349 }
1350 }
1351 fts_close(fts);
1352 }
1353
1354 std::vector<int64_t> ret;
1355 ret.push_back(totalSize);
1356 ret.push_back(audioSize);
1357 ret.push_back(videoSize);
1358 ret.push_back(imageSize);
1359#if MEASURE_DEBUG
1360 LOG(DEBUG) << "Final result " << toString(ret);
1361#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001362 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001363 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001364}
1365
David Sehr6727c2d2016-05-17 16:06:22 -07001366// Dumps the contents of a profile file, using pkgname's dex files for pretty
1367// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001368binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1369 const std::string& codePaths, bool* _aidl_return) {
1370 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001371 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001372 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001373
1374 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001375 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001376
Jeff Sharkey90aff262016-12-12 14:28:24 -07001377 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001378 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001379}
1380
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001381// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001382binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001383 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001384 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001385 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001386 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001387
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001388 const char* pkgname = packageName.c_str();
1389 *_aidl_return = analyse_profiles(uid, pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001390 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001391}
1392
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001393binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1394 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1395 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1396 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1397 const std::unique_ptr<std::string>& sharedLibraries) {
1398 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001399 CHECK_ARGUMENT_UUID(uuid);
1400 if (packageName && *packageName != "*") {
1401 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1402 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001403 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001404
1405 const char* apk_path = apkPath.c_str();
1406 const char* pkgname = packageName ? packageName->c_str() : "*";
1407 const char* instruction_set = instructionSet.c_str();
1408 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1409 const char* compiler_filter = compilerFilter.c_str();
1410 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1411 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1412
1413 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1414 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001415 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001416}
1417
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001418binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1419 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001420 std::lock_guard<std::recursive_mutex> lock(mLock);
1421
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001422 const char* instruction_set = instructionSet.c_str();
1423
1424 char boot_marker_path[PKG_PATH_MAX];
1425 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001426 "%s/%s/%s/.booting",
1427 android_data_dir.path,
1428 DALVIK_CACHE,
1429 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001430
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001431 ALOGV("mark_boot_complete : %s", boot_marker_path);
1432 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001433 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001434 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001435 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001436}
1437
Mike Lockwood94afecf2012-10-24 10:45:23 -07001438void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1439 struct stat* statbuf)
1440{
1441 while (path[basepos] != 0) {
1442 if (path[basepos] == '/') {
1443 path[basepos] = 0;
1444 if (lstat(path, statbuf) < 0) {
1445 ALOGV("Making directory: %s\n", path);
1446 if (mkdir(path, mode) == 0) {
1447 chown(path, uid, gid);
1448 } else {
1449 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1450 }
1451 }
1452 path[basepos] = '/';
1453 basepos++;
1454 }
1455 basepos++;
1456 }
1457}
1458
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001459binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1460 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1461 const std::string& nativeLibPath32, int32_t userId) {
1462 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001463 CHECK_ARGUMENT_UUID(uuid);
1464 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001465 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001466
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001467 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1468 const char* pkgname = packageName.c_str();
1469 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001470 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001471 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001472
Jeff Sharkey423e7462016-12-09 18:18:43 -07001473 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1474 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001475
1476 const char* pkgdir = _pkgdir.c_str();
1477 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001478
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001479 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001480 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001481 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001482
1483 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001484 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001485 }
1486
1487 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001488 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001489 goto out;
1490 }
1491
1492 if (lstat(libsymlink, &libStat) < 0) {
1493 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001494 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001495 goto out;
1496 }
1497 } else {
1498 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001499 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001500 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001501 goto out;
1502 }
1503 } else if (S_ISLNK(libStat.st_mode)) {
1504 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001505 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001506 goto out;
1507 }
1508 }
1509 }
1510
1511 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001512 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001513 goto out;
1514 }
1515
1516out:
1517 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001518 auto msg = "Failed to cleanup chmod " + _pkgdir;
1519 if (res.isOk()) {
1520 res = error(msg);
1521 } else {
1522 PLOG(ERROR) << msg;
1523 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001524 }
1525
1526 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001527 auto msg = "Failed to cleanup chown " + _pkgdir;
1528 if (res.isOk()) {
1529 res = error(msg);
1530 } else {
1531 PLOG(ERROR) << msg;
1532 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001533 }
1534
Jeff Sharkey423e7462016-12-09 18:18:43 -07001535 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001536}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001537
1538static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1539{
1540 static const char *IDMAP_BIN = "/system/bin/idmap";
1541 static const size_t MAX_INT_LEN = 32;
1542 char idmap_str[MAX_INT_LEN];
1543
1544 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1545
1546 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1547 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1548}
1549
1550// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1551// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1552static int flatten_path(const char *prefix, const char *suffix,
1553 const char *overlay_path, char *idmap_path, size_t N)
1554{
1555 if (overlay_path == NULL || idmap_path == NULL) {
1556 return -1;
1557 }
1558 const size_t len_overlay_path = strlen(overlay_path);
1559 // will access overlay_path + 1 further below; requires absolute path
1560 if (len_overlay_path < 2 || *overlay_path != '/') {
1561 return -1;
1562 }
1563 const size_t len_idmap_root = strlen(prefix);
1564 const size_t len_suffix = strlen(suffix);
1565 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1566 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1567 // additions below would cause overflow
1568 return -1;
1569 }
1570 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1571 return -1;
1572 }
1573 memset(idmap_path, 0, N);
1574 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1575 char *ch = idmap_path + len_idmap_root;
1576 while (*ch != '\0') {
1577 if (*ch == '/') {
1578 *ch = '@';
1579 }
1580 ++ch;
1581 }
1582 return 0;
1583}
1584
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001585binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1586 const std::string& overlayApkPath, int32_t uid) {
1587 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001588 std::lock_guard<std::recursive_mutex> lock(mLock);
1589
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001590 const char* target_apk = targetApkPath.c_str();
1591 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001592 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1593
1594 int idmap_fd = -1;
1595 char idmap_path[PATH_MAX];
1596
1597 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1598 idmap_path, sizeof(idmap_path)) == -1) {
1599 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1600 goto fail;
1601 }
1602
1603 unlink(idmap_path);
1604 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1605 if (idmap_fd < 0) {
1606 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1607 goto fail;
1608 }
1609 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1610 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1611 goto fail;
1612 }
1613 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1614 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1615 goto fail;
1616 }
1617
1618 pid_t pid;
1619 pid = fork();
1620 if (pid == 0) {
1621 /* child -- drop privileges before continuing */
1622 if (setgid(uid) != 0) {
1623 ALOGE("setgid(%d) failed during idmap\n", uid);
1624 exit(1);
1625 }
1626 if (setuid(uid) != 0) {
1627 ALOGE("setuid(%d) failed during idmap\n", uid);
1628 exit(1);
1629 }
1630 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1631 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1632 exit(1);
1633 }
1634
1635 run_idmap(target_apk, overlay_apk, idmap_fd);
1636 exit(1); /* only if exec call to idmap failed */
1637 } else {
1638 int status = wait_child(pid);
1639 if (status != 0) {
1640 ALOGE("idmap failed, status=0x%04x\n", status);
1641 goto fail;
1642 }
1643 }
1644
1645 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001646 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001647fail:
1648 if (idmap_fd >= 0) {
1649 close(idmap_fd);
1650 unlink(idmap_path);
1651 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001652 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001653}
Robert Craige9887e42014-02-20 10:25:56 -05001654
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001655binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1656 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1657 const std::string& seInfo) {
1658 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001659 CHECK_ARGUMENT_UUID(uuid);
1660 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001661 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001662
1663 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05001664
Robert Craigda30dc72014-03-27 10:21:12 -04001665 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001666 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001667 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1668 const char* pkgName = packageName.c_str();
1669 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04001670
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001671 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001672 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001673 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001674 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001675 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001676 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001677 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001678 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001679 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001680 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001681 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001682 }
Robert Craige9887e42014-02-20 10:25:56 -05001683 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001684 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001685}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001686
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001687binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1688 const std::string& instructionSet) {
1689 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001690 std::lock_guard<std::recursive_mutex> lock(mLock);
1691
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001692 const char* oat_dir = oatDir.c_str();
1693 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001694 char oat_instr_dir[PKG_PATH_MAX];
1695
1696 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001697 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001698 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001699 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001700 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001701 }
1702 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001703 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001704 }
1705 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001706 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001707 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001708 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001709 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001710}
1711
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001712binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1713 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001714 std::lock_guard<std::recursive_mutex> lock(mLock);
1715
Jeff Sharkey423e7462016-12-09 18:18:43 -07001716 if (validate_apk_path(packageDir.c_str())) {
1717 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001718 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001719 if (delete_dir_contents_and_dir(packageDir) != 0) {
1720 return error("Failed to delete " + packageDir);
1721 }
1722 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001723}
1724
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001725binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1726 const std::string& fromBase, const std::string& toBase) {
1727 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001728 std::lock_guard<std::recursive_mutex> lock(mLock);
1729
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001730 const char* relative_path = relativePath.c_str();
1731 const char* from_base = fromBase.c_str();
1732 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01001733 char from_path[PKG_PATH_MAX];
1734 char to_path[PKG_PATH_MAX];
1735 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1736 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1737
1738 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001739 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001740 }
1741
1742 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001743 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001744 }
1745
Jeff Sharkey423e7462016-12-09 18:18:43 -07001746 if (link(from_path, to_path) < 0) {
1747 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001748 }
1749
Jeff Sharkey423e7462016-12-09 18:18:43 -07001750 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01001751}
1752
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001753binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1754 const std::string& instructionSet, const std::string& outputPath) {
1755 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001756 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001757
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001758 const char* apk_path = apkPath.c_str();
1759 const char* instruction_set = instructionSet.c_str();
1760 const char* oat_dir = outputPath.c_str();
Andreas Gamped089ca12016-06-27 14:25:30 -07001761
Jeff Sharkey90aff262016-12-12 14:28:24 -07001762 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001763 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08001764}
1765
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001766binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
1767 const std::string& instructionSet, const std::string& outputPath) {
1768 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001769 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001770
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001771 const char* apk_path = apkPath.c_str();
1772 const char* instruction_set = instructionSet.c_str();
1773 const char* oat_dir = outputPath.c_str();
1774
Jeff Sharkey90aff262016-12-12 14:28:24 -07001775 bool res = delete_odex(apk_path, instruction_set, oat_dir);
1776 return res ? ok() : error();
Andreas Gampeb31206b2016-09-09 17:07:04 -07001777}
1778
Andreas Gampe02d0de52015-11-11 20:43:16 -08001779} // namespace installd
1780} // namespace android