blob: c7d9245d1763ff3d4f42fba75f39b69b87cc7c92 [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) {
947 // TODO(narayan): Should we clear clear the rolled back CE data if
948 // something goes wrong here ? We're choosing between leaving the
949 // app devoid of all its data or with just its ce data installed.
950 res = error(rc, "Failed copying " + from_de + " to " + to_de);
951 return res;
952 }
953 }
954
955 // Finally, restore the SELinux label on the app data.
956 return restoreconAppData(volumeUuid, packageName, user, storageFlags, appId, seInfo);
957}
958
Nikita Ioffe8755f792019-01-25 13:54:43 +0000959binder::Status InstalldNativeService::destroyAppDataSnapshot(
960 const std::unique_ptr<std::string> &volumeUuid, const std::string& packageName,
961 const int32_t user, const int64_t ceSnapshotInode, int32_t storageFlags) {
962 ENFORCE_UID(AID_SYSTEM);
963 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
964 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
965 std::lock_guard<std::recursive_mutex> lock(mLock);
966
967 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
968 const char* package_name = packageName.c_str();
969
970 if (storageFlags & FLAG_STORAGE_DE) {
971 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid,
972 user, package_name);
973
974 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
975 if (res != 0) {
976 return error(res, "Failed clearing snapshot " + de_snapshot_path);
977 }
978 }
979
980 if (storageFlags & FLAG_STORAGE_CE) {
981 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid,
982 user, package_name, ceSnapshotInode);
983 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
984 if (res != 0) {
985 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
986 }
987 }
988 return ok();
989}
990
991
Jeff Sharkey0274c972016-12-06 09:32:04 -0700992binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
993 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
994 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
995 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700996 ENFORCE_UID(AID_SYSTEM);
997 CHECK_ARGUMENT_UUID(fromUuid);
998 CHECK_ARGUMENT_UUID(toUuid);
999 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001000 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -07001001
1002 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1003 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1004 const char* package_name = packageName.c_str();
1005 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001006
Jeff Sharkey423e7462016-12-09 18:18:43 -07001007 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001008 std::vector<userid_t> users = get_known_users(from_uuid);
1009
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001010 // Copy app
1011 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001012 auto from = create_data_app_package_path(from_uuid, data_app_name);
1013 auto to = create_data_app_package_path(to_uuid, data_app_name);
1014 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001015
Narayan Kamathdfdfb792019-01-14 15:21:52 +00001016 int rc = copy_directory_recursive(from.c_str(), to_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001017 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001018 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001019 goto fail;
1020 }
1021
1022 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001023 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001024 goto fail;
1025 }
1026 }
1027
1028 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -07001029 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -07001030
1031 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -06001032 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
1033 if (access(from_ce.c_str(), F_OK) != 0) {
1034 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001035 continue;
1036 }
1037
Jeff Sharkey0274c972016-12-06 09:32:04 -07001038 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -07001039 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001040 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001041 goto fail;
1042 }
1043
Jeff Sharkey51c94492016-05-10 17:46:39 -06001044 {
1045 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
1046 auto to = create_data_user_de_path(to_uuid, user);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001047
Narayan Kamathdfdfb792019-01-14 15:21:52 +00001048 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001049 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001050 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001051 goto fail;
1052 }
1053 }
1054 {
1055 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
1056 auto to = create_data_user_ce_path(to_uuid, user);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001057
Narayan Kamathdfdfb792019-01-14 15:21:52 +00001058 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001059 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001060 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001061 goto fail;
1062 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001063 }
1064
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001065 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1066 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001067 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001068 goto fail;
1069 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001070 }
1071
Jeff Sharkey31f08982015-07-07 13:31:37 -07001072 // We let the framework scan the new location and persist that before
1073 // deleting the data in the old location; this ordering ensures that
1074 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001075 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001076
1077fail:
1078 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001079 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001080 auto to = create_data_app_package_path(to_uuid, data_app_name);
Yi Kong954cf642018-07-17 16:16:24 -07001081 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001082 LOG(WARNING) << "Failed to rollback " << to;
1083 }
1084 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001085 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001086 {
1087 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
Yi Kong954cf642018-07-17 16:16:24 -07001088 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001089 LOG(WARNING) << "Failed to rollback " << to;
1090 }
1091 }
1092 {
1093 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
Yi Kong954cf642018-07-17 16:16:24 -07001094 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001095 LOG(WARNING) << "Failed to rollback " << to;
1096 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001097 }
1098 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001099 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001100}
1101
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001102binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
1103 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
1104 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001105 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001106 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001107
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001108 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001109 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001110 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001111 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001112 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07001113 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001114 }
1115 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001116
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001117 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001118}
1119
1120binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
1121 int32_t userId, int32_t flags) {
1122 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001123 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001124 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001125
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001126 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001127 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001128 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001129 auto path = create_data_user_de_path(uuid_, userId);
1130 if (delete_dir_contents_and_dir(path, true) != 0) {
1131 res = error("Failed to delete " + path);
1132 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001133 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001134 path = create_data_misc_legacy_path(userId);
1135 if (delete_dir_contents_and_dir(path, true) != 0) {
1136 res = error("Failed to delete " + path);
1137 }
Calin Juravle114f0812017-03-08 19:05:07 -08001138 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001139 if (delete_dir_contents_and_dir(path, true) != 0) {
1140 res = error("Failed to delete " + path);
1141 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001142 }
Robin Lee095c7632014-04-25 15:05:19 +01001143 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001144 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001145 auto path = create_data_user_ce_path(uuid_, userId);
1146 if (delete_dir_contents_and_dir(path, true) != 0) {
1147 res = error("Failed to delete " + path);
1148 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001149 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001150 if (delete_dir_contents_and_dir(path, true) != 0) {
1151 res = error("Failed to delete " + path);
1152 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001153 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001154 return res;
Robin Lee095c7632014-04-25 15:05:19 +01001155}
1156
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001157binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001158 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001159 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001160 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001161 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001162
Risan5f308262018-10-26 12:06:58 -06001163 auto uuidString = uuid ? *uuid : "";
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001164 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001165 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001166 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001167
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001168 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001169 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001170 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001171 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001172
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001173 int64_t cleared = 0;
1174 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001175 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001176 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001177
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001178 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001179 return ok();
1180 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001181
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001182 if (flags & FLAG_FREE_CACHE_V2) {
1183 // This new cache strategy fairly removes files from UIDs by deleting
1184 // files from the UIDs which are most over their allocated quota
1185
1186 // 1. Create trackers for every known UID
1187 ATRACE_BEGIN("create");
1188 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
1189 for (auto user : get_known_users(uuid_)) {
1190 FTS *fts;
1191 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001192 auto ce_path = create_data_user_ce_path(uuid_, user);
1193 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001194 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
1195 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
1196 (char*) media_path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001197 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001198 return error("Failed to fts_open");
1199 }
Yi Kong954cf642018-07-17 16:16:24 -07001200 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001201 if (p->fts_info == FTS_D && p->fts_level == 1) {
1202 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001203 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
1204 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
1205 + AID_APP_START;
1206 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001207 auto search = trackers.find(uid);
1208 if (search != trackers.end()) {
1209 search->second->addDataPath(p->fts_path);
1210 } else {
1211 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06001212 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001213 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001214 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001215 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001216 tracker->cacheQuota = mCacheQuotas[uid];
1217 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001218 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001219#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001220 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001221#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001222 tracker->cacheQuota = 67108864;
1223 }
1224 trackers[uid] = tracker;
1225 }
1226 fts_set(fts, p, FTS_SKIP);
1227 }
1228 }
1229 fts_close(fts);
1230 }
1231 ATRACE_END();
1232
1233 // 2. Populate tracker stats and insert into priority queue
1234 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001235 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001236 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1237 return (left->getCacheRatio() < right->getCacheRatio());
1238 };
1239 std::priority_queue<std::shared_ptr<CacheTracker>,
1240 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1241 for (const auto& it : trackers) {
1242 it.second->loadStats();
1243 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001244 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001245 }
1246 ATRACE_END();
1247
1248 // 3. Bounce across the queue, freeing items from whichever tracker is
1249 // the most over their assigned quota
1250 ATRACE_BEGIN("bounce");
1251 std::shared_ptr<CacheTracker> active;
1252 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001253 // Only look at apps under quota when explicitly requested
1254 if (active && (active->getCacheRatio() < 10000)
1255 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1256 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1257 << " isn't over quota, and defy not requested";
1258 break;
1259 }
1260
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001261 // Only keep clearing when we haven't pushed into reserved area
1262 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1263 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1264 break;
1265 }
1266
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001267 // Find the best tracker to work with; this might involve swapping
1268 // if the active tracker is no longer the most over quota
1269 bool nextBetter = active && !queue.empty()
1270 && active->getCacheRatio() < queue.top()->getCacheRatio();
1271 if (!active || nextBetter) {
1272 if (active) {
1273 // Current tracker still has items, so we'll consider it
1274 // again later once it bubbles up to surface
1275 queue.push(active);
1276 }
1277 active = queue.top(); queue.pop();
1278 active->ensureItems();
1279 continue;
1280 }
1281
1282 // If no items remain, go find another tracker
1283 if (active->items.empty()) {
1284 active = nullptr;
1285 continue;
1286 } else {
1287 auto item = active->items.back();
1288 active->items.pop_back();
1289
1290 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1291 if (!noop) {
1292 item->purge();
1293 }
1294 active->cacheUsed -= item->size;
1295 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001296 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001297 }
1298
1299 // Verify that we're actually done before bailing, since sneaky
1300 // apps might be using hardlinks
1301 if (needed <= 0) {
1302 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001303 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001304 if (needed <= 0) {
1305 break;
1306 } else {
1307 LOG(WARNING) << "Expected to be done but still need " << needed;
1308 }
1309 }
1310 }
1311 ATRACE_END();
1312
1313 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001314 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001315 }
1316
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001317 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001318 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001319 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001320 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001321 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001322 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001323 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001324}
1325
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001326binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1327 const std::string& instructionSet) {
1328 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07001329 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001330 std::lock_guard<std::recursive_mutex> lock(mLock);
1331
Mike Lockwood94afecf2012-10-24 10:45:23 -07001332 char dex_path[PKG_PATH_MAX];
1333
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001334 const char* path = codePath.c_str();
1335 const char* instruction_set = instructionSet.c_str();
1336
Jeff Sharkey770180a2014-09-08 17:14:26 -07001337 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001338 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001339 }
1340
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001341 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001342 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001343 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001344
1345 ALOGV("unlink %s\n", dex_path);
1346 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001347 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1348 // but could not be unlinked.
1349 if (errno != ENOENT) {
1350 return error(StringPrintf("Failed to unlink %s", dex_path));
1351 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001352 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001353 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001354}
1355
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001356struct stats {
1357 int64_t codeSize;
1358 int64_t dataSize;
1359 int64_t cacheSize;
1360};
1361
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001362#if MEASURE_DEBUG
1363static std::string toString(std::vector<int64_t> values) {
1364 std::stringstream res;
1365 res << "[";
1366 for (size_t i = 0; i < values.size(); i++) {
1367 res << values[i];
1368 if (i < values.size() - 1) {
1369 res << ",";
1370 }
1371 }
1372 res << "]";
1373 return res.str();
1374}
1375#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001376
Risan5f308262018-10-26 12:06:58 -06001377static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001378 int32_t appId, struct stats* stats, struct stats* extStats) {
Risan5f308262018-10-26 12:06:58 -06001379 int64_t space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001380 if (stats != nullptr) {
1381 uid_t uid = multiuser_get_uid(userId, appId);
Risan5f308262018-10-26 12:06:58 -06001382 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
1383 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001384 }
1385
1386 int cacheGid = multiuser_get_cache_gid(userId, appId);
1387 if (cacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001388 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
1389 stats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001390 }
1391 }
1392
1393 int sharedGid = multiuser_get_shared_gid(0, appId);
1394 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001395 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
1396 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001397 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001398 }
1399 }
1400
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001401 if (extStats != nullptr) {
1402 int extGid = multiuser_get_ext_gid(userId, appId);
1403 if (extGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001404 if ((space = GetOccupiedSpaceForGid(uuid, extGid)) != -1) {
1405 extStats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001406 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001407 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001408
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001409 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1410 if (extCacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001411 if ((space = GetOccupiedSpaceForGid(uuid, extCacheGid)) != -1) {
1412 extStats->dataSize += space;
1413 extStats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001414 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001415 }
1416 }
1417}
1418
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001419static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001420 DIR *d;
1421 int dfd;
1422 struct dirent *de;
1423 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001424
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001425 d = opendir(path.c_str());
1426 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001427 if (errno != ENOENT) {
1428 PLOG(WARNING) << "Failed to open " << path;
1429 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001430 return;
1431 }
1432 dfd = dirfd(d);
1433 while ((de = readdir(d))) {
1434 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001435
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001436 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001437 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001438 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001439 }
1440
1441 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001442 if (!strcmp(name, ".")) {
1443 // Don't recurse, but still count node size
1444 } else if (!strcmp(name, "..")) {
1445 // Don't recurse or count node size
1446 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001447 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001448 // Measure all children nodes
1449 size = 0;
1450 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001451 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001452
1453 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1454 stats->cacheSize += size;
1455 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001456 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001457
1458 // Legacy symlink isn't owned by app
1459 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1460 continue;
1461 }
1462
1463 // Everything found inside is considered data
1464 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001465 }
1466 closedir(d);
1467}
1468
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001469static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1470 bool exclude_apps = false) {
1471 DIR *d;
1472 int dfd;
1473 struct dirent *de;
1474 struct stat s;
1475
1476 d = opendir(path.c_str());
1477 if (d == nullptr) {
1478 if (errno != ENOENT) {
1479 PLOG(WARNING) << "Failed to open " << path;
1480 }
1481 return;
1482 }
1483 dfd = dirfd(d);
1484 while ((de = readdir(d))) {
1485 if (de->d_type == DT_DIR) {
1486 const char *name = de->d_name;
1487 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1488 continue;
1489 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001490 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001491 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1492 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001493 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001494 continue;
1495 } else {
1496 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1497 }
1498 }
1499 }
1500 closedir(d);
1501}
1502
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001503static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1504 FTS *fts;
1505 FTSENT *p;
1506 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001507 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001508 PLOG(ERROR) << "Failed to fts_open " << path;
1509 return;
1510 }
Yi Kong954cf642018-07-17 16:16:24 -07001511 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001512 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001513 switch (p->fts_info) {
1514 case FTS_D:
1515 if (p->fts_level == 4
1516 && !strcmp(p->fts_name, "cache")
1517 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1518 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1519 p->fts_number = 1;
1520 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001521 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001522 case FTS_DEFAULT:
1523 case FTS_F:
1524 case FTS_SL:
1525 case FTS_SLNONE:
1526 int64_t size = (p->fts_statp->st_blocks * 512);
1527 if (p->fts_number == 1) {
1528 stats->cacheSize += size;
1529 }
1530 stats->dataSize += size;
1531 break;
1532 }
1533 }
1534 fts_close(fts);
1535}
1536
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001537binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001538 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1539 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1540 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001541 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001542 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001543 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001544 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1545 }
Jeff Sharkey53594302018-02-24 18:59:39 -07001546 for (const auto& codePath : codePaths) {
1547 CHECK_ARGUMENT_PATH(codePath);
1548 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001549 // NOTE: Locking is relaxed on this method, since it's limited to
1550 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001551
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001552 // When modifying this logic, always verify using tests:
1553 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1554
1555#if MEASURE_DEBUG
1556 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1557#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001558
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001559 // Here's a summary of the common storage locations across the platform,
1560 // and how they're each tagged:
1561 //
1562 // /data/app/com.example UID system
1563 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001564 // /data/user/0/com.example UID u0_a10 GID u0_a10
1565 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1566 // /data/media/0/foo.txt UID u0_media_rw
1567 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1568 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1569 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1570 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001571
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001572 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001573 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001574 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001575 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001576
Risan5f308262018-10-26 12:06:58 -06001577 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001578 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001579
Risan5f308262018-10-26 12:06:58 -06001580 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001581 flags &= ~FLAG_USE_QUOTA;
1582 }
1583
Jeff Sharkey466459b2017-01-17 15:25:01 -07001584 ATRACE_BEGIN("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001585 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001586 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1587 calculate_tree_size(obbCodePath, &extStats.codeSize);
1588 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001589 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001590
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001591 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001592 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001593 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001594 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001595 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001596 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001597 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001598
Jeff Sharkey466459b2017-01-17 15:25:01 -07001599 ATRACE_BEGIN("quota");
Risan5f308262018-10-26 12:06:58 -06001600 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001601 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001602 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001603 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001604 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001605 calculate_tree_size(codePath, &stats.codeSize);
1606 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001607 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001608
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001609 for (size_t i = 0; i < packageNames.size(); i++) {
1610 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001611
Jeff Sharkey466459b2017-01-17 15:25:01 -07001612 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001613 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1614 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001615 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1616 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001617 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001618
Jeff Sharkey06a61842017-04-15 12:03:31 -06001619 if (!uuid) {
1620 ATRACE_BEGIN("profiles");
1621 calculate_tree_size(
1622 create_primary_current_profile_package_dir_path(userId, pkgname),
1623 &stats.dataSize);
1624 calculate_tree_size(
1625 create_primary_reference_profile_package_dir_path(pkgname),
1626 &stats.codeSize);
1627 ATRACE_END();
1628 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001629
Jeff Sharkey466459b2017-01-17 15:25:01 -07001630 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001631 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001632 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001633 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001634 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001635 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001636 }
1637
Jeff Sharkey06a61842017-04-15 12:03:31 -06001638 if (!uuid) {
1639 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001640 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001641 if (sharedGid != -1) {
1642 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1643 sharedGid, -1);
1644 }
1645 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001646 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001647 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001648
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001649 std::vector<int64_t> ret;
1650 ret.push_back(stats.codeSize);
1651 ret.push_back(stats.dataSize);
1652 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001653 ret.push_back(extStats.codeSize);
1654 ret.push_back(extStats.dataSize);
1655 ret.push_back(extStats.cacheSize);
1656#if MEASURE_DEBUG
1657 LOG(DEBUG) << "Final result " << toString(ret);
1658#endif
1659 *_aidl_return = ret;
1660 return ok();
1661}
1662
1663binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1664 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1665 std::vector<int64_t>* _aidl_return) {
1666 ENFORCE_UID(AID_SYSTEM);
1667 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001668 // NOTE: Locking is relaxed on this method, since it's limited to
1669 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001670
1671 // When modifying this logic, always verify using tests:
1672 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1673
1674#if MEASURE_DEBUG
1675 LOG(INFO) << "Measuring user " << userId;
1676#endif
1677
1678 struct stats stats;
1679 struct stats extStats;
1680 memset(&stats, 0, sizeof(stats));
1681 memset(&extStats, 0, sizeof(extStats));
1682
Risan5f308262018-10-26 12:06:58 -06001683 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001684 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1685
Risan5f308262018-10-26 12:06:58 -06001686 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001687 flags &= ~FLAG_USE_QUOTA;
1688 }
1689
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001690 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001691 int64_t space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001692
1693 ATRACE_BEGIN("obb");
Risan5f308262018-10-26 12:06:58 -06001694 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1695 extStats.codeSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001696 }
1697 ATRACE_END();
1698
Jeff Sharkey466459b2017-01-17 15:25:01 -07001699 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001700 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001701 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001702
Jeff Sharkey466459b2017-01-17 15:25:01 -07001703 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001704 auto cePath = create_data_user_ce_path(uuid_, userId);
1705 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001706 auto dePath = create_data_user_de_path(uuid_, userId);
1707 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001708 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001709
Jeff Sharkey06a61842017-04-15 12:03:31 -06001710 if (!uuid) {
1711 ATRACE_BEGIN("profile");
1712 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1713 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1714 auto refProfilePath = create_primary_ref_profile_dir_path();
1715 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1716 ATRACE_END();
1717 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001718
Jeff Sharkey466459b2017-01-17 15:25:01 -07001719 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001720 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001721 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1722 extStats.dataSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001723 }
1724 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001725
Jeff Sharkey06a61842017-04-15 12:03:31 -06001726 if (!uuid) {
1727 ATRACE_BEGIN("dalvik");
1728 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1729 -1, -1, true);
1730 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1731 -1, -1, true);
1732 ATRACE_END();
1733 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001734
Jeff Sharkey466459b2017-01-17 15:25:01 -07001735 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001736 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001737 for (auto appId : appIds) {
1738 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001739 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001740
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001741#if MEASURE_DEBUG
1742 // Sleep to make sure we don't lose logs
1743 usleep(1);
1744#endif
1745 }
1746 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001747 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001748 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001749 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001750 ATRACE_BEGIN("obb");
1751 auto obbPath = create_data_path(uuid_) + "/media/obb";
1752 calculate_tree_size(obbPath, &extStats.codeSize);
1753 ATRACE_END();
1754
Jeff Sharkey466459b2017-01-17 15:25:01 -07001755 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001756 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001757 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001758
Jeff Sharkey466459b2017-01-17 15:25:01 -07001759 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001760 auto cePath = create_data_user_ce_path(uuid_, userId);
1761 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001762 auto dePath = create_data_user_de_path(uuid_, userId);
1763 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001764 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001765
Jeff Sharkey06a61842017-04-15 12:03:31 -06001766 if (!uuid) {
1767 ATRACE_BEGIN("profile");
1768 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1769 calculate_tree_size(userProfilePath, &stats.dataSize);
1770 auto refProfilePath = create_primary_ref_profile_dir_path();
1771 calculate_tree_size(refProfilePath, &stats.codeSize);
1772 ATRACE_END();
1773 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001774
Jeff Sharkey466459b2017-01-17 15:25:01 -07001775 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001776 auto dataMediaPath = create_data_media_path(uuid_, userId);
1777 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1778#if MEASURE_DEBUG
1779 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1780 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001781#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001782 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001783
Jeff Sharkey06a61842017-04-15 12:03:31 -06001784 if (!uuid) {
1785 ATRACE_BEGIN("dalvik");
1786 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1787 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1788 ATRACE_END();
1789 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001790 }
1791
1792 std::vector<int64_t> ret;
1793 ret.push_back(stats.codeSize);
1794 ret.push_back(stats.dataSize);
1795 ret.push_back(stats.cacheSize);
1796 ret.push_back(extStats.codeSize);
1797 ret.push_back(extStats.dataSize);
1798 ret.push_back(extStats.cacheSize);
1799#if MEASURE_DEBUG
1800 LOG(DEBUG) << "Final result " << toString(ret);
1801#endif
1802 *_aidl_return = ret;
1803 return ok();
1804}
1805
1806binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001807 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1808 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001809 ENFORCE_UID(AID_SYSTEM);
1810 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001811 // NOTE: Locking is relaxed on this method, since it's limited to
1812 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001813
1814 // When modifying this logic, always verify using tests:
1815 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1816
1817#if MEASURE_DEBUG
1818 LOG(INFO) << "Measuring external " << userId;
1819#endif
1820
Risan5f308262018-10-26 12:06:58 -06001821 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001822 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1823
1824 int64_t totalSize = 0;
1825 int64_t audioSize = 0;
1826 int64_t videoSize = 0;
1827 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001828 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001829 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001830
Risan5f308262018-10-26 12:06:58 -06001831 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001832 flags &= ~FLAG_USE_QUOTA;
1833 }
1834
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001835 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001836 int64_t space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001837
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001838 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001839 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001840 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1841 totalSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001842 }
1843
1844 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
Risan5f308262018-10-26 12:06:58 -06001845 if ((space = GetOccupiedSpaceForGid(uuidString, audioGid)) != -1) {
1846 audioSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001847 }
1848 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
Risan5f308262018-10-26 12:06:58 -06001849 if ((space = GetOccupiedSpaceForGid(uuidString, videoGid)) != -1) {
1850 videoSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001851 }
1852 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
Risan5f308262018-10-26 12:06:58 -06001853 if ((space = GetOccupiedSpaceForGid(uuidString, imageGid)) != -1) {
1854 imageSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001855 }
Risan5f308262018-10-26 12:06:58 -06001856 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1857 obbSize = space;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001858 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001859 ATRACE_END();
1860
1861 ATRACE_BEGIN("apps");
1862 struct stats extStats;
1863 memset(&extStats, 0, sizeof(extStats));
1864 for (auto appId : appIds) {
1865 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001866 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001867 }
1868 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001869 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001870 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001871 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001872 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001873 FTS *fts;
1874 FTSENT *p;
1875 auto path = create_data_media_path(uuid_, userId);
1876 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001877 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001878 return error("Failed to fts_open " + path);
1879 }
Yi Kong954cf642018-07-17 16:16:24 -07001880 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001881 char* ext;
1882 int64_t size = (p->fts_statp->st_blocks * 512);
1883 switch (p->fts_info) {
1884 case FTS_F:
1885 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001886 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001887 ext = strrchr(p->fts_name, '.');
1888 if (ext != nullptr) {
1889 switch (MatchExtension(++ext)) {
1890 case AID_MEDIA_AUDIO: audioSize += size; break;
1891 case AID_MEDIA_VIDEO: videoSize += size; break;
1892 case AID_MEDIA_IMAGE: imageSize += size; break;
1893 }
1894 }
1895 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001896 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001897 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001898 // Ignore data belonging to specific apps
1899 p->fts_number = p->fts_parent->fts_number;
1900 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1901 p->fts_number = 1;
1902 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001903 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001904 case FTS_DEFAULT:
1905 case FTS_SL:
1906 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001907 if (p->fts_parent->fts_number == 1) {
1908 appSize += size;
1909 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001910 totalSize += size;
1911 break;
1912 }
1913 }
1914 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001915 ATRACE_END();
Jeff Sharkeya0136982017-07-06 11:29:37 -06001916
1917 ATRACE_BEGIN("obb");
1918 auto obbPath = create_data_media_obb_path(uuid_, "");
1919 calculate_tree_size(obbPath, &obbSize);
1920 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001921 }
1922
1923 std::vector<int64_t> ret;
1924 ret.push_back(totalSize);
1925 ret.push_back(audioSize);
1926 ret.push_back(videoSize);
1927 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001928 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06001929 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001930#if MEASURE_DEBUG
1931 LOG(DEBUG) << "Final result " << toString(ret);
1932#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001933 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001934 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001935}
1936
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001937binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1938 int32_t userId, int32_t appId, int64_t cacheQuota) {
1939 ENFORCE_UID(AID_SYSTEM);
1940 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001941 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001942
1943 int32_t uid = multiuser_get_uid(userId, appId);
1944 mCacheQuotas[uid] = cacheQuota;
1945
1946 return ok();
1947}
1948
David Sehr6727c2d2016-05-17 16:06:22 -07001949// Dumps the contents of a profile file, using pkgname's dex files for pretty
1950// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001951binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08001952 const std::string& profileName, const std::string& codePath, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001953 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001954 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07001955 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001956 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001957
Calin Juravle562de812018-01-20 23:34:18 -08001958 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001959 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001960}
1961
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001962// Copy the contents of a system profile over the data profile.
1963binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08001964 int32_t packageUid, const std::string& packageName, const std::string& profileName,
1965 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001966 ENFORCE_UID(AID_SYSTEM);
1967 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1968 std::lock_guard<std::recursive_mutex> lock(mLock);
Calin Juravle562de812018-01-20 23:34:18 -08001969 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001970 return ok();
1971}
1972
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001973// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001974binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08001975 const std::string& profileName, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001976 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001977 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001978 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001979
Calin Juravle562de812018-01-20 23:34:18 -08001980 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001981 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001982}
1983
Calin Juravlec41dac22017-12-05 12:29:15 -08001984binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08001985 const std::string& packageName, const std::string& profileName,
1986 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08001987 ENFORCE_UID(AID_SYSTEM);
1988 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1989 std::lock_guard<std::recursive_mutex> lock(mLock);
1990
Calin Juravlee61189e2018-01-23 19:54:11 -08001991 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08001992 return ok();
1993}
1994
1995binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08001996 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08001997 ENFORCE_UID(AID_SYSTEM);
1998 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1999 std::lock_guard<std::recursive_mutex> lock(mLock);
2000
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002001 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002002 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002003 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002004 }
2005 return ok();
2006}
2007
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002008static const char* getCStr(const std::unique_ptr<std::string>& data,
2009 const char* default_value = nullptr) {
2010 return data == nullptr ? default_value : data->c_str();
2011}
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002012binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2013 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2014 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2015 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle1d667612017-07-13 22:50:21 -07002016 const std::unique_ptr<std::string>& classLoaderContext,
Calin Juravle562de812018-01-20 23:34:18 -08002017 const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002018 const std::unique_ptr<std::string>& profileName,
Calin Juravledcccd832018-02-13 18:31:32 -08002019 const std::unique_ptr<std::string>& dexMetadataPath,
2020 const std::unique_ptr<std::string>& compilationReason) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002021 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002022 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07002023 CHECK_ARGUMENT_PATH(apkPath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002024 if (packageName && *packageName != "*") {
2025 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
2026 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002027 CHECK_ARGUMENT_PATH(outputPath);
2028 CHECK_ARGUMENT_PATH(dexMetadataPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002029 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002030
2031 const char* apk_path = apkPath.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002032 const char* pkgname = getCStr(packageName, "*");
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002033 const char* instruction_set = instructionSet.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002034 const char* oat_dir = getCStr(outputPath);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002035 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002036 const char* volume_uuid = getCStr(uuid);
2037 const char* class_loader_context = getCStr(classLoaderContext);
2038 const char* se_info = getCStr(seInfo);
2039 const char* profile_name = getCStr(profileName);
2040 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08002041 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08002042 std::string error_msg;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002043 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07002044 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Andreas Gampe023b2242018-02-28 16:03:25 -08002045 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg);
2046 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002047}
2048
Eric Holk2af5e6a2019-01-09 18:17:27 -08002049binder::Status InstalldNativeService::compileLayouts(const std::string& apkPath,
2050 const std::string& packageName,
2051 const std ::string& outDexFile, int uid,
2052 bool* _aidl_return) {
2053 const char* apk_path = apkPath.c_str();
2054 const char* package_name = packageName.c_str();
2055 const char* out_dex_file = outDexFile.c_str();
2056 *_aidl_return = android::installd::view_compiler(apk_path, package_name, out_dex_file, uid);
2057 return *_aidl_return ? ok() : error("viewcompiler failed");
2058}
2059
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002060binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2061 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002062 std::lock_guard<std::recursive_mutex> lock(mLock);
2063
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002064 const char* instruction_set = instructionSet.c_str();
2065
2066 char boot_marker_path[PKG_PATH_MAX];
2067 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002068 "%s/%s/%s/.booting",
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -06002069 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08002070 DALVIK_CACHE,
2071 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002072
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002073 ALOGV("mark_boot_complete : %s", boot_marker_path);
2074 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002075 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002076 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002077 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002078}
2079
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002080binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2081 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2082 const std::string& nativeLibPath32, int32_t userId) {
2083 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002084 CHECK_ARGUMENT_UUID(uuid);
2085 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002086 CHECK_ARGUMENT_PATH(nativeLibPath32);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002087 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002088
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002089 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2090 const char* pkgname = packageName.c_str();
2091 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002092 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002093 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002094
Jeff Sharkey423e7462016-12-09 18:18:43 -07002095 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
2096 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002097
2098 const char* pkgdir = _pkgdir.c_str();
2099 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002100
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002101 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002102 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002103 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002104
Nick Kralevich85958b62019-01-30 12:32:21 -08002105 char *con = nullptr;
2106 if (lgetfilecon(pkgdir, &con) < 0) {
2107 return error("Failed to lgetfilecon " + _pkgdir);
2108 }
2109
Mike Lockwood94afecf2012-10-24 10:45:23 -07002110 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08002111 res = error("Failed to chown " + _pkgdir);
2112 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002113 }
2114
2115 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002116 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002117 goto out;
2118 }
2119
2120 if (lstat(libsymlink, &libStat) < 0) {
2121 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002122 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002123 goto out;
2124 }
2125 } else {
2126 if (S_ISDIR(libStat.st_mode)) {
Yi Kong954cf642018-07-17 16:16:24 -07002127 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002128 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002129 goto out;
2130 }
2131 } else if (S_ISLNK(libStat.st_mode)) {
2132 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002133 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002134 goto out;
2135 }
2136 }
2137 }
2138
2139 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002140 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002141 goto out;
2142 }
2143
Nick Kralevich85958b62019-01-30 12:32:21 -08002144 if (lsetfilecon(libsymlink, con) < 0) {
2145 res = error("Failed to lsetfilecon " + _libsymlink);
2146 goto out;
2147 }
2148
Mike Lockwood94afecf2012-10-24 10:45:23 -07002149out:
Nick Kralevich85958b62019-01-30 12:32:21 -08002150 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002151 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002152 auto msg = "Failed to cleanup chmod " + _pkgdir;
2153 if (res.isOk()) {
2154 res = error(msg);
2155 } else {
2156 PLOG(ERROR) << msg;
2157 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002158 }
2159
2160 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002161 auto msg = "Failed to cleanup chown " + _pkgdir;
2162 if (res.isOk()) {
2163 res = error(msg);
2164 } else {
2165 PLOG(ERROR) << msg;
2166 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002167 }
2168
Jeff Sharkey423e7462016-12-09 18:18:43 -07002169 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002170}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002171
2172static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2173{
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002174 execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
Yi Kong954cf642018-07-17 16:16:24 -07002175 StringPrintf("%d", idmap_fd).c_str(), (char*)nullptr);
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002176 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2177}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002178
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002179static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2180{
2181 execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
Yi Kong954cf642018-07-17 16:16:24 -07002182 StringPrintf("%d", idmap_fd).c_str(), (char*)nullptr);
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002183 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2184}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002185
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002186static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
2187 const char* idmap_path, int32_t uid) {
2188 int idmap_fd = open(idmap_path, O_RDWR);
2189 if (idmap_fd < 0) {
2190 PLOG(ERROR) << "idmap open failed: " << idmap_path;
2191 unlink(idmap_path);
2192 return true;
2193 }
2194
2195 pid_t pid;
2196 pid = fork();
2197 if (pid == 0) {
2198 /* child -- drop privileges before continuing */
2199 if (setgid(uid) != 0) {
2200 LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
2201 exit(1);
2202 }
2203 if (setuid(uid) != 0) {
2204 LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
2205 exit(1);
2206 }
2207 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2208 PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
2209 exit(1);
2210 }
2211
2212 run_verify_idmap(target_apk, overlay_apk, idmap_fd);
2213 exit(1); /* only if exec call to deleting stale idmap failed */
2214 } else {
2215 int status = wait_child(pid);
2216 close(idmap_fd);
2217
2218 if (status != 0) {
2219 // Failed on verifying if idmap is made from target_apk and overlay_apk.
2220 LOG(DEBUG) << "delete stale idmap: " << idmap_path;
2221 unlink(idmap_path);
2222 return true;
2223 }
2224 }
2225 return false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002226}
2227
2228// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2229// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2230static int flatten_path(const char *prefix, const char *suffix,
2231 const char *overlay_path, char *idmap_path, size_t N)
2232{
Yi Kong954cf642018-07-17 16:16:24 -07002233 if (overlay_path == nullptr || idmap_path == nullptr) {
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002234 return -1;
2235 }
2236 const size_t len_overlay_path = strlen(overlay_path);
2237 // will access overlay_path + 1 further below; requires absolute path
2238 if (len_overlay_path < 2 || *overlay_path != '/') {
2239 return -1;
2240 }
2241 const size_t len_idmap_root = strlen(prefix);
2242 const size_t len_suffix = strlen(suffix);
2243 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2244 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2245 // additions below would cause overflow
2246 return -1;
2247 }
2248 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2249 return -1;
2250 }
2251 memset(idmap_path, 0, N);
2252 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2253 char *ch = idmap_path + len_idmap_root;
2254 while (*ch != '\0') {
2255 if (*ch == '/') {
2256 *ch = '@';
2257 }
2258 ++ch;
2259 }
2260 return 0;
2261}
2262
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002263binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2264 const std::string& overlayApkPath, int32_t uid) {
2265 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002266 CHECK_ARGUMENT_PATH(targetApkPath);
2267 CHECK_ARGUMENT_PATH(overlayApkPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002268 std::lock_guard<std::recursive_mutex> lock(mLock);
2269
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002270 const char* target_apk = targetApkPath.c_str();
2271 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002272 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2273
2274 int idmap_fd = -1;
2275 char idmap_path[PATH_MAX];
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002276 struct stat idmap_stat;
2277 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002278
2279 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2280 idmap_path, sizeof(idmap_path)) == -1) {
2281 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2282 goto fail;
2283 }
2284
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002285 if (stat(idmap_path, &idmap_stat) < 0) {
2286 outdated = true;
2287 } else {
2288 outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2289 }
2290
2291 if (outdated) {
2292 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2293 } else {
2294 idmap_fd = open(idmap_path, O_RDWR);
2295 }
2296
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002297 if (idmap_fd < 0) {
2298 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2299 goto fail;
2300 }
2301 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2302 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2303 goto fail;
2304 }
2305 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2306 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2307 goto fail;
2308 }
2309
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002310 if (!outdated) {
2311 close(idmap_fd);
2312 return ok();
2313 }
2314
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002315 pid_t pid;
2316 pid = fork();
2317 if (pid == 0) {
2318 /* child -- drop privileges before continuing */
2319 if (setgid(uid) != 0) {
2320 ALOGE("setgid(%d) failed during idmap\n", uid);
2321 exit(1);
2322 }
2323 if (setuid(uid) != 0) {
2324 ALOGE("setuid(%d) failed during idmap\n", uid);
2325 exit(1);
2326 }
2327 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2328 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2329 exit(1);
2330 }
2331
2332 run_idmap(target_apk, overlay_apk, idmap_fd);
2333 exit(1); /* only if exec call to idmap failed */
2334 } else {
2335 int status = wait_child(pid);
2336 if (status != 0) {
2337 ALOGE("idmap failed, status=0x%04x\n", status);
2338 goto fail;
2339 }
2340 }
2341
2342 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002343 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002344fail:
2345 if (idmap_fd >= 0) {
2346 close(idmap_fd);
2347 unlink(idmap_path);
2348 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002349 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002350}
Robert Craige9887e42014-02-20 10:25:56 -05002351
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002352binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
Jeff Sharkey53594302018-02-24 18:59:39 -07002353 ENFORCE_UID(AID_SYSTEM);
2354 CHECK_ARGUMENT_PATH(overlayApkPath);
2355 std::lock_guard<std::recursive_mutex> lock(mLock);
2356
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002357 const char* overlay_apk = overlayApkPath.c_str();
2358 char idmap_path[PATH_MAX];
2359
2360 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2361 idmap_path, sizeof(idmap_path)) == -1) {
2362 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2363 return error();
2364 }
2365 if (unlink(idmap_path) < 0) {
2366 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2367 return error();
2368 }
2369 return ok();
2370}
2371
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002372binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2373 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2374 const std::string& seInfo) {
2375 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002376 CHECK_ARGUMENT_UUID(uuid);
2377 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002378 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002379
2380 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002381
Robert Craigda30dc72014-03-27 10:21:12 -04002382 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002383 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002384 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2385 const char* pkgName = packageName.c_str();
2386 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002387
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002388 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002389 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002390 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002391 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002392 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002393 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002394 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002395 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002396 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002397 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002398 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002399 }
Robert Craige9887e42014-02-20 10:25:56 -05002400 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002401 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002402}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002403
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002404binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2405 const std::string& instructionSet) {
2406 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002407 CHECK_ARGUMENT_PATH(oatDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002408 std::lock_guard<std::recursive_mutex> lock(mLock);
2409
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002410 const char* oat_dir = oatDir.c_str();
2411 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002412 char oat_instr_dir[PKG_PATH_MAX];
2413
2414 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002415 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002416 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002417 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002418 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002419 }
2420 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002421 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002422 }
2423 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002424 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002425 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002426 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002427 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002428}
2429
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002430binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2431 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002432 CHECK_ARGUMENT_PATH(packageDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002433 std::lock_guard<std::recursive_mutex> lock(mLock);
2434
Jeff Sharkey423e7462016-12-09 18:18:43 -07002435 if (validate_apk_path(packageDir.c_str())) {
2436 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002437 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002438 if (delete_dir_contents_and_dir(packageDir) != 0) {
2439 return error("Failed to delete " + packageDir);
2440 }
2441 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002442}
2443
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002444binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2445 const std::string& fromBase, const std::string& toBase) {
2446 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002447 CHECK_ARGUMENT_PATH(fromBase);
2448 CHECK_ARGUMENT_PATH(toBase);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002449 std::lock_guard<std::recursive_mutex> lock(mLock);
2450
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002451 const char* relative_path = relativePath.c_str();
2452 const char* from_base = fromBase.c_str();
2453 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002454 char from_path[PKG_PATH_MAX];
2455 char to_path[PKG_PATH_MAX];
2456 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2457 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2458
2459 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002460 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002461 }
2462
2463 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002464 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002465 }
2466
Jeff Sharkey423e7462016-12-09 18:18:43 -07002467 if (link(from_path, to_path) < 0) {
2468 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002469 }
2470
Jeff Sharkey423e7462016-12-09 18:18:43 -07002471 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002472}
2473
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002474binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2475 const std::string& instructionSet, const std::string& outputPath) {
2476 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002477 CHECK_ARGUMENT_PATH(apkPath);
2478 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002479 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002480
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002481 const char* apk_path = apkPath.c_str();
2482 const char* instruction_set = instructionSet.c_str();
2483 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002484
Jeff Sharkey90aff262016-12-12 14:28:24 -07002485 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002486 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002487}
2488
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002489binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002490 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002491 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002492 CHECK_ARGUMENT_PATH(apkPath);
2493 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002494 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002495
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002496 const char* apk_path = apkPath.c_str();
2497 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002498 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002499
Jeff Sharkey90aff262016-12-12 14:28:24 -07002500 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2501 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002502}
2503
Victor Hsieh7ebd5132018-01-23 07:52:17 -08002504// This kernel feature is experimental.
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002505// TODO: remove local definition once upstreamed
Victor Hsieh18ac0272018-03-12 16:03:02 -07002506#ifndef FS_IOC_ENABLE_VERITY
2507
2508#define FS_IOC_ENABLE_VERITY _IO('f', 133)
2509#define FS_IOC_SET_VERITY_MEASUREMENT _IOW('f', 134, struct fsverity_measurement)
2510
2511#define FS_VERITY_ALG_SHA256 1
2512
2513struct fsverity_measurement {
2514 __u16 digest_algorithm;
2515 __u16 digest_size;
2516 __u32 reserved1;
2517 __u64 reserved2[3];
2518 __u8 digest[];
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002519};
2520
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002521#endif
2522
2523binder::Status InstalldNativeService::installApkVerity(const std::string& filePath,
Victor Hsieh18ac0272018-03-12 16:03:02 -07002524 const ::android::base::unique_fd& verityInputAshmem, int32_t contentSize) {
Victor Hsieh99de5162017-10-06 14:44:14 -07002525 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002526 CHECK_ARGUMENT_PATH(filePath);
2527 std::lock_guard<std::recursive_mutex> lock(mLock);
2528
Victor Hsieh99de5162017-10-06 14:44:14 -07002529 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2530 return ok();
2531 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002532#ifndef NDEBUG
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002533 ASSERT_PAGE_SIZE_4K();
2534#endif
2535 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2536 // TODO: change ashmem to some temporary file to support huge apk.
2537 if (!ashmem_valid(verityInputAshmem.get())) {
2538 return error("FD is not an ashmem");
2539 }
2540
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002541 // 1. Seek to the next page boundary beyond the end of the file.
Victor Hsieh93a98052018-01-24 14:56:32 -08002542 ::android::base::unique_fd wfd(open(filePath.c_str(), O_WRONLY));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002543 if (wfd.get() < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002544 return error("Failed to open " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002545 }
2546 struct stat st;
2547 if (fstat(wfd.get(), &st) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002548 return error("Failed to stat " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002549 }
2550 // fsverity starts from the block boundary.
Victor Hsieh93a98052018-01-24 14:56:32 -08002551 off_t padding = kVerityPageSize - st.st_size % kVerityPageSize;
2552 if (padding == kVerityPageSize) {
2553 padding = 0;
2554 }
2555 if (lseek(wfd.get(), st.st_size + padding, SEEK_SET) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002556 return error("Failed to lseek " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002557 }
2558
Victor Hsieh18ac0272018-03-12 16:03:02 -07002559 // 2. Write everything in the ashmem to the file. Note that allocated
2560 // ashmem size is multiple of page size, which is different from the
2561 // actual content size.
2562 int shmSize = ashmem_get_size_region(verityInputAshmem.get());
2563 if (shmSize < 0) {
2564 return error("Failed to get ashmem size: " + std::to_string(shmSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002565 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002566 if (contentSize < 0) {
2567 return error("Invalid content size: " + std::to_string(contentSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002568 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002569 if (contentSize > shmSize) {
2570 return error("Content size overflow: " + std::to_string(contentSize) + " > " +
2571 std::to_string(shmSize));
2572 }
2573 auto data = std::unique_ptr<void, std::function<void (void *)>>(
Yi Kong954cf642018-07-17 16:16:24 -07002574 mmap(nullptr, contentSize, PROT_READ, MAP_SHARED, verityInputAshmem.get(), 0),
Victor Hsieh18ac0272018-03-12 16:03:02 -07002575 [contentSize] (void* ptr) {
2576 if (ptr != MAP_FAILED) {
2577 munmap(ptr, contentSize);
2578 }
2579 });
2580
2581 if (data.get() == MAP_FAILED) {
2582 return error("Failed to mmap the ashmem");
2583 }
2584 char* cursor = reinterpret_cast<char*>(data.get());
2585 int remaining = contentSize;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002586 while (remaining > 0) {
Victor Hsieh93a98052018-01-24 14:56:32 -08002587 int ret = TEMP_FAILURE_RETRY(write(wfd.get(), cursor, remaining));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002588 if (ret < 0) {
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002589 return error("Failed to write to " + filePath + " (" + std::to_string(remaining) +
Victor Hsieh18ac0272018-03-12 16:03:02 -07002590 + "/" + std::to_string(contentSize) + ")");
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002591 }
Victor Hsieh93a98052018-01-24 14:56:32 -08002592 cursor += ret;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002593 remaining -= ret;
2594 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002595 wfd.reset();
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002596
Victor Hsieh18ac0272018-03-12 16:03:02 -07002597 // 3. Enable fsverity (needs readonly fd. Once it's done, the file becomes immutable.
2598 ::android::base::unique_fd rfd(open(filePath.c_str(), O_RDONLY));
2599 if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, nullptr) < 0) {
2600 return error("Failed to enable fsverity on " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002601 }
2602 return ok();
Victor Hsieh99de5162017-10-06 14:44:14 -07002603}
2604
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002605binder::Status InstalldNativeService::assertFsverityRootHashMatches(const std::string& filePath,
2606 const std::vector<uint8_t>& expectedHash) {
2607 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002608 CHECK_ARGUMENT_PATH(filePath);
2609 std::lock_guard<std::recursive_mutex> lock(mLock);
2610
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002611 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2612 return ok();
2613 }
2614 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2615 if (expectedHash.size() != kSha256Size) {
2616 return error("verity hash size should be " + std::to_string(kSha256Size) + " but is " +
2617 std::to_string(expectedHash.size()));
2618 }
2619
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002620 ::android::base::unique_fd fd(open(filePath.c_str(), O_RDONLY));
2621 if (fd.get() < 0) {
2622 return error("Failed to open " + filePath + ": " + strerror(errno));
2623 }
2624
Victor Hsieh18ac0272018-03-12 16:03:02 -07002625 unsigned int buffer_size = sizeof(fsverity_measurement) + kSha256Size;
2626 std::vector<char> buffer(buffer_size, 0);
2627
2628 fsverity_measurement* config = reinterpret_cast<fsverity_measurement*>(buffer.data());
2629 config->digest_algorithm = FS_VERITY_ALG_SHA256;
2630 config->digest_size = kSha256Size;
2631 memcpy(config->digest, expectedHash.data(), kSha256Size);
2632 if (ioctl(fd.get(), FS_IOC_SET_VERITY_MEASUREMENT, config) < 0) {
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002633 // This includes an expected failure case with no FSVerity setup. It normally happens when
2634 // the apk does not contains the Merkle tree root hash.
2635 return error("Failed to measure fsverity on " + filePath + ": " + strerror(errno));
2636 }
2637 return ok(); // hashes match
2638}
2639
Calin Juravlebd968362017-01-25 01:17:17 -08002640binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2641 const std::string& dexPath, const std::string& packageName, int32_t uid,
2642 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2643 int32_t storage_flag, bool* _aidl_return) {
2644 ENFORCE_UID(AID_SYSTEM);
2645 CHECK_ARGUMENT_UUID(volumeUuid);
2646 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002647 CHECK_ARGUMENT_PATH(dexPath);
Calin Juravlebd968362017-01-25 01:17:17 -08002648 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey53594302018-02-24 18:59:39 -07002649
Calin Juravlebd968362017-01-25 01:17:17 -08002650 bool result = android::installd::reconcile_secondary_dex_file(
2651 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2652 return result ? ok() : error();
2653}
2654
Alan Stokes753dc712017-10-16 10:56:00 +01002655binder::Status InstalldNativeService::hashSecondaryDexFile(
2656 const std::string& dexPath, const std::string& packageName, int32_t uid,
2657 const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
2658 std::vector<uint8_t>* _aidl_return) {
2659 ENFORCE_UID(AID_SYSTEM);
2660 CHECK_ARGUMENT_UUID(volumeUuid);
2661 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002662 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01002663
2664 // mLock is not taken here since we will never modify the file system.
2665 // If a file is modified just as we are reading it this may result in an
2666 // anomalous hash, but that's ok.
2667 bool result = android::installd::hash_secondary_dex_file(
2668 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
2669 return result ? ok() : error();
2670}
2671
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002672binder::Status InstalldNativeService::invalidateMounts() {
2673 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002674 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002675
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002676 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06002677
2678#if !BYPASS_QUOTA
2679 if (!InvalidateQuotaMounts()) {
2680 return error("Failed to read mounts");
2681 }
2682#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002683
2684 std::ifstream in("/proc/mounts");
2685 if (!in.is_open()) {
2686 return error("Failed to read mounts");
2687 }
2688
2689 std::string source;
2690 std::string target;
2691 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002692 while (!in.eof()) {
2693 std::getline(in, source, ' ');
2694 std::getline(in, target, ' ');
2695 std::getline(in, ignored);
2696
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002697#if !BYPASS_SDCARDFS
2698 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2699 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2700 mStorageMounts[source] = target;
2701 }
2702#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002703 }
2704 return ok();
2705}
2706
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002707std::string InstalldNativeService::findDataMediaPath(
2708 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2709 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2710 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2711 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2712 auto resolved = mStorageMounts[path];
2713 if (resolved.empty()) {
2714 LOG(WARNING) << "Failed to find storage mount for " << path;
2715 resolved = path;
2716 }
2717 return StringPrintf("%s/%u", resolved.c_str(), userid);
2718}
2719
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002720binder::Status InstalldNativeService::isQuotaSupported(
Risan5f308262018-10-26 12:06:58 -06002721 const std::unique_ptr<std::string>& uuid, bool* _aidl_return) {
2722 auto uuidString = uuid ? *uuid : "";
2723 *_aidl_return = IsQuotaSupported(uuidString);
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002724 return ok();
2725}
2726
Calin Juravlebc5ab872018-01-18 22:32:58 -08002727binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
2728 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
2729 const std::unique_ptr<std::string>& dexMetadata, bool* _aidl_return) {
2730 ENFORCE_UID(AID_SYSTEM);
2731 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002732 CHECK_ARGUMENT_PATH(codePath);
Calin Juravlebc5ab872018-01-18 22:32:58 -08002733 std::lock_guard<std::recursive_mutex> lock(mLock);
2734
2735 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
2736 dexMetadata);
2737 return ok();
2738}
2739
Andreas Gampe02d0de52015-11-11 20:43:16 -08002740} // namespace installd
2741} // namespace android