blob: ccffd29b8a1272b1439ebe7815652898ff518f89 [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
Victor Hsiehc6d738a2018-01-20 15:06:39 -080021#include <algorithm>
Andreas Gampe02d0de52015-11-11 20:43:16 -080022#include <errno.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070023#include <fstream>
24#include <fts.h>
Victor Hsieh18ac0272018-03-12 16:03:02 -070025#include <functional>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080026#include <inttypes.h>
Andreas Gampe0354bd02016-06-27 14:25:30 -070027#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070029#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080030#include <sys/capability.h>
31#include <sys/file.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080032#include <sys/ioctl.h>
33#include <sys/mman.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080034#include <sys/resource.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070036#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070037#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000038#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070039#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080040#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070041
Andreas Gampeafa58d12016-06-03 16:09:32 -070042#include <android-base/logging.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070043#include <android-base/properties.h>
Narayan Kamathdfdfb792019-01-14 15:21:52 +000044#include <android-base/scopeguard.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080045#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070046#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010047#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080048#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080049#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070050#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070051#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070052#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070053#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080054#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070055#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080056#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070057#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070058
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070059#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070060#include "globals.h"
61#include "installd_deps.h"
62#include "otapreopt_utils.h"
63#include "utils.h"
Eric Holk2af5e6a2019-01-09 18:17:27 -080064#include "view_compiler.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070065
Jeff Sharkey88ddd942017-01-17 18:05:54 -070066#include "CacheTracker.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070067#include "MatchExtensionGen.h"
Risan5f308262018-10-26 12:06:58 -060068#include "QuotaUtils.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070069
Andreas Gampe02d0de52015-11-11 20:43:16 -080070#ifndef LOG_TAG
71#define LOG_TAG "installd"
72#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070073
74using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070075using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070076
Andreas Gampe02d0de52015-11-11 20:43:16 -080077namespace android {
78namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070079
Nikita Ioffe8e4d3462019-01-21 17:56:03 +000080// An uuid used in unit tests.
81static constexpr const char* kTestUuid = "TEST";
82
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070083static constexpr const char* kCpPath = "/system/bin/cp";
84static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070085
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070086static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000087
Andreas Gampe0354bd02016-06-27 14:25:30 -070088static constexpr const char* PKG_LIB_POSTFIX = "/lib";
89static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
90static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
91
Jaekyun Seok5cb903e2017-05-18 00:13:44 +090092static constexpr const char *kIdMapPath = "/system/bin/idmap";
Andreas Gampe0354bd02016-06-27 14:25:30 -070093static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
94static constexpr const char* IDMAP_SUFFIX = "@idmap";
95
Victor Hsieh3f16dd62018-01-13 13:43:11 -080096// fsverity assumes the page size is always 4096. If not, the feature can not be
97// enabled.
98static constexpr int kVerityPageSize = 4096;
Victor Hsiehc6d738a2018-01-20 15:06:39 -080099static constexpr size_t kSha256Size = 32;
Victor Hsieh99de5162017-10-06 14:44:14 -0700100static constexpr const char* kPropApkVerityMode = "ro.apk_verity.mode";
101
Andreas Gampe0354bd02016-06-27 14:25:30 -0700102// NOTE: keep in sync with Installer
103static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
104static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700105static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700106static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700107static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
108static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600109static constexpr int FLAG_FORCE = 1 << 16;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000110
Jeff Sharkey0274c972016-12-06 09:32:04 -0700111namespace {
112
113constexpr const char* kDump = "android.permission.DUMP";
114
Jeff Sharkey423e7462016-12-09 18:18:43 -0700115static binder::Status ok() {
116 return binder::Status::ok();
117}
118
119static binder::Status exception(uint32_t code, const std::string& msg) {
Jeff Sharkey8e9bf352018-02-27 11:40:45 -0700120 LOG(ERROR) << msg << " (" << code << ")";
Jeff Sharkey423e7462016-12-09 18:18:43 -0700121 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
122}
123
124static binder::Status error() {
125 return binder::Status::fromServiceSpecificError(errno);
126}
127
128static binder::Status error(const std::string& msg) {
129 PLOG(ERROR) << msg;
130 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
131}
132
133static binder::Status error(uint32_t code, const std::string& msg) {
134 LOG(ERROR) << msg << " (" << code << ")";
135 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
136}
137
Jeff Sharkey0274c972016-12-06 09:32:04 -0700138binder::Status checkPermission(const char* permission) {
139 pid_t pid;
140 uid_t uid;
141
142 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
143 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700144 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700145 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700146 return exception(binder::Status::EX_SECURITY,
147 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700148 }
149}
150
151binder::Status checkUid(uid_t expectedUid) {
152 uid_t uid = IPCThreadState::self()->getCallingUid();
153 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700154 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700155 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700156 return exception(binder::Status::EX_SECURITY,
157 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
158 }
159}
160
161binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
162 if (!uuid || is_valid_filename(*uuid)) {
163 return ok();
164 } else {
165 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
166 StringPrintf("UUID %s is malformed", uuid->c_str()));
167 }
168}
169
Nikita Ioffe8755f792019-01-25 13:54:43 +0000170binder::Status checkArgumentUuidTestOrNull(const std::unique_ptr<std::string>& uuid) {
171 if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
172 return ok();
173 } else {
174 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
175 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
176 }
177}
178
Jeff Sharkey423e7462016-12-09 18:18:43 -0700179binder::Status checkArgumentPackageName(const std::string& packageName) {
180 if (is_valid_package_name(packageName.c_str())) {
181 return ok();
182 } else {
183 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
184 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700185 }
186}
187
Jeff Sharkey53594302018-02-24 18:59:39 -0700188binder::Status checkArgumentPath(const std::string& path) {
189 if (path.empty()) {
190 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
191 }
192 if (path[0] != '/') {
193 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
194 StringPrintf("Path %s is relative", path.c_str()));
195 }
196 if ((path + '/').find("/../") != std::string::npos) {
197 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
198 StringPrintf("Path %s is shady", path.c_str()));
199 }
200 for (const char& c : path) {
201 if (c == '\0' || c == '\n') {
202 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
203 StringPrintf("Path %s is malformed", path.c_str()));
204 }
205 }
206 return ok();
207}
208
209binder::Status checkArgumentPath(const std::unique_ptr<std::string>& path) {
210 if (path) {
211 return checkArgumentPath(*path);
212 } else {
213 return ok();
214 }
215}
216
Jeff Sharkey0274c972016-12-06 09:32:04 -0700217#define ENFORCE_UID(uid) { \
218 binder::Status status = checkUid((uid)); \
219 if (!status.isOk()) { \
220 return status; \
221 } \
222}
223
Jeff Sharkey423e7462016-12-09 18:18:43 -0700224#define CHECK_ARGUMENT_UUID(uuid) { \
225 binder::Status status = checkArgumentUuid((uuid)); \
226 if (!status.isOk()) { \
227 return status; \
228 } \
229}
230
Nikita Ioffe8755f792019-01-25 13:54:43 +0000231#define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) { \
232 auto status = checkArgumentUuidTestOrNull(uuid); \
233 if (!status.isOk()) { \
234 return status; \
235 } \
236} \
237
Jeff Sharkey423e7462016-12-09 18:18:43 -0700238#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
239 binder::Status status = \
240 checkArgumentPackageName((packageName)); \
241 if (!status.isOk()) { \
242 return status; \
243 } \
244}
245
Jeff Sharkey53594302018-02-24 18:59:39 -0700246#define CHECK_ARGUMENT_PATH(path) { \
247 binder::Status status = checkArgumentPath((path)); \
248 if (!status.isOk()) { \
249 return status; \
250 } \
251}
252
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800253#define ASSERT_PAGE_SIZE_4K() { \
254 if (getpagesize() != kVerityPageSize) { \
Victor Hsieh7ebd5132018-01-23 07:52:17 -0800255 return error("FSVerity only supports 4K pages"); \
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800256 } \
257}
258
Jeff Sharkey0274c972016-12-06 09:32:04 -0700259} // namespace
260
261status_t InstalldNativeService::start() {
262 IPCThreadState::self()->disableBackgroundScheduling(true);
263 status_t ret = BinderService<InstalldNativeService>::publish();
264 if (ret != android::OK) {
265 return ret;
266 }
267 sp<ProcessState> ps(ProcessState::self());
268 ps->startThreadPool();
269 ps->giveThreadPoolName();
270 return android::OK;
271}
272
273status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700274 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700275 const binder::Status dump_permission = checkPermission(kDump);
276 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700277 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700278 return PERMISSION_DENIED;
279 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700280 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700281
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700282 out << "installd is happy!" << endl;
283
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700284 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600285 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
286 out << endl << "Storage mounts:" << endl;
287 for (const auto& n : mStorageMounts) {
288 out << " " << n.first << " = " << n.second << endl;
289 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700290 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700291
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700292 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600293 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700294 out << endl << "Per-UID cache quotas:" << endl;
295 for (const auto& n : mCacheQuotas) {
296 out << " " << n.first << " = " << n.second << endl;
297 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700298 }
299
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700300 out << endl;
301 out.flush();
302
Jeff Sharkey0274c972016-12-06 09:32:04 -0700303 return NO_ERROR;
304}
305
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600306/**
307 * Perform restorecon of the given path, but only perform recursive restorecon
308 * if the label of that top-level file actually changed. This can save us
309 * significant time by avoiding no-op traversals of large filesystem trees.
310 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700311static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
312 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600313 int res = 0;
314 char* before = nullptr;
315 char* after = nullptr;
316
317 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
318 // libselinux. Not needed here.
319
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600320 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600321 PLOG(ERROR) << "Failed before getfilecon for " << path;
322 goto fail;
323 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700324 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600325 PLOG(ERROR) << "Failed top-level restorecon for " << path;
326 goto fail;
327 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600328 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600329 PLOG(ERROR) << "Failed after getfilecon for " << path;
330 goto fail;
331 }
332
333 // If the initial top-level restorecon above changed the label, then go
334 // back and restorecon everything recursively
335 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700336 if (existing) {
337 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
338 << path << "; running recursive restorecon";
339 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700340 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600341 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
342 PLOG(ERROR) << "Failed recursive restorecon for " << path;
343 goto fail;
344 }
345 }
346
347 goto done;
348fail:
349 res = -1;
350done:
351 free(before);
352 free(after);
353 return res;
354}
355
Jeff Sharkey0274c972016-12-06 09:32:04 -0700356static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700357 const std::string& seInfo, uid_t uid, bool existing) {
358 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
359 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600360}
361
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600362static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600363 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
364 PLOG(ERROR) << "Failed to prepare " << path;
365 return -1;
366 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600367 return 0;
368}
369
Calin Juravled2affb82017-11-28 17:41:43 -0800370static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
371 if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
372 return true;
373 }
374
375 int32_t uid = multiuser_get_uid(userId, appId);
376 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
377 if (shared_app_gid == -1) {
378 // TODO(calin): this should no longer be possible but do not continue if we don't get
379 // a valid shared gid.
380 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
381 return true;
382 }
383
384 const std::string profile_dir =
385 create_primary_current_profile_package_dir_path(userId, packageName);
386 // read-write-execute only for the app user.
387 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
388 PLOG(ERROR) << "Failed to prepare " << profile_dir;
389 return false;
390 }
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800391
Calin Juravled2affb82017-11-28 17:41:43 -0800392 const std::string ref_profile_path =
393 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800394
395 // Prepare the reference profile directory. Note that we use the non strict version of
396 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
397 // This is particularly important given that in O there were some fixes for how the
398 // shared_app_gid is computed.
399 //
400 // Note that by the time we get here we know that we are using a correct uid (otherwise
401 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
402 // are sure that the gid being used belongs to the owning app and not someone else.
403 //
404 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
405 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800406 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
407 return false;
408 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800409
Calin Juravled2affb82017-11-28 17:41:43 -0800410 return true;
411}
412
Jeff Sharkey0274c972016-12-06 09:32:04 -0700413binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
414 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700415 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700416 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700417 CHECK_ARGUMENT_UUID(uuid);
418 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700419 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700420
421 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
422 const char* pkgname = packageName.c_str();
423
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700424 // Assume invalid inode unless filled in below
425 if (_aidl_return != nullptr) *_aidl_return = -1;
426
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700427 int32_t uid = multiuser_get_uid(userId, appId);
428 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700429 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
430
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700431 // If UID doesn't have a specific cache GID, use UID value
432 if (cacheGid == -1) {
433 cacheGid = uid;
434 }
435
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700436 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700437 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700438 bool existing = (access(path.c_str(), F_OK) == 0);
439
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700440 if (prepare_app_dir(path, targetMode, uid) ||
441 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
442 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700443 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600444 }
445
446 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700447 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
448 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
449 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700450 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700451 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600452
453 // Remember inode numbers of cache directories so that we can clear
454 // contents while CE storage is locked
455 if (write_path_inode(path, "cache", kXattrInodeCache) ||
456 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700457 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700458 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700459
460 // And return the CE inode of the top-level data directory so we can
461 // clear contents while CE storage is locked
462 if ((_aidl_return != nullptr)
463 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
464 return error("Failed to get_path_inode for " + path);
465 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700466 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700467 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700468 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700469 bool existing = (access(path.c_str(), F_OK) == 0);
470
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700471 if (prepare_app_dir(path, targetMode, uid) ||
472 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
473 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700474 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700475 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000476
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600477 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600478 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
479 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
480 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700481 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600482 }
483
Calin Juravled2affb82017-11-28 17:41:43 -0800484 if (!prepare_app_profile_dir(packageName, appId, userId)) {
485 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000486 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700487 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700488 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700489}
490
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700491binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
492 const std::string& packageName, int32_t userId, int32_t flags) {
493 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700494 CHECK_ARGUMENT_UUID(uuid);
495 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700496 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700497
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700498 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
499 const char* pkgname = packageName.c_str();
500
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700501 // This method only exists to upgrade system apps that have requested
502 // forceDeviceEncrypted, so their default storage always lives in a
503 // consistent location. This only works on non-FBE devices, since we
504 // never want to risk exposing data on a device with real CE/DE storage.
505
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700506 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
507 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700508
509 // If neither directory is marked as default, assume CE is default
510 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
511 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
512 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700513 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700514 }
515 }
516
517 // Migrate default data location if needed
518 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
519 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
520
521 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
522 LOG(WARNING) << "Requested default storage " << target
523 << " is not active; migrating from " << source;
524 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700525 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700526 }
527 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700528 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700529 }
530 }
531
Jeff Sharkey423e7462016-12-09 18:18:43 -0700532 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700533}
534
Calin Juravle6a1648e2016-02-01 12:12:16 +0000535
Calin Juravle562de812018-01-20 23:34:18 -0800536binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
537 const std::string& profileName) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700538 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700539 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700540 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700541
Jeff Sharkey423e7462016-12-09 18:18:43 -0700542 binder::Status res = ok();
Calin Juravle562de812018-01-20 23:34:18 -0800543 if (!clear_primary_reference_profile(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700544 res = error("Failed to clear reference profile for " + packageName);
545 }
Calin Juravle562de812018-01-20 23:34:18 -0800546 if (!clear_primary_current_profiles(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 res = error("Failed to clear current profiles for " + packageName);
548 }
549 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000550}
551
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700552binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
553 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
554 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700555 CHECK_ARGUMENT_UUID(uuid);
556 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700557 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700558
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700559 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
560 const char* pkgname = packageName.c_str();
561
Jeff Sharkey423e7462016-12-09 18:18:43 -0700562 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700563 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700564 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600565 if (flags & FLAG_CLEAR_CACHE_ONLY) {
566 path = read_path_inode(path, "cache", kXattrInodeCache);
567 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
568 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
569 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700570 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700571 if (delete_dir_contents(path) != 0) {
572 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900573 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
574 remove_path_xattr(path, kXattrInodeCache);
575 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700576 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700577 }
578 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700579 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600580 std::string suffix = "";
581 bool only_cache = false;
582 if (flags & FLAG_CLEAR_CACHE_ONLY) {
583 suffix = CACHE_DIR_POSTFIX;
584 only_cache = true;
585 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
586 suffix = CODE_CACHE_DIR_POSTFIX;
587 only_cache = true;
588 }
589
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700590 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700591 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700592 if (delete_dir_contents(path) != 0) {
593 res = error("Failed to delete contents of " + path);
594 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700595 }
596 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700597 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700598}
599
Calin Juravle76268c52017-03-09 13:19:42 -0800600static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100601 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800602 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100603 /*ignore_if_missing*/ true);
604}
605
Calin Juravle76268c52017-03-09 13:19:42 -0800606static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100607 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800608 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100609 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000610}
611
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700612binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
613 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700614 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700615 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700616
Jeff Sharkey423e7462016-12-09 18:18:43 -0700617 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000618 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
619 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800620 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700621 res = error("Failed to destroy current profiles for " + packageName);
622 }
Calin Juravleedae6692016-03-23 13:55:31 +0000623 }
Calin Juravle76268c52017-03-09 13:19:42 -0800624 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700625 res = error("Failed to destroy reference profile for " + packageName);
626 }
627 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000628}
629
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700630binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
631 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
632 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700633 CHECK_ARGUMENT_UUID(uuid);
634 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700635 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700636
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700637 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
638 const char* pkgname = packageName.c_str();
639
Jeff Sharkey423e7462016-12-09 18:18:43 -0700640 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700641 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700642 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
643 if (delete_dir_contents_and_dir(path) != 0) {
644 res = error("Failed to delete " + path);
645 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700646 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700647 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700648 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
649 if (delete_dir_contents_and_dir(path) != 0) {
650 res = error("Failed to delete " + path);
651 }
Calin Juravle76268c52017-03-09 13:19:42 -0800652 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100653 // TODO(calin): If the package is still installed by other users it's probably
654 // beneficial to keep the reference profile around.
655 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800656 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700657 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700658 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700659}
660
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600661static gid_t get_cache_gid(uid_t uid) {
662 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
663 return (gid != -1) ? gid : uid;
664}
665
666binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
667 int32_t flags) {
668 ENFORCE_UID(AID_SYSTEM);
669 CHECK_ARGUMENT_UUID(uuid);
670 std::lock_guard<std::recursive_mutex> lock(mLock);
671
672 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
673 for (auto user : get_known_users(uuid_)) {
674 ATRACE_BEGIN("fixup user");
675 FTS* fts;
676 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600677 auto ce_path = create_data_user_ce_path(uuid_, user);
678 auto de_path = create_data_user_de_path(uuid_, user);
679 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700680 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600681 return error("Failed to fts_open");
682 }
683 while ((p = fts_read(fts)) != nullptr) {
684 if (p->fts_info == FTS_D && p->fts_level == 1) {
685 // Track down inodes of cache directories
686 uint64_t raw = 0;
687 ino_t inode_cache = 0;
688 ino_t inode_code_cache = 0;
689 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
690 inode_cache = raw;
691 }
692 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
693 inode_code_cache = raw;
694 }
695
696 // Figure out expected GID of each child
697 FTSENT* child = fts_children(fts, 0);
698 while (child != nullptr) {
699 if ((child->fts_statp->st_ino == inode_cache)
700 || (child->fts_statp->st_ino == inode_code_cache)
701 || !strcmp(child->fts_name, "cache")
702 || !strcmp(child->fts_name, "code_cache")) {
703 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
704 } else {
705 child->fts_number = p->fts_statp->st_uid;
706 }
707 child = child->fts_link;
708 }
709 } else if (p->fts_level >= 2) {
710 if (p->fts_level > 2) {
711 // Inherit GID from parent once we're deeper into tree
712 p->fts_number = p->fts_parent->fts_number;
713 }
714
715 uid_t uid = p->fts_parent->fts_statp->st_uid;
716 gid_t cache_gid = get_cache_gid(uid);
717 gid_t expected = p->fts_number;
718 gid_t actual = p->fts_statp->st_gid;
719 if (actual == expected) {
720#if FIXUP_DEBUG
721 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
722#endif
723 if (!(flags & FLAG_FORCE)) {
724 fts_set(fts, p, FTS_SKIP);
725 }
726 } else if ((actual == uid) || (actual == cache_gid)) {
727 // Only consider fixing up when current GID belongs to app
728 if (p->fts_info != FTS_D) {
729 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
730 << " instead of " << expected;
731 }
732 switch (p->fts_info) {
733 case FTS_DP:
734 // If we're moving towards cache GID, we need to set S_ISGID
735 if (expected == cache_gid) {
736 if (chmod(p->fts_path, 02771) != 0) {
737 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
738 }
739 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -0700740 [[fallthrough]]; // also set GID
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600741 case FTS_F:
742 if (chown(p->fts_path, -1, expected) != 0) {
743 PLOG(WARNING) << "Failed to chown " << p->fts_path;
744 }
745 break;
746 case FTS_SL:
747 case FTS_SLNONE:
748 if (lchown(p->fts_path, -1, expected) != 0) {
749 PLOG(WARNING) << "Failed to chown " << p->fts_path;
750 }
751 break;
752 }
753 } else {
754 // Ignore all other GID transitions, since they're kinda shady
755 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
756 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -0600757 if (!(flags & FLAG_FORCE)) {
758 fts_set(fts, p, FTS_SKIP);
759 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600760 }
761 }
762 }
763 fts_close(fts);
764 ATRACE_END();
765 }
766 return ok();
767}
768
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000769static int32_t copy_directory_recursive(const char* from, const char* to) {
770 char *argv[] = {
771 (char*) kCpPath,
772 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
773 (char*) "-p", /* preserve timestamps, ownership, and permissions */
774 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
775 (char*) "-P", /* Do not follow symlinks [default] */
776 (char*) "-d", /* don't dereference symlinks */
777 (char*) from,
778 (char*) to
779 };
780
781 LOG(DEBUG) << "Copying " << from << " to " << to;
782 return android_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, true);
783}
784
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000785binder::Status InstalldNativeService::snapshotAppData(
786 const std::unique_ptr<std::string>& volumeUuid,
Nikita Ioffe8755f792019-01-25 13:54:43 +0000787 const std::string& packageName, int32_t user, int32_t storageFlags,
788 int64_t* _aidl_return) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000789 ENFORCE_UID(AID_SYSTEM);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000790 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000791 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
792 std::lock_guard<std::recursive_mutex> lock(mLock);
793
794 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
795 const char* package_name = packageName.c_str();
796
797 binder::Status res = ok();
Nikita Ioffe8755f792019-01-25 13:54:43 +0000798 // Default result to 0, it will be populated with inode of ce data snapshot
799 // if FLAG_STORAGE_CE has been passed.
800 if (_aidl_return != nullptr) *_aidl_return = 0;
801
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000802 bool clear_ce_on_exit = false;
803 bool clear_de_on_exit = false;
804
805 auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &user, &package_name] {
806 if (clear_de_on_exit) {
807 auto to = create_data_misc_de_rollback_package_path(volume_uuid, user, package_name);
808 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
809 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
810 }
811 }
812
813 if (clear_ce_on_exit) {
814 auto to = create_data_misc_ce_rollback_package_path(volume_uuid, user, package_name);
815 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
816 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
817 }
818 }
819 };
820
821 auto scope_guard = android::base::make_scope_guard(deleter);
822
823 // The app may not have any data at all, in which case it's OK to skip here.
824 auto from_ce = create_data_user_ce_package_path(volume_uuid, user, package_name);
825 if (access(from_ce.c_str(), F_OK) != 0) {
826 LOG(INFO) << "Missing source " << from_ce;
827 return ok();
828 }
829
Nikita Ioffe900b3c22019-01-23 14:32:48 +0000830 // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
831 binder::Status clear_cache_result = clearAppData(volumeUuid, packageName, user,
832 storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
833 if (!clear_cache_result.isOk()) {
834 // It should be fine to continue snapshot if we for some reason failed
835 // to clear cache.
836 LOG(WARNING) << "Failed to clear cache of app " << packageName;
837 }
838
839 // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
840 binder::Status clear_code_cache_result = clearAppData(volumeUuid, packageName, user,
841 storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY, 0);
842 if (!clear_code_cache_result.isOk()) {
843 // It should be fine to continue snapshot if we for some reason failed
844 // to clear code_cache.
845 LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
846 }
847
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000848 if (storageFlags & FLAG_STORAGE_DE) {
849 auto from = create_data_user_de_package_path(volume_uuid, user, package_name);
850 auto to = create_data_misc_de_rollback_path(volume_uuid, user);
851
Nikita Ioffe835ae772019-01-23 16:32:13 +0000852 int rd = delete_dir_contents(to, true /* ignore_if_missing */);
853 if (rd != 0) {
854 res = error(rd, "Failed clearing existing snapshot " + to);
855 return res;
856 }
857
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000858 int rc = copy_directory_recursive(from.c_str(), to.c_str());
859 if (rc != 0) {
860 res = error(rc, "Failed copying " + from + " to " + to);
861 clear_de_on_exit = true;
862 return res;
863 }
864 }
865
866 if (storageFlags & FLAG_STORAGE_CE) {
867 auto from = create_data_user_ce_package_path(volume_uuid, user, package_name);
868 auto to = create_data_misc_ce_rollback_path(volume_uuid, user);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000869
870 int rd = delete_dir_contents(to, true /* ignore_if_missing */);
871 if (rd != 0) {
872 res = error(rd, "Failed clearing existing snapshot " + to);
873 return res;
874 }
875
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000876 int rc = copy_directory_recursive(from.c_str(), to.c_str());
877 if (rc != 0) {
878 res = error(rc, "Failed copying " + from + " to " + to);
879 clear_ce_on_exit = true;
880 return res;
881 }
Nikita Ioffe8755f792019-01-25 13:54:43 +0000882 if (_aidl_return != nullptr) {
883 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid, user,
884 package_name);
885 rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
886 if (rc != 0) {
887 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
888 clear_ce_on_exit = true;
889 return res;
890 }
891 }
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000892 }
893
894 return res;
895}
896
897binder::Status InstalldNativeService::restoreAppDataSnapshot(
898 const std::unique_ptr<std::string>& volumeUuid, const std::string& packageName,
899 const int32_t appId, const int64_t ceDataInode, const std::string& seInfo,
900 const int32_t user, int32_t storageFlags) {
901 ENFORCE_UID(AID_SYSTEM);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000902 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000903 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
904 std::lock_guard<std::recursive_mutex> lock(mLock);
905
906 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
907 const char* package_name = packageName.c_str();
908
909 auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid,
910 user, package_name);
911 auto from_de = create_data_misc_de_rollback_package_path(volume_uuid,
912 user, package_name);
913
914 const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
915 (access(from_ce.c_str(), F_OK) == 0);
916 const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
917 (access(from_de.c_str(), F_OK) == 0);
918
919 if (!needs_ce_rollback && !needs_de_rollback) {
920 return ok();
921 }
922
923 // We know we're going to rollback one of the CE or DE data, so we clear
924 // application data first. Note that it's possible that we're asked to
925 // restore both CE & DE data but that one of the restores fail. Leaving the
926 // app with no data in those cases is arguably better than leaving the app
927 // with mismatched / stale data.
928 LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
929 binder::Status res = clearAppData(volumeUuid, packageName, user, storageFlags, ceDataInode);
930 if (!res.isOk()) {
931 return res;
932 }
933
934 if (needs_ce_rollback) {
935 auto to_ce = create_data_user_ce_path(volume_uuid, user);
936 int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
937 if (rc != 0) {
938 res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
939 return res;
940 }
941 }
942
943 if (needs_de_rollback) {
944 auto to_de = create_data_user_de_path(volume_uuid, user);
945 int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
946 if (rc != 0) {
Nikita Ioffefd2ccd42019-01-25 11:44:36 +0000947 if (needs_ce_rollback) {
948 auto ce_data = create_data_user_ce_package_path(volume_uuid, user, package_name);
949 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
950 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
951 LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
952 }
953 }
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000954 res = error(rc, "Failed copying " + from_de + " to " + to_de);
955 return res;
956 }
957 }
958
959 // Finally, restore the SELinux label on the app data.
960 return restoreconAppData(volumeUuid, packageName, user, storageFlags, appId, seInfo);
961}
962
Nikita Ioffe8755f792019-01-25 13:54:43 +0000963binder::Status InstalldNativeService::destroyAppDataSnapshot(
964 const std::unique_ptr<std::string> &volumeUuid, const std::string& packageName,
965 const int32_t user, const int64_t ceSnapshotInode, int32_t storageFlags) {
966 ENFORCE_UID(AID_SYSTEM);
967 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
968 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
969 std::lock_guard<std::recursive_mutex> lock(mLock);
970
971 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
972 const char* package_name = packageName.c_str();
973
974 if (storageFlags & FLAG_STORAGE_DE) {
975 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid,
976 user, package_name);
977
978 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
979 if (res != 0) {
980 return error(res, "Failed clearing snapshot " + de_snapshot_path);
981 }
982 }
983
984 if (storageFlags & FLAG_STORAGE_CE) {
985 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid,
986 user, package_name, ceSnapshotInode);
987 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
988 if (res != 0) {
989 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
990 }
991 }
992 return ok();
993}
994
995
Jeff Sharkey0274c972016-12-06 09:32:04 -0700996binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
997 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
998 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
999 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001000 ENFORCE_UID(AID_SYSTEM);
1001 CHECK_ARGUMENT_UUID(fromUuid);
1002 CHECK_ARGUMENT_UUID(toUuid);
1003 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001004 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -07001005
1006 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1007 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1008 const char* package_name = packageName.c_str();
1009 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001010
Jeff Sharkey423e7462016-12-09 18:18:43 -07001011 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001012 std::vector<userid_t> users = get_known_users(from_uuid);
1013
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001014 // Copy app
1015 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001016 auto from = create_data_app_package_path(from_uuid, data_app_name);
1017 auto to = create_data_app_package_path(to_uuid, data_app_name);
1018 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001019
Narayan Kamathdfdfb792019-01-14 15:21:52 +00001020 int rc = copy_directory_recursive(from.c_str(), to_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001021 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001022 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001023 goto fail;
1024 }
1025
1026 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001027 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001028 goto fail;
1029 }
1030 }
1031
1032 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -07001033 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -07001034
1035 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -06001036 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
1037 if (access(from_ce.c_str(), F_OK) != 0) {
1038 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001039 continue;
1040 }
1041
Jeff Sharkey0274c972016-12-06 09:32:04 -07001042 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -07001043 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001044 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001045 goto fail;
1046 }
1047
Jeff Sharkey51c94492016-05-10 17:46:39 -06001048 {
1049 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
1050 auto to = create_data_user_de_path(to_uuid, user);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001051
Narayan Kamathdfdfb792019-01-14 15:21:52 +00001052 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001053 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001054 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001055 goto fail;
1056 }
1057 }
1058 {
1059 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
1060 auto to = create_data_user_ce_path(to_uuid, user);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001061
Narayan Kamathdfdfb792019-01-14 15:21:52 +00001062 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001063 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001064 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001065 goto fail;
1066 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001067 }
1068
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001069 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1070 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001071 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001072 goto fail;
1073 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001074 }
1075
Jeff Sharkey31f08982015-07-07 13:31:37 -07001076 // We let the framework scan the new location and persist that before
1077 // deleting the data in the old location; this ordering ensures that
1078 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001079 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001080
1081fail:
1082 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001083 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001084 auto to = create_data_app_package_path(to_uuid, data_app_name);
Yi Kong954cf642018-07-17 16:16:24 -07001085 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001086 LOG(WARNING) << "Failed to rollback " << to;
1087 }
1088 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001089 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001090 {
1091 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
Yi Kong954cf642018-07-17 16:16:24 -07001092 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001093 LOG(WARNING) << "Failed to rollback " << to;
1094 }
1095 }
1096 {
1097 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
Yi Kong954cf642018-07-17 16:16:24 -07001098 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001099 LOG(WARNING) << "Failed to rollback " << to;
1100 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001101 }
1102 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001103 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001104}
1105
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001106binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
1107 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
1108 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001109 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001110 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001111
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001112 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001113 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001114 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001115 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001116 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07001117 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001118 }
1119 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001120
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001121 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001122}
1123
1124binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
1125 int32_t userId, int32_t flags) {
1126 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001127 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001128 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001129
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001130 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001131 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001132 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001133 auto path = create_data_user_de_path(uuid_, userId);
1134 if (delete_dir_contents_and_dir(path, true) != 0) {
1135 res = error("Failed to delete " + path);
1136 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001137 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001138 path = create_data_misc_legacy_path(userId);
1139 if (delete_dir_contents_and_dir(path, true) != 0) {
1140 res = error("Failed to delete " + path);
1141 }
Calin Juravle114f0812017-03-08 19:05:07 -08001142 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001143 if (delete_dir_contents_and_dir(path, true) != 0) {
1144 res = error("Failed to delete " + path);
1145 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001146 }
Robin Lee095c7632014-04-25 15:05:19 +01001147 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001148 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001149 auto path = create_data_user_ce_path(uuid_, userId);
1150 if (delete_dir_contents_and_dir(path, true) != 0) {
1151 res = error("Failed to delete " + path);
1152 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001153 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001154 if (delete_dir_contents_and_dir(path, true) != 0) {
1155 res = error("Failed to delete " + path);
1156 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001157 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001158 return res;
Robin Lee095c7632014-04-25 15:05:19 +01001159}
1160
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001161binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001162 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001163 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001164 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001165 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001166
Risan5f308262018-10-26 12:06:58 -06001167 auto uuidString = uuid ? *uuid : "";
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001168 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001169 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001170 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001171
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001172 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001173 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001174 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001175 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001176
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001177 int64_t cleared = 0;
1178 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001179 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001180 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001181
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001182 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001183 return ok();
1184 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001185
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001186 if (flags & FLAG_FREE_CACHE_V2) {
1187 // This new cache strategy fairly removes files from UIDs by deleting
1188 // files from the UIDs which are most over their allocated quota
1189
1190 // 1. Create trackers for every known UID
1191 ATRACE_BEGIN("create");
1192 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
1193 for (auto user : get_known_users(uuid_)) {
1194 FTS *fts;
1195 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001196 auto ce_path = create_data_user_ce_path(uuid_, user);
1197 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001198 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
1199 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
1200 (char*) media_path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001201 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001202 return error("Failed to fts_open");
1203 }
Yi Kong954cf642018-07-17 16:16:24 -07001204 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001205 if (p->fts_info == FTS_D && p->fts_level == 1) {
1206 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001207 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
1208 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
1209 + AID_APP_START;
1210 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001211 auto search = trackers.find(uid);
1212 if (search != trackers.end()) {
1213 search->second->addDataPath(p->fts_path);
1214 } else {
1215 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06001216 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001217 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001218 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001219 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001220 tracker->cacheQuota = mCacheQuotas[uid];
1221 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001222 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001223#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001224 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001225#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001226 tracker->cacheQuota = 67108864;
1227 }
1228 trackers[uid] = tracker;
1229 }
1230 fts_set(fts, p, FTS_SKIP);
1231 }
1232 }
1233 fts_close(fts);
1234 }
1235 ATRACE_END();
1236
1237 // 2. Populate tracker stats and insert into priority queue
1238 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001239 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001240 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1241 return (left->getCacheRatio() < right->getCacheRatio());
1242 };
1243 std::priority_queue<std::shared_ptr<CacheTracker>,
1244 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1245 for (const auto& it : trackers) {
1246 it.second->loadStats();
1247 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001248 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001249 }
1250 ATRACE_END();
1251
1252 // 3. Bounce across the queue, freeing items from whichever tracker is
1253 // the most over their assigned quota
1254 ATRACE_BEGIN("bounce");
1255 std::shared_ptr<CacheTracker> active;
1256 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001257 // Only look at apps under quota when explicitly requested
1258 if (active && (active->getCacheRatio() < 10000)
1259 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1260 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1261 << " isn't over quota, and defy not requested";
1262 break;
1263 }
1264
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001265 // Only keep clearing when we haven't pushed into reserved area
1266 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1267 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1268 break;
1269 }
1270
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001271 // Find the best tracker to work with; this might involve swapping
1272 // if the active tracker is no longer the most over quota
1273 bool nextBetter = active && !queue.empty()
1274 && active->getCacheRatio() < queue.top()->getCacheRatio();
1275 if (!active || nextBetter) {
1276 if (active) {
1277 // Current tracker still has items, so we'll consider it
1278 // again later once it bubbles up to surface
1279 queue.push(active);
1280 }
1281 active = queue.top(); queue.pop();
1282 active->ensureItems();
1283 continue;
1284 }
1285
1286 // If no items remain, go find another tracker
1287 if (active->items.empty()) {
1288 active = nullptr;
1289 continue;
1290 } else {
1291 auto item = active->items.back();
1292 active->items.pop_back();
1293
1294 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1295 if (!noop) {
1296 item->purge();
1297 }
1298 active->cacheUsed -= item->size;
1299 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001300 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001301 }
1302
1303 // Verify that we're actually done before bailing, since sneaky
1304 // apps might be using hardlinks
1305 if (needed <= 0) {
1306 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001307 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001308 if (needed <= 0) {
1309 break;
1310 } else {
1311 LOG(WARNING) << "Expected to be done but still need " << needed;
1312 }
1313 }
1314 }
1315 ATRACE_END();
1316
1317 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001318 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001319 }
1320
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001321 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001322 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001323 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001324 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001325 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001326 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001327 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001328}
1329
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001330binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1331 const std::string& instructionSet) {
1332 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07001333 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001334 std::lock_guard<std::recursive_mutex> lock(mLock);
1335
Mike Lockwood94afecf2012-10-24 10:45:23 -07001336 char dex_path[PKG_PATH_MAX];
1337
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001338 const char* path = codePath.c_str();
1339 const char* instruction_set = instructionSet.c_str();
1340
Jeff Sharkey770180a2014-09-08 17:14:26 -07001341 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001342 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001343 }
1344
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001345 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001346 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001347 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001348
1349 ALOGV("unlink %s\n", dex_path);
1350 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001351 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1352 // but could not be unlinked.
1353 if (errno != ENOENT) {
1354 return error(StringPrintf("Failed to unlink %s", dex_path));
1355 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001356 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001357 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001358}
1359
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001360struct stats {
1361 int64_t codeSize;
1362 int64_t dataSize;
1363 int64_t cacheSize;
1364};
1365
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001366#if MEASURE_DEBUG
1367static std::string toString(std::vector<int64_t> values) {
1368 std::stringstream res;
1369 res << "[";
1370 for (size_t i = 0; i < values.size(); i++) {
1371 res << values[i];
1372 if (i < values.size() - 1) {
1373 res << ",";
1374 }
1375 }
1376 res << "]";
1377 return res.str();
1378}
1379#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001380
Risan5f308262018-10-26 12:06:58 -06001381static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001382 int32_t appId, struct stats* stats, struct stats* extStats) {
Risan5f308262018-10-26 12:06:58 -06001383 int64_t space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001384 if (stats != nullptr) {
1385 uid_t uid = multiuser_get_uid(userId, appId);
Risan5f308262018-10-26 12:06:58 -06001386 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
1387 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001388 }
1389
1390 int cacheGid = multiuser_get_cache_gid(userId, appId);
1391 if (cacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001392 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
1393 stats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001394 }
1395 }
1396
1397 int sharedGid = multiuser_get_shared_gid(0, appId);
1398 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001399 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
1400 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001401 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001402 }
1403 }
1404
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001405 if (extStats != nullptr) {
1406 int extGid = multiuser_get_ext_gid(userId, appId);
1407 if (extGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001408 if ((space = GetOccupiedSpaceForGid(uuid, extGid)) != -1) {
1409 extStats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001410 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001411 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001412
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001413 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1414 if (extCacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001415 if ((space = GetOccupiedSpaceForGid(uuid, extCacheGid)) != -1) {
1416 extStats->dataSize += space;
1417 extStats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001418 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001419 }
1420 }
1421}
1422
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001423static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001424 DIR *d;
1425 int dfd;
1426 struct dirent *de;
1427 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001428
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001429 d = opendir(path.c_str());
1430 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001431 if (errno != ENOENT) {
1432 PLOG(WARNING) << "Failed to open " << path;
1433 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001434 return;
1435 }
1436 dfd = dirfd(d);
1437 while ((de = readdir(d))) {
1438 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001439
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001440 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001441 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001442 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001443 }
1444
1445 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001446 if (!strcmp(name, ".")) {
1447 // Don't recurse, but still count node size
1448 } else if (!strcmp(name, "..")) {
1449 // Don't recurse or count node size
1450 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001451 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001452 // Measure all children nodes
1453 size = 0;
1454 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001455 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001456
1457 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1458 stats->cacheSize += size;
1459 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001460 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001461
1462 // Legacy symlink isn't owned by app
1463 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1464 continue;
1465 }
1466
1467 // Everything found inside is considered data
1468 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001469 }
1470 closedir(d);
1471}
1472
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001473static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1474 bool exclude_apps = false) {
1475 DIR *d;
1476 int dfd;
1477 struct dirent *de;
1478 struct stat s;
1479
1480 d = opendir(path.c_str());
1481 if (d == nullptr) {
1482 if (errno != ENOENT) {
1483 PLOG(WARNING) << "Failed to open " << path;
1484 }
1485 return;
1486 }
1487 dfd = dirfd(d);
1488 while ((de = readdir(d))) {
1489 if (de->d_type == DT_DIR) {
1490 const char *name = de->d_name;
1491 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1492 continue;
1493 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001494 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001495 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1496 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001497 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001498 continue;
1499 } else {
1500 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1501 }
1502 }
1503 }
1504 closedir(d);
1505}
1506
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001507static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1508 FTS *fts;
1509 FTSENT *p;
1510 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001511 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001512 PLOG(ERROR) << "Failed to fts_open " << path;
1513 return;
1514 }
Yi Kong954cf642018-07-17 16:16:24 -07001515 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001516 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001517 switch (p->fts_info) {
1518 case FTS_D:
1519 if (p->fts_level == 4
1520 && !strcmp(p->fts_name, "cache")
1521 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1522 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1523 p->fts_number = 1;
1524 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001525 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001526 case FTS_DEFAULT:
1527 case FTS_F:
1528 case FTS_SL:
1529 case FTS_SLNONE:
1530 int64_t size = (p->fts_statp->st_blocks * 512);
1531 if (p->fts_number == 1) {
1532 stats->cacheSize += size;
1533 }
1534 stats->dataSize += size;
1535 break;
1536 }
1537 }
1538 fts_close(fts);
1539}
1540
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001541binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001542 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1543 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1544 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001545 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001546 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001547 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001548 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1549 }
Jeff Sharkey53594302018-02-24 18:59:39 -07001550 for (const auto& codePath : codePaths) {
1551 CHECK_ARGUMENT_PATH(codePath);
1552 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001553 // NOTE: Locking is relaxed on this method, since it's limited to
1554 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001555
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001556 // When modifying this logic, always verify using tests:
1557 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1558
1559#if MEASURE_DEBUG
1560 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1561#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001562
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001563 // Here's a summary of the common storage locations across the platform,
1564 // and how they're each tagged:
1565 //
1566 // /data/app/com.example UID system
1567 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001568 // /data/user/0/com.example UID u0_a10 GID u0_a10
1569 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1570 // /data/media/0/foo.txt UID u0_media_rw
1571 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1572 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1573 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1574 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001575
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001576 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001577 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001578 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001579 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001580
Risan5f308262018-10-26 12:06:58 -06001581 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001582 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001583
Risan5f308262018-10-26 12:06:58 -06001584 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001585 flags &= ~FLAG_USE_QUOTA;
1586 }
1587
Jeff Sharkey466459b2017-01-17 15:25:01 -07001588 ATRACE_BEGIN("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001589 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001590 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1591 calculate_tree_size(obbCodePath, &extStats.codeSize);
1592 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001593 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001594
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001595 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001596 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001597 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001598 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001599 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001600 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001601 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001602
Jeff Sharkey466459b2017-01-17 15:25:01 -07001603 ATRACE_BEGIN("quota");
Risan5f308262018-10-26 12:06:58 -06001604 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001605 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001606 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001607 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001608 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001609 calculate_tree_size(codePath, &stats.codeSize);
1610 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001611 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001612
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001613 for (size_t i = 0; i < packageNames.size(); i++) {
1614 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001615
Jeff Sharkey466459b2017-01-17 15:25:01 -07001616 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001617 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1618 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001619 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1620 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001621 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001622
Jeff Sharkey06a61842017-04-15 12:03:31 -06001623 if (!uuid) {
1624 ATRACE_BEGIN("profiles");
1625 calculate_tree_size(
1626 create_primary_current_profile_package_dir_path(userId, pkgname),
1627 &stats.dataSize);
1628 calculate_tree_size(
1629 create_primary_reference_profile_package_dir_path(pkgname),
1630 &stats.codeSize);
1631 ATRACE_END();
1632 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001633
Jeff Sharkey466459b2017-01-17 15:25:01 -07001634 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001635 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001636 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001637 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001638 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001639 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001640 }
1641
Jeff Sharkey06a61842017-04-15 12:03:31 -06001642 if (!uuid) {
1643 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001644 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001645 if (sharedGid != -1) {
1646 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1647 sharedGid, -1);
1648 }
1649 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001650 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001651 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001652
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001653 std::vector<int64_t> ret;
1654 ret.push_back(stats.codeSize);
1655 ret.push_back(stats.dataSize);
1656 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001657 ret.push_back(extStats.codeSize);
1658 ret.push_back(extStats.dataSize);
1659 ret.push_back(extStats.cacheSize);
1660#if MEASURE_DEBUG
1661 LOG(DEBUG) << "Final result " << toString(ret);
1662#endif
1663 *_aidl_return = ret;
1664 return ok();
1665}
1666
1667binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1668 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1669 std::vector<int64_t>* _aidl_return) {
1670 ENFORCE_UID(AID_SYSTEM);
1671 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001672 // NOTE: Locking is relaxed on this method, since it's limited to
1673 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001674
1675 // When modifying this logic, always verify using tests:
1676 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1677
1678#if MEASURE_DEBUG
1679 LOG(INFO) << "Measuring user " << userId;
1680#endif
1681
1682 struct stats stats;
1683 struct stats extStats;
1684 memset(&stats, 0, sizeof(stats));
1685 memset(&extStats, 0, sizeof(extStats));
1686
Risan5f308262018-10-26 12:06:58 -06001687 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001688 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1689
Risan5f308262018-10-26 12:06:58 -06001690 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001691 flags &= ~FLAG_USE_QUOTA;
1692 }
1693
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001694 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001695 int64_t space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001696
1697 ATRACE_BEGIN("obb");
Risan5f308262018-10-26 12:06:58 -06001698 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1699 extStats.codeSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001700 }
1701 ATRACE_END();
1702
Jeff Sharkey466459b2017-01-17 15:25:01 -07001703 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001704 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001705 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001706
Jeff Sharkey466459b2017-01-17 15:25:01 -07001707 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001708 auto cePath = create_data_user_ce_path(uuid_, userId);
1709 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001710 auto dePath = create_data_user_de_path(uuid_, userId);
1711 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001712 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001713
Jeff Sharkey06a61842017-04-15 12:03:31 -06001714 if (!uuid) {
1715 ATRACE_BEGIN("profile");
1716 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1717 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1718 auto refProfilePath = create_primary_ref_profile_dir_path();
1719 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1720 ATRACE_END();
1721 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001722
Jeff Sharkey466459b2017-01-17 15:25:01 -07001723 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001724 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001725 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1726 extStats.dataSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001727 }
1728 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001729
Jeff Sharkey06a61842017-04-15 12:03:31 -06001730 if (!uuid) {
1731 ATRACE_BEGIN("dalvik");
1732 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1733 -1, -1, true);
1734 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1735 -1, -1, true);
1736 ATRACE_END();
1737 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001738
Jeff Sharkey466459b2017-01-17 15:25:01 -07001739 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001740 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001741 for (auto appId : appIds) {
1742 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001743 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001744
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001745#if MEASURE_DEBUG
1746 // Sleep to make sure we don't lose logs
1747 usleep(1);
1748#endif
1749 }
1750 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001751 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001752 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001753 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001754 ATRACE_BEGIN("obb");
1755 auto obbPath = create_data_path(uuid_) + "/media/obb";
1756 calculate_tree_size(obbPath, &extStats.codeSize);
1757 ATRACE_END();
1758
Jeff Sharkey466459b2017-01-17 15:25:01 -07001759 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001760 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001761 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001762
Jeff Sharkey466459b2017-01-17 15:25:01 -07001763 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001764 auto cePath = create_data_user_ce_path(uuid_, userId);
1765 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001766 auto dePath = create_data_user_de_path(uuid_, userId);
1767 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001768 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001769
Jeff Sharkey06a61842017-04-15 12:03:31 -06001770 if (!uuid) {
1771 ATRACE_BEGIN("profile");
1772 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1773 calculate_tree_size(userProfilePath, &stats.dataSize);
1774 auto refProfilePath = create_primary_ref_profile_dir_path();
1775 calculate_tree_size(refProfilePath, &stats.codeSize);
1776 ATRACE_END();
1777 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001778
Jeff Sharkey466459b2017-01-17 15:25:01 -07001779 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001780 auto dataMediaPath = create_data_media_path(uuid_, userId);
1781 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1782#if MEASURE_DEBUG
1783 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1784 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001785#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001786 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001787
Jeff Sharkey06a61842017-04-15 12:03:31 -06001788 if (!uuid) {
1789 ATRACE_BEGIN("dalvik");
1790 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1791 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1792 ATRACE_END();
1793 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001794 }
1795
1796 std::vector<int64_t> ret;
1797 ret.push_back(stats.codeSize);
1798 ret.push_back(stats.dataSize);
1799 ret.push_back(stats.cacheSize);
1800 ret.push_back(extStats.codeSize);
1801 ret.push_back(extStats.dataSize);
1802 ret.push_back(extStats.cacheSize);
1803#if MEASURE_DEBUG
1804 LOG(DEBUG) << "Final result " << toString(ret);
1805#endif
1806 *_aidl_return = ret;
1807 return ok();
1808}
1809
1810binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001811 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1812 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001813 ENFORCE_UID(AID_SYSTEM);
1814 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001815 // NOTE: Locking is relaxed on this method, since it's limited to
1816 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001817
1818 // When modifying this logic, always verify using tests:
1819 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1820
1821#if MEASURE_DEBUG
1822 LOG(INFO) << "Measuring external " << userId;
1823#endif
1824
Risan5f308262018-10-26 12:06:58 -06001825 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001826 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1827
1828 int64_t totalSize = 0;
1829 int64_t audioSize = 0;
1830 int64_t videoSize = 0;
1831 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001832 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001833 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001834
Risan5f308262018-10-26 12:06:58 -06001835 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001836 flags &= ~FLAG_USE_QUOTA;
1837 }
1838
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001839 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001840 int64_t space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001841
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001842 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001843 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001844 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1845 totalSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001846 }
1847
1848 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
Risan5f308262018-10-26 12:06:58 -06001849 if ((space = GetOccupiedSpaceForGid(uuidString, audioGid)) != -1) {
1850 audioSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001851 }
1852 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
Risan5f308262018-10-26 12:06:58 -06001853 if ((space = GetOccupiedSpaceForGid(uuidString, videoGid)) != -1) {
1854 videoSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001855 }
1856 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
Risan5f308262018-10-26 12:06:58 -06001857 if ((space = GetOccupiedSpaceForGid(uuidString, imageGid)) != -1) {
1858 imageSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001859 }
Risan5f308262018-10-26 12:06:58 -06001860 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1861 obbSize = space;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001862 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001863 ATRACE_END();
1864
1865 ATRACE_BEGIN("apps");
1866 struct stats extStats;
1867 memset(&extStats, 0, sizeof(extStats));
1868 for (auto appId : appIds) {
1869 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001870 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001871 }
1872 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001873 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001874 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001875 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001876 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001877 FTS *fts;
1878 FTSENT *p;
1879 auto path = create_data_media_path(uuid_, userId);
1880 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001881 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001882 return error("Failed to fts_open " + path);
1883 }
Yi Kong954cf642018-07-17 16:16:24 -07001884 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001885 char* ext;
1886 int64_t size = (p->fts_statp->st_blocks * 512);
1887 switch (p->fts_info) {
1888 case FTS_F:
1889 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001890 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001891 ext = strrchr(p->fts_name, '.');
1892 if (ext != nullptr) {
1893 switch (MatchExtension(++ext)) {
1894 case AID_MEDIA_AUDIO: audioSize += size; break;
1895 case AID_MEDIA_VIDEO: videoSize += size; break;
1896 case AID_MEDIA_IMAGE: imageSize += size; break;
1897 }
1898 }
1899 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001900 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001901 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001902 // Ignore data belonging to specific apps
1903 p->fts_number = p->fts_parent->fts_number;
1904 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1905 p->fts_number = 1;
1906 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001907 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001908 case FTS_DEFAULT:
1909 case FTS_SL:
1910 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001911 if (p->fts_parent->fts_number == 1) {
1912 appSize += size;
1913 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001914 totalSize += size;
1915 break;
1916 }
1917 }
1918 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001919 ATRACE_END();
Jeff Sharkeya0136982017-07-06 11:29:37 -06001920
1921 ATRACE_BEGIN("obb");
1922 auto obbPath = create_data_media_obb_path(uuid_, "");
1923 calculate_tree_size(obbPath, &obbSize);
1924 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001925 }
1926
1927 std::vector<int64_t> ret;
1928 ret.push_back(totalSize);
1929 ret.push_back(audioSize);
1930 ret.push_back(videoSize);
1931 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001932 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06001933 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001934#if MEASURE_DEBUG
1935 LOG(DEBUG) << "Final result " << toString(ret);
1936#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001937 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001938 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001939}
1940
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001941binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1942 int32_t userId, int32_t appId, int64_t cacheQuota) {
1943 ENFORCE_UID(AID_SYSTEM);
1944 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001945 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001946
1947 int32_t uid = multiuser_get_uid(userId, appId);
1948 mCacheQuotas[uid] = cacheQuota;
1949
1950 return ok();
1951}
1952
David Sehr6727c2d2016-05-17 16:06:22 -07001953// Dumps the contents of a profile file, using pkgname's dex files for pretty
1954// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001955binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08001956 const std::string& profileName, const std::string& codePath, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001957 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001958 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07001959 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001960 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001961
Calin Juravle562de812018-01-20 23:34:18 -08001962 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001963 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001964}
1965
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001966// Copy the contents of a system profile over the data profile.
1967binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08001968 int32_t packageUid, const std::string& packageName, const std::string& profileName,
1969 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001970 ENFORCE_UID(AID_SYSTEM);
1971 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1972 std::lock_guard<std::recursive_mutex> lock(mLock);
Calin Juravle562de812018-01-20 23:34:18 -08001973 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001974 return ok();
1975}
1976
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001977// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001978binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08001979 const std::string& profileName, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001980 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001981 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001982 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001983
Calin Juravle562de812018-01-20 23:34:18 -08001984 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001985 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001986}
1987
Calin Juravlec41dac22017-12-05 12:29:15 -08001988binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08001989 const std::string& packageName, const std::string& profileName,
1990 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08001991 ENFORCE_UID(AID_SYSTEM);
1992 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1993 std::lock_guard<std::recursive_mutex> lock(mLock);
1994
Calin Juravlee61189e2018-01-23 19:54:11 -08001995 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08001996 return ok();
1997}
1998
1999binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002000 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08002001 ENFORCE_UID(AID_SYSTEM);
2002 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2003 std::lock_guard<std::recursive_mutex> lock(mLock);
2004
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002005 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002006 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002007 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002008 }
2009 return ok();
2010}
2011
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002012static const char* getCStr(const std::unique_ptr<std::string>& data,
2013 const char* default_value = nullptr) {
2014 return data == nullptr ? default_value : data->c_str();
2015}
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002016binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2017 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2018 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2019 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle1d667612017-07-13 22:50:21 -07002020 const std::unique_ptr<std::string>& classLoaderContext,
Calin Juravle562de812018-01-20 23:34:18 -08002021 const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002022 const std::unique_ptr<std::string>& profileName,
Calin Juravledcccd832018-02-13 18:31:32 -08002023 const std::unique_ptr<std::string>& dexMetadataPath,
2024 const std::unique_ptr<std::string>& compilationReason) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002025 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002026 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07002027 CHECK_ARGUMENT_PATH(apkPath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002028 if (packageName && *packageName != "*") {
2029 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
2030 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002031 CHECK_ARGUMENT_PATH(outputPath);
2032 CHECK_ARGUMENT_PATH(dexMetadataPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002033 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002034
2035 const char* apk_path = apkPath.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002036 const char* pkgname = getCStr(packageName, "*");
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002037 const char* instruction_set = instructionSet.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002038 const char* oat_dir = getCStr(outputPath);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002039 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002040 const char* volume_uuid = getCStr(uuid);
2041 const char* class_loader_context = getCStr(classLoaderContext);
2042 const char* se_info = getCStr(seInfo);
2043 const char* profile_name = getCStr(profileName);
2044 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08002045 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08002046 std::string error_msg;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002047 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07002048 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Andreas Gampe023b2242018-02-28 16:03:25 -08002049 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg);
2050 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002051}
2052
Eric Holk2af5e6a2019-01-09 18:17:27 -08002053binder::Status InstalldNativeService::compileLayouts(const std::string& apkPath,
2054 const std::string& packageName,
2055 const std ::string& outDexFile, int uid,
2056 bool* _aidl_return) {
2057 const char* apk_path = apkPath.c_str();
2058 const char* package_name = packageName.c_str();
2059 const char* out_dex_file = outDexFile.c_str();
2060 *_aidl_return = android::installd::view_compiler(apk_path, package_name, out_dex_file, uid);
2061 return *_aidl_return ? ok() : error("viewcompiler failed");
2062}
2063
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002064binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2065 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002066 std::lock_guard<std::recursive_mutex> lock(mLock);
2067
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002068 const char* instruction_set = instructionSet.c_str();
2069
2070 char boot_marker_path[PKG_PATH_MAX];
2071 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002072 "%s/%s/%s/.booting",
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -06002073 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08002074 DALVIK_CACHE,
2075 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002076
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002077 ALOGV("mark_boot_complete : %s", boot_marker_path);
2078 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002079 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002080 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002081 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002082}
2083
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002084binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2085 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2086 const std::string& nativeLibPath32, int32_t userId) {
2087 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002088 CHECK_ARGUMENT_UUID(uuid);
2089 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002090 CHECK_ARGUMENT_PATH(nativeLibPath32);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002091 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002092
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002093 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2094 const char* pkgname = packageName.c_str();
2095 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002096 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002097 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002098
Jeff Sharkey423e7462016-12-09 18:18:43 -07002099 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
2100 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002101
2102 const char* pkgdir = _pkgdir.c_str();
2103 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002104
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002105 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002106 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002107 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002108
Nick Kralevich85958b62019-01-30 12:32:21 -08002109 char *con = nullptr;
2110 if (lgetfilecon(pkgdir, &con) < 0) {
2111 return error("Failed to lgetfilecon " + _pkgdir);
2112 }
2113
Mike Lockwood94afecf2012-10-24 10:45:23 -07002114 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08002115 res = error("Failed to chown " + _pkgdir);
2116 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002117 }
2118
2119 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002120 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002121 goto out;
2122 }
2123
2124 if (lstat(libsymlink, &libStat) < 0) {
2125 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002126 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002127 goto out;
2128 }
2129 } else {
2130 if (S_ISDIR(libStat.st_mode)) {
Yi Kong954cf642018-07-17 16:16:24 -07002131 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002132 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002133 goto out;
2134 }
2135 } else if (S_ISLNK(libStat.st_mode)) {
2136 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002137 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002138 goto out;
2139 }
2140 }
2141 }
2142
2143 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002144 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002145 goto out;
2146 }
2147
Nick Kralevich85958b62019-01-30 12:32:21 -08002148 if (lsetfilecon(libsymlink, con) < 0) {
2149 res = error("Failed to lsetfilecon " + _libsymlink);
2150 goto out;
2151 }
2152
Mike Lockwood94afecf2012-10-24 10:45:23 -07002153out:
Nick Kralevich85958b62019-01-30 12:32:21 -08002154 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002155 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002156 auto msg = "Failed to cleanup chmod " + _pkgdir;
2157 if (res.isOk()) {
2158 res = error(msg);
2159 } else {
2160 PLOG(ERROR) << msg;
2161 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002162 }
2163
2164 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002165 auto msg = "Failed to cleanup chown " + _pkgdir;
2166 if (res.isOk()) {
2167 res = error(msg);
2168 } else {
2169 PLOG(ERROR) << msg;
2170 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002171 }
2172
Jeff Sharkey423e7462016-12-09 18:18:43 -07002173 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002174}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002175
2176static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2177{
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002178 execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
Yi Kong954cf642018-07-17 16:16:24 -07002179 StringPrintf("%d", idmap_fd).c_str(), (char*)nullptr);
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002180 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2181}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002182
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002183static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2184{
2185 execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
Yi Kong954cf642018-07-17 16:16:24 -07002186 StringPrintf("%d", idmap_fd).c_str(), (char*)nullptr);
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002187 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2188}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002189
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002190static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
2191 const char* idmap_path, int32_t uid) {
2192 int idmap_fd = open(idmap_path, O_RDWR);
2193 if (idmap_fd < 0) {
2194 PLOG(ERROR) << "idmap open failed: " << idmap_path;
2195 unlink(idmap_path);
2196 return true;
2197 }
2198
2199 pid_t pid;
2200 pid = fork();
2201 if (pid == 0) {
2202 /* child -- drop privileges before continuing */
2203 if (setgid(uid) != 0) {
2204 LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
2205 exit(1);
2206 }
2207 if (setuid(uid) != 0) {
2208 LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
2209 exit(1);
2210 }
2211 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2212 PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
2213 exit(1);
2214 }
2215
2216 run_verify_idmap(target_apk, overlay_apk, idmap_fd);
2217 exit(1); /* only if exec call to deleting stale idmap failed */
2218 } else {
2219 int status = wait_child(pid);
2220 close(idmap_fd);
2221
2222 if (status != 0) {
2223 // Failed on verifying if idmap is made from target_apk and overlay_apk.
2224 LOG(DEBUG) << "delete stale idmap: " << idmap_path;
2225 unlink(idmap_path);
2226 return true;
2227 }
2228 }
2229 return false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002230}
2231
2232// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2233// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2234static int flatten_path(const char *prefix, const char *suffix,
2235 const char *overlay_path, char *idmap_path, size_t N)
2236{
Yi Kong954cf642018-07-17 16:16:24 -07002237 if (overlay_path == nullptr || idmap_path == nullptr) {
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002238 return -1;
2239 }
2240 const size_t len_overlay_path = strlen(overlay_path);
2241 // will access overlay_path + 1 further below; requires absolute path
2242 if (len_overlay_path < 2 || *overlay_path != '/') {
2243 return -1;
2244 }
2245 const size_t len_idmap_root = strlen(prefix);
2246 const size_t len_suffix = strlen(suffix);
2247 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2248 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2249 // additions below would cause overflow
2250 return -1;
2251 }
2252 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2253 return -1;
2254 }
2255 memset(idmap_path, 0, N);
2256 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2257 char *ch = idmap_path + len_idmap_root;
2258 while (*ch != '\0') {
2259 if (*ch == '/') {
2260 *ch = '@';
2261 }
2262 ++ch;
2263 }
2264 return 0;
2265}
2266
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002267binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2268 const std::string& overlayApkPath, int32_t uid) {
2269 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002270 CHECK_ARGUMENT_PATH(targetApkPath);
2271 CHECK_ARGUMENT_PATH(overlayApkPath);
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* target_apk = targetApkPath.c_str();
2275 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002276 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2277
2278 int idmap_fd = -1;
2279 char idmap_path[PATH_MAX];
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002280 struct stat idmap_stat;
2281 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002282
2283 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2284 idmap_path, sizeof(idmap_path)) == -1) {
2285 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2286 goto fail;
2287 }
2288
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002289 if (stat(idmap_path, &idmap_stat) < 0) {
2290 outdated = true;
2291 } else {
2292 outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2293 }
2294
2295 if (outdated) {
2296 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2297 } else {
2298 idmap_fd = open(idmap_path, O_RDWR);
2299 }
2300
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002301 if (idmap_fd < 0) {
2302 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2303 goto fail;
2304 }
2305 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2306 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2307 goto fail;
2308 }
2309 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2310 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2311 goto fail;
2312 }
2313
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002314 if (!outdated) {
2315 close(idmap_fd);
2316 return ok();
2317 }
2318
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002319 pid_t pid;
2320 pid = fork();
2321 if (pid == 0) {
2322 /* child -- drop privileges before continuing */
2323 if (setgid(uid) != 0) {
2324 ALOGE("setgid(%d) failed during idmap\n", uid);
2325 exit(1);
2326 }
2327 if (setuid(uid) != 0) {
2328 ALOGE("setuid(%d) failed during idmap\n", uid);
2329 exit(1);
2330 }
2331 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2332 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2333 exit(1);
2334 }
2335
2336 run_idmap(target_apk, overlay_apk, idmap_fd);
2337 exit(1); /* only if exec call to idmap failed */
2338 } else {
2339 int status = wait_child(pid);
2340 if (status != 0) {
2341 ALOGE("idmap failed, status=0x%04x\n", status);
2342 goto fail;
2343 }
2344 }
2345
2346 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002347 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002348fail:
2349 if (idmap_fd >= 0) {
2350 close(idmap_fd);
2351 unlink(idmap_path);
2352 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002353 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002354}
Robert Craige9887e42014-02-20 10:25:56 -05002355
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002356binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
Jeff Sharkey53594302018-02-24 18:59:39 -07002357 ENFORCE_UID(AID_SYSTEM);
2358 CHECK_ARGUMENT_PATH(overlayApkPath);
2359 std::lock_guard<std::recursive_mutex> lock(mLock);
2360
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002361 const char* overlay_apk = overlayApkPath.c_str();
2362 char idmap_path[PATH_MAX];
2363
2364 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2365 idmap_path, sizeof(idmap_path)) == -1) {
2366 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2367 return error();
2368 }
2369 if (unlink(idmap_path) < 0) {
2370 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2371 return error();
2372 }
2373 return ok();
2374}
2375
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002376binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2377 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2378 const std::string& seInfo) {
2379 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002380 CHECK_ARGUMENT_UUID(uuid);
2381 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002382 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002383
2384 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002385
Robert Craigda30dc72014-03-27 10:21:12 -04002386 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002387 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002388 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2389 const char* pkgName = packageName.c_str();
2390 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002391
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002392 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002393 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002394 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002395 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002396 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002397 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002398 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002399 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002400 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002401 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002402 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002403 }
Robert Craige9887e42014-02-20 10:25:56 -05002404 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002405 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002406}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002407
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002408binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2409 const std::string& instructionSet) {
2410 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002411 CHECK_ARGUMENT_PATH(oatDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002412 std::lock_guard<std::recursive_mutex> lock(mLock);
2413
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002414 const char* oat_dir = oatDir.c_str();
2415 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002416 char oat_instr_dir[PKG_PATH_MAX];
2417
2418 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002419 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002420 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002421 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002422 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002423 }
2424 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002425 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002426 }
2427 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002428 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002429 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002430 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002431 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002432}
2433
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002434binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2435 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002436 CHECK_ARGUMENT_PATH(packageDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002437 std::lock_guard<std::recursive_mutex> lock(mLock);
2438
Jeff Sharkey423e7462016-12-09 18:18:43 -07002439 if (validate_apk_path(packageDir.c_str())) {
2440 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002441 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002442 if (delete_dir_contents_and_dir(packageDir) != 0) {
2443 return error("Failed to delete " + packageDir);
2444 }
2445 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002446}
2447
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002448binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2449 const std::string& fromBase, const std::string& toBase) {
2450 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002451 CHECK_ARGUMENT_PATH(fromBase);
2452 CHECK_ARGUMENT_PATH(toBase);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002453 std::lock_guard<std::recursive_mutex> lock(mLock);
2454
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002455 const char* relative_path = relativePath.c_str();
2456 const char* from_base = fromBase.c_str();
2457 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002458 char from_path[PKG_PATH_MAX];
2459 char to_path[PKG_PATH_MAX];
2460 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2461 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2462
2463 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002464 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002465 }
2466
2467 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002468 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002469 }
2470
Jeff Sharkey423e7462016-12-09 18:18:43 -07002471 if (link(from_path, to_path) < 0) {
2472 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002473 }
2474
Jeff Sharkey423e7462016-12-09 18:18:43 -07002475 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002476}
2477
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002478binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2479 const std::string& instructionSet, const std::string& outputPath) {
2480 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002481 CHECK_ARGUMENT_PATH(apkPath);
2482 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002483 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002484
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002485 const char* apk_path = apkPath.c_str();
2486 const char* instruction_set = instructionSet.c_str();
2487 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002488
Jeff Sharkey90aff262016-12-12 14:28:24 -07002489 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002490 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002491}
2492
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002493binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002494 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002495 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002496 CHECK_ARGUMENT_PATH(apkPath);
2497 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002498 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002499
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002500 const char* apk_path = apkPath.c_str();
2501 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002502 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002503
Jeff Sharkey90aff262016-12-12 14:28:24 -07002504 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2505 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002506}
2507
Victor Hsieh7ebd5132018-01-23 07:52:17 -08002508// This kernel feature is experimental.
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002509// TODO: remove local definition once upstreamed
Victor Hsieh18ac0272018-03-12 16:03:02 -07002510#ifndef FS_IOC_ENABLE_VERITY
2511
2512#define FS_IOC_ENABLE_VERITY _IO('f', 133)
2513#define FS_IOC_SET_VERITY_MEASUREMENT _IOW('f', 134, struct fsverity_measurement)
2514
2515#define FS_VERITY_ALG_SHA256 1
2516
2517struct fsverity_measurement {
2518 __u16 digest_algorithm;
2519 __u16 digest_size;
2520 __u32 reserved1;
2521 __u64 reserved2[3];
2522 __u8 digest[];
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002523};
2524
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002525#endif
2526
2527binder::Status InstalldNativeService::installApkVerity(const std::string& filePath,
Victor Hsieh18ac0272018-03-12 16:03:02 -07002528 const ::android::base::unique_fd& verityInputAshmem, int32_t contentSize) {
Victor Hsieh99de5162017-10-06 14:44:14 -07002529 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002530 CHECK_ARGUMENT_PATH(filePath);
2531 std::lock_guard<std::recursive_mutex> lock(mLock);
2532
Victor Hsieh99de5162017-10-06 14:44:14 -07002533 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2534 return ok();
2535 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002536#ifndef NDEBUG
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002537 ASSERT_PAGE_SIZE_4K();
2538#endif
2539 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2540 // TODO: change ashmem to some temporary file to support huge apk.
2541 if (!ashmem_valid(verityInputAshmem.get())) {
2542 return error("FD is not an ashmem");
2543 }
2544
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002545 // 1. Seek to the next page boundary beyond the end of the file.
Victor Hsieh93a98052018-01-24 14:56:32 -08002546 ::android::base::unique_fd wfd(open(filePath.c_str(), O_WRONLY));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002547 if (wfd.get() < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002548 return error("Failed to open " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002549 }
2550 struct stat st;
2551 if (fstat(wfd.get(), &st) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002552 return error("Failed to stat " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002553 }
2554 // fsverity starts from the block boundary.
Victor Hsieh93a98052018-01-24 14:56:32 -08002555 off_t padding = kVerityPageSize - st.st_size % kVerityPageSize;
2556 if (padding == kVerityPageSize) {
2557 padding = 0;
2558 }
2559 if (lseek(wfd.get(), st.st_size + padding, SEEK_SET) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002560 return error("Failed to lseek " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002561 }
2562
Victor Hsieh18ac0272018-03-12 16:03:02 -07002563 // 2. Write everything in the ashmem to the file. Note that allocated
2564 // ashmem size is multiple of page size, which is different from the
2565 // actual content size.
2566 int shmSize = ashmem_get_size_region(verityInputAshmem.get());
2567 if (shmSize < 0) {
2568 return error("Failed to get ashmem size: " + std::to_string(shmSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002569 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002570 if (contentSize < 0) {
2571 return error("Invalid content size: " + std::to_string(contentSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002572 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002573 if (contentSize > shmSize) {
2574 return error("Content size overflow: " + std::to_string(contentSize) + " > " +
2575 std::to_string(shmSize));
2576 }
2577 auto data = std::unique_ptr<void, std::function<void (void *)>>(
Yi Kong954cf642018-07-17 16:16:24 -07002578 mmap(nullptr, contentSize, PROT_READ, MAP_SHARED, verityInputAshmem.get(), 0),
Victor Hsieh18ac0272018-03-12 16:03:02 -07002579 [contentSize] (void* ptr) {
2580 if (ptr != MAP_FAILED) {
2581 munmap(ptr, contentSize);
2582 }
2583 });
2584
2585 if (data.get() == MAP_FAILED) {
2586 return error("Failed to mmap the ashmem");
2587 }
2588 char* cursor = reinterpret_cast<char*>(data.get());
2589 int remaining = contentSize;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002590 while (remaining > 0) {
Victor Hsieh93a98052018-01-24 14:56:32 -08002591 int ret = TEMP_FAILURE_RETRY(write(wfd.get(), cursor, remaining));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002592 if (ret < 0) {
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002593 return error("Failed to write to " + filePath + " (" + std::to_string(remaining) +
Victor Hsieh18ac0272018-03-12 16:03:02 -07002594 + "/" + std::to_string(contentSize) + ")");
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002595 }
Victor Hsieh93a98052018-01-24 14:56:32 -08002596 cursor += ret;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002597 remaining -= ret;
2598 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002599 wfd.reset();
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002600
Victor Hsieh18ac0272018-03-12 16:03:02 -07002601 // 3. Enable fsverity (needs readonly fd. Once it's done, the file becomes immutable.
2602 ::android::base::unique_fd rfd(open(filePath.c_str(), O_RDONLY));
2603 if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, nullptr) < 0) {
2604 return error("Failed to enable fsverity on " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002605 }
2606 return ok();
Victor Hsieh99de5162017-10-06 14:44:14 -07002607}
2608
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002609binder::Status InstalldNativeService::assertFsverityRootHashMatches(const std::string& filePath,
2610 const std::vector<uint8_t>& expectedHash) {
2611 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002612 CHECK_ARGUMENT_PATH(filePath);
2613 std::lock_guard<std::recursive_mutex> lock(mLock);
2614
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002615 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2616 return ok();
2617 }
2618 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2619 if (expectedHash.size() != kSha256Size) {
2620 return error("verity hash size should be " + std::to_string(kSha256Size) + " but is " +
2621 std::to_string(expectedHash.size()));
2622 }
2623
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002624 ::android::base::unique_fd fd(open(filePath.c_str(), O_RDONLY));
2625 if (fd.get() < 0) {
2626 return error("Failed to open " + filePath + ": " + strerror(errno));
2627 }
2628
Victor Hsieh18ac0272018-03-12 16:03:02 -07002629 unsigned int buffer_size = sizeof(fsverity_measurement) + kSha256Size;
2630 std::vector<char> buffer(buffer_size, 0);
2631
2632 fsverity_measurement* config = reinterpret_cast<fsverity_measurement*>(buffer.data());
2633 config->digest_algorithm = FS_VERITY_ALG_SHA256;
2634 config->digest_size = kSha256Size;
2635 memcpy(config->digest, expectedHash.data(), kSha256Size);
2636 if (ioctl(fd.get(), FS_IOC_SET_VERITY_MEASUREMENT, config) < 0) {
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002637 // This includes an expected failure case with no FSVerity setup. It normally happens when
2638 // the apk does not contains the Merkle tree root hash.
2639 return error("Failed to measure fsverity on " + filePath + ": " + strerror(errno));
2640 }
2641 return ok(); // hashes match
2642}
2643
Calin Juravlebd968362017-01-25 01:17:17 -08002644binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2645 const std::string& dexPath, const std::string& packageName, int32_t uid,
2646 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2647 int32_t storage_flag, bool* _aidl_return) {
2648 ENFORCE_UID(AID_SYSTEM);
2649 CHECK_ARGUMENT_UUID(volumeUuid);
2650 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002651 CHECK_ARGUMENT_PATH(dexPath);
Calin Juravlebd968362017-01-25 01:17:17 -08002652 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey53594302018-02-24 18:59:39 -07002653
Calin Juravlebd968362017-01-25 01:17:17 -08002654 bool result = android::installd::reconcile_secondary_dex_file(
2655 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2656 return result ? ok() : error();
2657}
2658
Alan Stokes753dc712017-10-16 10:56:00 +01002659binder::Status InstalldNativeService::hashSecondaryDexFile(
2660 const std::string& dexPath, const std::string& packageName, int32_t uid,
2661 const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
2662 std::vector<uint8_t>* _aidl_return) {
2663 ENFORCE_UID(AID_SYSTEM);
2664 CHECK_ARGUMENT_UUID(volumeUuid);
2665 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002666 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01002667
2668 // mLock is not taken here since we will never modify the file system.
2669 // If a file is modified just as we are reading it this may result in an
2670 // anomalous hash, but that's ok.
2671 bool result = android::installd::hash_secondary_dex_file(
2672 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
2673 return result ? ok() : error();
2674}
2675
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002676binder::Status InstalldNativeService::invalidateMounts() {
2677 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002678 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002679
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002680 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06002681
2682#if !BYPASS_QUOTA
2683 if (!InvalidateQuotaMounts()) {
2684 return error("Failed to read mounts");
2685 }
2686#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002687
2688 std::ifstream in("/proc/mounts");
2689 if (!in.is_open()) {
2690 return error("Failed to read mounts");
2691 }
2692
2693 std::string source;
2694 std::string target;
2695 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002696 while (!in.eof()) {
2697 std::getline(in, source, ' ');
2698 std::getline(in, target, ' ');
2699 std::getline(in, ignored);
2700
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002701#if !BYPASS_SDCARDFS
2702 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2703 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2704 mStorageMounts[source] = target;
2705 }
2706#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002707 }
2708 return ok();
2709}
2710
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002711std::string InstalldNativeService::findDataMediaPath(
2712 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2713 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2714 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2715 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2716 auto resolved = mStorageMounts[path];
2717 if (resolved.empty()) {
2718 LOG(WARNING) << "Failed to find storage mount for " << path;
2719 resolved = path;
2720 }
2721 return StringPrintf("%s/%u", resolved.c_str(), userid);
2722}
2723
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002724binder::Status InstalldNativeService::isQuotaSupported(
Risan5f308262018-10-26 12:06:58 -06002725 const std::unique_ptr<std::string>& uuid, bool* _aidl_return) {
2726 auto uuidString = uuid ? *uuid : "";
2727 *_aidl_return = IsQuotaSupported(uuidString);
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002728 return ok();
2729}
2730
Calin Juravlebc5ab872018-01-18 22:32:58 -08002731binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
2732 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
2733 const std::unique_ptr<std::string>& dexMetadata, bool* _aidl_return) {
2734 ENFORCE_UID(AID_SYSTEM);
2735 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002736 CHECK_ARGUMENT_PATH(codePath);
Calin Juravlebc5ab872018-01-18 22:32:58 -08002737 std::lock_guard<std::recursive_mutex> lock(mLock);
2738
2739 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
2740 dexMetadata);
2741 return ok();
2742}
2743
Andreas Gampe02d0de52015-11-11 20:43:16 -08002744} // namespace installd
2745} // namespace android