blob: f7878873710b2f4e9041ca96322049013294f117 [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>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070040#include <android-base/properties.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080041#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070042#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010043#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080044#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070046#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070047#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070048#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080049#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070050#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080051#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070052#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070053
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070054#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070055#include "globals.h"
56#include "installd_deps.h"
57#include "otapreopt_utils.h"
58#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070059
Jeff Sharkey88ddd942017-01-17 18:05:54 -070060#include "CacheTracker.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070061#include "MatchExtensionGen.h"
62
Andreas Gampe02d0de52015-11-11 20:43:16 -080063#ifndef LOG_TAG
64#define LOG_TAG "installd"
65#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070066
67using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070068using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070069
Andreas Gampe02d0de52015-11-11 20:43:16 -080070namespace android {
71namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070072
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070073static constexpr const char* kCpPath = "/system/bin/cp";
74static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070075static constexpr const char* kPropHasReserved = "vold.has_reserved";
Jeff Sharkeye3637242015-04-08 20:56:42 -070076
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070077static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000078
Andreas Gampe0354bd02016-06-27 14:25:30 -070079static constexpr const char* PKG_LIB_POSTFIX = "/lib";
80static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
81static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
82
Jaekyun Seok5cb903e2017-05-18 00:13:44 +090083static constexpr const char *kIdMapPath = "/system/bin/idmap";
Andreas Gampe0354bd02016-06-27 14:25:30 -070084static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
85static constexpr const char* IDMAP_SUFFIX = "@idmap";
86
Victor Hsieh99de5162017-10-06 14:44:14 -070087static constexpr const char* kPropApkVerityMode = "ro.apk_verity.mode";
88
Andreas Gampe0354bd02016-06-27 14:25:30 -070089// NOTE: keep in sync with Installer
90static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
91static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070092static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -070093static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
Jeff Sharkey871a8f22017-02-21 18:30:28 -070094static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
95static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
Jeff Sharkeye12d5962017-04-03 16:41:02 -060096static constexpr int FLAG_FORCE = 1 << 16;
Calin Juravle6a1648e2016-02-01 12:12:16 +000097
Jeff Sharkey0274c972016-12-06 09:32:04 -070098namespace {
99
100constexpr const char* kDump = "android.permission.DUMP";
101
Jeff Sharkey423e7462016-12-09 18:18:43 -0700102static binder::Status ok() {
103 return binder::Status::ok();
104}
105
106static binder::Status exception(uint32_t code, const std::string& msg) {
107 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
108}
109
110static binder::Status error() {
111 return binder::Status::fromServiceSpecificError(errno);
112}
113
114static binder::Status error(const std::string& msg) {
115 PLOG(ERROR) << msg;
116 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
117}
118
119static binder::Status error(uint32_t code, const std::string& msg) {
120 LOG(ERROR) << msg << " (" << code << ")";
121 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
122}
123
Jeff Sharkey0274c972016-12-06 09:32:04 -0700124binder::Status checkPermission(const char* permission) {
125 pid_t pid;
126 uid_t uid;
127
128 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
129 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700130 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700131 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700132 return exception(binder::Status::EX_SECURITY,
133 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700134 }
135}
136
137binder::Status checkUid(uid_t expectedUid) {
138 uid_t uid = IPCThreadState::self()->getCallingUid();
139 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700140 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700141 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700142 return exception(binder::Status::EX_SECURITY,
143 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
144 }
145}
146
147binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
148 if (!uuid || is_valid_filename(*uuid)) {
149 return ok();
150 } else {
151 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
152 StringPrintf("UUID %s is malformed", uuid->c_str()));
153 }
154}
155
156binder::Status checkArgumentPackageName(const std::string& packageName) {
157 if (is_valid_package_name(packageName.c_str())) {
158 return ok();
159 } else {
160 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
161 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700162 }
163}
164
165#define ENFORCE_UID(uid) { \
166 binder::Status status = checkUid((uid)); \
167 if (!status.isOk()) { \
168 return status; \
169 } \
170}
171
Jeff Sharkey423e7462016-12-09 18:18:43 -0700172#define CHECK_ARGUMENT_UUID(uuid) { \
173 binder::Status status = checkArgumentUuid((uuid)); \
174 if (!status.isOk()) { \
175 return status; \
176 } \
177}
178
179#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
180 binder::Status status = \
181 checkArgumentPackageName((packageName)); \
182 if (!status.isOk()) { \
183 return status; \
184 } \
185}
186
Jeff Sharkey0274c972016-12-06 09:32:04 -0700187} // namespace
188
189status_t InstalldNativeService::start() {
190 IPCThreadState::self()->disableBackgroundScheduling(true);
191 status_t ret = BinderService<InstalldNativeService>::publish();
192 if (ret != android::OK) {
193 return ret;
194 }
195 sp<ProcessState> ps(ProcessState::self());
196 ps->startThreadPool();
197 ps->giveThreadPoolName();
198 return android::OK;
199}
200
201status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700202 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700203 const binder::Status dump_permission = checkPermission(kDump);
204 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700205 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700206 return PERMISSION_DENIED;
207 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700208 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700209
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700210 out << "installd is happy!" << endl;
211
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700212 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600213 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
214 out << endl << "Storage mounts:" << endl;
215 for (const auto& n : mStorageMounts) {
216 out << " " << n.first << " = " << n.second << endl;
217 }
218
219 out << endl << "Quota reverse mounts:" << endl;
220 for (const auto& n : mQuotaReverseMounts) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700221 out << " " << n.first << " = " << n.second << endl;
222 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700223 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700224
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700225 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600226 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700227 out << endl << "Per-UID cache quotas:" << endl;
228 for (const auto& n : mCacheQuotas) {
229 out << " " << n.first << " = " << n.second << endl;
230 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700231 }
232
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700233 out << endl;
234 out.flush();
235
Jeff Sharkey0274c972016-12-06 09:32:04 -0700236 return NO_ERROR;
237}
238
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600239/**
240 * Perform restorecon of the given path, but only perform recursive restorecon
241 * if the label of that top-level file actually changed. This can save us
242 * significant time by avoiding no-op traversals of large filesystem trees.
243 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700244static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
245 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600246 int res = 0;
247 char* before = nullptr;
248 char* after = nullptr;
249
250 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
251 // libselinux. Not needed here.
252
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600253 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600254 PLOG(ERROR) << "Failed before getfilecon for " << path;
255 goto fail;
256 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700257 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600258 PLOG(ERROR) << "Failed top-level restorecon for " << path;
259 goto fail;
260 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600261 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600262 PLOG(ERROR) << "Failed after getfilecon for " << path;
263 goto fail;
264 }
265
266 // If the initial top-level restorecon above changed the label, then go
267 // back and restorecon everything recursively
268 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700269 if (existing) {
270 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
271 << path << "; running recursive restorecon";
272 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700273 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600274 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
275 PLOG(ERROR) << "Failed recursive restorecon for " << path;
276 goto fail;
277 }
278 }
279
280 goto done;
281fail:
282 res = -1;
283done:
284 free(before);
285 free(after);
286 return res;
287}
288
Jeff Sharkey0274c972016-12-06 09:32:04 -0700289static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700290 const std::string& seInfo, uid_t uid, bool existing) {
291 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
292 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600293}
294
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600295static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600296 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
297 PLOG(ERROR) << "Failed to prepare " << path;
298 return -1;
299 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600300 return 0;
301}
302
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600303/**
304 * Ensure that we have a hard-limit quota to protect against abusive apps;
305 * they should never use more than 90% of blocks or 50% of inodes.
306 */
307static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
308 uid_t uid) {
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -0700309 // Skip when reserved blocks are protecting us against abusive apps
310 if (android::base::GetBoolProperty(kPropHasReserved, false)) return 0;
311 // Skip when device no quotas present
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600312 if (device.empty()) return 0;
313
314 struct dqblk dq;
315 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
316 reinterpret_cast<char*>(&dq)) != 0) {
317 PLOG(WARNING) << "Failed to find quota for " << uid;
318 return -1;
319 }
320
Jeff Sharkeybdd4de82017-08-11 15:13:31 -0600321#if APPLY_HARD_QUOTAS
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600322 if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
323 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
324 struct statvfs stat;
325 if (statvfs(path.c_str(), &stat) != 0) {
326 PLOG(WARNING) << "Failed to statvfs " << path;
327 return -1;
328 }
329
330 dq.dqb_valid = QIF_LIMITS;
Jerry Wongbcb87472017-07-28 15:54:58 -0700331 dq.dqb_bhardlimit =
332 (((static_cast<uint64_t>(stat.f_blocks) * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600333 dq.dqb_ihardlimit = (stat.f_files / 2);
334 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
335 reinterpret_cast<char*>(&dq)) != 0) {
336 PLOG(WARNING) << "Failed to set hard quota for " << uid;
337 return -1;
338 } else {
339 LOG(DEBUG) << "Applied hard quotas for " << uid;
340 return 0;
341 }
342 } else {
343 // Hard quota already set; assume it's reasonable
344 return 0;
345 }
Jeff Sharkeybdd4de82017-08-11 15:13:31 -0600346#else
347 // Hard quotas disabled
348 return 0;
349#endif
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600350}
351
Calin Juravled2affb82017-11-28 17:41:43 -0800352static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
353 if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
354 return true;
355 }
356
357 int32_t uid = multiuser_get_uid(userId, appId);
358 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
359 if (shared_app_gid == -1) {
360 // TODO(calin): this should no longer be possible but do not continue if we don't get
361 // a valid shared gid.
362 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
363 return true;
364 }
365
366 const std::string profile_dir =
367 create_primary_current_profile_package_dir_path(userId, packageName);
368 // read-write-execute only for the app user.
369 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
370 PLOG(ERROR) << "Failed to prepare " << profile_dir;
371 return false;
372 }
373 const std::string profile_file = create_current_profile_path(userId, packageName,
374 /*is_secondary_dex*/false);
375 // read-write only for the app user.
376 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
377 PLOG(ERROR) << "Failed to prepare " << profile_file;
378 return false;
379 }
380
381 const std::string ref_profile_path =
382 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800383
384 // Prepare the reference profile directory. Note that we use the non strict version of
385 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
386 // This is particularly important given that in O there were some fixes for how the
387 // shared_app_gid is computed.
388 //
389 // Note that by the time we get here we know that we are using a correct uid (otherwise
390 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
391 // are sure that the gid being used belongs to the owning app and not someone else.
392 //
393 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
394 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800395 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
396 return false;
397 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800398
Calin Juravled2affb82017-11-28 17:41:43 -0800399 return true;
400}
401
Jeff Sharkey0274c972016-12-06 09:32:04 -0700402binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
403 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700404 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700405 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700406 CHECK_ARGUMENT_UUID(uuid);
407 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700408 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700409
410 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
411 const char* pkgname = packageName.c_str();
412
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700413 // Assume invalid inode unless filled in below
414 if (_aidl_return != nullptr) *_aidl_return = -1;
415
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700416 int32_t uid = multiuser_get_uid(userId, appId);
417 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700418 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
419
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700420 // If UID doesn't have a specific cache GID, use UID value
421 if (cacheGid == -1) {
422 cacheGid = uid;
423 }
424
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700425 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700426 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700427 bool existing = (access(path.c_str(), F_OK) == 0);
428
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700429 if (prepare_app_dir(path, targetMode, uid) ||
430 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
431 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700432 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600433 }
434
435 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700436 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
437 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
438 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700439 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700440 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600441
442 // Remember inode numbers of cache directories so that we can clear
443 // contents while CE storage is locked
444 if (write_path_inode(path, "cache", kXattrInodeCache) ||
445 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700446 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700447 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700448
449 // And return the CE inode of the top-level data directory so we can
450 // clear contents while CE storage is locked
451 if ((_aidl_return != nullptr)
452 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
453 return error("Failed to get_path_inode for " + path);
454 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700455 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700456 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700457 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700458 bool existing = (access(path.c_str(), F_OK) == 0);
459
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700460 if (prepare_app_dir(path, targetMode, uid) ||
461 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
462 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700463 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700464 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000465
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600466 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600467 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
468 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
469 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700470 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600471 }
472
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600473 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
474 return error("Failed to set hard quota " + path);
475 }
476
Calin Juravled2affb82017-11-28 17:41:43 -0800477 if (!prepare_app_profile_dir(packageName, appId, userId)) {
478 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000479 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700480 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700481 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700482}
483
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700484binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
485 const std::string& packageName, int32_t userId, int32_t flags) {
486 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700487 CHECK_ARGUMENT_UUID(uuid);
488 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700489 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700490
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700491 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
492 const char* pkgname = packageName.c_str();
493
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700494 // This method only exists to upgrade system apps that have requested
495 // forceDeviceEncrypted, so their default storage always lives in a
496 // consistent location. This only works on non-FBE devices, since we
497 // never want to risk exposing data on a device with real CE/DE storage.
498
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700499 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
500 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700501
502 // If neither directory is marked as default, assume CE is default
503 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
504 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
505 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700506 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700507 }
508 }
509
510 // Migrate default data location if needed
511 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
512 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
513
514 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
515 LOG(WARNING) << "Requested default storage " << target
516 << " is not active; migrating from " << source;
517 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700518 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700519 }
520 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700521 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700522 }
523 }
524
Jeff Sharkey423e7462016-12-09 18:18:43 -0700525 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700526}
527
Calin Juravle6a1648e2016-02-01 12:12:16 +0000528
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700529binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
530 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700531 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700532 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700533
Jeff Sharkey423e7462016-12-09 18:18:43 -0700534 binder::Status res = ok();
Calin Juravle114f0812017-03-08 19:05:07 -0800535 if (!clear_primary_reference_profile(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700536 res = error("Failed to clear reference profile for " + packageName);
537 }
Calin Juravle114f0812017-03-08 19:05:07 -0800538 if (!clear_primary_current_profiles(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700539 res = error("Failed to clear current profiles for " + packageName);
540 }
541 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000542}
543
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700544binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
545 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
546 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 CHECK_ARGUMENT_UUID(uuid);
548 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700549 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700550
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700551 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
552 const char* pkgname = packageName.c_str();
553
Jeff Sharkey423e7462016-12-09 18:18:43 -0700554 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700555 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700556 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600557 if (flags & FLAG_CLEAR_CACHE_ONLY) {
558 path = read_path_inode(path, "cache", kXattrInodeCache);
559 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
560 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
561 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700562 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700563 if (delete_dir_contents(path) != 0) {
564 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900565 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
566 remove_path_xattr(path, kXattrInodeCache);
567 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700568 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700569 }
570 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700571 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600572 std::string suffix = "";
573 bool only_cache = false;
574 if (flags & FLAG_CLEAR_CACHE_ONLY) {
575 suffix = CACHE_DIR_POSTFIX;
576 only_cache = true;
577 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
578 suffix = CODE_CACHE_DIR_POSTFIX;
579 only_cache = true;
580 }
581
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700582 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700583 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700584 if (delete_dir_contents(path) != 0) {
585 res = error("Failed to delete contents of " + path);
586 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700587 }
Calin Juravleedae6692016-03-23 13:55:31 +0000588 if (!only_cache) {
Calin Juravle114f0812017-03-08 19:05:07 -0800589 if (!clear_primary_current_profile(packageName, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700590 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000591 }
592 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700593 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700594 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700595}
596
Calin Juravle76268c52017-03-09 13:19:42 -0800597static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100598 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800599 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100600 /*ignore_if_missing*/ true);
601}
602
Calin Juravle76268c52017-03-09 13:19:42 -0800603static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100604 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800605 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100606 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000607}
608
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700609binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
610 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700611 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700612 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700613
Jeff Sharkey423e7462016-12-09 18:18:43 -0700614 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000615 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
616 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800617 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700618 res = error("Failed to destroy current profiles for " + packageName);
619 }
Calin Juravleedae6692016-03-23 13:55:31 +0000620 }
Calin Juravle76268c52017-03-09 13:19:42 -0800621 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700622 res = error("Failed to destroy reference profile for " + packageName);
623 }
624 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000625}
626
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700627binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
628 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
629 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700630 CHECK_ARGUMENT_UUID(uuid);
631 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700632 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700633
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700634 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
635 const char* pkgname = packageName.c_str();
636
Jeff Sharkey423e7462016-12-09 18:18:43 -0700637 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700638 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700639 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
640 if (delete_dir_contents_and_dir(path) != 0) {
641 res = error("Failed to delete " + path);
642 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700643 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700644 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700645 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
646 if (delete_dir_contents_and_dir(path) != 0) {
647 res = error("Failed to delete " + path);
648 }
Calin Juravle76268c52017-03-09 13:19:42 -0800649 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100650 // TODO(calin): If the package is still installed by other users it's probably
651 // beneficial to keep the reference profile around.
652 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800653 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700654 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700655 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700656}
657
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600658static gid_t get_cache_gid(uid_t uid) {
659 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
660 return (gid != -1) ? gid : uid;
661}
662
663binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
664 int32_t flags) {
665 ENFORCE_UID(AID_SYSTEM);
666 CHECK_ARGUMENT_UUID(uuid);
667 std::lock_guard<std::recursive_mutex> lock(mLock);
668
669 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
670 for (auto user : get_known_users(uuid_)) {
671 ATRACE_BEGIN("fixup user");
672 FTS* fts;
673 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600674 auto ce_path = create_data_user_ce_path(uuid_, user);
675 auto de_path = create_data_user_de_path(uuid_, user);
676 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600677 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
678 return error("Failed to fts_open");
679 }
680 while ((p = fts_read(fts)) != nullptr) {
681 if (p->fts_info == FTS_D && p->fts_level == 1) {
682 // Track down inodes of cache directories
683 uint64_t raw = 0;
684 ino_t inode_cache = 0;
685 ino_t inode_code_cache = 0;
686 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
687 inode_cache = raw;
688 }
689 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
690 inode_code_cache = raw;
691 }
692
693 // Figure out expected GID of each child
694 FTSENT* child = fts_children(fts, 0);
695 while (child != nullptr) {
696 if ((child->fts_statp->st_ino == inode_cache)
697 || (child->fts_statp->st_ino == inode_code_cache)
698 || !strcmp(child->fts_name, "cache")
699 || !strcmp(child->fts_name, "code_cache")) {
700 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
701 } else {
702 child->fts_number = p->fts_statp->st_uid;
703 }
704 child = child->fts_link;
705 }
706 } else if (p->fts_level >= 2) {
707 if (p->fts_level > 2) {
708 // Inherit GID from parent once we're deeper into tree
709 p->fts_number = p->fts_parent->fts_number;
710 }
711
712 uid_t uid = p->fts_parent->fts_statp->st_uid;
713 gid_t cache_gid = get_cache_gid(uid);
714 gid_t expected = p->fts_number;
715 gid_t actual = p->fts_statp->st_gid;
716 if (actual == expected) {
717#if FIXUP_DEBUG
718 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
719#endif
720 if (!(flags & FLAG_FORCE)) {
721 fts_set(fts, p, FTS_SKIP);
722 }
723 } else if ((actual == uid) || (actual == cache_gid)) {
724 // Only consider fixing up when current GID belongs to app
725 if (p->fts_info != FTS_D) {
726 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
727 << " instead of " << expected;
728 }
729 switch (p->fts_info) {
730 case FTS_DP:
731 // If we're moving towards cache GID, we need to set S_ISGID
732 if (expected == cache_gid) {
733 if (chmod(p->fts_path, 02771) != 0) {
734 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
735 }
736 }
737 // Intentional fall through to also set GID
738 case FTS_F:
739 if (chown(p->fts_path, -1, expected) != 0) {
740 PLOG(WARNING) << "Failed to chown " << p->fts_path;
741 }
742 break;
743 case FTS_SL:
744 case FTS_SLNONE:
745 if (lchown(p->fts_path, -1, expected) != 0) {
746 PLOG(WARNING) << "Failed to chown " << p->fts_path;
747 }
748 break;
749 }
750 } else {
751 // Ignore all other GID transitions, since they're kinda shady
752 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
753 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -0600754 if (!(flags & FLAG_FORCE)) {
755 fts_set(fts, p, FTS_SKIP);
756 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600757 }
758 }
759 }
760 fts_close(fts);
761 ATRACE_END();
762 }
763 return ok();
764}
765
Jeff Sharkey0274c972016-12-06 09:32:04 -0700766binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
767 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
768 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
769 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700770 ENFORCE_UID(AID_SYSTEM);
771 CHECK_ARGUMENT_UUID(fromUuid);
772 CHECK_ARGUMENT_UUID(toUuid);
773 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700774 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700775
776 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
777 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
778 const char* package_name = packageName.c_str();
779 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700780
Jeff Sharkey423e7462016-12-09 18:18:43 -0700781 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700782 std::vector<userid_t> users = get_known_users(from_uuid);
783
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700784 // Copy app
785 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600786 auto from = create_data_app_package_path(from_uuid, data_app_name);
787 auto to = create_data_app_package_path(to_uuid, data_app_name);
788 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700789
790 char *argv[] = {
791 (char*) kCpPath,
792 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
793 (char*) "-p", /* preserve timestamps, ownership, and permissions */
794 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
795 (char*) "-P", /* Do not follow symlinks [default] */
796 (char*) "-d", /* don't dereference symlinks */
797 (char*) from.c_str(),
798 (char*) to_parent.c_str()
799 };
800
801 LOG(DEBUG) << "Copying " << from << " to " << to;
802 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700803 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700804 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700805 goto fail;
806 }
807
808 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700809 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700810 goto fail;
811 }
812 }
813
814 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700815 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700816
817 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600818 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
819 if (access(from_ce.c_str(), F_OK) != 0) {
820 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700821 continue;
822 }
823
Jeff Sharkey0274c972016-12-06 09:32:04 -0700824 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700825 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700826 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700827 goto fail;
828 }
829
830 char *argv[] = {
831 (char*) kCpPath,
832 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
833 (char*) "-p", /* preserve timestamps, ownership, and permissions */
834 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
835 (char*) "-P", /* Do not follow symlinks [default] */
836 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600837 nullptr,
838 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700839 };
840
Jeff Sharkey51c94492016-05-10 17:46:39 -0600841 {
842 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
843 auto to = create_data_user_de_path(to_uuid, user);
844 argv[6] = (char*) from.c_str();
845 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700846
Jeff Sharkey51c94492016-05-10 17:46:39 -0600847 LOG(DEBUG) << "Copying " << from << " to " << to;
848 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
849 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700850 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600851 goto fail;
852 }
853 }
854 {
855 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
856 auto to = create_data_user_ce_path(to_uuid, user);
857 argv[6] = (char*) from.c_str();
858 argv[7] = (char*) to.c_str();
859
860 LOG(DEBUG) << "Copying " << from << " to " << to;
861 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
862 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700863 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600864 goto fail;
865 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700866 }
867
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700868 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
869 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700870 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700871 goto fail;
872 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700873 }
874
Jeff Sharkey31f08982015-07-07 13:31:37 -0700875 // We let the framework scan the new location and persist that before
876 // deleting the data in the old location; this ordering ensures that
877 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700878 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700879
880fail:
881 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700882 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600883 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700884 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
885 LOG(WARNING) << "Failed to rollback " << to;
886 }
887 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700888 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600889 {
890 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
891 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
892 LOG(WARNING) << "Failed to rollback " << to;
893 }
894 }
895 {
896 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
897 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
898 LOG(WARNING) << "Failed to rollback " << to;
899 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700900 }
901 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700902 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700903}
904
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700905binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
906 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
907 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700908 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700909 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700910
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700911 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600912 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700913 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700914 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700915 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700916 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700917 }
918 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600919
920 // Data under /data/media doesn't have an app, but we still want
921 // to limit it to prevent abuse.
922 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
923 multiuser_get_uid(userId, AID_MEDIA_RW))) {
924 return error("Failed to set hard quota for media_rw");
925 }
926
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700927 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700928}
929
930binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
931 int32_t userId, int32_t flags) {
932 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700933 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700934 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700935
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700936 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700937 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700938 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700939 auto path = create_data_user_de_path(uuid_, userId);
940 if (delete_dir_contents_and_dir(path, true) != 0) {
941 res = error("Failed to delete " + path);
942 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700943 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700944 path = create_data_misc_legacy_path(userId);
945 if (delete_dir_contents_and_dir(path, true) != 0) {
946 res = error("Failed to delete " + path);
947 }
Calin Juravle114f0812017-03-08 19:05:07 -0800948 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700949 if (delete_dir_contents_and_dir(path, true) != 0) {
950 res = error("Failed to delete " + path);
951 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700952 }
Robin Lee095c7632014-04-25 15:05:19 +0100953 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600954 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700955 auto path = create_data_user_ce_path(uuid_, userId);
956 if (delete_dir_contents_and_dir(path, true) != 0) {
957 res = error("Failed to delete " + path);
958 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600959 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700960 if (delete_dir_contents_and_dir(path, true) != 0) {
961 res = error("Failed to delete " + path);
962 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600963 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700964 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100965}
966
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700967binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600968 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700969 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700970 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700971 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700972
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700973 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700974 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700975 auto device = findQuotaDeviceForUuid(uuid);
976 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700977
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700978 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700979 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700980 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700981 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700982
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600983 int64_t cleared = 0;
984 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600985 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600986 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600987
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600988 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600989 return ok();
990 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700991
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700992 if (flags & FLAG_FREE_CACHE_V2) {
993 // This new cache strategy fairly removes files from UIDs by deleting
994 // files from the UIDs which are most over their allocated quota
995
996 // 1. Create trackers for every known UID
997 ATRACE_BEGIN("create");
998 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
999 for (auto user : get_known_users(uuid_)) {
1000 FTS *fts;
1001 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001002 auto ce_path = create_data_user_ce_path(uuid_, user);
1003 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001004 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
1005 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
1006 (char*) media_path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001007 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001008 return error("Failed to fts_open");
1009 }
1010 while ((p = fts_read(fts)) != NULL) {
1011 if (p->fts_info == FTS_D && p->fts_level == 1) {
1012 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001013 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
1014 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
1015 + AID_APP_START;
1016 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001017 auto search = trackers.find(uid);
1018 if (search != trackers.end()) {
1019 search->second->addDataPath(p->fts_path);
1020 } else {
1021 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
1022 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
1023 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001024 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001025 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001026 tracker->cacheQuota = mCacheQuotas[uid];
1027 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001028 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001029#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001030 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001031#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001032 tracker->cacheQuota = 67108864;
1033 }
1034 trackers[uid] = tracker;
1035 }
1036 fts_set(fts, p, FTS_SKIP);
1037 }
1038 }
1039 fts_close(fts);
1040 }
1041 ATRACE_END();
1042
1043 // 2. Populate tracker stats and insert into priority queue
1044 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001045 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001046 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1047 return (left->getCacheRatio() < right->getCacheRatio());
1048 };
1049 std::priority_queue<std::shared_ptr<CacheTracker>,
1050 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1051 for (const auto& it : trackers) {
1052 it.second->loadStats();
1053 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001054 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001055 }
1056 ATRACE_END();
1057
1058 // 3. Bounce across the queue, freeing items from whichever tracker is
1059 // the most over their assigned quota
1060 ATRACE_BEGIN("bounce");
1061 std::shared_ptr<CacheTracker> active;
1062 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001063 // Only look at apps under quota when explicitly requested
1064 if (active && (active->getCacheRatio() < 10000)
1065 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1066 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1067 << " isn't over quota, and defy not requested";
1068 break;
1069 }
1070
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001071 // Only keep clearing when we haven't pushed into reserved area
1072 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1073 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1074 break;
1075 }
1076
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001077 // Find the best tracker to work with; this might involve swapping
1078 // if the active tracker is no longer the most over quota
1079 bool nextBetter = active && !queue.empty()
1080 && active->getCacheRatio() < queue.top()->getCacheRatio();
1081 if (!active || nextBetter) {
1082 if (active) {
1083 // Current tracker still has items, so we'll consider it
1084 // again later once it bubbles up to surface
1085 queue.push(active);
1086 }
1087 active = queue.top(); queue.pop();
1088 active->ensureItems();
1089 continue;
1090 }
1091
1092 // If no items remain, go find another tracker
1093 if (active->items.empty()) {
1094 active = nullptr;
1095 continue;
1096 } else {
1097 auto item = active->items.back();
1098 active->items.pop_back();
1099
1100 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1101 if (!noop) {
1102 item->purge();
1103 }
1104 active->cacheUsed -= item->size;
1105 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001106 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001107 }
1108
1109 // Verify that we're actually done before bailing, since sneaky
1110 // apps might be using hardlinks
1111 if (needed <= 0) {
1112 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001113 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001114 if (needed <= 0) {
1115 break;
1116 } else {
1117 LOG(WARNING) << "Expected to be done but still need " << needed;
1118 }
1119 }
1120 }
1121 ATRACE_END();
1122
1123 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001124 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001125 }
1126
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001127 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001128 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001129 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001130 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001131 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001132 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001133 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001134}
1135
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001136binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1137 const std::string& instructionSet) {
1138 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001139 std::lock_guard<std::recursive_mutex> lock(mLock);
1140
Mike Lockwood94afecf2012-10-24 10:45:23 -07001141 char dex_path[PKG_PATH_MAX];
1142
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001143 const char* path = codePath.c_str();
1144 const char* instruction_set = instructionSet.c_str();
1145
Jeff Sharkey770180a2014-09-08 17:14:26 -07001146 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001147 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001148 }
1149
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001150 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001151 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001152 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001153
1154 ALOGV("unlink %s\n", dex_path);
1155 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001156 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1157 // but could not be unlinked.
1158 if (errno != ENOENT) {
1159 return error(StringPrintf("Failed to unlink %s", dex_path));
1160 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001161 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001162 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001163}
1164
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001165struct stats {
1166 int64_t codeSize;
1167 int64_t dataSize;
1168 int64_t cacheSize;
1169};
1170
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001171#if MEASURE_DEBUG
1172static std::string toString(std::vector<int64_t> values) {
1173 std::stringstream res;
1174 res << "[";
1175 for (size_t i = 0; i < values.size(); i++) {
1176 res << values[i];
1177 if (i < values.size() - 1) {
1178 res << ",";
1179 }
1180 }
1181 res << "]";
1182 return res.str();
1183}
1184#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001185
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001186static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001187 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001188 if (device.empty()) return;
1189
1190 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001191
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001192 if (stats != nullptr) {
1193 uid_t uid = multiuser_get_uid(userId, appId);
1194 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001195 reinterpret_cast<char*>(&dq)) != 0) {
1196 if (errno != ESRCH) {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001197 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001198 }
1199 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001200#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001201 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001202#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001203 stats->dataSize += dq.dqb_curspace;
1204 }
1205
1206 int cacheGid = multiuser_get_cache_gid(userId, appId);
1207 if (cacheGid != -1) {
1208 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1209 reinterpret_cast<char*>(&dq)) != 0) {
1210 if (errno != ESRCH) {
1211 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1212 }
1213 } else {
1214#if MEASURE_DEBUG
1215 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1216#endif
1217 stats->cacheSize += dq.dqb_curspace;
1218 }
1219 }
1220
1221 int sharedGid = multiuser_get_shared_gid(0, appId);
1222 if (sharedGid != -1) {
1223 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1224 reinterpret_cast<char*>(&dq)) != 0) {
1225 if (errno != ESRCH) {
1226 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1227 }
1228 } else {
1229#if MEASURE_DEBUG
1230 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1231#endif
1232 stats->codeSize += dq.dqb_curspace;
1233 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001234 }
1235 }
1236
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001237 if (extStats != nullptr) {
1238 int extGid = multiuser_get_ext_gid(userId, appId);
1239 if (extGid != -1) {
1240 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1241 reinterpret_cast<char*>(&dq)) != 0) {
1242 if (errno != ESRCH) {
1243 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1244 }
1245 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001246#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001247 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001248#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001249 extStats->dataSize += dq.dqb_curspace;
1250 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001251 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001252
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001253 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1254 if (extCacheGid != -1) {
1255 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extCacheGid,
1256 reinterpret_cast<char*>(&dq)) != 0) {
1257 if (errno != ESRCH) {
1258 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extCacheGid;
1259 }
1260 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001261#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001262 LOG(DEBUG) << "quotactl() for GID " << extCacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001263#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001264 extStats->dataSize += dq.dqb_curspace;
1265 extStats->cacheSize += dq.dqb_curspace;
1266 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001267 }
1268 }
1269}
1270
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001271static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001272 DIR *d;
1273 int dfd;
1274 struct dirent *de;
1275 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001276
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001277 d = opendir(path.c_str());
1278 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001279 if (errno != ENOENT) {
1280 PLOG(WARNING) << "Failed to open " << path;
1281 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001282 return;
1283 }
1284 dfd = dirfd(d);
1285 while ((de = readdir(d))) {
1286 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001287
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001288 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001289 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001290 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001291 }
1292
1293 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001294 if (!strcmp(name, ".")) {
1295 // Don't recurse, but still count node size
1296 } else if (!strcmp(name, "..")) {
1297 // Don't recurse or count node size
1298 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001299 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001300 // Measure all children nodes
1301 size = 0;
1302 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001303 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001304
1305 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1306 stats->cacheSize += size;
1307 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001308 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001309
1310 // Legacy symlink isn't owned by app
1311 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1312 continue;
1313 }
1314
1315 // Everything found inside is considered data
1316 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001317 }
1318 closedir(d);
1319}
1320
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001321static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1322 bool exclude_apps = false) {
1323 DIR *d;
1324 int dfd;
1325 struct dirent *de;
1326 struct stat s;
1327
1328 d = opendir(path.c_str());
1329 if (d == nullptr) {
1330 if (errno != ENOENT) {
1331 PLOG(WARNING) << "Failed to open " << path;
1332 }
1333 return;
1334 }
1335 dfd = dirfd(d);
1336 while ((de = readdir(d))) {
1337 if (de->d_type == DT_DIR) {
1338 const char *name = de->d_name;
1339 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1340 continue;
1341 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001342 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001343 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1344 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001345 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001346 continue;
1347 } else {
1348 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1349 }
1350 }
1351 }
1352 closedir(d);
1353}
1354
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001355static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1356 FTS *fts;
1357 FTSENT *p;
1358 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001359 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001360 PLOG(ERROR) << "Failed to fts_open " << path;
1361 return;
1362 }
1363 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001364 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001365 switch (p->fts_info) {
1366 case FTS_D:
1367 if (p->fts_level == 4
1368 && !strcmp(p->fts_name, "cache")
1369 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1370 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1371 p->fts_number = 1;
1372 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001373 // Fall through to count the directory
1374 case FTS_DEFAULT:
1375 case FTS_F:
1376 case FTS_SL:
1377 case FTS_SLNONE:
1378 int64_t size = (p->fts_statp->st_blocks * 512);
1379 if (p->fts_number == 1) {
1380 stats->cacheSize += size;
1381 }
1382 stats->dataSize += size;
1383 break;
1384 }
1385 }
1386 fts_close(fts);
1387}
1388
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001389binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001390 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1391 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1392 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001393 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001394 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001395 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001396 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1397 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001398 // NOTE: Locking is relaxed on this method, since it's limited to
1399 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001400
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001401 // When modifying this logic, always verify using tests:
1402 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1403
1404#if MEASURE_DEBUG
1405 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1406#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001407
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001408 // Here's a summary of the common storage locations across the platform,
1409 // and how they're each tagged:
1410 //
1411 // /data/app/com.example UID system
1412 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001413 // /data/user/0/com.example UID u0_a10 GID u0_a10
1414 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1415 // /data/media/0/foo.txt UID u0_media_rw
1416 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1417 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1418 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1419 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001420
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001421 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001422 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001423 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001424 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001425
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001426 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001427
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001428 auto device = findQuotaDeviceForUuid(uuid);
1429 if (device.empty()) {
1430 flags &= ~FLAG_USE_QUOTA;
1431 }
1432
Jeff Sharkey466459b2017-01-17 15:25:01 -07001433 ATRACE_BEGIN("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001434 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001435 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1436 calculate_tree_size(obbCodePath, &extStats.codeSize);
1437 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001438 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001439
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001440 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001441 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001442 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001443 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001444 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001445 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001446 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001447
Jeff Sharkey466459b2017-01-17 15:25:01 -07001448 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001449 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001450 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001451 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001452 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001453 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001454 calculate_tree_size(codePath, &stats.codeSize);
1455 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001456 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001457
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001458 for (size_t i = 0; i < packageNames.size(); i++) {
1459 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001460
Jeff Sharkey466459b2017-01-17 15:25:01 -07001461 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001462 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1463 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001464 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1465 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001466 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001467
Jeff Sharkey06a61842017-04-15 12:03:31 -06001468 if (!uuid) {
1469 ATRACE_BEGIN("profiles");
1470 calculate_tree_size(
1471 create_primary_current_profile_package_dir_path(userId, pkgname),
1472 &stats.dataSize);
1473 calculate_tree_size(
1474 create_primary_reference_profile_package_dir_path(pkgname),
1475 &stats.codeSize);
1476 ATRACE_END();
1477 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001478
Jeff Sharkey466459b2017-01-17 15:25:01 -07001479 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001480 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001481 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001482 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001483 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001484 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001485 }
1486
Jeff Sharkey06a61842017-04-15 12:03:31 -06001487 if (!uuid) {
1488 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001489 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001490 if (sharedGid != -1) {
1491 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1492 sharedGid, -1);
1493 }
1494 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001495 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001496 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001497
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001498 std::vector<int64_t> ret;
1499 ret.push_back(stats.codeSize);
1500 ret.push_back(stats.dataSize);
1501 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001502 ret.push_back(extStats.codeSize);
1503 ret.push_back(extStats.dataSize);
1504 ret.push_back(extStats.cacheSize);
1505#if MEASURE_DEBUG
1506 LOG(DEBUG) << "Final result " << toString(ret);
1507#endif
1508 *_aidl_return = ret;
1509 return ok();
1510}
1511
1512binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1513 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1514 std::vector<int64_t>* _aidl_return) {
1515 ENFORCE_UID(AID_SYSTEM);
1516 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001517 // NOTE: Locking is relaxed on this method, since it's limited to
1518 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001519
1520 // When modifying this logic, always verify using tests:
1521 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1522
1523#if MEASURE_DEBUG
1524 LOG(INFO) << "Measuring user " << userId;
1525#endif
1526
1527 struct stats stats;
1528 struct stats extStats;
1529 memset(&stats, 0, sizeof(stats));
1530 memset(&extStats, 0, sizeof(extStats));
1531
1532 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1533
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001534 auto device = findQuotaDeviceForUuid(uuid);
1535 if (device.empty()) {
1536 flags &= ~FLAG_USE_QUOTA;
1537 }
1538
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001539 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001540 struct dqblk dq;
1541
1542 ATRACE_BEGIN("obb");
1543 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1544 reinterpret_cast<char*>(&dq)) != 0) {
1545 if (errno != ESRCH) {
1546 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1547 }
1548 } else {
1549#if MEASURE_DEBUG
1550 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1551#endif
1552 extStats.codeSize += dq.dqb_curspace;
1553 }
1554 ATRACE_END();
1555
Jeff Sharkey466459b2017-01-17 15:25:01 -07001556 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001557 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001558 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001559
Jeff Sharkey466459b2017-01-17 15:25:01 -07001560 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001561 auto cePath = create_data_user_ce_path(uuid_, userId);
1562 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001563 auto dePath = create_data_user_de_path(uuid_, userId);
1564 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001565 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001566
Jeff Sharkey06a61842017-04-15 12:03:31 -06001567 if (!uuid) {
1568 ATRACE_BEGIN("profile");
1569 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1570 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1571 auto refProfilePath = create_primary_ref_profile_dir_path();
1572 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1573 ATRACE_END();
1574 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001575
Jeff Sharkey466459b2017-01-17 15:25:01 -07001576 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001577 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1578 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1579 reinterpret_cast<char*>(&dq)) != 0) {
1580 if (errno != ESRCH) {
1581 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1582 }
1583 } else {
1584#if MEASURE_DEBUG
1585 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001586#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001587 extStats.dataSize += dq.dqb_curspace;
1588 }
1589 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001590
Jeff Sharkey06a61842017-04-15 12:03:31 -06001591 if (!uuid) {
1592 ATRACE_BEGIN("dalvik");
1593 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1594 -1, -1, true);
1595 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1596 -1, -1, true);
1597 ATRACE_END();
1598 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001599
Jeff Sharkey466459b2017-01-17 15:25:01 -07001600 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001601 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001602 for (auto appId : appIds) {
1603 if (appId >= AID_APP_START) {
1604 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001605
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001606#if MEASURE_DEBUG
1607 // Sleep to make sure we don't lose logs
1608 usleep(1);
1609#endif
1610 }
1611 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001612 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001613 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001614 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001615 ATRACE_BEGIN("obb");
1616 auto obbPath = create_data_path(uuid_) + "/media/obb";
1617 calculate_tree_size(obbPath, &extStats.codeSize);
1618 ATRACE_END();
1619
Jeff Sharkey466459b2017-01-17 15:25:01 -07001620 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001621 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001622 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001623
Jeff Sharkey466459b2017-01-17 15:25:01 -07001624 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001625 auto cePath = create_data_user_ce_path(uuid_, userId);
1626 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001627 auto dePath = create_data_user_de_path(uuid_, userId);
1628 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001629 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001630
Jeff Sharkey06a61842017-04-15 12:03:31 -06001631 if (!uuid) {
1632 ATRACE_BEGIN("profile");
1633 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1634 calculate_tree_size(userProfilePath, &stats.dataSize);
1635 auto refProfilePath = create_primary_ref_profile_dir_path();
1636 calculate_tree_size(refProfilePath, &stats.codeSize);
1637 ATRACE_END();
1638 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001639
Jeff Sharkey466459b2017-01-17 15:25:01 -07001640 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001641 auto dataMediaPath = create_data_media_path(uuid_, userId);
1642 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1643#if MEASURE_DEBUG
1644 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1645 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001646#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001647 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001648
Jeff Sharkey06a61842017-04-15 12:03:31 -06001649 if (!uuid) {
1650 ATRACE_BEGIN("dalvik");
1651 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1652 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1653 ATRACE_END();
1654 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001655 }
1656
1657 std::vector<int64_t> ret;
1658 ret.push_back(stats.codeSize);
1659 ret.push_back(stats.dataSize);
1660 ret.push_back(stats.cacheSize);
1661 ret.push_back(extStats.codeSize);
1662 ret.push_back(extStats.dataSize);
1663 ret.push_back(extStats.cacheSize);
1664#if MEASURE_DEBUG
1665 LOG(DEBUG) << "Final result " << toString(ret);
1666#endif
1667 *_aidl_return = ret;
1668 return ok();
1669}
1670
1671binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001672 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1673 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001674 ENFORCE_UID(AID_SYSTEM);
1675 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001676 // NOTE: Locking is relaxed on this method, since it's limited to
1677 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001678
1679 // When modifying this logic, always verify using tests:
1680 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1681
1682#if MEASURE_DEBUG
1683 LOG(INFO) << "Measuring external " << userId;
1684#endif
1685
1686 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1687
1688 int64_t totalSize = 0;
1689 int64_t audioSize = 0;
1690 int64_t videoSize = 0;
1691 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001692 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001693 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001694
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001695 auto device = findQuotaDeviceForUuid(uuid);
1696 if (device.empty()) {
1697 flags &= ~FLAG_USE_QUOTA;
1698 }
1699
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001700 if (flags & FLAG_USE_QUOTA) {
1701 struct dqblk dq;
1702
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001703 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001704 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1705 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1706 reinterpret_cast<char*>(&dq)) != 0) {
1707 if (errno != ESRCH) {
1708 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1709 }
1710 } else {
1711#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001712 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001713#endif
1714 totalSize = dq.dqb_curspace;
1715 }
1716
1717 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1718 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1719 reinterpret_cast<char*>(&dq)) == 0) {
1720#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001721 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001722#endif
1723 audioSize = dq.dqb_curspace;
1724 }
1725 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1726 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1727 reinterpret_cast<char*>(&dq)) == 0) {
1728#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001729 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001730#endif
1731 videoSize = dq.dqb_curspace;
1732 }
1733 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1734 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1735 reinterpret_cast<char*>(&dq)) == 0) {
1736#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001737 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001738#endif
1739 imageSize = dq.dqb_curspace;
1740 }
Jeff Sharkeya0136982017-07-06 11:29:37 -06001741 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1742 reinterpret_cast<char*>(&dq)) == 0) {
1743#if MEASURE_DEBUG
1744 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1745#endif
1746 obbSize = dq.dqb_curspace;
1747 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001748 ATRACE_END();
1749
1750 ATRACE_BEGIN("apps");
1751 struct stats extStats;
1752 memset(&extStats, 0, sizeof(extStats));
1753 for (auto appId : appIds) {
1754 if (appId >= AID_APP_START) {
1755 collectQuotaStats(device, userId, appId, nullptr, &extStats);
1756 }
1757 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001758 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001759 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001760 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001761 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001762 FTS *fts;
1763 FTSENT *p;
1764 auto path = create_data_media_path(uuid_, userId);
1765 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001766 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001767 return error("Failed to fts_open " + path);
1768 }
1769 while ((p = fts_read(fts)) != NULL) {
1770 char* ext;
1771 int64_t size = (p->fts_statp->st_blocks * 512);
1772 switch (p->fts_info) {
1773 case FTS_F:
1774 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001775 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001776 ext = strrchr(p->fts_name, '.');
1777 if (ext != nullptr) {
1778 switch (MatchExtension(++ext)) {
1779 case AID_MEDIA_AUDIO: audioSize += size; break;
1780 case AID_MEDIA_VIDEO: videoSize += size; break;
1781 case AID_MEDIA_IMAGE: imageSize += size; break;
1782 }
1783 }
1784 }
1785 // Fall through to always count against total
1786 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001787 // Ignore data belonging to specific apps
1788 p->fts_number = p->fts_parent->fts_number;
1789 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1790 p->fts_number = 1;
1791 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001792 case FTS_DEFAULT:
1793 case FTS_SL:
1794 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001795 if (p->fts_parent->fts_number == 1) {
1796 appSize += size;
1797 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001798 totalSize += size;
1799 break;
1800 }
1801 }
1802 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001803 ATRACE_END();
Jeff Sharkeya0136982017-07-06 11:29:37 -06001804
1805 ATRACE_BEGIN("obb");
1806 auto obbPath = create_data_media_obb_path(uuid_, "");
1807 calculate_tree_size(obbPath, &obbSize);
1808 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001809 }
1810
1811 std::vector<int64_t> ret;
1812 ret.push_back(totalSize);
1813 ret.push_back(audioSize);
1814 ret.push_back(videoSize);
1815 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001816 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06001817 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001818#if MEASURE_DEBUG
1819 LOG(DEBUG) << "Final result " << toString(ret);
1820#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001821 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001822 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001823}
1824
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001825binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1826 int32_t userId, int32_t appId, int64_t cacheQuota) {
1827 ENFORCE_UID(AID_SYSTEM);
1828 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001829 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001830
1831 int32_t uid = multiuser_get_uid(userId, appId);
1832 mCacheQuotas[uid] = cacheQuota;
1833
1834 return ok();
1835}
1836
David Sehr6727c2d2016-05-17 16:06:22 -07001837// Dumps the contents of a profile file, using pkgname's dex files for pretty
1838// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001839binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1840 const std::string& codePaths, bool* _aidl_return) {
1841 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001842 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001843 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001844
1845 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001846 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001847
Jeff Sharkey90aff262016-12-12 14:28:24 -07001848 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001849 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001850}
1851
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001852// Copy the contents of a system profile over the data profile.
1853binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
1854 int32_t packageUid, const std::string& packageName, bool* _aidl_return) {
1855 ENFORCE_UID(AID_SYSTEM);
1856 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1857 std::lock_guard<std::recursive_mutex> lock(mLock);
1858 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName);
1859 return ok();
1860}
1861
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001862// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001863binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001864 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001865 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001866 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001867 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001868
Calin Juravle114f0812017-03-08 19:05:07 -08001869 *_aidl_return = analyze_primary_profiles(uid, packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001870 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001871}
1872
Calin Juravlec41dac22017-12-05 12:29:15 -08001873binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
1874 const std::string& packageName, const std::string& codePath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08001875 ENFORCE_UID(AID_SYSTEM);
1876 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1877 std::lock_guard<std::recursive_mutex> lock(mLock);
1878
Calin Juravlec41dac22017-12-05 12:29:15 -08001879 *_aidl_return = create_profile_snapshot(appId, packageName, codePath);
Calin Juravle29591732017-11-20 17:46:19 -08001880 return ok();
1881}
1882
1883binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
1884 const std::string& codePath) {
1885 ENFORCE_UID(AID_SYSTEM);
1886 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1887 std::lock_guard<std::recursive_mutex> lock(mLock);
1888
1889 std::string snapshot = create_snapshot_profile_path(packageName, codePath);
1890 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
1891 return error("Failed to destroy profile snapshot for " + packageName + ":" + codePath);
1892 }
1893 return ok();
1894}
1895
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001896binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1897 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1898 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1899 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle1d667612017-07-13 22:50:21 -07001900 const std::unique_ptr<std::string>& classLoaderContext,
David Brazdil570d3982018-01-16 20:15:43 +00001901 const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001902 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001903 CHECK_ARGUMENT_UUID(uuid);
1904 if (packageName && *packageName != "*") {
1905 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1906 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001907 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001908
1909 const char* apk_path = apkPath.c_str();
1910 const char* pkgname = packageName ? packageName->c_str() : "*";
1911 const char* instruction_set = instructionSet.c_str();
1912 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1913 const char* compiler_filter = compilerFilter.c_str();
1914 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
Calin Juravle1d667612017-07-13 22:50:21 -07001915 const char* class_loader_context = classLoaderContext ? classLoaderContext->c_str() : nullptr;
Calin Juravlecb556e32017-04-04 20:22:50 -07001916 const char* se_info = seInfo ? seInfo->c_str() : nullptr;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001917 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07001918 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
David Brazdil570d3982018-01-16 20:15:43 +00001919 downgrade, targetSdkVersion);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001920 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001921}
1922
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001923binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1924 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001925 std::lock_guard<std::recursive_mutex> lock(mLock);
1926
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001927 const char* instruction_set = instructionSet.c_str();
1928
1929 char boot_marker_path[PKG_PATH_MAX];
1930 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001931 "%s/%s/%s/.booting",
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -06001932 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08001933 DALVIK_CACHE,
1934 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001935
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001936 ALOGV("mark_boot_complete : %s", boot_marker_path);
1937 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001938 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001939 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001940 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001941}
1942
Mike Lockwood94afecf2012-10-24 10:45:23 -07001943void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1944 struct stat* statbuf)
1945{
1946 while (path[basepos] != 0) {
1947 if (path[basepos] == '/') {
1948 path[basepos] = 0;
1949 if (lstat(path, statbuf) < 0) {
1950 ALOGV("Making directory: %s\n", path);
1951 if (mkdir(path, mode) == 0) {
1952 chown(path, uid, gid);
1953 } else {
1954 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1955 }
1956 }
1957 path[basepos] = '/';
1958 basepos++;
1959 }
1960 basepos++;
1961 }
1962}
1963
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001964binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1965 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1966 const std::string& nativeLibPath32, int32_t userId) {
1967 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001968 CHECK_ARGUMENT_UUID(uuid);
1969 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001970 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001971
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001972 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1973 const char* pkgname = packageName.c_str();
1974 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001975 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001976 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001977
Jeff Sharkey423e7462016-12-09 18:18:43 -07001978 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1979 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001980
1981 const char* pkgdir = _pkgdir.c_str();
1982 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001983
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001984 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001985 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001986 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001987
1988 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001989 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001990 }
1991
1992 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001993 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001994 goto out;
1995 }
1996
1997 if (lstat(libsymlink, &libStat) < 0) {
1998 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001999 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002000 goto out;
2001 }
2002 } else {
2003 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002004 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002005 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002006 goto out;
2007 }
2008 } else if (S_ISLNK(libStat.st_mode)) {
2009 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002010 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002011 goto out;
2012 }
2013 }
2014 }
2015
2016 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002017 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002018 goto out;
2019 }
2020
2021out:
2022 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002023 auto msg = "Failed to cleanup chmod " + _pkgdir;
2024 if (res.isOk()) {
2025 res = error(msg);
2026 } else {
2027 PLOG(ERROR) << msg;
2028 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002029 }
2030
2031 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002032 auto msg = "Failed to cleanup chown " + _pkgdir;
2033 if (res.isOk()) {
2034 res = error(msg);
2035 } else {
2036 PLOG(ERROR) << msg;
2037 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002038 }
2039
Jeff Sharkey423e7462016-12-09 18:18:43 -07002040 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002041}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002042
2043static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2044{
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002045 execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
2046 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
2047 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2048}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002049
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002050static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2051{
2052 execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
2053 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
2054 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2055}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002056
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002057static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
2058 const char* idmap_path, int32_t uid) {
2059 int idmap_fd = open(idmap_path, O_RDWR);
2060 if (idmap_fd < 0) {
2061 PLOG(ERROR) << "idmap open failed: " << idmap_path;
2062 unlink(idmap_path);
2063 return true;
2064 }
2065
2066 pid_t pid;
2067 pid = fork();
2068 if (pid == 0) {
2069 /* child -- drop privileges before continuing */
2070 if (setgid(uid) != 0) {
2071 LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
2072 exit(1);
2073 }
2074 if (setuid(uid) != 0) {
2075 LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
2076 exit(1);
2077 }
2078 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2079 PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
2080 exit(1);
2081 }
2082
2083 run_verify_idmap(target_apk, overlay_apk, idmap_fd);
2084 exit(1); /* only if exec call to deleting stale idmap failed */
2085 } else {
2086 int status = wait_child(pid);
2087 close(idmap_fd);
2088
2089 if (status != 0) {
2090 // Failed on verifying if idmap is made from target_apk and overlay_apk.
2091 LOG(DEBUG) << "delete stale idmap: " << idmap_path;
2092 unlink(idmap_path);
2093 return true;
2094 }
2095 }
2096 return false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002097}
2098
2099// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2100// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2101static int flatten_path(const char *prefix, const char *suffix,
2102 const char *overlay_path, char *idmap_path, size_t N)
2103{
2104 if (overlay_path == NULL || idmap_path == NULL) {
2105 return -1;
2106 }
2107 const size_t len_overlay_path = strlen(overlay_path);
2108 // will access overlay_path + 1 further below; requires absolute path
2109 if (len_overlay_path < 2 || *overlay_path != '/') {
2110 return -1;
2111 }
2112 const size_t len_idmap_root = strlen(prefix);
2113 const size_t len_suffix = strlen(suffix);
2114 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2115 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2116 // additions below would cause overflow
2117 return -1;
2118 }
2119 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2120 return -1;
2121 }
2122 memset(idmap_path, 0, N);
2123 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2124 char *ch = idmap_path + len_idmap_root;
2125 while (*ch != '\0') {
2126 if (*ch == '/') {
2127 *ch = '@';
2128 }
2129 ++ch;
2130 }
2131 return 0;
2132}
2133
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002134binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2135 const std::string& overlayApkPath, int32_t uid) {
2136 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002137 std::lock_guard<std::recursive_mutex> lock(mLock);
2138
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002139 const char* target_apk = targetApkPath.c_str();
2140 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002141 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2142
2143 int idmap_fd = -1;
2144 char idmap_path[PATH_MAX];
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002145 struct stat idmap_stat;
2146 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002147
2148 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2149 idmap_path, sizeof(idmap_path)) == -1) {
2150 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2151 goto fail;
2152 }
2153
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002154 if (stat(idmap_path, &idmap_stat) < 0) {
2155 outdated = true;
2156 } else {
2157 outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2158 }
2159
2160 if (outdated) {
2161 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2162 } else {
2163 idmap_fd = open(idmap_path, O_RDWR);
2164 }
2165
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002166 if (idmap_fd < 0) {
2167 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2168 goto fail;
2169 }
2170 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2171 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2172 goto fail;
2173 }
2174 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2175 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2176 goto fail;
2177 }
2178
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002179 if (!outdated) {
2180 close(idmap_fd);
2181 return ok();
2182 }
2183
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002184 pid_t pid;
2185 pid = fork();
2186 if (pid == 0) {
2187 /* child -- drop privileges before continuing */
2188 if (setgid(uid) != 0) {
2189 ALOGE("setgid(%d) failed during idmap\n", uid);
2190 exit(1);
2191 }
2192 if (setuid(uid) != 0) {
2193 ALOGE("setuid(%d) failed during idmap\n", uid);
2194 exit(1);
2195 }
2196 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2197 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2198 exit(1);
2199 }
2200
2201 run_idmap(target_apk, overlay_apk, idmap_fd);
2202 exit(1); /* only if exec call to idmap failed */
2203 } else {
2204 int status = wait_child(pid);
2205 if (status != 0) {
2206 ALOGE("idmap failed, status=0x%04x\n", status);
2207 goto fail;
2208 }
2209 }
2210
2211 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002212 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002213fail:
2214 if (idmap_fd >= 0) {
2215 close(idmap_fd);
2216 unlink(idmap_path);
2217 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002218 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002219}
Robert Craige9887e42014-02-20 10:25:56 -05002220
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002221binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
2222 const char* overlay_apk = overlayApkPath.c_str();
2223 char idmap_path[PATH_MAX];
2224
2225 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2226 idmap_path, sizeof(idmap_path)) == -1) {
2227 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2228 return error();
2229 }
2230 if (unlink(idmap_path) < 0) {
2231 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2232 return error();
2233 }
2234 return ok();
2235}
2236
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002237binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2238 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2239 const std::string& seInfo) {
2240 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002241 CHECK_ARGUMENT_UUID(uuid);
2242 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002243 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002244
2245 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002246
Robert Craigda30dc72014-03-27 10:21:12 -04002247 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002248 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002249 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2250 const char* pkgName = packageName.c_str();
2251 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002252
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002253 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002254 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002255 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002256 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002257 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002258 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002259 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002260 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002261 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002262 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002263 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002264 }
Robert Craige9887e42014-02-20 10:25:56 -05002265 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002266 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002267}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002268
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002269binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2270 const std::string& instructionSet) {
2271 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002272 std::lock_guard<std::recursive_mutex> lock(mLock);
2273
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002274 const char* oat_dir = oatDir.c_str();
2275 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002276 char oat_instr_dir[PKG_PATH_MAX];
2277
2278 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002279 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002280 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002281 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002282 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002283 }
2284 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002285 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002286 }
2287 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002288 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002289 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002290 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002291 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002292}
2293
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002294binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2295 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002296 std::lock_guard<std::recursive_mutex> lock(mLock);
2297
Jeff Sharkey423e7462016-12-09 18:18:43 -07002298 if (validate_apk_path(packageDir.c_str())) {
2299 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002300 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002301 if (delete_dir_contents_and_dir(packageDir) != 0) {
2302 return error("Failed to delete " + packageDir);
2303 }
2304 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002305}
2306
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002307binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2308 const std::string& fromBase, const std::string& toBase) {
2309 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002310 std::lock_guard<std::recursive_mutex> lock(mLock);
2311
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002312 const char* relative_path = relativePath.c_str();
2313 const char* from_base = fromBase.c_str();
2314 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002315 char from_path[PKG_PATH_MAX];
2316 char to_path[PKG_PATH_MAX];
2317 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2318 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2319
2320 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002321 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002322 }
2323
2324 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002325 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002326 }
2327
Jeff Sharkey423e7462016-12-09 18:18:43 -07002328 if (link(from_path, to_path) < 0) {
2329 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002330 }
2331
Jeff Sharkey423e7462016-12-09 18:18:43 -07002332 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002333}
2334
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002335binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2336 const std::string& instructionSet, const std::string& outputPath) {
2337 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002338 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002339
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002340 const char* apk_path = apkPath.c_str();
2341 const char* instruction_set = instructionSet.c_str();
2342 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002343
Jeff Sharkey90aff262016-12-12 14:28:24 -07002344 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002345 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002346}
2347
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002348binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002349 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002350 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002351 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002352
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002353 const char* apk_path = apkPath.c_str();
2354 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002355 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002356
Jeff Sharkey90aff262016-12-12 14:28:24 -07002357 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2358 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002359}
2360
Victor Hsieh99de5162017-10-06 14:44:14 -07002361binder::Status InstalldNativeService::installApkVerity(const std::string& /*filePath*/,
2362 const ::android::base::unique_fd& /*verityInput*/) {
2363 ENFORCE_UID(AID_SYSTEM);
2364 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2365 return ok();
2366 }
2367 // TODO: Append verity to filePath then issue ioctl to enable
2368 // it and hide the tree. See b/30972906.
2369 return error("not implemented yet");
2370}
2371
Calin Juravlebd968362017-01-25 01:17:17 -08002372binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2373 const std::string& dexPath, const std::string& packageName, int32_t uid,
2374 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2375 int32_t storage_flag, bool* _aidl_return) {
2376 ENFORCE_UID(AID_SYSTEM);
2377 CHECK_ARGUMENT_UUID(volumeUuid);
2378 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2379
2380 std::lock_guard<std::recursive_mutex> lock(mLock);
2381 bool result = android::installd::reconcile_secondary_dex_file(
2382 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2383 return result ? ok() : error();
2384}
2385
Alan Stokes753dc712017-10-16 10:56:00 +01002386binder::Status InstalldNativeService::hashSecondaryDexFile(
2387 const std::string& dexPath, const std::string& packageName, int32_t uid,
2388 const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
2389 std::vector<uint8_t>* _aidl_return) {
2390 ENFORCE_UID(AID_SYSTEM);
2391 CHECK_ARGUMENT_UUID(volumeUuid);
2392 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2393
2394 // mLock is not taken here since we will never modify the file system.
2395 // If a file is modified just as we are reading it this may result in an
2396 // anomalous hash, but that's ok.
2397 bool result = android::installd::hash_secondary_dex_file(
2398 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
2399 return result ? ok() : error();
2400}
2401
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002402binder::Status InstalldNativeService::invalidateMounts() {
2403 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002404 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002405
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002406 mStorageMounts.clear();
2407 mQuotaReverseMounts.clear();
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002408
2409 std::ifstream in("/proc/mounts");
2410 if (!in.is_open()) {
2411 return error("Failed to read mounts");
2412 }
2413
2414 std::string source;
2415 std::string target;
2416 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002417 while (!in.eof()) {
2418 std::getline(in, source, ' ');
2419 std::getline(in, target, ' ');
2420 std::getline(in, ignored);
2421
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002422#if !BYPASS_SDCARDFS
2423 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2424 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2425 mStorageMounts[source] = target;
2426 }
2427#endif
2428
2429#if !BYPASS_QUOTA
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002430 if (source.compare(0, 11, "/dev/block/") == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002431 struct dqblk dq;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002432 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2433 reinterpret_cast<char*>(&dq)) == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002434 LOG(DEBUG) << "Found quota mount " << source << " at " << target;
2435 mQuotaReverseMounts[target] = source;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002436
2437 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -07002438 // need to kick it again to enable DQUOT_LIMITS_ENABLED. We
2439 // only need hard limits enabled when we're not being protected
2440 // by reserved blocks.
2441 if (!android::base::GetBoolProperty(kPropHasReserved, false)) {
2442 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1,
2443 nullptr) != 0 && errno != EBUSY) {
2444 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2445 }
2446 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1,
2447 nullptr) != 0 && errno != EBUSY) {
2448 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2449 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002450 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002451 }
2452 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002453#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002454 }
2455 return ok();
2456}
2457
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002458std::string InstalldNativeService::findDataMediaPath(
2459 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2460 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2461 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2462 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2463 auto resolved = mStorageMounts[path];
2464 if (resolved.empty()) {
2465 LOG(WARNING) << "Failed to find storage mount for " << path;
2466 resolved = path;
2467 }
2468 return StringPrintf("%s/%u", resolved.c_str(), userid);
2469}
2470
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002471std::string InstalldNativeService::findQuotaDeviceForUuid(
2472 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002473 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002474 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002475 return mQuotaReverseMounts[path];
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002476}
2477
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002478binder::Status InstalldNativeService::isQuotaSupported(
2479 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2480 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2481 return ok();
2482}
2483
Andreas Gampe02d0de52015-11-11 20:43:16 -08002484} // namespace installd
2485} // namespace android