blob: daa744f8592d75da14daa5167567df457cea0faa [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
Jeff Sharkey466459b2017-01-17 15:25:01 -070019#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
20
Andreas Gampe02d0de52015-11-11 20:43:16 -080021#include <errno.h>
22#include <inttypes.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070023#include <fstream>
24#include <fts.h>
Andreas Gampe0354bd02016-06-27 14:25:30 -070025#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070027#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028#include <sys/capability.h>
29#include <sys/file.h>
30#include <sys/resource.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070031#include <sys/quota.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080032#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070033#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070034#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000035#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070036#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080037#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070038
Andreas Gampeafa58d12016-06-03 16:09:32 -070039#include <android-base/logging.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080040#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070041#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010042#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080043#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070044#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070045#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070046#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070047#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080048#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070049#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080050#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070051#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070052
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070053#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070054#include "globals.h"
55#include "installd_deps.h"
56#include "otapreopt_utils.h"
57#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070058
Jeff Sharkey88ddd942017-01-17 18:05:54 -070059#include "CacheTracker.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070060#include "MatchExtensionGen.h"
61
Andreas Gampe02d0de52015-11-11 20:43:16 -080062#ifndef LOG_TAG
63#define LOG_TAG "installd"
64#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070065
66using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070067using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070068
Andreas Gampe02d0de52015-11-11 20:43:16 -080069namespace android {
70namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070071
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070072static constexpr const char* kCpPath = "/system/bin/cp";
73static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070074
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070075static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000076
Andreas Gampe0354bd02016-06-27 14:25:30 -070077static constexpr const char* PKG_LIB_POSTFIX = "/lib";
78static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
79static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
80
Jaekyun Seok5cb903e2017-05-18 00:13:44 +090081static constexpr const char *kIdMapPath = "/system/bin/idmap";
Andreas Gampe0354bd02016-06-27 14:25:30 -070082static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
83static constexpr const char* IDMAP_SUFFIX = "@idmap";
84
Andreas Gampe0354bd02016-06-27 14:25:30 -070085// NOTE: keep in sync with Installer
86static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
87static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070088static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -070089static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
Jeff Sharkey871a8f22017-02-21 18:30:28 -070090static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
91static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
Jeff Sharkeye12d5962017-04-03 16:41:02 -060092static constexpr int FLAG_FORCE = 1 << 16;
Calin Juravle6a1648e2016-02-01 12:12:16 +000093
Jeff Sharkey0274c972016-12-06 09:32:04 -070094namespace {
95
96constexpr const char* kDump = "android.permission.DUMP";
97
Jeff Sharkey423e7462016-12-09 18:18:43 -070098static binder::Status ok() {
99 return binder::Status::ok();
100}
101
102static binder::Status exception(uint32_t code, const std::string& msg) {
103 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
104}
105
106static binder::Status error() {
107 return binder::Status::fromServiceSpecificError(errno);
108}
109
110static binder::Status error(const std::string& msg) {
111 PLOG(ERROR) << msg;
112 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
113}
114
115static binder::Status error(uint32_t code, const std::string& msg) {
116 LOG(ERROR) << msg << " (" << code << ")";
117 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
118}
119
Jeff Sharkey0274c972016-12-06 09:32:04 -0700120binder::Status checkPermission(const char* permission) {
121 pid_t pid;
122 uid_t uid;
123
124 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
125 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700126 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700127 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700128 return exception(binder::Status::EX_SECURITY,
129 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700130 }
131}
132
133binder::Status checkUid(uid_t expectedUid) {
134 uid_t uid = IPCThreadState::self()->getCallingUid();
135 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700136 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700137 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700138 return exception(binder::Status::EX_SECURITY,
139 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
140 }
141}
142
143binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
144 if (!uuid || is_valid_filename(*uuid)) {
145 return ok();
146 } else {
147 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
148 StringPrintf("UUID %s is malformed", uuid->c_str()));
149 }
150}
151
152binder::Status checkArgumentPackageName(const std::string& packageName) {
153 if (is_valid_package_name(packageName.c_str())) {
154 return ok();
155 } else {
156 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
157 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700158 }
159}
160
161#define ENFORCE_UID(uid) { \
162 binder::Status status = checkUid((uid)); \
163 if (!status.isOk()) { \
164 return status; \
165 } \
166}
167
Jeff Sharkey423e7462016-12-09 18:18:43 -0700168#define CHECK_ARGUMENT_UUID(uuid) { \
169 binder::Status status = checkArgumentUuid((uuid)); \
170 if (!status.isOk()) { \
171 return status; \
172 } \
173}
174
175#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
176 binder::Status status = \
177 checkArgumentPackageName((packageName)); \
178 if (!status.isOk()) { \
179 return status; \
180 } \
181}
182
Jeff Sharkey0274c972016-12-06 09:32:04 -0700183} // namespace
184
185status_t InstalldNativeService::start() {
186 IPCThreadState::self()->disableBackgroundScheduling(true);
187 status_t ret = BinderService<InstalldNativeService>::publish();
188 if (ret != android::OK) {
189 return ret;
190 }
191 sp<ProcessState> ps(ProcessState::self());
192 ps->startThreadPool();
193 ps->giveThreadPoolName();
194 return android::OK;
195}
196
197status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700198 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700199 const binder::Status dump_permission = checkPermission(kDump);
200 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700201 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700202 return PERMISSION_DENIED;
203 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700204 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700205
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700206 out << "installd is happy!" << endl;
207
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700208 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600209 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
210 out << endl << "Storage mounts:" << endl;
211 for (const auto& n : mStorageMounts) {
212 out << " " << n.first << " = " << n.second << endl;
213 }
214
215 out << endl << "Quota reverse mounts:" << endl;
216 for (const auto& n : mQuotaReverseMounts) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700217 out << " " << n.first << " = " << n.second << endl;
218 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700219 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700220
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700221 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600222 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700223 out << endl << "Per-UID cache quotas:" << endl;
224 for (const auto& n : mCacheQuotas) {
225 out << " " << n.first << " = " << n.second << endl;
226 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700227 }
228
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700229 out << endl;
230 out.flush();
231
Jeff Sharkey0274c972016-12-06 09:32:04 -0700232 return NO_ERROR;
233}
234
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600235/**
236 * Perform restorecon of the given path, but only perform recursive restorecon
237 * if the label of that top-level file actually changed. This can save us
238 * significant time by avoiding no-op traversals of large filesystem trees.
239 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700240static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
241 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600242 int res = 0;
243 char* before = nullptr;
244 char* after = nullptr;
245
246 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
247 // libselinux. Not needed here.
248
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600249 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600250 PLOG(ERROR) << "Failed before getfilecon for " << path;
251 goto fail;
252 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700253 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600254 PLOG(ERROR) << "Failed top-level restorecon for " << path;
255 goto fail;
256 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600257 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600258 PLOG(ERROR) << "Failed after getfilecon for " << path;
259 goto fail;
260 }
261
262 // If the initial top-level restorecon above changed the label, then go
263 // back and restorecon everything recursively
264 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700265 if (existing) {
266 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
267 << path << "; running recursive restorecon";
268 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700269 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600270 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
271 PLOG(ERROR) << "Failed recursive restorecon for " << path;
272 goto fail;
273 }
274 }
275
276 goto done;
277fail:
278 res = -1;
279done:
280 free(before);
281 free(after);
282 return res;
283}
284
Jeff Sharkey0274c972016-12-06 09:32:04 -0700285static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700286 const std::string& seInfo, uid_t uid, bool existing) {
287 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
288 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600289}
290
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600291static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600292 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
293 PLOG(ERROR) << "Failed to prepare " << path;
294 return -1;
295 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600296 return 0;
297}
298
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600299/**
300 * Ensure that we have a hard-limit quota to protect against abusive apps;
301 * they should never use more than 90% of blocks or 50% of inodes.
302 */
303static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
304 uid_t uid) {
305 if (device.empty()) return 0;
306
307 struct dqblk dq;
308 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
309 reinterpret_cast<char*>(&dq)) != 0) {
310 PLOG(WARNING) << "Failed to find quota for " << uid;
311 return -1;
312 }
313
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600314#if APPLY_HARD_QUOTAS
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600315 if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
316 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
317 struct statvfs stat;
318 if (statvfs(path.c_str(), &stat) != 0) {
319 PLOG(WARNING) << "Failed to statvfs " << path;
320 return -1;
321 }
322
323 dq.dqb_valid = QIF_LIMITS;
Jerry Wonge761ac32017-07-28 15:54:58 -0700324 dq.dqb_bhardlimit =
325 (((static_cast<uint64_t>(stat.f_blocks) * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600326 dq.dqb_ihardlimit = (stat.f_files / 2);
327 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
328 reinterpret_cast<char*>(&dq)) != 0) {
329 PLOG(WARNING) << "Failed to set hard quota for " << uid;
330 return -1;
331 } else {
332 LOG(DEBUG) << "Applied hard quotas for " << uid;
333 return 0;
334 }
335 } else {
336 // Hard quota already set; assume it's reasonable
337 return 0;
338 }
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600339#else
340 // Hard quotas disabled
341 return 0;
342#endif
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600343}
344
Calin Juravled2affb82017-11-28 17:41:43 -0800345static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
346 if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
347 return true;
348 }
349
350 int32_t uid = multiuser_get_uid(userId, appId);
351 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
352 if (shared_app_gid == -1) {
353 // TODO(calin): this should no longer be possible but do not continue if we don't get
354 // a valid shared gid.
355 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
356 return true;
357 }
358
359 const std::string profile_dir =
360 create_primary_current_profile_package_dir_path(userId, packageName);
361 // read-write-execute only for the app user.
362 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
363 PLOG(ERROR) << "Failed to prepare " << profile_dir;
364 return false;
365 }
366 const std::string profile_file = create_current_profile_path(userId, packageName,
367 /*is_secondary_dex*/false);
368 // read-write only for the app user.
369 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
370 PLOG(ERROR) << "Failed to prepare " << profile_file;
371 return false;
372 }
373
374 const std::string ref_profile_path =
375 create_primary_reference_profile_package_dir_path(packageName);
376 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
377 // profiles.
378 if (fs_prepare_dir_strict(
379 ref_profile_path.c_str(), 0701, shared_app_gid, shared_app_gid) != 0) {
380 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
381 return false;
382 }
383 return true;
384}
385
Jeff Sharkey0274c972016-12-06 09:32:04 -0700386binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
387 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700388 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700389 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700390 CHECK_ARGUMENT_UUID(uuid);
391 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700392 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700393
394 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
395 const char* pkgname = packageName.c_str();
396
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700397 // Assume invalid inode unless filled in below
398 if (_aidl_return != nullptr) *_aidl_return = -1;
399
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700400 int32_t uid = multiuser_get_uid(userId, appId);
401 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700402 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
403
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700404 // If UID doesn't have a specific cache GID, use UID value
405 if (cacheGid == -1) {
406 cacheGid = uid;
407 }
408
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700409 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700410 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700411 bool existing = (access(path.c_str(), F_OK) == 0);
412
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700413 if (prepare_app_dir(path, targetMode, uid) ||
414 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
415 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700416 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600417 }
418
419 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700420 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
421 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
422 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700423 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700424 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600425
426 // Remember inode numbers of cache directories so that we can clear
427 // contents while CE storage is locked
428 if (write_path_inode(path, "cache", kXattrInodeCache) ||
429 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700430 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700431 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700432
433 // And return the CE inode of the top-level data directory so we can
434 // clear contents while CE storage is locked
435 if ((_aidl_return != nullptr)
436 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
437 return error("Failed to get_path_inode for " + path);
438 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700439 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700440 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700441 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700442 bool existing = (access(path.c_str(), F_OK) == 0);
443
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700444 if (prepare_app_dir(path, targetMode, uid) ||
445 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
446 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700447 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700448 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000449
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600450 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600451 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
452 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
453 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700454 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600455 }
456
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600457 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
458 return error("Failed to set hard quota " + path);
459 }
460
Calin Juravled2affb82017-11-28 17:41:43 -0800461 if (!prepare_app_profile_dir(packageName, appId, userId)) {
462 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000463 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700464 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700465 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700466}
467
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700468binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
469 const std::string& packageName, int32_t userId, int32_t flags) {
470 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700471 CHECK_ARGUMENT_UUID(uuid);
472 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700473 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700474
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700475 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
476 const char* pkgname = packageName.c_str();
477
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700478 // This method only exists to upgrade system apps that have requested
479 // forceDeviceEncrypted, so their default storage always lives in a
480 // consistent location. This only works on non-FBE devices, since we
481 // never want to risk exposing data on a device with real CE/DE storage.
482
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700483 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
484 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700485
486 // If neither directory is marked as default, assume CE is default
487 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
488 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
489 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700490 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700491 }
492 }
493
494 // Migrate default data location if needed
495 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
496 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
497
498 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
499 LOG(WARNING) << "Requested default storage " << target
500 << " is not active; migrating from " << source;
501 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700502 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700503 }
504 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700505 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700506 }
507 }
508
Jeff Sharkey423e7462016-12-09 18:18:43 -0700509 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700510}
511
Calin Juravle6a1648e2016-02-01 12:12:16 +0000512
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700513binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
514 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700515 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700516 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700517
Jeff Sharkey423e7462016-12-09 18:18:43 -0700518 binder::Status res = ok();
Calin Juravle114f0812017-03-08 19:05:07 -0800519 if (!clear_primary_reference_profile(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700520 res = error("Failed to clear reference profile for " + packageName);
521 }
Calin Juravle114f0812017-03-08 19:05:07 -0800522 if (!clear_primary_current_profiles(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700523 res = error("Failed to clear current profiles for " + packageName);
524 }
525 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000526}
527
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700528binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
529 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
530 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700531 CHECK_ARGUMENT_UUID(uuid);
532 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700533 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700534
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700535 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
536 const char* pkgname = packageName.c_str();
537
Jeff Sharkey423e7462016-12-09 18:18:43 -0700538 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700539 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700540 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600541 if (flags & FLAG_CLEAR_CACHE_ONLY) {
542 path = read_path_inode(path, "cache", kXattrInodeCache);
543 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
544 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
545 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700546 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 if (delete_dir_contents(path) != 0) {
548 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900549 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
550 remove_path_xattr(path, kXattrInodeCache);
551 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700552 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700553 }
554 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700555 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600556 std::string suffix = "";
557 bool only_cache = false;
558 if (flags & FLAG_CLEAR_CACHE_ONLY) {
559 suffix = CACHE_DIR_POSTFIX;
560 only_cache = true;
561 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
562 suffix = CODE_CACHE_DIR_POSTFIX;
563 only_cache = true;
564 }
565
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700566 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700567 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700568 if (delete_dir_contents(path) != 0) {
569 res = error("Failed to delete contents of " + path);
570 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700571 }
Calin Juravleedae6692016-03-23 13:55:31 +0000572 if (!only_cache) {
Calin Juravle114f0812017-03-08 19:05:07 -0800573 if (!clear_primary_current_profile(packageName, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700574 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000575 }
576 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700577 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700578 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700579}
580
Calin Juravle76268c52017-03-09 13:19:42 -0800581static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100582 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800583 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100584 /*ignore_if_missing*/ true);
585}
586
Calin Juravle76268c52017-03-09 13:19:42 -0800587static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100588 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800589 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100590 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000591}
592
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700593binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
594 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700595 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700596 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700597
Jeff Sharkey423e7462016-12-09 18:18:43 -0700598 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000599 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
600 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800601 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700602 res = error("Failed to destroy current profiles for " + packageName);
603 }
Calin Juravleedae6692016-03-23 13:55:31 +0000604 }
Calin Juravle76268c52017-03-09 13:19:42 -0800605 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700606 res = error("Failed to destroy reference profile for " + packageName);
607 }
608 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000609}
610
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700611binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
612 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
613 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700614 CHECK_ARGUMENT_UUID(uuid);
615 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700616 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700617
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700618 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
619 const char* pkgname = packageName.c_str();
620
Jeff Sharkey423e7462016-12-09 18:18:43 -0700621 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700622 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700623 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
624 if (delete_dir_contents_and_dir(path) != 0) {
625 res = error("Failed to delete " + path);
626 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700627 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700628 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700629 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
630 if (delete_dir_contents_and_dir(path) != 0) {
631 res = error("Failed to delete " + path);
632 }
Calin Juravle76268c52017-03-09 13:19:42 -0800633 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100634 // TODO(calin): If the package is still installed by other users it's probably
635 // beneficial to keep the reference profile around.
636 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800637 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700638 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700639 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700640}
641
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600642static gid_t get_cache_gid(uid_t uid) {
643 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
644 return (gid != -1) ? gid : uid;
645}
646
647binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
648 int32_t flags) {
649 ENFORCE_UID(AID_SYSTEM);
650 CHECK_ARGUMENT_UUID(uuid);
651 std::lock_guard<std::recursive_mutex> lock(mLock);
652
653 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
654 for (auto user : get_known_users(uuid_)) {
655 ATRACE_BEGIN("fixup user");
656 FTS* fts;
657 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600658 auto ce_path = create_data_user_ce_path(uuid_, user);
659 auto de_path = create_data_user_de_path(uuid_, user);
660 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600661 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
662 return error("Failed to fts_open");
663 }
664 while ((p = fts_read(fts)) != nullptr) {
665 if (p->fts_info == FTS_D && p->fts_level == 1) {
666 // Track down inodes of cache directories
667 uint64_t raw = 0;
668 ino_t inode_cache = 0;
669 ino_t inode_code_cache = 0;
670 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
671 inode_cache = raw;
672 }
673 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
674 inode_code_cache = raw;
675 }
676
677 // Figure out expected GID of each child
678 FTSENT* child = fts_children(fts, 0);
679 while (child != nullptr) {
680 if ((child->fts_statp->st_ino == inode_cache)
681 || (child->fts_statp->st_ino == inode_code_cache)
682 || !strcmp(child->fts_name, "cache")
683 || !strcmp(child->fts_name, "code_cache")) {
684 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
685 } else {
686 child->fts_number = p->fts_statp->st_uid;
687 }
688 child = child->fts_link;
689 }
690 } else if (p->fts_level >= 2) {
691 if (p->fts_level > 2) {
692 // Inherit GID from parent once we're deeper into tree
693 p->fts_number = p->fts_parent->fts_number;
694 }
695
696 uid_t uid = p->fts_parent->fts_statp->st_uid;
697 gid_t cache_gid = get_cache_gid(uid);
698 gid_t expected = p->fts_number;
699 gid_t actual = p->fts_statp->st_gid;
700 if (actual == expected) {
701#if FIXUP_DEBUG
702 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
703#endif
704 if (!(flags & FLAG_FORCE)) {
705 fts_set(fts, p, FTS_SKIP);
706 }
707 } else if ((actual == uid) || (actual == cache_gid)) {
708 // Only consider fixing up when current GID belongs to app
709 if (p->fts_info != FTS_D) {
710 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
711 << " instead of " << expected;
712 }
713 switch (p->fts_info) {
714 case FTS_DP:
715 // If we're moving towards cache GID, we need to set S_ISGID
716 if (expected == cache_gid) {
717 if (chmod(p->fts_path, 02771) != 0) {
718 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
719 }
720 }
721 // Intentional fall through to also set GID
722 case FTS_F:
723 if (chown(p->fts_path, -1, expected) != 0) {
724 PLOG(WARNING) << "Failed to chown " << p->fts_path;
725 }
726 break;
727 case FTS_SL:
728 case FTS_SLNONE:
729 if (lchown(p->fts_path, -1, expected) != 0) {
730 PLOG(WARNING) << "Failed to chown " << p->fts_path;
731 }
732 break;
733 }
734 } else {
735 // Ignore all other GID transitions, since they're kinda shady
736 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
737 << " instead of " << expected;
Jeff Sharkeye2cff6a2017-09-21 15:41:37 -0600738 if (!(flags & FLAG_FORCE)) {
739 fts_set(fts, p, FTS_SKIP);
740 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600741 }
742 }
743 }
744 fts_close(fts);
745 ATRACE_END();
746 }
747 return ok();
748}
749
Jeff Sharkey0274c972016-12-06 09:32:04 -0700750binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
751 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
752 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
753 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700754 ENFORCE_UID(AID_SYSTEM);
755 CHECK_ARGUMENT_UUID(fromUuid);
756 CHECK_ARGUMENT_UUID(toUuid);
757 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700758 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700759
760 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
761 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
762 const char* package_name = packageName.c_str();
763 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700764
Jeff Sharkey423e7462016-12-09 18:18:43 -0700765 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700766 std::vector<userid_t> users = get_known_users(from_uuid);
767
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700768 // Copy app
769 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600770 auto from = create_data_app_package_path(from_uuid, data_app_name);
771 auto to = create_data_app_package_path(to_uuid, data_app_name);
772 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700773
774 char *argv[] = {
775 (char*) kCpPath,
776 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
777 (char*) "-p", /* preserve timestamps, ownership, and permissions */
778 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
779 (char*) "-P", /* Do not follow symlinks [default] */
780 (char*) "-d", /* don't dereference symlinks */
781 (char*) from.c_str(),
782 (char*) to_parent.c_str()
783 };
784
785 LOG(DEBUG) << "Copying " << from << " to " << to;
786 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700787 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700788 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700789 goto fail;
790 }
791
792 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700793 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700794 goto fail;
795 }
796 }
797
798 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700799 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700800
801 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600802 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
803 if (access(from_ce.c_str(), F_OK) != 0) {
804 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700805 continue;
806 }
807
Jeff Sharkey0274c972016-12-06 09:32:04 -0700808 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700809 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700810 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700811 goto fail;
812 }
813
814 char *argv[] = {
815 (char*) kCpPath,
816 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
817 (char*) "-p", /* preserve timestamps, ownership, and permissions */
818 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
819 (char*) "-P", /* Do not follow symlinks [default] */
820 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600821 nullptr,
822 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700823 };
824
Jeff Sharkey51c94492016-05-10 17:46:39 -0600825 {
826 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
827 auto to = create_data_user_de_path(to_uuid, user);
828 argv[6] = (char*) from.c_str();
829 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700830
Jeff Sharkey51c94492016-05-10 17:46:39 -0600831 LOG(DEBUG) << "Copying " << from << " to " << to;
832 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
833 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700834 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600835 goto fail;
836 }
837 }
838 {
839 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
840 auto to = create_data_user_ce_path(to_uuid, user);
841 argv[6] = (char*) from.c_str();
842 argv[7] = (char*) to.c_str();
843
844 LOG(DEBUG) << "Copying " << from << " to " << to;
845 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
846 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700847 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600848 goto fail;
849 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700850 }
851
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700852 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
853 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700854 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700855 goto fail;
856 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700857 }
858
Jeff Sharkey31f08982015-07-07 13:31:37 -0700859 // We let the framework scan the new location and persist that before
860 // deleting the data in the old location; this ordering ensures that
861 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700862 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700863
864fail:
865 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700866 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600867 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700868 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
869 LOG(WARNING) << "Failed to rollback " << to;
870 }
871 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700872 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600873 {
874 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
875 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
876 LOG(WARNING) << "Failed to rollback " << to;
877 }
878 }
879 {
880 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
881 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
882 LOG(WARNING) << "Failed to rollback " << to;
883 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700884 }
885 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700886 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700887}
888
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700889binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
890 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
891 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700892 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700893 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700894
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700895 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600896 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700897 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700898 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700899 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700900 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700901 }
902 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600903
904 // Data under /data/media doesn't have an app, but we still want
905 // to limit it to prevent abuse.
906 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
907 multiuser_get_uid(userId, AID_MEDIA_RW))) {
908 return error("Failed to set hard quota for media_rw");
909 }
910
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700911 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700912}
913
914binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
915 int32_t userId, int32_t flags) {
916 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700917 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700918 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700919
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700920 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700921 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700922 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700923 auto path = create_data_user_de_path(uuid_, userId);
924 if (delete_dir_contents_and_dir(path, true) != 0) {
925 res = error("Failed to delete " + path);
926 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700927 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700928 path = create_data_misc_legacy_path(userId);
929 if (delete_dir_contents_and_dir(path, true) != 0) {
930 res = error("Failed to delete " + path);
931 }
Calin Juravle114f0812017-03-08 19:05:07 -0800932 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700933 if (delete_dir_contents_and_dir(path, true) != 0) {
934 res = error("Failed to delete " + path);
935 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700936 }
Robin Lee095c7632014-04-25 15:05:19 +0100937 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600938 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700939 auto path = create_data_user_ce_path(uuid_, userId);
940 if (delete_dir_contents_and_dir(path, true) != 0) {
941 res = error("Failed to delete " + path);
942 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600943 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700944 if (delete_dir_contents_and_dir(path, true) != 0) {
945 res = error("Failed to delete " + path);
946 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600947 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700948 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100949}
950
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700951binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600952 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700953 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700954 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700955 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700956
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700957 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700958 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700959 auto device = findQuotaDeviceForUuid(uuid);
960 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700961
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700962 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700963 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700964 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700965 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700966
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600967 int64_t cleared = 0;
968 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600969 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600970 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600971
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600972 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600973 return ok();
974 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700975
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700976 if (flags & FLAG_FREE_CACHE_V2) {
977 // This new cache strategy fairly removes files from UIDs by deleting
978 // files from the UIDs which are most over their allocated quota
979
980 // 1. Create trackers for every known UID
981 ATRACE_BEGIN("create");
982 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
983 for (auto user : get_known_users(uuid_)) {
984 FTS *fts;
985 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600986 auto ce_path = create_data_user_ce_path(uuid_, user);
987 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600988 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
989 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
990 (char*) media_path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700991 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700992 return error("Failed to fts_open");
993 }
994 while ((p = fts_read(fts)) != NULL) {
995 if (p->fts_info == FTS_D && p->fts_level == 1) {
996 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600997 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
998 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
999 + AID_APP_START;
1000 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001001 auto search = trackers.find(uid);
1002 if (search != trackers.end()) {
1003 search->second->addDataPath(p->fts_path);
1004 } else {
1005 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
1006 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
1007 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001008 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001009 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001010 tracker->cacheQuota = mCacheQuotas[uid];
1011 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001012 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001013#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001014 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001015#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001016 tracker->cacheQuota = 67108864;
1017 }
1018 trackers[uid] = tracker;
1019 }
1020 fts_set(fts, p, FTS_SKIP);
1021 }
1022 }
1023 fts_close(fts);
1024 }
1025 ATRACE_END();
1026
1027 // 2. Populate tracker stats and insert into priority queue
1028 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001029 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001030 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1031 return (left->getCacheRatio() < right->getCacheRatio());
1032 };
1033 std::priority_queue<std::shared_ptr<CacheTracker>,
1034 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1035 for (const auto& it : trackers) {
1036 it.second->loadStats();
1037 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001038 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001039 }
1040 ATRACE_END();
1041
1042 // 3. Bounce across the queue, freeing items from whichever tracker is
1043 // the most over their assigned quota
1044 ATRACE_BEGIN("bounce");
1045 std::shared_ptr<CacheTracker> active;
1046 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001047 // Only look at apps under quota when explicitly requested
1048 if (active && (active->getCacheRatio() < 10000)
1049 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1050 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1051 << " isn't over quota, and defy not requested";
1052 break;
1053 }
1054
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001055 // Only keep clearing when we haven't pushed into reserved area
1056 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1057 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1058 break;
1059 }
1060
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001061 // Find the best tracker to work with; this might involve swapping
1062 // if the active tracker is no longer the most over quota
1063 bool nextBetter = active && !queue.empty()
1064 && active->getCacheRatio() < queue.top()->getCacheRatio();
1065 if (!active || nextBetter) {
1066 if (active) {
1067 // Current tracker still has items, so we'll consider it
1068 // again later once it bubbles up to surface
1069 queue.push(active);
1070 }
1071 active = queue.top(); queue.pop();
1072 active->ensureItems();
1073 continue;
1074 }
1075
1076 // If no items remain, go find another tracker
1077 if (active->items.empty()) {
1078 active = nullptr;
1079 continue;
1080 } else {
1081 auto item = active->items.back();
1082 active->items.pop_back();
1083
1084 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1085 if (!noop) {
1086 item->purge();
1087 }
1088 active->cacheUsed -= item->size;
1089 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001090 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001091 }
1092
1093 // Verify that we're actually done before bailing, since sneaky
1094 // apps might be using hardlinks
1095 if (needed <= 0) {
1096 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001097 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001098 if (needed <= 0) {
1099 break;
1100 } else {
1101 LOG(WARNING) << "Expected to be done but still need " << needed;
1102 }
1103 }
1104 }
1105 ATRACE_END();
1106
1107 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001108 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001109 }
1110
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001111 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001112 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001113 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001114 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001115 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001116 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001117 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001118}
1119
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001120binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1121 const std::string& instructionSet) {
1122 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001123 std::lock_guard<std::recursive_mutex> lock(mLock);
1124
Mike Lockwood94afecf2012-10-24 10:45:23 -07001125 char dex_path[PKG_PATH_MAX];
1126
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001127 const char* path = codePath.c_str();
1128 const char* instruction_set = instructionSet.c_str();
1129
Jeff Sharkey770180a2014-09-08 17:14:26 -07001130 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001131 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001132 }
1133
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001134 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001135 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001136 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001137
1138 ALOGV("unlink %s\n", dex_path);
1139 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001140 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1141 // but could not be unlinked.
1142 if (errno != ENOENT) {
1143 return error(StringPrintf("Failed to unlink %s", dex_path));
1144 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001145 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001146 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001147}
1148
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001149struct stats {
1150 int64_t codeSize;
1151 int64_t dataSize;
1152 int64_t cacheSize;
1153};
1154
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001155#if MEASURE_DEBUG
1156static std::string toString(std::vector<int64_t> values) {
1157 std::stringstream res;
1158 res << "[";
1159 for (size_t i = 0; i < values.size(); i++) {
1160 res << values[i];
1161 if (i < values.size() - 1) {
1162 res << ",";
1163 }
1164 }
1165 res << "]";
1166 return res.str();
1167}
1168#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001169
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001170static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001171 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001172 if (device.empty()) return;
1173
1174 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001175
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001176 if (stats != nullptr) {
1177 uid_t uid = multiuser_get_uid(userId, appId);
1178 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001179 reinterpret_cast<char*>(&dq)) != 0) {
1180 if (errno != ESRCH) {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001181 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001182 }
1183 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001184#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001185 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001186#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001187 stats->dataSize += dq.dqb_curspace;
1188 }
1189
1190 int cacheGid = multiuser_get_cache_gid(userId, appId);
1191 if (cacheGid != -1) {
1192 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1193 reinterpret_cast<char*>(&dq)) != 0) {
1194 if (errno != ESRCH) {
1195 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1196 }
1197 } else {
1198#if MEASURE_DEBUG
1199 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1200#endif
1201 stats->cacheSize += dq.dqb_curspace;
1202 }
1203 }
1204
1205 int sharedGid = multiuser_get_shared_gid(0, appId);
1206 if (sharedGid != -1) {
1207 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1208 reinterpret_cast<char*>(&dq)) != 0) {
1209 if (errno != ESRCH) {
1210 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1211 }
1212 } else {
1213#if MEASURE_DEBUG
1214 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1215#endif
1216 stats->codeSize += dq.dqb_curspace;
1217 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001218 }
1219 }
1220
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001221 if (extStats != nullptr) {
1222 int extGid = multiuser_get_ext_gid(userId, appId);
1223 if (extGid != -1) {
1224 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1225 reinterpret_cast<char*>(&dq)) != 0) {
1226 if (errno != ESRCH) {
1227 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1228 }
1229 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001230#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001231 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001232#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001233 extStats->dataSize += dq.dqb_curspace;
1234 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001235 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001236
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001237 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1238 if (extCacheGid != -1) {
1239 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extCacheGid,
1240 reinterpret_cast<char*>(&dq)) != 0) {
1241 if (errno != ESRCH) {
1242 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extCacheGid;
1243 }
1244 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001245#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001246 LOG(DEBUG) << "quotactl() for GID " << extCacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001247#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001248 extStats->dataSize += dq.dqb_curspace;
1249 extStats->cacheSize += dq.dqb_curspace;
1250 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001251 }
1252 }
1253}
1254
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001255static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001256 DIR *d;
1257 int dfd;
1258 struct dirent *de;
1259 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001260
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001261 d = opendir(path.c_str());
1262 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001263 if (errno != ENOENT) {
1264 PLOG(WARNING) << "Failed to open " << path;
1265 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001266 return;
1267 }
1268 dfd = dirfd(d);
1269 while ((de = readdir(d))) {
1270 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001271
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001272 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001273 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001274 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001275 }
1276
1277 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001278 if (!strcmp(name, ".")) {
1279 // Don't recurse, but still count node size
1280 } else if (!strcmp(name, "..")) {
1281 // Don't recurse or count node size
1282 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001283 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001284 // Measure all children nodes
1285 size = 0;
1286 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001287 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001288
1289 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1290 stats->cacheSize += size;
1291 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001292 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001293
1294 // Legacy symlink isn't owned by app
1295 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1296 continue;
1297 }
1298
1299 // Everything found inside is considered data
1300 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001301 }
1302 closedir(d);
1303}
1304
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001305static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1306 bool exclude_apps = false) {
1307 DIR *d;
1308 int dfd;
1309 struct dirent *de;
1310 struct stat s;
1311
1312 d = opendir(path.c_str());
1313 if (d == nullptr) {
1314 if (errno != ENOENT) {
1315 PLOG(WARNING) << "Failed to open " << path;
1316 }
1317 return;
1318 }
1319 dfd = dirfd(d);
1320 while ((de = readdir(d))) {
1321 if (de->d_type == DT_DIR) {
1322 const char *name = de->d_name;
1323 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1324 continue;
1325 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001326 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001327 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1328 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001329 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001330 continue;
1331 } else {
1332 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1333 }
1334 }
1335 }
1336 closedir(d);
1337}
1338
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001339static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1340 FTS *fts;
1341 FTSENT *p;
1342 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001343 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001344 PLOG(ERROR) << "Failed to fts_open " << path;
1345 return;
1346 }
1347 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001348 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001349 switch (p->fts_info) {
1350 case FTS_D:
1351 if (p->fts_level == 4
1352 && !strcmp(p->fts_name, "cache")
1353 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1354 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1355 p->fts_number = 1;
1356 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001357 // Fall through to count the directory
1358 case FTS_DEFAULT:
1359 case FTS_F:
1360 case FTS_SL:
1361 case FTS_SLNONE:
1362 int64_t size = (p->fts_statp->st_blocks * 512);
1363 if (p->fts_number == 1) {
1364 stats->cacheSize += size;
1365 }
1366 stats->dataSize += size;
1367 break;
1368 }
1369 }
1370 fts_close(fts);
1371}
1372
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001373binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001374 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1375 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1376 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001377 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001378 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -07001379 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001380 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1381 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001382 // NOTE: Locking is relaxed on this method, since it's limited to
1383 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001384
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001385 // When modifying this logic, always verify using tests:
1386 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1387
1388#if MEASURE_DEBUG
1389 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1390#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001391
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001392 // Here's a summary of the common storage locations across the platform,
1393 // and how they're each tagged:
1394 //
1395 // /data/app/com.example UID system
1396 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001397 // /data/user/0/com.example UID u0_a10 GID u0_a10
1398 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1399 // /data/media/0/foo.txt UID u0_media_rw
1400 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1401 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1402 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1403 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001404
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001405 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001406 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001407 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001408 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001409
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001410 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001411
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001412 auto device = findQuotaDeviceForUuid(uuid);
1413 if (device.empty()) {
1414 flags &= ~FLAG_USE_QUOTA;
1415 }
1416
Jeff Sharkey466459b2017-01-17 15:25:01 -07001417 ATRACE_BEGIN("obb");
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -07001418 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001419 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1420 calculate_tree_size(obbCodePath, &extStats.codeSize);
1421 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001422 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001423
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001424 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001425 ATRACE_BEGIN("code");
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -07001426 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001427 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001428 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001429 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001430 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001431
Jeff Sharkey466459b2017-01-17 15:25:01 -07001432 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001433 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001434 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001435 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001436 ATRACE_BEGIN("code");
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -07001437 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001438 calculate_tree_size(codePath, &stats.codeSize);
1439 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001440 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001441
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001442 for (size_t i = 0; i < packageNames.size(); i++) {
1443 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001444
Jeff Sharkey466459b2017-01-17 15:25:01 -07001445 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001446 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1447 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001448 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1449 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001450 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001451
Jeff Sharkey06a61842017-04-15 12:03:31 -06001452 if (!uuid) {
1453 ATRACE_BEGIN("profiles");
1454 calculate_tree_size(
1455 create_primary_current_profile_package_dir_path(userId, pkgname),
1456 &stats.dataSize);
1457 calculate_tree_size(
1458 create_primary_reference_profile_package_dir_path(pkgname),
1459 &stats.codeSize);
1460 ATRACE_END();
1461 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001462
Jeff Sharkey466459b2017-01-17 15:25:01 -07001463 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001464 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001465 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001466 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001467 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001468 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001469 }
1470
Jeff Sharkey06a61842017-04-15 12:03:31 -06001471 if (!uuid) {
1472 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001473 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001474 if (sharedGid != -1) {
1475 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1476 sharedGid, -1);
1477 }
1478 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001479 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001480 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001481
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001482 std::vector<int64_t> ret;
1483 ret.push_back(stats.codeSize);
1484 ret.push_back(stats.dataSize);
1485 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001486 ret.push_back(extStats.codeSize);
1487 ret.push_back(extStats.dataSize);
1488 ret.push_back(extStats.cacheSize);
1489#if MEASURE_DEBUG
1490 LOG(DEBUG) << "Final result " << toString(ret);
1491#endif
1492 *_aidl_return = ret;
1493 return ok();
1494}
1495
1496binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1497 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1498 std::vector<int64_t>* _aidl_return) {
1499 ENFORCE_UID(AID_SYSTEM);
1500 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001501 // NOTE: Locking is relaxed on this method, since it's limited to
1502 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001503
1504 // When modifying this logic, always verify using tests:
1505 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1506
1507#if MEASURE_DEBUG
1508 LOG(INFO) << "Measuring user " << userId;
1509#endif
1510
1511 struct stats stats;
1512 struct stats extStats;
1513 memset(&stats, 0, sizeof(stats));
1514 memset(&extStats, 0, sizeof(extStats));
1515
1516 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1517
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001518 auto device = findQuotaDeviceForUuid(uuid);
1519 if (device.empty()) {
1520 flags &= ~FLAG_USE_QUOTA;
1521 }
1522
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001523 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001524 struct dqblk dq;
1525
1526 ATRACE_BEGIN("obb");
1527 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1528 reinterpret_cast<char*>(&dq)) != 0) {
1529 if (errno != ESRCH) {
1530 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1531 }
1532 } else {
1533#if MEASURE_DEBUG
1534 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1535#endif
1536 extStats.codeSize += dq.dqb_curspace;
1537 }
1538 ATRACE_END();
1539
Jeff Sharkey466459b2017-01-17 15:25:01 -07001540 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001541 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001542 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001543
Jeff Sharkey466459b2017-01-17 15:25:01 -07001544 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001545 auto cePath = create_data_user_ce_path(uuid_, userId);
1546 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001547 auto dePath = create_data_user_de_path(uuid_, userId);
1548 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001549 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001550
Jeff Sharkey06a61842017-04-15 12:03:31 -06001551 if (!uuid) {
1552 ATRACE_BEGIN("profile");
1553 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1554 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1555 auto refProfilePath = create_primary_ref_profile_dir_path();
1556 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1557 ATRACE_END();
1558 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001559
Jeff Sharkey466459b2017-01-17 15:25:01 -07001560 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001561 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1562 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1563 reinterpret_cast<char*>(&dq)) != 0) {
1564 if (errno != ESRCH) {
1565 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1566 }
1567 } else {
1568#if MEASURE_DEBUG
1569 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001570#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001571 extStats.dataSize += dq.dqb_curspace;
1572 }
1573 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001574
Jeff Sharkey06a61842017-04-15 12:03:31 -06001575 if (!uuid) {
1576 ATRACE_BEGIN("dalvik");
1577 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1578 -1, -1, true);
1579 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1580 -1, -1, true);
1581 ATRACE_END();
1582 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001583
Jeff Sharkey466459b2017-01-17 15:25:01 -07001584 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001585 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001586 for (auto appId : appIds) {
1587 if (appId >= AID_APP_START) {
1588 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001589
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001590#if MEASURE_DEBUG
1591 // Sleep to make sure we don't lose logs
1592 usleep(1);
1593#endif
1594 }
1595 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001596 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001597 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001598 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001599 ATRACE_BEGIN("obb");
1600 auto obbPath = create_data_path(uuid_) + "/media/obb";
1601 calculate_tree_size(obbPath, &extStats.codeSize);
1602 ATRACE_END();
1603
Jeff Sharkey466459b2017-01-17 15:25:01 -07001604 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001605 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001606 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001607
Jeff Sharkey466459b2017-01-17 15:25:01 -07001608 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001609 auto cePath = create_data_user_ce_path(uuid_, userId);
1610 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001611 auto dePath = create_data_user_de_path(uuid_, userId);
1612 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001613 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001614
Jeff Sharkey06a61842017-04-15 12:03:31 -06001615 if (!uuid) {
1616 ATRACE_BEGIN("profile");
1617 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1618 calculate_tree_size(userProfilePath, &stats.dataSize);
1619 auto refProfilePath = create_primary_ref_profile_dir_path();
1620 calculate_tree_size(refProfilePath, &stats.codeSize);
1621 ATRACE_END();
1622 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001623
Jeff Sharkey466459b2017-01-17 15:25:01 -07001624 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001625 auto dataMediaPath = create_data_media_path(uuid_, userId);
1626 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1627#if MEASURE_DEBUG
1628 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1629 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001630#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001631 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001632
Jeff Sharkey06a61842017-04-15 12:03:31 -06001633 if (!uuid) {
1634 ATRACE_BEGIN("dalvik");
1635 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1636 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1637 ATRACE_END();
1638 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001639 }
1640
1641 std::vector<int64_t> ret;
1642 ret.push_back(stats.codeSize);
1643 ret.push_back(stats.dataSize);
1644 ret.push_back(stats.cacheSize);
1645 ret.push_back(extStats.codeSize);
1646 ret.push_back(extStats.dataSize);
1647 ret.push_back(extStats.cacheSize);
1648#if MEASURE_DEBUG
1649 LOG(DEBUG) << "Final result " << toString(ret);
1650#endif
1651 *_aidl_return = ret;
1652 return ok();
1653}
1654
1655binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001656 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1657 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001658 ENFORCE_UID(AID_SYSTEM);
1659 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001660 // NOTE: Locking is relaxed on this method, since it's limited to
1661 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001662
1663 // When modifying this logic, always verify using tests:
1664 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1665
1666#if MEASURE_DEBUG
1667 LOG(INFO) << "Measuring external " << userId;
1668#endif
1669
1670 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1671
1672 int64_t totalSize = 0;
1673 int64_t audioSize = 0;
1674 int64_t videoSize = 0;
1675 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001676 int64_t appSize = 0;
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001677 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001678
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001679 auto device = findQuotaDeviceForUuid(uuid);
1680 if (device.empty()) {
1681 flags &= ~FLAG_USE_QUOTA;
1682 }
1683
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001684 if (flags & FLAG_USE_QUOTA) {
1685 struct dqblk dq;
1686
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001687 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001688 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1689 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1690 reinterpret_cast<char*>(&dq)) != 0) {
1691 if (errno != ESRCH) {
1692 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1693 }
1694 } else {
1695#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001696 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001697#endif
1698 totalSize = dq.dqb_curspace;
1699 }
1700
1701 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1702 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1703 reinterpret_cast<char*>(&dq)) == 0) {
1704#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001705 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001706#endif
1707 audioSize = dq.dqb_curspace;
1708 }
1709 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1710 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1711 reinterpret_cast<char*>(&dq)) == 0) {
1712#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001713 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001714#endif
1715 videoSize = dq.dqb_curspace;
1716 }
1717 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1718 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1719 reinterpret_cast<char*>(&dq)) == 0) {
1720#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001721 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001722#endif
1723 imageSize = dq.dqb_curspace;
1724 }
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001725 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1726 reinterpret_cast<char*>(&dq)) == 0) {
1727#if MEASURE_DEBUG
1728 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1729#endif
1730 obbSize = dq.dqb_curspace;
1731 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001732 ATRACE_END();
1733
1734 ATRACE_BEGIN("apps");
1735 struct stats extStats;
1736 memset(&extStats, 0, sizeof(extStats));
1737 for (auto appId : appIds) {
1738 if (appId >= AID_APP_START) {
1739 collectQuotaStats(device, userId, appId, nullptr, &extStats);
1740 }
1741 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001742 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001743 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001744 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001745 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001746 FTS *fts;
1747 FTSENT *p;
1748 auto path = create_data_media_path(uuid_, userId);
1749 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001750 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001751 return error("Failed to fts_open " + path);
1752 }
1753 while ((p = fts_read(fts)) != NULL) {
1754 char* ext;
1755 int64_t size = (p->fts_statp->st_blocks * 512);
1756 switch (p->fts_info) {
1757 case FTS_F:
1758 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001759 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001760 ext = strrchr(p->fts_name, '.');
1761 if (ext != nullptr) {
1762 switch (MatchExtension(++ext)) {
1763 case AID_MEDIA_AUDIO: audioSize += size; break;
1764 case AID_MEDIA_VIDEO: videoSize += size; break;
1765 case AID_MEDIA_IMAGE: imageSize += size; break;
1766 }
1767 }
1768 }
1769 // Fall through to always count against total
1770 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001771 // Ignore data belonging to specific apps
1772 p->fts_number = p->fts_parent->fts_number;
1773 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1774 p->fts_number = 1;
1775 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001776 case FTS_DEFAULT:
1777 case FTS_SL:
1778 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001779 if (p->fts_parent->fts_number == 1) {
1780 appSize += size;
1781 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001782 totalSize += size;
1783 break;
1784 }
1785 }
1786 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001787 ATRACE_END();
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001788
1789 ATRACE_BEGIN("obb");
1790 auto obbPath = create_data_media_obb_path(uuid_, "");
1791 calculate_tree_size(obbPath, &obbSize);
1792 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001793 }
1794
1795 std::vector<int64_t> ret;
1796 ret.push_back(totalSize);
1797 ret.push_back(audioSize);
1798 ret.push_back(videoSize);
1799 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001800 ret.push_back(appSize);
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001801 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001802#if MEASURE_DEBUG
1803 LOG(DEBUG) << "Final result " << toString(ret);
1804#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001805 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001806 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001807}
1808
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001809binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1810 int32_t userId, int32_t appId, int64_t cacheQuota) {
1811 ENFORCE_UID(AID_SYSTEM);
1812 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001813 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001814
1815 int32_t uid = multiuser_get_uid(userId, appId);
1816 mCacheQuotas[uid] = cacheQuota;
1817
1818 return ok();
1819}
1820
David Sehr6727c2d2016-05-17 16:06:22 -07001821// Dumps the contents of a profile file, using pkgname's dex files for pretty
1822// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001823binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1824 const std::string& codePaths, bool* _aidl_return) {
1825 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001826 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001827 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001828
1829 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001830 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001831
Jeff Sharkey90aff262016-12-12 14:28:24 -07001832 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001833 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001834}
1835
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001836// Copy the contents of a system profile over the data profile.
1837binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
1838 int32_t packageUid, const std::string& packageName, bool* _aidl_return) {
1839 ENFORCE_UID(AID_SYSTEM);
1840 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1841 std::lock_guard<std::recursive_mutex> lock(mLock);
1842 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName);
1843 return ok();
1844}
1845
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001846// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001847binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001848 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001849 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001850 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001851 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001852
Calin Juravle114f0812017-03-08 19:05:07 -08001853 *_aidl_return = analyze_primary_profiles(uid, packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001854 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001855}
1856
Calin Juravle29591732017-11-20 17:46:19 -08001857binder::Status InstalldNativeService::snapshotProfile(int32_t appId, const std::string& packageName,
1858 const std::string& codePath, bool* _aidl_return) {
1859 ENFORCE_UID(AID_SYSTEM);
1860 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1861 std::lock_guard<std::recursive_mutex> lock(mLock);
1862
1863 *_aidl_return = snapshot_profile(appId, packageName, codePath);
1864 return ok();
1865}
1866
1867binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
1868 const std::string& codePath) {
1869 ENFORCE_UID(AID_SYSTEM);
1870 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1871 std::lock_guard<std::recursive_mutex> lock(mLock);
1872
1873 std::string snapshot = create_snapshot_profile_path(packageName, codePath);
1874 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
1875 return error("Failed to destroy profile snapshot for " + packageName + ":" + codePath);
1876 }
1877 return ok();
1878}
1879
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001880binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1881 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1882 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1883 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle52c45822017-07-13 22:50:21 -07001884 const std::unique_ptr<std::string>& classLoaderContext,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001885 const std::unique_ptr<std::string>& seInfo, bool downgrade) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001886 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001887 CHECK_ARGUMENT_UUID(uuid);
1888 if (packageName && *packageName != "*") {
1889 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1890 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001891 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001892
1893 const char* apk_path = apkPath.c_str();
1894 const char* pkgname = packageName ? packageName->c_str() : "*";
1895 const char* instruction_set = instructionSet.c_str();
1896 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1897 const char* compiler_filter = compilerFilter.c_str();
1898 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
Calin Juravle52c45822017-07-13 22:50:21 -07001899 const char* class_loader_context = classLoaderContext ? classLoaderContext->c_str() : nullptr;
Calin Juravlecb556e32017-04-04 20:22:50 -07001900 const char* se_info = seInfo ? seInfo->c_str() : nullptr;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001901 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle52c45822017-07-13 22:50:21 -07001902 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Shubham Ajmera54ef8622017-06-22 11:10:27 -07001903 downgrade);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001904 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001905}
1906
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001907binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1908 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001909 std::lock_guard<std::recursive_mutex> lock(mLock);
1910
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001911 const char* instruction_set = instructionSet.c_str();
1912
1913 char boot_marker_path[PKG_PATH_MAX];
1914 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001915 "%s/%s/%s/.booting",
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001916 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08001917 DALVIK_CACHE,
1918 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001919
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001920 ALOGV("mark_boot_complete : %s", boot_marker_path);
1921 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001922 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001923 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001924 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001925}
1926
Mike Lockwood94afecf2012-10-24 10:45:23 -07001927void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1928 struct stat* statbuf)
1929{
1930 while (path[basepos] != 0) {
1931 if (path[basepos] == '/') {
1932 path[basepos] = 0;
1933 if (lstat(path, statbuf) < 0) {
1934 ALOGV("Making directory: %s\n", path);
1935 if (mkdir(path, mode) == 0) {
1936 chown(path, uid, gid);
1937 } else {
1938 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1939 }
1940 }
1941 path[basepos] = '/';
1942 basepos++;
1943 }
1944 basepos++;
1945 }
1946}
1947
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001948binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1949 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1950 const std::string& nativeLibPath32, int32_t userId) {
1951 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001952 CHECK_ARGUMENT_UUID(uuid);
1953 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001954 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001955
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001956 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1957 const char* pkgname = packageName.c_str();
1958 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001959 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001960 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001961
Jeff Sharkey423e7462016-12-09 18:18:43 -07001962 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1963 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001964
1965 const char* pkgdir = _pkgdir.c_str();
1966 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001967
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001968 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001969 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001970 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001971
1972 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001973 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001974 }
1975
1976 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001977 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001978 goto out;
1979 }
1980
1981 if (lstat(libsymlink, &libStat) < 0) {
1982 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001983 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001984 goto out;
1985 }
1986 } else {
1987 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001988 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001989 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001990 goto out;
1991 }
1992 } else if (S_ISLNK(libStat.st_mode)) {
1993 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001994 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001995 goto out;
1996 }
1997 }
1998 }
1999
2000 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002001 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002002 goto out;
2003 }
2004
2005out:
2006 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002007 auto msg = "Failed to cleanup chmod " + _pkgdir;
2008 if (res.isOk()) {
2009 res = error(msg);
2010 } else {
2011 PLOG(ERROR) << msg;
2012 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002013 }
2014
2015 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002016 auto msg = "Failed to cleanup chown " + _pkgdir;
2017 if (res.isOk()) {
2018 res = error(msg);
2019 } else {
2020 PLOG(ERROR) << msg;
2021 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002022 }
2023
Jeff Sharkey423e7462016-12-09 18:18:43 -07002024 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002025}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002026
2027static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2028{
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002029 execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
2030 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
2031 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2032}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002033
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002034static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2035{
2036 execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
2037 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
2038 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2039}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002040
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002041static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
2042 const char* idmap_path, int32_t uid) {
2043 int idmap_fd = open(idmap_path, O_RDWR);
2044 if (idmap_fd < 0) {
2045 PLOG(ERROR) << "idmap open failed: " << idmap_path;
2046 unlink(idmap_path);
2047 return true;
2048 }
2049
2050 pid_t pid;
2051 pid = fork();
2052 if (pid == 0) {
2053 /* child -- drop privileges before continuing */
2054 if (setgid(uid) != 0) {
2055 LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
2056 exit(1);
2057 }
2058 if (setuid(uid) != 0) {
2059 LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
2060 exit(1);
2061 }
2062 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2063 PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
2064 exit(1);
2065 }
2066
2067 run_verify_idmap(target_apk, overlay_apk, idmap_fd);
2068 exit(1); /* only if exec call to deleting stale idmap failed */
2069 } else {
2070 int status = wait_child(pid);
2071 close(idmap_fd);
2072
2073 if (status != 0) {
2074 // Failed on verifying if idmap is made from target_apk and overlay_apk.
2075 LOG(DEBUG) << "delete stale idmap: " << idmap_path;
2076 unlink(idmap_path);
2077 return true;
2078 }
2079 }
2080 return false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002081}
2082
2083// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2084// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2085static int flatten_path(const char *prefix, const char *suffix,
2086 const char *overlay_path, char *idmap_path, size_t N)
2087{
2088 if (overlay_path == NULL || idmap_path == NULL) {
2089 return -1;
2090 }
2091 const size_t len_overlay_path = strlen(overlay_path);
2092 // will access overlay_path + 1 further below; requires absolute path
2093 if (len_overlay_path < 2 || *overlay_path != '/') {
2094 return -1;
2095 }
2096 const size_t len_idmap_root = strlen(prefix);
2097 const size_t len_suffix = strlen(suffix);
2098 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2099 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2100 // additions below would cause overflow
2101 return -1;
2102 }
2103 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2104 return -1;
2105 }
2106 memset(idmap_path, 0, N);
2107 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2108 char *ch = idmap_path + len_idmap_root;
2109 while (*ch != '\0') {
2110 if (*ch == '/') {
2111 *ch = '@';
2112 }
2113 ++ch;
2114 }
2115 return 0;
2116}
2117
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002118binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2119 const std::string& overlayApkPath, int32_t uid) {
2120 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002121 std::lock_guard<std::recursive_mutex> lock(mLock);
2122
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002123 const char* target_apk = targetApkPath.c_str();
2124 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002125 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2126
2127 int idmap_fd = -1;
2128 char idmap_path[PATH_MAX];
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002129 struct stat idmap_stat;
2130 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002131
2132 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2133 idmap_path, sizeof(idmap_path)) == -1) {
2134 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2135 goto fail;
2136 }
2137
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002138 if (stat(idmap_path, &idmap_stat) < 0) {
2139 outdated = true;
2140 } else {
2141 outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2142 }
2143
2144 if (outdated) {
2145 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2146 } else {
2147 idmap_fd = open(idmap_path, O_RDWR);
2148 }
2149
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002150 if (idmap_fd < 0) {
2151 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2152 goto fail;
2153 }
2154 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2155 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2156 goto fail;
2157 }
2158 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2159 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2160 goto fail;
2161 }
2162
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002163 if (!outdated) {
2164 close(idmap_fd);
2165 return ok();
2166 }
2167
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002168 pid_t pid;
2169 pid = fork();
2170 if (pid == 0) {
2171 /* child -- drop privileges before continuing */
2172 if (setgid(uid) != 0) {
2173 ALOGE("setgid(%d) failed during idmap\n", uid);
2174 exit(1);
2175 }
2176 if (setuid(uid) != 0) {
2177 ALOGE("setuid(%d) failed during idmap\n", uid);
2178 exit(1);
2179 }
2180 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2181 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2182 exit(1);
2183 }
2184
2185 run_idmap(target_apk, overlay_apk, idmap_fd);
2186 exit(1); /* only if exec call to idmap failed */
2187 } else {
2188 int status = wait_child(pid);
2189 if (status != 0) {
2190 ALOGE("idmap failed, status=0x%04x\n", status);
2191 goto fail;
2192 }
2193 }
2194
2195 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002196 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002197fail:
2198 if (idmap_fd >= 0) {
2199 close(idmap_fd);
2200 unlink(idmap_path);
2201 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002202 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002203}
Robert Craige9887e42014-02-20 10:25:56 -05002204
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002205binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
2206 const char* overlay_apk = overlayApkPath.c_str();
2207 char idmap_path[PATH_MAX];
2208
2209 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2210 idmap_path, sizeof(idmap_path)) == -1) {
2211 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2212 return error();
2213 }
2214 if (unlink(idmap_path) < 0) {
2215 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2216 return error();
2217 }
2218 return ok();
2219}
2220
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002221binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2222 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2223 const std::string& seInfo) {
2224 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002225 CHECK_ARGUMENT_UUID(uuid);
2226 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002227 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002228
2229 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002230
Robert Craigda30dc72014-03-27 10:21:12 -04002231 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002232 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002233 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2234 const char* pkgName = packageName.c_str();
2235 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002236
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002237 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002238 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002239 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002240 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002241 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002242 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002243 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002244 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002245 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002246 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002247 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002248 }
Robert Craige9887e42014-02-20 10:25:56 -05002249 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002250 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002251}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002252
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002253binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2254 const std::string& instructionSet) {
2255 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002256 std::lock_guard<std::recursive_mutex> lock(mLock);
2257
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002258 const char* oat_dir = oatDir.c_str();
2259 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002260 char oat_instr_dir[PKG_PATH_MAX];
2261
2262 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002263 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002264 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002265 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002266 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002267 }
2268 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002269 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002270 }
2271 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002272 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002273 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002274 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002275 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002276}
2277
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002278binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2279 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002280 std::lock_guard<std::recursive_mutex> lock(mLock);
2281
Jeff Sharkey423e7462016-12-09 18:18:43 -07002282 if (validate_apk_path(packageDir.c_str())) {
2283 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002284 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002285 if (delete_dir_contents_and_dir(packageDir) != 0) {
2286 return error("Failed to delete " + packageDir);
2287 }
2288 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002289}
2290
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002291binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2292 const std::string& fromBase, const std::string& toBase) {
2293 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002294 std::lock_guard<std::recursive_mutex> lock(mLock);
2295
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002296 const char* relative_path = relativePath.c_str();
2297 const char* from_base = fromBase.c_str();
2298 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002299 char from_path[PKG_PATH_MAX];
2300 char to_path[PKG_PATH_MAX];
2301 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2302 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2303
2304 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002305 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002306 }
2307
2308 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002309 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002310 }
2311
Jeff Sharkey423e7462016-12-09 18:18:43 -07002312 if (link(from_path, to_path) < 0) {
2313 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002314 }
2315
Jeff Sharkey423e7462016-12-09 18:18:43 -07002316 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002317}
2318
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002319binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2320 const std::string& instructionSet, const std::string& outputPath) {
2321 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002322 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002323
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002324 const char* apk_path = apkPath.c_str();
2325 const char* instruction_set = instructionSet.c_str();
2326 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002327
Jeff Sharkey90aff262016-12-12 14:28:24 -07002328 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002329 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002330}
2331
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002332binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002333 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002334 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002335 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002336
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002337 const char* apk_path = apkPath.c_str();
2338 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002339 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002340
Jeff Sharkey90aff262016-12-12 14:28:24 -07002341 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2342 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002343}
2344
Calin Juravlebd968362017-01-25 01:17:17 -08002345binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2346 const std::string& dexPath, const std::string& packageName, int32_t uid,
2347 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2348 int32_t storage_flag, bool* _aidl_return) {
2349 ENFORCE_UID(AID_SYSTEM);
2350 CHECK_ARGUMENT_UUID(volumeUuid);
2351 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2352
2353 std::lock_guard<std::recursive_mutex> lock(mLock);
2354 bool result = android::installd::reconcile_secondary_dex_file(
2355 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2356 return result ? ok() : error();
2357}
2358
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002359binder::Status InstalldNativeService::invalidateMounts() {
2360 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002361 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002362
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002363 mStorageMounts.clear();
2364 mQuotaReverseMounts.clear();
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002365
2366 std::ifstream in("/proc/mounts");
2367 if (!in.is_open()) {
2368 return error("Failed to read mounts");
2369 }
2370
2371 std::string source;
2372 std::string target;
2373 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002374 while (!in.eof()) {
2375 std::getline(in, source, ' ');
2376 std::getline(in, target, ' ');
2377 std::getline(in, ignored);
2378
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002379#if !BYPASS_SDCARDFS
2380 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2381 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2382 mStorageMounts[source] = target;
2383 }
2384#endif
2385
2386#if !BYPASS_QUOTA
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002387 if (source.compare(0, 11, "/dev/block/") == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002388 struct dqblk dq;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002389 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2390 reinterpret_cast<char*>(&dq)) == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002391 LOG(DEBUG) << "Found quota mount " << source << " at " << target;
2392 mQuotaReverseMounts[target] = source;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002393
2394 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
2395 // need to kick it again to enable DQUOT_LIMITS_ENABLED.
2396 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2397 && errno != EBUSY) {
2398 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2399 }
2400 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2401 && errno != EBUSY) {
2402 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2403 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002404 }
2405 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002406#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002407 }
2408 return ok();
2409}
2410
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002411std::string InstalldNativeService::findDataMediaPath(
2412 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2413 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2414 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2415 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2416 auto resolved = mStorageMounts[path];
2417 if (resolved.empty()) {
2418 LOG(WARNING) << "Failed to find storage mount for " << path;
2419 resolved = path;
2420 }
2421 return StringPrintf("%s/%u", resolved.c_str(), userid);
2422}
2423
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002424std::string InstalldNativeService::findQuotaDeviceForUuid(
2425 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002426 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002427 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002428 return mQuotaReverseMounts[path];
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002429}
2430
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002431binder::Status InstalldNativeService::isQuotaSupported(
2432 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2433 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2434 return ok();
2435}
2436
Andreas Gampe02d0de52015-11-11 20:43:16 -08002437} // namespace installd
2438} // namespace android