blob: 6b14beefd0d4f5705b363dcb61f336a746b127ea [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>
Ricky Waiff9d3ea2019-11-18 18:18:24 +000034#include <sys/mount.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080035#include <sys/resource.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080036#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070037#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070038#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000039#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070040#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080041#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070042
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000043#include <android-base/file.h>
Andreas Gampeafa58d12016-06-03 16:09:32 -070044#include <android-base/logging.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070045#include <android-base/properties.h>
Narayan Kamathe63ca7d2019-01-14 15:21:52 +000046#include <android-base/scopeguard.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080047#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070048#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010049#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080050#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080051#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070052#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070053#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070054#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070055#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080056#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070057#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080058#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070059#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070060
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070061#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070062#include "globals.h"
63#include "installd_deps.h"
64#include "otapreopt_utils.h"
65#include "utils.h"
Eric Holk0ebbe0f2019-01-09 18:17:27 -080066#include "view_compiler.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070067
Jeff Sharkey88ddd942017-01-17 18:05:54 -070068#include "CacheTracker.h"
Felka Chang2a0a2462019-11-20 14:20:40 +080069#include "CrateManager.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070070#include "MatchExtensionGen.h"
Risan5f308262018-10-26 12:06:58 -060071#include "QuotaUtils.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070072
Andreas Gampe02d0de52015-11-11 20:43:16 -080073#ifndef LOG_TAG
74#define LOG_TAG "installd"
75#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070076
77using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070078using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070079
Andreas Gampe02d0de52015-11-11 20:43:16 -080080namespace android {
81namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070082
Nikita Ioffe8e4d3462019-01-21 17:56:03 +000083// An uuid used in unit tests.
84static constexpr const char* kTestUuid = "TEST";
85
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000086static constexpr const mode_t kRollbackFolderMode = 0700;
87
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070088static constexpr const char* kCpPath = "/system/bin/cp";
89static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070090
Ricky Waiff9d3ea2019-11-18 18:18:24 +000091static constexpr const char* kDataMirrorCePath = "/data_mirror/data_ce";
92static constexpr const char* kDataMirrorDePath = "/data_mirror/data_de";
93
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070094static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000095
Andreas Gampe0354bd02016-06-27 14:25:30 -070096static constexpr const char* PKG_LIB_POSTFIX = "/lib";
97static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
98static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
99
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800100// fsverity assumes the page size is always 4096. If not, the feature can not be
101// enabled.
102static constexpr int kVerityPageSize = 4096;
Victor Hsiehc6d738a2018-01-20 15:06:39 -0800103static constexpr size_t kSha256Size = 32;
Victor Hsieh99de5162017-10-06 14:44:14 -0700104static constexpr const char* kPropApkVerityMode = "ro.apk_verity.mode";
Zim0ce832d2019-12-03 17:03:58 +0000105static constexpr const char* kFuseProp = "persist.sys.fuse";
Victor Hsieh99de5162017-10-06 14:44:14 -0700106
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000107/**
108 * Property to control if app data isolation is enabled.
109 */
110static constexpr const char* kAppDataIsolationEnabledProperty = "persist.zygote.app_data_isolation";
111
112static std::atomic<bool> sAppDataIsolationEnabled(false);
113
Jeff Sharkey0274c972016-12-06 09:32:04 -0700114namespace {
115
116constexpr const char* kDump = "android.permission.DUMP";
117
Jeff Sharkey423e7462016-12-09 18:18:43 -0700118static binder::Status ok() {
119 return binder::Status::ok();
120}
121
122static binder::Status exception(uint32_t code, const std::string& msg) {
Jeff Sharkey8e9bf352018-02-27 11:40:45 -0700123 LOG(ERROR) << msg << " (" << code << ")";
Jeff Sharkey423e7462016-12-09 18:18:43 -0700124 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
125}
126
127static binder::Status error() {
128 return binder::Status::fromServiceSpecificError(errno);
129}
130
131static binder::Status error(const std::string& msg) {
132 PLOG(ERROR) << msg;
133 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
134}
135
136static binder::Status error(uint32_t code, const std::string& msg) {
137 LOG(ERROR) << msg << " (" << code << ")";
138 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
139}
140
Jeff Sharkey0274c972016-12-06 09:32:04 -0700141binder::Status checkPermission(const char* permission) {
142 pid_t pid;
143 uid_t uid;
144
145 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
146 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700147 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700148 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700149 return exception(binder::Status::EX_SECURITY,
150 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700151 }
152}
153
154binder::Status checkUid(uid_t expectedUid) {
155 uid_t uid = IPCThreadState::self()->getCallingUid();
156 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700157 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700158 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700159 return exception(binder::Status::EX_SECURITY,
160 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
161 }
162}
163
164binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
165 if (!uuid || is_valid_filename(*uuid)) {
166 return ok();
167 } else {
168 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
169 StringPrintf("UUID %s is malformed", uuid->c_str()));
170 }
171}
172
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000173binder::Status checkArgumentUuidTestOrNull(const std::unique_ptr<std::string>& uuid) {
174 if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
175 return ok();
176 } else {
177 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
178 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
179 }
180}
181
Jeff Sharkey423e7462016-12-09 18:18:43 -0700182binder::Status checkArgumentPackageName(const std::string& packageName) {
Greg Kaiser6d758fc2019-03-26 08:55:32 -0700183 if (is_valid_package_name(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700184 return ok();
185 } else {
186 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
187 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700188 }
189}
190
Jeff Sharkey53594302018-02-24 18:59:39 -0700191binder::Status checkArgumentPath(const std::string& path) {
192 if (path.empty()) {
193 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
194 }
195 if (path[0] != '/') {
196 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
197 StringPrintf("Path %s is relative", path.c_str()));
198 }
199 if ((path + '/').find("/../") != std::string::npos) {
200 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
201 StringPrintf("Path %s is shady", path.c_str()));
202 }
203 for (const char& c : path) {
204 if (c == '\0' || c == '\n') {
205 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
206 StringPrintf("Path %s is malformed", path.c_str()));
207 }
208 }
209 return ok();
210}
211
212binder::Status checkArgumentPath(const std::unique_ptr<std::string>& path) {
213 if (path) {
214 return checkArgumentPath(*path);
215 } else {
216 return ok();
217 }
218}
219
Jeff Sharkey0274c972016-12-06 09:32:04 -0700220#define ENFORCE_UID(uid) { \
221 binder::Status status = checkUid((uid)); \
222 if (!status.isOk()) { \
223 return status; \
224 } \
225}
226
Jeff Sharkey423e7462016-12-09 18:18:43 -0700227#define CHECK_ARGUMENT_UUID(uuid) { \
228 binder::Status status = checkArgumentUuid((uuid)); \
229 if (!status.isOk()) { \
230 return status; \
231 } \
232}
233
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000234#define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) { \
235 auto status = checkArgumentUuidTestOrNull(uuid); \
236 if (!status.isOk()) { \
237 return status; \
238 } \
239} \
240
Jeff Sharkey423e7462016-12-09 18:18:43 -0700241#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
242 binder::Status status = \
243 checkArgumentPackageName((packageName)); \
244 if (!status.isOk()) { \
245 return status; \
246 } \
247}
248
Jeff Sharkey53594302018-02-24 18:59:39 -0700249#define CHECK_ARGUMENT_PATH(path) { \
250 binder::Status status = checkArgumentPath((path)); \
251 if (!status.isOk()) { \
252 return status; \
253 } \
254}
255
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800256#define ASSERT_PAGE_SIZE_4K() { \
257 if (getpagesize() != kVerityPageSize) { \
Victor Hsieh7ebd5132018-01-23 07:52:17 -0800258 return error("FSVerity only supports 4K pages"); \
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800259 } \
260}
261
Jeff Sharkey0274c972016-12-06 09:32:04 -0700262} // namespace
263
264status_t InstalldNativeService::start() {
265 IPCThreadState::self()->disableBackgroundScheduling(true);
266 status_t ret = BinderService<InstalldNativeService>::publish();
267 if (ret != android::OK) {
268 return ret;
269 }
270 sp<ProcessState> ps(ProcessState::self());
271 ps->startThreadPool();
272 ps->giveThreadPoolName();
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000273 sAppDataIsolationEnabled = android::base::GetBoolProperty(
274 kAppDataIsolationEnabledProperty, false);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700275 return android::OK;
276}
277
278status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700279 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700280 const binder::Status dump_permission = checkPermission(kDump);
281 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700282 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700283 return PERMISSION_DENIED;
284 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700285 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700286
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700287 out << "installd is happy!" << endl;
288
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700289 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600290 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
291 out << endl << "Storage mounts:" << endl;
292 for (const auto& n : mStorageMounts) {
293 out << " " << n.first << " = " << n.second << endl;
294 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700295 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700296
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700297 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600298 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700299 out << endl << "Per-UID cache quotas:" << endl;
300 for (const auto& n : mCacheQuotas) {
301 out << " " << n.first << " = " << n.second << endl;
302 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700303 }
304
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700305 out << endl;
306 out.flush();
307
Jeff Sharkey0274c972016-12-06 09:32:04 -0700308 return NO_ERROR;
309}
310
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600311/**
312 * Perform restorecon of the given path, but only perform recursive restorecon
313 * if the label of that top-level file actually changed. This can save us
314 * significant time by avoiding no-op traversals of large filesystem trees.
315 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700316static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
317 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600318 int res = 0;
319 char* before = nullptr;
320 char* after = nullptr;
321
322 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
323 // libselinux. Not needed here.
324
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600325 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600326 PLOG(ERROR) << "Failed before getfilecon for " << path;
327 goto fail;
328 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700329 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600330 PLOG(ERROR) << "Failed top-level restorecon for " << path;
331 goto fail;
332 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600333 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600334 PLOG(ERROR) << "Failed after getfilecon for " << path;
335 goto fail;
336 }
337
338 // If the initial top-level restorecon above changed the label, then go
339 // back and restorecon everything recursively
340 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700341 if (existing) {
342 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
343 << path << "; running recursive restorecon";
344 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700345 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600346 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
347 PLOG(ERROR) << "Failed recursive restorecon for " << path;
348 goto fail;
349 }
350 }
351
352 goto done;
353fail:
354 res = -1;
355done:
356 free(before);
357 free(after);
358 return res;
359}
360
Jeff Sharkey0274c972016-12-06 09:32:04 -0700361static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700362 const std::string& seInfo, uid_t uid, bool existing) {
363 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
364 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600365}
366
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600367static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600368 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
369 PLOG(ERROR) << "Failed to prepare " << path;
370 return -1;
371 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600372 return 0;
373}
374
Calin Juravled2affb82017-11-28 17:41:43 -0800375static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
376 if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
377 return true;
378 }
379
380 int32_t uid = multiuser_get_uid(userId, appId);
381 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
382 if (shared_app_gid == -1) {
383 // TODO(calin): this should no longer be possible but do not continue if we don't get
384 // a valid shared gid.
385 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
386 return true;
387 }
388
389 const std::string profile_dir =
390 create_primary_current_profile_package_dir_path(userId, packageName);
391 // read-write-execute only for the app user.
392 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
393 PLOG(ERROR) << "Failed to prepare " << profile_dir;
394 return false;
395 }
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800396
Calin Juravled2affb82017-11-28 17:41:43 -0800397 const std::string ref_profile_path =
398 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800399
400 // Prepare the reference profile directory. Note that we use the non strict version of
401 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
402 // This is particularly important given that in O there were some fixes for how the
403 // shared_app_gid is computed.
404 //
405 // Note that by the time we get here we know that we are using a correct uid (otherwise
406 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
407 // are sure that the gid being used belongs to the owning app and not someone else.
408 //
409 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
410 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800411 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
412 return false;
413 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800414
Calin Juravled2affb82017-11-28 17:41:43 -0800415 return true;
416}
417
Jeff Sharkey0274c972016-12-06 09:32:04 -0700418binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
419 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700420 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700421 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700422 CHECK_ARGUMENT_UUID(uuid);
423 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700424 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700425
426 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
427 const char* pkgname = packageName.c_str();
428
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700429 // Assume invalid inode unless filled in below
430 if (_aidl_return != nullptr) *_aidl_return = -1;
431
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700432 int32_t uid = multiuser_get_uid(userId, appId);
433 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700434 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
435
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700436 // If UID doesn't have a specific cache GID, use UID value
437 if (cacheGid == -1) {
438 cacheGid = uid;
439 }
440
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700441 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700442 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700443 bool existing = (access(path.c_str(), F_OK) == 0);
444
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700445 if (prepare_app_dir(path, targetMode, uid) ||
446 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
447 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700448 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600449 }
450
451 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700452 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
453 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
454 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700455 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700456 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600457
458 // Remember inode numbers of cache directories so that we can clear
459 // contents while CE storage is locked
460 if (write_path_inode(path, "cache", kXattrInodeCache) ||
461 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700462 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700463 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700464
465 // And return the CE inode of the top-level data directory so we can
466 // clear contents while CE storage is locked
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000467 if (_aidl_return != nullptr) {
468 ino_t result;
469 if (get_path_inode(path, &result) != 0) {
470 return error("Failed to get_path_inode for " + path);
471 }
472 *_aidl_return = static_cast<uint64_t>(result);
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700473 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700474 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700475 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700476 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700477 bool existing = (access(path.c_str(), F_OK) == 0);
478
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700479 if (prepare_app_dir(path, targetMode, uid) ||
480 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
481 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700482 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700483 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000484
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600485 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600486 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
487 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
488 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700489 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600490 }
491
Calin Juravled2affb82017-11-28 17:41:43 -0800492 if (!prepare_app_profile_dir(packageName, appId, userId)) {
493 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000494 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700495 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700496 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700497}
498
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700499binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
500 const std::string& packageName, int32_t userId, int32_t flags) {
501 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700502 CHECK_ARGUMENT_UUID(uuid);
503 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700504 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700505
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700506 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
507 const char* pkgname = packageName.c_str();
508
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700509 // This method only exists to upgrade system apps that have requested
510 // forceDeviceEncrypted, so their default storage always lives in a
511 // consistent location. This only works on non-FBE devices, since we
512 // never want to risk exposing data on a device with real CE/DE storage.
513
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700514 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
515 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700516
517 // If neither directory is marked as default, assume CE is default
518 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
519 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
520 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700521 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700522 }
523 }
524
525 // Migrate default data location if needed
526 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
527 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
528
529 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
530 LOG(WARNING) << "Requested default storage " << target
531 << " is not active; migrating from " << source;
532 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700533 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700534 }
535 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700536 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700537 }
538 }
539
Jeff Sharkey423e7462016-12-09 18:18:43 -0700540 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700541}
542
Calin Juravle6a1648e2016-02-01 12:12:16 +0000543
Calin Juravle562de812018-01-20 23:34:18 -0800544binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
545 const std::string& profileName) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700546 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700548 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700549
Jeff Sharkey423e7462016-12-09 18:18:43 -0700550 binder::Status res = ok();
Calin Juravle562de812018-01-20 23:34:18 -0800551 if (!clear_primary_reference_profile(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700552 res = error("Failed to clear reference profile for " + packageName);
553 }
Calin Juravle562de812018-01-20 23:34:18 -0800554 if (!clear_primary_current_profiles(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700555 res = error("Failed to clear current profiles for " + packageName);
556 }
557 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000558}
559
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700560binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
561 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
562 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700563 CHECK_ARGUMENT_UUID(uuid);
564 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700565 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700566
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700567 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
568 const char* pkgname = packageName.c_str();
569
Jeff Sharkey423e7462016-12-09 18:18:43 -0700570 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700571 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700572 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600573 if (flags & FLAG_CLEAR_CACHE_ONLY) {
574 path = read_path_inode(path, "cache", kXattrInodeCache);
575 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
576 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
577 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700578 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700579 if (delete_dir_contents(path) != 0) {
580 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900581 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
582 remove_path_xattr(path, kXattrInodeCache);
583 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700584 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700585 }
586 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700587 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600588 std::string suffix = "";
589 bool only_cache = false;
590 if (flags & FLAG_CLEAR_CACHE_ONLY) {
591 suffix = CACHE_DIR_POSTFIX;
592 only_cache = true;
593 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
594 suffix = CODE_CACHE_DIR_POSTFIX;
595 only_cache = true;
596 }
597
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700598 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700599 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700600 if (delete_dir_contents(path) != 0) {
601 res = error("Failed to delete contents of " + path);
602 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700603 }
604 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600605 if (flags & FLAG_STORAGE_EXTERNAL) {
606 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
607 for (const auto& n : mStorageMounts) {
608 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +0000609
610 if (android::base::GetBoolProperty(kFuseProp, false)) {
611 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
612 if (std::regex_match(extPath, re)) {
613 extPath += "/" + std::to_string(userId);
614 }
615 } else {
616 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
617 extPath += StringPrintf("/%d", userId);
618 } else if (userId != 0) {
619 // TODO: support devices mounted under secondary users
620 continue;
621 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600622 }
Zim0ce832d2019-12-03 17:03:58 +0000623
Jeff Sharkey6e175692019-05-14 14:55:33 -0600624 if (flags & FLAG_CLEAR_CACHE_ONLY) {
625 // Clear only cached data from shared storage
626 auto path = StringPrintf("%s/Android/data/%s/cache", extPath.c_str(), pkgname);
627 if (delete_dir_contents(path, true) != 0) {
628 res = error("Failed to delete contents of " + path);
629 }
630 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
631 // No code cache on shared storage
632 } else {
633 // Clear everything on shared storage
634 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
635 if (delete_dir_contents(path, true) != 0) {
636 res = error("Failed to delete contents of " + path);
637 }
638 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
639 if (delete_dir_contents(path, true) != 0) {
640 res = error("Failed to delete contents of " + path);
641 }
Martijn Coenen24a93072020-01-08 10:10:43 +0100642 // Note that we explicitly don't delete OBBs - those are only removed on
643 // app uninstall.
Jeff Sharkey6e175692019-05-14 14:55:33 -0600644 }
645 }
646 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700647 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700648}
649
Calin Juravle76268c52017-03-09 13:19:42 -0800650static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100651 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800652 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100653 /*ignore_if_missing*/ true);
654}
655
Calin Juravle76268c52017-03-09 13:19:42 -0800656static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100657 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800658 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100659 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000660}
661
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700662binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
663 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700664 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700665 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700666
Jeff Sharkey423e7462016-12-09 18:18:43 -0700667 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000668 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
669 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800670 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700671 res = error("Failed to destroy current profiles for " + packageName);
672 }
Calin Juravleedae6692016-03-23 13:55:31 +0000673 }
Calin Juravle76268c52017-03-09 13:19:42 -0800674 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700675 res = error("Failed to destroy reference profile for " + packageName);
676 }
677 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000678}
679
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700680binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
681 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
682 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700683 CHECK_ARGUMENT_UUID(uuid);
684 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700685 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700686
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700687 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
688 const char* pkgname = packageName.c_str();
689
Jeff Sharkey423e7462016-12-09 18:18:43 -0700690 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700691 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700692 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
693 if (delete_dir_contents_and_dir(path) != 0) {
694 res = error("Failed to delete " + path);
695 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700696 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700697 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700698 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
699 if (delete_dir_contents_and_dir(path) != 0) {
700 res = error("Failed to delete " + path);
701 }
Calin Juravle76268c52017-03-09 13:19:42 -0800702 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100703 // TODO(calin): If the package is still installed by other users it's probably
704 // beneficial to keep the reference profile around.
705 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800706 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700707 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600708 if (flags & FLAG_STORAGE_EXTERNAL) {
709 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
710 for (const auto& n : mStorageMounts) {
711 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +0000712
713 if (android::base::GetBoolProperty(kFuseProp, false)) {
714 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
715 if (std::regex_match(extPath, re)) {
716 extPath += "/" + std::to_string(userId);
717 }
718 } else {
719 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
720 extPath += StringPrintf("/%d", userId);
721 } else if (userId != 0) {
722 // TODO: support devices mounted under secondary users
723 continue;
724 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600725 }
Zim0ce832d2019-12-03 17:03:58 +0000726
Jeff Sharkey6e175692019-05-14 14:55:33 -0600727 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
728 if (delete_dir_contents_and_dir(path, true) != 0) {
729 res = error("Failed to delete contents of " + path);
730 }
Zim0ce832d2019-12-03 17:03:58 +0000731
Jeff Sharkey6e175692019-05-14 14:55:33 -0600732 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
733 if (delete_dir_contents_and_dir(path, true) != 0) {
734 res = error("Failed to delete contents of " + path);
735 }
736 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
737 if (delete_dir_contents_and_dir(path, true) != 0) {
738 res = error("Failed to delete contents of " + path);
739 }
740 }
741 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700742 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700743}
744
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600745static gid_t get_cache_gid(uid_t uid) {
746 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
747 return (gid != -1) ? gid : uid;
748}
749
750binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
751 int32_t flags) {
752 ENFORCE_UID(AID_SYSTEM);
753 CHECK_ARGUMENT_UUID(uuid);
754 std::lock_guard<std::recursive_mutex> lock(mLock);
755
756 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
757 for (auto user : get_known_users(uuid_)) {
758 ATRACE_BEGIN("fixup user");
759 FTS* fts;
760 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600761 auto ce_path = create_data_user_ce_path(uuid_, user);
762 auto de_path = create_data_user_de_path(uuid_, user);
763 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -0700764 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600765 return error("Failed to fts_open");
766 }
767 while ((p = fts_read(fts)) != nullptr) {
768 if (p->fts_info == FTS_D && p->fts_level == 1) {
769 // Track down inodes of cache directories
770 uint64_t raw = 0;
771 ino_t inode_cache = 0;
772 ino_t inode_code_cache = 0;
773 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
774 inode_cache = raw;
775 }
776 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
777 inode_code_cache = raw;
778 }
779
780 // Figure out expected GID of each child
781 FTSENT* child = fts_children(fts, 0);
782 while (child != nullptr) {
783 if ((child->fts_statp->st_ino == inode_cache)
784 || (child->fts_statp->st_ino == inode_code_cache)
785 || !strcmp(child->fts_name, "cache")
786 || !strcmp(child->fts_name, "code_cache")) {
787 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
788 } else {
789 child->fts_number = p->fts_statp->st_uid;
790 }
791 child = child->fts_link;
792 }
793 } else if (p->fts_level >= 2) {
794 if (p->fts_level > 2) {
795 // Inherit GID from parent once we're deeper into tree
796 p->fts_number = p->fts_parent->fts_number;
797 }
798
799 uid_t uid = p->fts_parent->fts_statp->st_uid;
800 gid_t cache_gid = get_cache_gid(uid);
801 gid_t expected = p->fts_number;
802 gid_t actual = p->fts_statp->st_gid;
803 if (actual == expected) {
804#if FIXUP_DEBUG
805 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
806#endif
807 if (!(flags & FLAG_FORCE)) {
808 fts_set(fts, p, FTS_SKIP);
809 }
810 } else if ((actual == uid) || (actual == cache_gid)) {
811 // Only consider fixing up when current GID belongs to app
812 if (p->fts_info != FTS_D) {
813 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
814 << " instead of " << expected;
815 }
816 switch (p->fts_info) {
817 case FTS_DP:
818 // If we're moving towards cache GID, we need to set S_ISGID
819 if (expected == cache_gid) {
820 if (chmod(p->fts_path, 02771) != 0) {
821 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
822 }
823 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -0700824 [[fallthrough]]; // also set GID
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600825 case FTS_F:
826 if (chown(p->fts_path, -1, expected) != 0) {
827 PLOG(WARNING) << "Failed to chown " << p->fts_path;
828 }
829 break;
830 case FTS_SL:
831 case FTS_SLNONE:
832 if (lchown(p->fts_path, -1, expected) != 0) {
833 PLOG(WARNING) << "Failed to chown " << p->fts_path;
834 }
835 break;
836 }
837 } else {
838 // Ignore all other GID transitions, since they're kinda shady
839 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
840 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -0600841 if (!(flags & FLAG_FORCE)) {
842 fts_set(fts, p, FTS_SKIP);
843 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600844 }
845 }
846 }
847 fts_close(fts);
848 ATRACE_END();
849 }
850 return ok();
851}
852
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000853static int32_t copy_directory_recursive(const char* from, const char* to) {
854 char *argv[] = {
855 (char*) kCpPath,
856 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
857 (char*) "-p", /* preserve timestamps, ownership, and permissions */
858 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
859 (char*) "-P", /* Do not follow symlinks [default] */
860 (char*) "-d", /* don't dereference symlinks */
861 (char*) from,
862 (char*) to
863 };
864
865 LOG(DEBUG) << "Copying " << from << " to " << to;
Tom Cherrye79cde52019-09-25 16:51:56 -0700866 return logwrap_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, LOG_ALOG, false, nullptr);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000867}
868
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000869binder::Status InstalldNativeService::snapshotAppData(
870 const std::unique_ptr<std::string>& volumeUuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000871 const std::string& packageName, int32_t user, int32_t snapshotId,
872 int32_t storageFlags, int64_t* _aidl_return) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000873 ENFORCE_UID(AID_SYSTEM);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000874 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000875 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
876 std::lock_guard<std::recursive_mutex> lock(mLock);
877
878 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
879 const char* package_name = packageName.c_str();
880
881 binder::Status res = ok();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000882 // Default result to 0, it will be populated with inode of ce data snapshot
883 // if FLAG_STORAGE_CE has been passed.
884 if (_aidl_return != nullptr) *_aidl_return = 0;
885
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000886 bool clear_ce_on_exit = false;
887 bool clear_de_on_exit = false;
888
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000889 auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &user, &package_name,
890 &snapshotId] {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000891 if (clear_de_on_exit) {
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000892 auto to = create_data_misc_de_rollback_package_path(volume_uuid, user, snapshotId,
893 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000894 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
895 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
896 }
897 }
898
899 if (clear_ce_on_exit) {
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000900 auto to = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshotId,
901 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000902 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
903 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
904 }
905 }
906 };
907
908 auto scope_guard = android::base::make_scope_guard(deleter);
909
910 // The app may not have any data at all, in which case it's OK to skip here.
911 auto from_ce = create_data_user_ce_package_path(volume_uuid, user, package_name);
912 if (access(from_ce.c_str(), F_OK) != 0) {
913 LOG(INFO) << "Missing source " << from_ce;
914 return ok();
915 }
916
Nikita Ioffe900b3c22019-01-23 14:32:48 +0000917 // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
918 binder::Status clear_cache_result = clearAppData(volumeUuid, packageName, user,
919 storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
920 if (!clear_cache_result.isOk()) {
921 // It should be fine to continue snapshot if we for some reason failed
922 // to clear cache.
923 LOG(WARNING) << "Failed to clear cache of app " << packageName;
924 }
925
926 // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
927 binder::Status clear_code_cache_result = clearAppData(volumeUuid, packageName, user,
928 storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY, 0);
929 if (!clear_code_cache_result.isOk()) {
930 // It should be fine to continue snapshot if we for some reason failed
931 // to clear code_cache.
932 LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
933 }
934
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000935 if (storageFlags & FLAG_STORAGE_DE) {
936 auto from = create_data_user_de_package_path(volume_uuid, user, package_name);
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000937 auto to = create_data_misc_de_rollback_path(volume_uuid, user, snapshotId);
938 auto rollback_package_path = create_data_misc_de_rollback_package_path(volume_uuid, user,
939 snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000940
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000941 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
942 if (rc != 0) {
943 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000944 }
945
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000946 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
947 if (rc != 0) {
948 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
949 }
950
951 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000952 if (rc != 0) {
953 res = error(rc, "Failed copying " + from + " to " + to);
954 clear_de_on_exit = true;
955 return res;
956 }
957 }
958
959 if (storageFlags & FLAG_STORAGE_CE) {
960 auto from = create_data_user_ce_package_path(volume_uuid, user, package_name);
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000961 auto to = create_data_misc_ce_rollback_path(volume_uuid, user, snapshotId);
962 auto rollback_package_path = create_data_misc_ce_rollback_package_path(volume_uuid, user,
963 snapshotId, package_name);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000964
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000965 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
966 if (rc != 0) {
967 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000968 }
969
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000970 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
971 if (rc != 0) {
972 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
973 }
974
975 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000976 if (rc != 0) {
977 res = error(rc, "Failed copying " + from + " to " + to);
978 clear_ce_on_exit = true;
979 return res;
980 }
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000981 if (_aidl_return != nullptr) {
982 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid, user,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000983 snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000984 rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
985 if (rc != 0) {
986 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
987 clear_ce_on_exit = true;
988 return res;
989 }
990 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000991 }
992
993 return res;
994}
995
996binder::Status InstalldNativeService::restoreAppDataSnapshot(
997 const std::unique_ptr<std::string>& volumeUuid, const std::string& packageName,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000998 const int32_t appId, const std::string& seInfo, const int32_t user,
999 const int32_t snapshotId, int32_t storageFlags) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001000 ENFORCE_UID(AID_SYSTEM);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001001 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001002 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1003 std::lock_guard<std::recursive_mutex> lock(mLock);
1004
1005 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1006 const char* package_name = packageName.c_str();
1007
1008 auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001009 user, snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001010 auto from_de = create_data_misc_de_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001011 user, snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001012
1013 const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
1014 (access(from_ce.c_str(), F_OK) == 0);
1015 const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
1016 (access(from_de.c_str(), F_OK) == 0);
1017
1018 if (!needs_ce_rollback && !needs_de_rollback) {
1019 return ok();
1020 }
1021
1022 // We know we're going to rollback one of the CE or DE data, so we clear
1023 // application data first. Note that it's possible that we're asked to
1024 // restore both CE & DE data but that one of the restores fail. Leaving the
1025 // app with no data in those cases is arguably better than leaving the app
1026 // with mismatched / stale data.
1027 LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001028 // It's fine to pass 0 as ceDataInode here, because restoreAppDataSnapshot
1029 // can only be called when user unlocks the phone, meaning that CE user data
1030 // is decrypted.
1031 binder::Status res = clearAppData(volumeUuid, packageName, user, storageFlags,
1032 0 /* ceDataInode */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001033 if (!res.isOk()) {
1034 return res;
1035 }
1036
1037 if (needs_ce_rollback) {
1038 auto to_ce = create_data_user_ce_path(volume_uuid, user);
1039 int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
1040 if (rc != 0) {
1041 res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
1042 return res;
1043 }
1044 }
1045
1046 if (needs_de_rollback) {
1047 auto to_de = create_data_user_de_path(volume_uuid, user);
1048 int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
1049 if (rc != 0) {
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001050 if (needs_ce_rollback) {
1051 auto ce_data = create_data_user_ce_package_path(volume_uuid, user, package_name);
1052 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
1053 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
1054 LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
1055 }
1056 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001057 res = error(rc, "Failed copying " + from_de + " to " + to_de);
1058 return res;
1059 }
1060 }
1061
1062 // Finally, restore the SELinux label on the app data.
1063 return restoreconAppData(volumeUuid, packageName, user, storageFlags, appId, seInfo);
1064}
1065
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001066binder::Status InstalldNativeService::destroyAppDataSnapshot(
1067 const std::unique_ptr<std::string> &volumeUuid, const std::string& packageName,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001068 const int32_t user, const int64_t ceSnapshotInode, const int32_t snapshotId,
1069 int32_t storageFlags) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001070 ENFORCE_UID(AID_SYSTEM);
1071 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1072 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1073 std::lock_guard<std::recursive_mutex> lock(mLock);
1074
1075 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1076 const char* package_name = packageName.c_str();
1077
1078 if (storageFlags & FLAG_STORAGE_DE) {
1079 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001080 user, snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001081
1082 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
1083 if (res != 0) {
1084 return error(res, "Failed clearing snapshot " + de_snapshot_path);
1085 }
1086 }
1087
1088 if (storageFlags & FLAG_STORAGE_CE) {
1089 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001090 user, snapshotId, package_name, ceSnapshotInode);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001091 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
1092 if (res != 0) {
1093 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
1094 }
1095 }
1096 return ok();
1097}
1098
1099
Jeff Sharkey0274c972016-12-06 09:32:04 -07001100binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
1101 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
1102 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
1103 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001104 ENFORCE_UID(AID_SYSTEM);
1105 CHECK_ARGUMENT_UUID(fromUuid);
1106 CHECK_ARGUMENT_UUID(toUuid);
1107 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001108 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -07001109
1110 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1111 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1112 const char* package_name = packageName.c_str();
1113 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001114
Jeff Sharkey423e7462016-12-09 18:18:43 -07001115 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001116 std::vector<userid_t> users = get_known_users(from_uuid);
1117
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001118 // Copy app
1119 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001120 auto from = create_data_app_package_path(from_uuid, data_app_name);
1121 auto to = create_data_app_package_path(to_uuid, data_app_name);
1122 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001123
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001124 int rc = copy_directory_recursive(from.c_str(), to_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001125 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001126 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001127 goto fail;
1128 }
1129
1130 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001131 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001132 goto fail;
1133 }
1134 }
1135
1136 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -07001137 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -07001138
1139 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -06001140 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
1141 if (access(from_ce.c_str(), F_OK) != 0) {
1142 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001143 continue;
1144 }
1145
Jeff Sharkey0274c972016-12-06 09:32:04 -07001146 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -07001147 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001148 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001149 goto fail;
1150 }
1151
Jeff Sharkey51c94492016-05-10 17:46:39 -06001152 {
1153 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
1154 auto to = create_data_user_de_path(to_uuid, user);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001155
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001156 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001157 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001158 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001159 goto fail;
1160 }
1161 }
1162 {
1163 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
1164 auto to = create_data_user_ce_path(to_uuid, user);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001165
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001166 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001167 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001168 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001169 goto fail;
1170 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001171 }
1172
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001173 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1174 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001175 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001176 goto fail;
1177 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001178 }
1179
Jeff Sharkey31f08982015-07-07 13:31:37 -07001180 // We let the framework scan the new location and persist that before
1181 // deleting the data in the old location; this ordering ensures that
1182 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001183 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001184
1185fail:
1186 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001187 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001188 auto to = create_data_app_package_path(to_uuid, data_app_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001189 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001190 LOG(WARNING) << "Failed to rollback " << to;
1191 }
1192 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001193 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001194 {
1195 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001196 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001197 LOG(WARNING) << "Failed to rollback " << to;
1198 }
1199 }
1200 {
1201 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001202 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001203 LOG(WARNING) << "Failed to rollback " << to;
1204 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001205 }
1206 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001207 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001208}
1209
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001210binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
1211 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
1212 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001213 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001214 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001215
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001216 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001217 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001218 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001219 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001220 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07001221 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001222 }
1223 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001224
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001225 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001226}
1227
1228binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
1229 int32_t userId, int32_t flags) {
1230 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001231 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001232 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001233
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001234 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001235 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001236 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001237 auto path = create_data_user_de_path(uuid_, userId);
1238 if (delete_dir_contents_and_dir(path, true) != 0) {
1239 res = error("Failed to delete " + path);
1240 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001241 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001242 path = create_data_misc_legacy_path(userId);
1243 if (delete_dir_contents_and_dir(path, true) != 0) {
1244 res = error("Failed to delete " + path);
1245 }
Calin Juravle114f0812017-03-08 19:05:07 -08001246 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001247 if (delete_dir_contents_and_dir(path, true) != 0) {
1248 res = error("Failed to delete " + path);
1249 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001250 }
Robin Lee095c7632014-04-25 15:05:19 +01001251 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001252 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001253 auto path = create_data_user_ce_path(uuid_, userId);
1254 if (delete_dir_contents_and_dir(path, true) != 0) {
1255 res = error("Failed to delete " + path);
1256 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001257 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001258 if (delete_dir_contents_and_dir(path, true) != 0) {
1259 res = error("Failed to delete " + path);
1260 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001261 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001262 return res;
Robin Lee095c7632014-04-25 15:05:19 +01001263}
1264
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001265binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001266 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001267 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001268 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001269 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001270
Risan5f308262018-10-26 12:06:58 -06001271 auto uuidString = uuid ? *uuid : "";
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001272 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001273 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001274 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001275
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001276 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001277 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001278 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001279 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001280
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001281 int64_t cleared = 0;
1282 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001283 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001284 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001285
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001286 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001287 return ok();
1288 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001289
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001290 if (flags & FLAG_FREE_CACHE_V2) {
1291 // This new cache strategy fairly removes files from UIDs by deleting
1292 // files from the UIDs which are most over their allocated quota
1293
1294 // 1. Create trackers for every known UID
1295 ATRACE_BEGIN("create");
1296 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
1297 for (auto user : get_known_users(uuid_)) {
1298 FTS *fts;
1299 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001300 auto ce_path = create_data_user_ce_path(uuid_, user);
1301 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001302 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
1303 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
1304 (char*) media_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001305 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001306 return error("Failed to fts_open");
1307 }
Yi Konge7bf3772018-07-17 16:16:24 -07001308 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001309 if (p->fts_info == FTS_D && p->fts_level == 1) {
1310 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001311 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
1312 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
1313 + AID_APP_START;
1314 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001315 auto search = trackers.find(uid);
1316 if (search != trackers.end()) {
1317 search->second->addDataPath(p->fts_path);
1318 } else {
1319 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06001320 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001321 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001322 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001323 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001324 tracker->cacheQuota = mCacheQuotas[uid];
1325 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001326 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001327#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001328 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001329#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001330 tracker->cacheQuota = 67108864;
1331 }
1332 trackers[uid] = tracker;
1333 }
1334 fts_set(fts, p, FTS_SKIP);
1335 }
1336 }
1337 fts_close(fts);
1338 }
1339 ATRACE_END();
1340
1341 // 2. Populate tracker stats and insert into priority queue
1342 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001343 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001344 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1345 return (left->getCacheRatio() < right->getCacheRatio());
1346 };
1347 std::priority_queue<std::shared_ptr<CacheTracker>,
1348 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1349 for (const auto& it : trackers) {
1350 it.second->loadStats();
1351 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001352 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001353 }
1354 ATRACE_END();
1355
1356 // 3. Bounce across the queue, freeing items from whichever tracker is
1357 // the most over their assigned quota
1358 ATRACE_BEGIN("bounce");
1359 std::shared_ptr<CacheTracker> active;
1360 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001361 // Only look at apps under quota when explicitly requested
1362 if (active && (active->getCacheRatio() < 10000)
1363 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1364 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1365 << " isn't over quota, and defy not requested";
1366 break;
1367 }
1368
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001369 // Only keep clearing when we haven't pushed into reserved area
1370 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1371 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1372 break;
1373 }
1374
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001375 // Find the best tracker to work with; this might involve swapping
1376 // if the active tracker is no longer the most over quota
1377 bool nextBetter = active && !queue.empty()
1378 && active->getCacheRatio() < queue.top()->getCacheRatio();
1379 if (!active || nextBetter) {
1380 if (active) {
1381 // Current tracker still has items, so we'll consider it
1382 // again later once it bubbles up to surface
1383 queue.push(active);
1384 }
1385 active = queue.top(); queue.pop();
1386 active->ensureItems();
1387 continue;
1388 }
1389
1390 // If no items remain, go find another tracker
1391 if (active->items.empty()) {
1392 active = nullptr;
1393 continue;
1394 } else {
1395 auto item = active->items.back();
1396 active->items.pop_back();
1397
1398 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1399 if (!noop) {
1400 item->purge();
1401 }
1402 active->cacheUsed -= item->size;
1403 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001404 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001405 }
1406
1407 // Verify that we're actually done before bailing, since sneaky
1408 // apps might be using hardlinks
1409 if (needed <= 0) {
1410 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001411 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001412 if (needed <= 0) {
1413 break;
1414 } else {
1415 LOG(WARNING) << "Expected to be done but still need " << needed;
1416 }
1417 }
1418 }
1419 ATRACE_END();
1420
1421 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001422 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001423 }
1424
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001425 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001426 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001427 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001428 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001429 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001430 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001431 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001432}
1433
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001434binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1435 const std::string& instructionSet) {
1436 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07001437 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001438 std::lock_guard<std::recursive_mutex> lock(mLock);
1439
Mike Lockwood94afecf2012-10-24 10:45:23 -07001440 char dex_path[PKG_PATH_MAX];
1441
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001442 const char* path = codePath.c_str();
1443 const char* instruction_set = instructionSet.c_str();
1444
Jeff Sharkey770180a2014-09-08 17:14:26 -07001445 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001446 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001447 }
1448
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001449 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001450 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001451 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001452
1453 ALOGV("unlink %s\n", dex_path);
1454 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001455 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1456 // but could not be unlinked.
1457 if (errno != ENOENT) {
1458 return error(StringPrintf("Failed to unlink %s", dex_path));
1459 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001460 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001461 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001462}
1463
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001464struct stats {
1465 int64_t codeSize;
1466 int64_t dataSize;
1467 int64_t cacheSize;
1468};
1469
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001470#if MEASURE_DEBUG
1471static std::string toString(std::vector<int64_t> values) {
1472 std::stringstream res;
1473 res << "[";
1474 for (size_t i = 0; i < values.size(); i++) {
1475 res << values[i];
1476 if (i < values.size() - 1) {
1477 res << ",";
1478 }
1479 }
1480 res << "]";
1481 return res.str();
1482}
1483#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001484
Risan5f308262018-10-26 12:06:58 -06001485static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001486 int32_t appId, struct stats* stats, struct stats* extStats) {
Risan5f308262018-10-26 12:06:58 -06001487 int64_t space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001488 if (stats != nullptr) {
1489 uid_t uid = multiuser_get_uid(userId, appId);
Risan5f308262018-10-26 12:06:58 -06001490 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
1491 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001492 }
1493
1494 int cacheGid = multiuser_get_cache_gid(userId, appId);
1495 if (cacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001496 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
1497 stats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001498 }
1499 }
1500
1501 int sharedGid = multiuser_get_shared_gid(0, appId);
1502 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001503 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
1504 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001505 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001506 }
1507 }
1508
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001509 if (extStats != nullptr) {
1510 int extGid = multiuser_get_ext_gid(userId, appId);
1511 if (extGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001512 if ((space = GetOccupiedSpaceForGid(uuid, extGid)) != -1) {
1513 extStats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001514 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001515 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001516
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001517 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1518 if (extCacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001519 if ((space = GetOccupiedSpaceForGid(uuid, extCacheGid)) != -1) {
1520 extStats->dataSize += space;
1521 extStats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001522 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001523 }
1524 }
1525}
1526
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001527static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001528 DIR *d;
1529 int dfd;
1530 struct dirent *de;
1531 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001532
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001533 d = opendir(path.c_str());
1534 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001535 if (errno != ENOENT) {
1536 PLOG(WARNING) << "Failed to open " << path;
1537 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001538 return;
1539 }
1540 dfd = dirfd(d);
1541 while ((de = readdir(d))) {
1542 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001543
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001544 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001545 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001546 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001547 }
1548
1549 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001550 if (!strcmp(name, ".")) {
1551 // Don't recurse, but still count node size
1552 } else if (!strcmp(name, "..")) {
1553 // Don't recurse or count node size
1554 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001555 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001556 // Measure all children nodes
1557 size = 0;
1558 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001559 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001560
1561 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1562 stats->cacheSize += size;
1563 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001564 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001565
1566 // Legacy symlink isn't owned by app
1567 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1568 continue;
1569 }
1570
1571 // Everything found inside is considered data
1572 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001573 }
1574 closedir(d);
1575}
1576
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001577static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1578 bool exclude_apps = false) {
1579 DIR *d;
1580 int dfd;
1581 struct dirent *de;
1582 struct stat s;
1583
1584 d = opendir(path.c_str());
1585 if (d == nullptr) {
1586 if (errno != ENOENT) {
1587 PLOG(WARNING) << "Failed to open " << path;
1588 }
1589 return;
1590 }
1591 dfd = dirfd(d);
1592 while ((de = readdir(d))) {
1593 if (de->d_type == DT_DIR) {
1594 const char *name = de->d_name;
1595 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1596 continue;
1597 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001598 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001599 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1600 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001601 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001602 continue;
1603 } else {
1604 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1605 }
1606 }
1607 }
1608 closedir(d);
1609}
1610
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001611static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1612 FTS *fts;
1613 FTSENT *p;
1614 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001615 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001616 PLOG(ERROR) << "Failed to fts_open " << path;
1617 return;
1618 }
Yi Konge7bf3772018-07-17 16:16:24 -07001619 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001620 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001621 switch (p->fts_info) {
1622 case FTS_D:
1623 if (p->fts_level == 4
1624 && !strcmp(p->fts_name, "cache")
1625 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1626 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1627 p->fts_number = 1;
1628 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001629 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001630 case FTS_DEFAULT:
1631 case FTS_F:
1632 case FTS_SL:
1633 case FTS_SLNONE:
1634 int64_t size = (p->fts_statp->st_blocks * 512);
1635 if (p->fts_number == 1) {
1636 stats->cacheSize += size;
1637 }
1638 stats->dataSize += size;
1639 break;
1640 }
1641 }
1642 fts_close(fts);
1643}
1644
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001645binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001646 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1647 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1648 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001649 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001650 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001651 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001652 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1653 }
Jeff Sharkey53594302018-02-24 18:59:39 -07001654 for (const auto& codePath : codePaths) {
1655 CHECK_ARGUMENT_PATH(codePath);
1656 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001657 // NOTE: Locking is relaxed on this method, since it's limited to
1658 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001659
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001660 // When modifying this logic, always verify using tests:
1661 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1662
1663#if MEASURE_DEBUG
1664 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1665#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001666
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001667 // Here's a summary of the common storage locations across the platform,
1668 // and how they're each tagged:
1669 //
1670 // /data/app/com.example UID system
1671 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001672 // /data/user/0/com.example UID u0_a10 GID u0_a10
1673 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1674 // /data/media/0/foo.txt UID u0_media_rw
1675 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1676 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1677 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1678 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001679
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001680 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001681 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001682 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001683 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001684
Risan5f308262018-10-26 12:06:58 -06001685 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001686 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001687
Risan5f308262018-10-26 12:06:58 -06001688 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001689 flags &= ~FLAG_USE_QUOTA;
1690 }
1691
Jeff Sharkey466459b2017-01-17 15:25:01 -07001692 ATRACE_BEGIN("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001693 for (const auto& packageName : packageNames) {
Jeff Sharkey6d775c52019-03-22 13:46:20 -06001694 auto obbCodePath = create_data_media_package_path(uuid_, userId,
1695 "obb", packageName.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001696 calculate_tree_size(obbCodePath, &extStats.codeSize);
1697 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001698 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001699
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001700 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001701 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001702 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001703 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001704 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001705 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001706 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001707
Jeff Sharkey466459b2017-01-17 15:25:01 -07001708 ATRACE_BEGIN("quota");
Risan5f308262018-10-26 12:06:58 -06001709 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001710 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001711 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001712 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001713 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001714 calculate_tree_size(codePath, &stats.codeSize);
1715 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001716 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001717
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001718 for (size_t i = 0; i < packageNames.size(); i++) {
1719 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001720
Jeff Sharkey466459b2017-01-17 15:25:01 -07001721 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001722 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1723 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001724 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1725 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001726 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001727
Jeff Sharkey06a61842017-04-15 12:03:31 -06001728 if (!uuid) {
1729 ATRACE_BEGIN("profiles");
1730 calculate_tree_size(
1731 create_primary_current_profile_package_dir_path(userId, pkgname),
1732 &stats.dataSize);
1733 calculate_tree_size(
1734 create_primary_reference_profile_package_dir_path(pkgname),
1735 &stats.codeSize);
1736 ATRACE_END();
1737 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001738
Jeff Sharkey466459b2017-01-17 15:25:01 -07001739 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001740 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001741 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001742 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001743 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001744 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001745 }
1746
Jeff Sharkey06a61842017-04-15 12:03:31 -06001747 if (!uuid) {
1748 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001749 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001750 if (sharedGid != -1) {
1751 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1752 sharedGid, -1);
1753 }
1754 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001755 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001756 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001757
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001758 std::vector<int64_t> ret;
1759 ret.push_back(stats.codeSize);
1760 ret.push_back(stats.dataSize);
1761 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001762 ret.push_back(extStats.codeSize);
1763 ret.push_back(extStats.dataSize);
1764 ret.push_back(extStats.cacheSize);
1765#if MEASURE_DEBUG
1766 LOG(DEBUG) << "Final result " << toString(ret);
1767#endif
1768 *_aidl_return = ret;
1769 return ok();
1770}
1771
1772binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1773 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1774 std::vector<int64_t>* _aidl_return) {
1775 ENFORCE_UID(AID_SYSTEM);
1776 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001777 // NOTE: Locking is relaxed on this method, since it's limited to
1778 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001779
1780 // When modifying this logic, always verify using tests:
1781 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1782
1783#if MEASURE_DEBUG
1784 LOG(INFO) << "Measuring user " << userId;
1785#endif
1786
1787 struct stats stats;
1788 struct stats extStats;
1789 memset(&stats, 0, sizeof(stats));
1790 memset(&extStats, 0, sizeof(extStats));
1791
Risan5f308262018-10-26 12:06:58 -06001792 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001793 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1794
Risan5f308262018-10-26 12:06:58 -06001795 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001796 flags &= ~FLAG_USE_QUOTA;
1797 }
1798
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001799 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001800 int64_t space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001801
1802 ATRACE_BEGIN("obb");
Risan5f308262018-10-26 12:06:58 -06001803 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1804 extStats.codeSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001805 }
1806 ATRACE_END();
1807
Jeff Sharkey466459b2017-01-17 15:25:01 -07001808 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001809 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001810 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001811
Jeff Sharkey466459b2017-01-17 15:25:01 -07001812 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001813 auto cePath = create_data_user_ce_path(uuid_, userId);
1814 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001815 auto dePath = create_data_user_de_path(uuid_, userId);
1816 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001817 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001818
Jeff Sharkey06a61842017-04-15 12:03:31 -06001819 if (!uuid) {
1820 ATRACE_BEGIN("profile");
1821 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1822 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1823 auto refProfilePath = create_primary_ref_profile_dir_path();
1824 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1825 ATRACE_END();
1826 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001827
Jeff Sharkey466459b2017-01-17 15:25:01 -07001828 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001829 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001830 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1831 extStats.dataSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001832 }
1833 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001834
Jeff Sharkey06a61842017-04-15 12:03:31 -06001835 if (!uuid) {
1836 ATRACE_BEGIN("dalvik");
1837 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1838 -1, -1, true);
1839 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1840 -1, -1, true);
1841 ATRACE_END();
1842 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001843
Jeff Sharkey466459b2017-01-17 15:25:01 -07001844 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001845 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001846 for (auto appId : appIds) {
1847 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001848 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001849
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001850#if MEASURE_DEBUG
1851 // Sleep to make sure we don't lose logs
1852 usleep(1);
1853#endif
1854 }
1855 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001856 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001857 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001858 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001859 ATRACE_BEGIN("obb");
1860 auto obbPath = create_data_path(uuid_) + "/media/obb";
1861 calculate_tree_size(obbPath, &extStats.codeSize);
1862 ATRACE_END();
1863
Jeff Sharkey466459b2017-01-17 15:25:01 -07001864 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001865 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001866 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001867
Jeff Sharkey466459b2017-01-17 15:25:01 -07001868 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001869 auto cePath = create_data_user_ce_path(uuid_, userId);
1870 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001871 auto dePath = create_data_user_de_path(uuid_, userId);
1872 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001873 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001874
Jeff Sharkey06a61842017-04-15 12:03:31 -06001875 if (!uuid) {
1876 ATRACE_BEGIN("profile");
1877 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1878 calculate_tree_size(userProfilePath, &stats.dataSize);
1879 auto refProfilePath = create_primary_ref_profile_dir_path();
1880 calculate_tree_size(refProfilePath, &stats.codeSize);
1881 ATRACE_END();
1882 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001883
Jeff Sharkey466459b2017-01-17 15:25:01 -07001884 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001885 auto dataMediaPath = create_data_media_path(uuid_, userId);
1886 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1887#if MEASURE_DEBUG
1888 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1889 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001890#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001891 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001892
Jeff Sharkey06a61842017-04-15 12:03:31 -06001893 if (!uuid) {
1894 ATRACE_BEGIN("dalvik");
1895 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1896 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1897 ATRACE_END();
1898 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001899 }
1900
1901 std::vector<int64_t> ret;
1902 ret.push_back(stats.codeSize);
1903 ret.push_back(stats.dataSize);
1904 ret.push_back(stats.cacheSize);
1905 ret.push_back(extStats.codeSize);
1906 ret.push_back(extStats.dataSize);
1907 ret.push_back(extStats.cacheSize);
1908#if MEASURE_DEBUG
1909 LOG(DEBUG) << "Final result " << toString(ret);
1910#endif
1911 *_aidl_return = ret;
1912 return ok();
1913}
1914
1915binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001916 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1917 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001918 ENFORCE_UID(AID_SYSTEM);
1919 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001920 // NOTE: Locking is relaxed on this method, since it's limited to
1921 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001922
1923 // When modifying this logic, always verify using tests:
1924 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1925
1926#if MEASURE_DEBUG
1927 LOG(INFO) << "Measuring external " << userId;
1928#endif
1929
Risan5f308262018-10-26 12:06:58 -06001930 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001931 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1932
1933 int64_t totalSize = 0;
1934 int64_t audioSize = 0;
1935 int64_t videoSize = 0;
1936 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001937 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001938 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001939
Risan5f308262018-10-26 12:06:58 -06001940 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001941 flags &= ~FLAG_USE_QUOTA;
1942 }
1943
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001944 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001945 int64_t space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001946
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001947 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001948 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001949 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1950 totalSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001951 }
1952
1953 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
Risan5f308262018-10-26 12:06:58 -06001954 if ((space = GetOccupiedSpaceForGid(uuidString, audioGid)) != -1) {
1955 audioSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001956 }
1957 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
Risan5f308262018-10-26 12:06:58 -06001958 if ((space = GetOccupiedSpaceForGid(uuidString, videoGid)) != -1) {
1959 videoSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001960 }
1961 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
Risan5f308262018-10-26 12:06:58 -06001962 if ((space = GetOccupiedSpaceForGid(uuidString, imageGid)) != -1) {
1963 imageSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001964 }
Risan5f308262018-10-26 12:06:58 -06001965 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1966 obbSize = space;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001967 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001968 ATRACE_END();
1969
1970 ATRACE_BEGIN("apps");
1971 struct stats extStats;
1972 memset(&extStats, 0, sizeof(extStats));
1973 for (auto appId : appIds) {
1974 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001975 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001976 }
1977 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001978 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001979 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001980 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001981 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001982 FTS *fts;
1983 FTSENT *p;
1984 auto path = create_data_media_path(uuid_, userId);
1985 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001986 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001987 return error("Failed to fts_open " + path);
1988 }
Yi Konge7bf3772018-07-17 16:16:24 -07001989 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001990 char* ext;
1991 int64_t size = (p->fts_statp->st_blocks * 512);
1992 switch (p->fts_info) {
1993 case FTS_F:
1994 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001995 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001996 ext = strrchr(p->fts_name, '.');
1997 if (ext != nullptr) {
1998 switch (MatchExtension(++ext)) {
1999 case AID_MEDIA_AUDIO: audioSize += size; break;
2000 case AID_MEDIA_VIDEO: videoSize += size; break;
2001 case AID_MEDIA_IMAGE: imageSize += size; break;
2002 }
2003 }
2004 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002005 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002006 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06002007 // Ignore data belonging to specific apps
2008 p->fts_number = p->fts_parent->fts_number;
2009 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
2010 p->fts_number = 1;
2011 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002012 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002013 case FTS_DEFAULT:
2014 case FTS_SL:
2015 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002016 if (p->fts_parent->fts_number == 1) {
2017 appSize += size;
2018 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002019 totalSize += size;
2020 break;
2021 }
2022 }
2023 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002024 ATRACE_END();
Jeff Sharkeya0136982017-07-06 11:29:37 -06002025
2026 ATRACE_BEGIN("obb");
Jeff Sharkey6d775c52019-03-22 13:46:20 -06002027 auto obbPath = StringPrintf("%s/Android/obb",
2028 create_data_media_path(uuid_, userId).c_str());
Jeff Sharkeya0136982017-07-06 11:29:37 -06002029 calculate_tree_size(obbPath, &obbSize);
2030 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002031 }
2032
2033 std::vector<int64_t> ret;
2034 ret.push_back(totalSize);
2035 ret.push_back(audioSize);
2036 ret.push_back(videoSize);
2037 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002038 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06002039 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002040#if MEASURE_DEBUG
2041 LOG(DEBUG) << "Final result " << toString(ret);
2042#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002043 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002044 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002045}
2046
Felka Chang2a0a2462019-11-20 14:20:40 +08002047binder::Status InstalldNativeService::getAppCrates(
2048 const std::unique_ptr<std::string>& uuid,
2049 const std::vector<std::string>& packageNames, int32_t userId,
2050 std::unique_ptr<std::vector<std::unique_ptr<CrateMetadata>>>* _aidl_return) {
2051 ENFORCE_UID(AID_SYSTEM);
2052 CHECK_ARGUMENT_UUID(uuid);
2053 for (const auto& packageName : packageNames) {
2054 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2055 }
2056 std::lock_guard<std::recursive_mutex> lock(mLock);
2057
2058 auto retVector = std::make_unique<std::vector<std::unique_ptr<CrateMetadata>>>();
2059 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2060
2061 std::function<void(CratedFolder, std::unique_ptr<CrateMetadata> &)> onCreateCrate =
2062 [&](CratedFolder cratedFolder, std::unique_ptr<CrateMetadata> &crateMetadata) -> void {
2063 if (cratedFolder == nullptr) {
2064 return;
2065 }
2066 retVector->push_back(std::move(crateMetadata));
2067 };
2068
2069 for (const auto& packageName : packageNames) {
2070#if CRATE_DEBUG
2071 LOG(DEBUG) << "packageName = " << packageName;
2072#endif
2073 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageName);
2074 crateManager->traverseAllCrates(onCreateCrate);
2075 }
2076
2077#if CRATE_DEBUG
2078 LOG(WARNING) << "retVector->size() =" << retVector->size();
2079 for (auto iter = retVector->begin(); iter != retVector->end(); ++iter) {
2080 CrateManager::dump(*iter);
2081 }
2082#endif
2083
2084 *_aidl_return = std::move(retVector);
2085 return ok();
2086}
2087
2088binder::Status InstalldNativeService::getUserCrates(
2089 const std::unique_ptr<std::string>& uuid, int32_t userId,
2090 std::unique_ptr<std::vector<std::unique_ptr<CrateMetadata>>>* _aidl_return) {
2091 ENFORCE_UID(AID_SYSTEM);
2092 CHECK_ARGUMENT_UUID(uuid);
2093 std::lock_guard<std::recursive_mutex> lock(mLock);
2094
2095 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2096 auto retVector = std::make_unique<std::vector<std::unique_ptr<CrateMetadata>>>();
2097
2098 std::function<void(CratedFolder, std::unique_ptr<CrateMetadata> &)> onCreateCrate =
2099 [&](CratedFolder cratedFolder, std::unique_ptr<CrateMetadata> &crateMetadata) -> void {
2100 if (cratedFolder == nullptr) {
2101 return;
2102 }
2103 retVector->push_back(std::move(crateMetadata));
2104 };
2105
2106 std::function<void(FTSENT*)> onHandingPackage = [&](FTSENT* packageDir) -> void {
2107 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageDir->fts_name);
2108 crateManager->traverseAllCrates(onCreateCrate);
2109 };
2110 CrateManager::traverseAllPackagesForUser(uuid, userId, onHandingPackage);
2111
2112#if CRATE_DEBUG
2113 LOG(DEBUG) << "retVector->size() =" << retVector->size();
2114 for (auto iter = retVector->begin(); iter != retVector->end(); ++iter) {
2115 CrateManager::dump(*iter);
2116 }
2117#endif
2118
2119 *_aidl_return = std::move(retVector);
2120 return ok();
2121}
2122
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002123binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
2124 int32_t userId, int32_t appId, int64_t cacheQuota) {
2125 ENFORCE_UID(AID_SYSTEM);
2126 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002127 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002128
2129 int32_t uid = multiuser_get_uid(userId, appId);
2130 mCacheQuotas[uid] = cacheQuota;
2131
2132 return ok();
2133}
2134
David Sehr6727c2d2016-05-17 16:06:22 -07002135// Dumps the contents of a profile file, using pkgname's dex files for pretty
2136// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002137binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08002138 const std::string& profileName, const std::string& codePath, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002139 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002140 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002141 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002142 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002143
Calin Juravle562de812018-01-20 23:34:18 -08002144 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002145 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07002146}
2147
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002148// Copy the contents of a system profile over the data profile.
2149binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08002150 int32_t packageUid, const std::string& packageName, const std::string& profileName,
2151 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002152 ENFORCE_UID(AID_SYSTEM);
2153 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2154 std::lock_guard<std::recursive_mutex> lock(mLock);
Calin Juravle562de812018-01-20 23:34:18 -08002155 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002156 return ok();
2157}
2158
Andreas Gampe4d0f8252016-03-20 11:30:28 -07002159// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002160binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08002161 const std::string& profileName, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002162 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002163 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002164 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002165
Calin Juravle562de812018-01-20 23:34:18 -08002166 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002167 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07002168}
2169
Calin Juravlec41dac22017-12-05 12:29:15 -08002170binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08002171 const std::string& packageName, const std::string& profileName,
2172 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08002173 ENFORCE_UID(AID_SYSTEM);
2174 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2175 std::lock_guard<std::recursive_mutex> lock(mLock);
2176
Calin Juravlee61189e2018-01-23 19:54:11 -08002177 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08002178 return ok();
2179}
2180
2181binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002182 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08002183 ENFORCE_UID(AID_SYSTEM);
2184 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2185 std::lock_guard<std::recursive_mutex> lock(mLock);
2186
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002187 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002188 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002189 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002190 }
2191 return ok();
2192}
2193
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002194static const char* getCStr(const std::unique_ptr<std::string>& data,
2195 const char* default_value = nullptr) {
2196 return data == nullptr ? default_value : data->c_str();
2197}
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002198binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2199 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2200 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2201 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle1d667612017-07-13 22:50:21 -07002202 const std::unique_ptr<std::string>& classLoaderContext,
Calin Juravle562de812018-01-20 23:34:18 -08002203 const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002204 const std::unique_ptr<std::string>& profileName,
Calin Juravledcccd832018-02-13 18:31:32 -08002205 const std::unique_ptr<std::string>& dexMetadataPath,
2206 const std::unique_ptr<std::string>& compilationReason) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002207 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002208 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07002209 CHECK_ARGUMENT_PATH(apkPath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002210 if (packageName && *packageName != "*") {
2211 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
2212 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002213 CHECK_ARGUMENT_PATH(outputPath);
2214 CHECK_ARGUMENT_PATH(dexMetadataPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002215 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002216
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07002217 const char* oat_dir = getCStr(outputPath);
2218 const char* instruction_set = instructionSet.c_str();
2219 if (oat_dir != nullptr && !createOatDir(oat_dir, instruction_set).isOk()) {
2220 // Can't create oat dir - let dexopt use cache dir.
2221 oat_dir = nullptr;
2222 }
2223
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002224 const char* apk_path = apkPath.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002225 const char* pkgname = getCStr(packageName, "*");
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002226 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002227 const char* volume_uuid = getCStr(uuid);
2228 const char* class_loader_context = getCStr(classLoaderContext);
2229 const char* se_info = getCStr(seInfo);
2230 const char* profile_name = getCStr(profileName);
2231 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08002232 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08002233 std::string error_msg;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002234 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07002235 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Andreas Gampe023b2242018-02-28 16:03:25 -08002236 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg);
2237 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002238}
2239
Eric Holk0ebbe0f2019-01-09 18:17:27 -08002240binder::Status InstalldNativeService::compileLayouts(const std::string& apkPath,
2241 const std::string& packageName,
2242 const std ::string& outDexFile, int uid,
2243 bool* _aidl_return) {
2244 const char* apk_path = apkPath.c_str();
2245 const char* package_name = packageName.c_str();
2246 const char* out_dex_file = outDexFile.c_str();
2247 *_aidl_return = android::installd::view_compiler(apk_path, package_name, out_dex_file, uid);
2248 return *_aidl_return ? ok() : error("viewcompiler failed");
2249}
2250
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002251binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2252 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002253 std::lock_guard<std::recursive_mutex> lock(mLock);
2254
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002255 const char* instruction_set = instructionSet.c_str();
2256
2257 char boot_marker_path[PKG_PATH_MAX];
2258 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002259 "%s/%s/%s/.booting",
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -06002260 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08002261 DALVIK_CACHE,
2262 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002263
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002264 ALOGV("mark_boot_complete : %s", boot_marker_path);
2265 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002266 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002267 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002268 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002269}
2270
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002271binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2272 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2273 const std::string& nativeLibPath32, int32_t userId) {
2274 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002275 CHECK_ARGUMENT_UUID(uuid);
2276 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002277 CHECK_ARGUMENT_PATH(nativeLibPath32);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002278 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002279
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002280 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2281 const char* pkgname = packageName.c_str();
2282 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002283 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002284 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002285
Jeff Sharkey423e7462016-12-09 18:18:43 -07002286 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
2287 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002288
2289 const char* pkgdir = _pkgdir.c_str();
2290 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002291
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002292 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002293 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002294 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002295
Nick Kralevich85958b62019-01-30 12:32:21 -08002296 char *con = nullptr;
2297 if (lgetfilecon(pkgdir, &con) < 0) {
2298 return error("Failed to lgetfilecon " + _pkgdir);
2299 }
2300
Mike Lockwood94afecf2012-10-24 10:45:23 -07002301 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08002302 res = error("Failed to chown " + _pkgdir);
2303 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002304 }
2305
2306 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002307 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002308 goto out;
2309 }
2310
2311 if (lstat(libsymlink, &libStat) < 0) {
2312 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002313 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002314 goto out;
2315 }
2316 } else {
2317 if (S_ISDIR(libStat.st_mode)) {
Yi Konge7bf3772018-07-17 16:16:24 -07002318 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002319 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002320 goto out;
2321 }
2322 } else if (S_ISLNK(libStat.st_mode)) {
2323 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002324 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002325 goto out;
2326 }
2327 }
2328 }
2329
2330 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002331 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002332 goto out;
2333 }
2334
Nick Kralevich85958b62019-01-30 12:32:21 -08002335 if (lsetfilecon(libsymlink, con) < 0) {
2336 res = error("Failed to lsetfilecon " + _libsymlink);
2337 goto out;
2338 }
2339
Mike Lockwood94afecf2012-10-24 10:45:23 -07002340out:
Nick Kralevich85958b62019-01-30 12:32:21 -08002341 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002342 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002343 auto msg = "Failed to cleanup chmod " + _pkgdir;
2344 if (res.isOk()) {
2345 res = error(msg);
2346 } else {
2347 PLOG(ERROR) << msg;
2348 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002349 }
2350
2351 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002352 auto msg = "Failed to cleanup chown " + _pkgdir;
2353 if (res.isOk()) {
2354 res = error(msg);
2355 } else {
2356 PLOG(ERROR) << msg;
2357 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002358 }
2359
Jeff Sharkey423e7462016-12-09 18:18:43 -07002360 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002361}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002362
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002363binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2364 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2365 const std::string& seInfo) {
2366 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002367 CHECK_ARGUMENT_UUID(uuid);
2368 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002369 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002370
2371 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002372
Robert Craigda30dc72014-03-27 10:21:12 -04002373 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002374 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002375 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2376 const char* pkgName = packageName.c_str();
2377 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002378
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002379 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002380 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002381 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002382 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002383 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002384 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002385 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002386 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002387 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002388 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002389 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002390 }
Robert Craige9887e42014-02-20 10:25:56 -05002391 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002392 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002393}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002394
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002395binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2396 const std::string& instructionSet) {
2397 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002398 CHECK_ARGUMENT_PATH(oatDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002399 std::lock_guard<std::recursive_mutex> lock(mLock);
2400
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002401 const char* oat_dir = oatDir.c_str();
2402 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002403 char oat_instr_dir[PKG_PATH_MAX];
2404
2405 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002406 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002407 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002408 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002409 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002410 }
2411 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002412 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002413 }
2414 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002415 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002416 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002417 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002418 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002419}
2420
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002421binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2422 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002423 CHECK_ARGUMENT_PATH(packageDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002424 std::lock_guard<std::recursive_mutex> lock(mLock);
2425
Jeff Sharkey423e7462016-12-09 18:18:43 -07002426 if (validate_apk_path(packageDir.c_str())) {
2427 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002428 }
Oleksandr Peletskyid2be6322019-01-24 17:59:45 +01002429 if (rm_package_dir(packageDir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002430 return error("Failed to delete " + packageDir);
2431 }
2432 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002433}
2434
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002435binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2436 const std::string& fromBase, const std::string& toBase) {
2437 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002438 CHECK_ARGUMENT_PATH(fromBase);
2439 CHECK_ARGUMENT_PATH(toBase);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002440 std::lock_guard<std::recursive_mutex> lock(mLock);
2441
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002442 const char* relative_path = relativePath.c_str();
2443 const char* from_base = fromBase.c_str();
2444 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002445 char from_path[PKG_PATH_MAX];
2446 char to_path[PKG_PATH_MAX];
2447 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2448 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2449
2450 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002451 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002452 }
2453
2454 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002455 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002456 }
2457
Jeff Sharkey423e7462016-12-09 18:18:43 -07002458 if (link(from_path, to_path) < 0) {
2459 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002460 }
2461
Jeff Sharkey423e7462016-12-09 18:18:43 -07002462 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002463}
2464
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002465binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2466 const std::string& instructionSet, const std::string& outputPath) {
2467 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002468 CHECK_ARGUMENT_PATH(apkPath);
2469 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002470 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002471
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002472 const char* apk_path = apkPath.c_str();
2473 const char* instruction_set = instructionSet.c_str();
2474 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002475
Jeff Sharkey90aff262016-12-12 14:28:24 -07002476 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002477 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002478}
2479
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002480binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002481 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002482 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002483 CHECK_ARGUMENT_PATH(apkPath);
2484 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002485 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002486
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002487 const char* apk_path = apkPath.c_str();
2488 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002489 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002490
Jeff Sharkey90aff262016-12-12 14:28:24 -07002491 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2492 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002493}
2494
Victor Hsieh7ebd5132018-01-23 07:52:17 -08002495// This kernel feature is experimental.
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002496// TODO: remove local definition once upstreamed
Victor Hsieh18ac0272018-03-12 16:03:02 -07002497#ifndef FS_IOC_ENABLE_VERITY
2498
2499#define FS_IOC_ENABLE_VERITY _IO('f', 133)
2500#define FS_IOC_SET_VERITY_MEASUREMENT _IOW('f', 134, struct fsverity_measurement)
2501
2502#define FS_VERITY_ALG_SHA256 1
2503
2504struct fsverity_measurement {
2505 __u16 digest_algorithm;
2506 __u16 digest_size;
2507 __u32 reserved1;
2508 __u64 reserved2[3];
2509 __u8 digest[];
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002510};
2511
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002512#endif
2513
2514binder::Status InstalldNativeService::installApkVerity(const std::string& filePath,
Jiyong Park3b25ae12019-11-25 11:06:16 +09002515 android::base::unique_fd verityInputAshmem, int32_t contentSize) {
Victor Hsieh99de5162017-10-06 14:44:14 -07002516 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002517 CHECK_ARGUMENT_PATH(filePath);
2518 std::lock_guard<std::recursive_mutex> lock(mLock);
2519
Victor Hsieh99de5162017-10-06 14:44:14 -07002520 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2521 return ok();
2522 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002523#ifndef NDEBUG
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002524 ASSERT_PAGE_SIZE_4K();
2525#endif
2526 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2527 // TODO: change ashmem to some temporary file to support huge apk.
2528 if (!ashmem_valid(verityInputAshmem.get())) {
2529 return error("FD is not an ashmem");
2530 }
2531
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002532 // 1. Seek to the next page boundary beyond the end of the file.
Victor Hsieh93a98052018-01-24 14:56:32 -08002533 ::android::base::unique_fd wfd(open(filePath.c_str(), O_WRONLY));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002534 if (wfd.get() < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002535 return error("Failed to open " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002536 }
2537 struct stat st;
2538 if (fstat(wfd.get(), &st) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002539 return error("Failed to stat " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002540 }
2541 // fsverity starts from the block boundary.
Victor Hsieh93a98052018-01-24 14:56:32 -08002542 off_t padding = kVerityPageSize - st.st_size % kVerityPageSize;
2543 if (padding == kVerityPageSize) {
2544 padding = 0;
2545 }
2546 if (lseek(wfd.get(), st.st_size + padding, SEEK_SET) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002547 return error("Failed to lseek " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002548 }
2549
Victor Hsieh18ac0272018-03-12 16:03:02 -07002550 // 2. Write everything in the ashmem to the file. Note that allocated
2551 // ashmem size is multiple of page size, which is different from the
2552 // actual content size.
2553 int shmSize = ashmem_get_size_region(verityInputAshmem.get());
2554 if (shmSize < 0) {
2555 return error("Failed to get ashmem size: " + std::to_string(shmSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002556 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002557 if (contentSize < 0) {
2558 return error("Invalid content size: " + std::to_string(contentSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002559 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002560 if (contentSize > shmSize) {
2561 return error("Content size overflow: " + std::to_string(contentSize) + " > " +
2562 std::to_string(shmSize));
2563 }
2564 auto data = std::unique_ptr<void, std::function<void (void *)>>(
Yi Konge7bf3772018-07-17 16:16:24 -07002565 mmap(nullptr, contentSize, PROT_READ, MAP_SHARED, verityInputAshmem.get(), 0),
Victor Hsieh18ac0272018-03-12 16:03:02 -07002566 [contentSize] (void* ptr) {
2567 if (ptr != MAP_FAILED) {
2568 munmap(ptr, contentSize);
2569 }
2570 });
2571
2572 if (data.get() == MAP_FAILED) {
2573 return error("Failed to mmap the ashmem");
2574 }
2575 char* cursor = reinterpret_cast<char*>(data.get());
2576 int remaining = contentSize;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002577 while (remaining > 0) {
Victor Hsieh93a98052018-01-24 14:56:32 -08002578 int ret = TEMP_FAILURE_RETRY(write(wfd.get(), cursor, remaining));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002579 if (ret < 0) {
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002580 return error("Failed to write to " + filePath + " (" + std::to_string(remaining) +
Victor Hsieh18ac0272018-03-12 16:03:02 -07002581 + "/" + std::to_string(contentSize) + ")");
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002582 }
Victor Hsieh93a98052018-01-24 14:56:32 -08002583 cursor += ret;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002584 remaining -= ret;
2585 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002586 wfd.reset();
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002587
Victor Hsieh18ac0272018-03-12 16:03:02 -07002588 // 3. Enable fsverity (needs readonly fd. Once it's done, the file becomes immutable.
2589 ::android::base::unique_fd rfd(open(filePath.c_str(), O_RDONLY));
2590 if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, nullptr) < 0) {
2591 return error("Failed to enable fsverity on " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002592 }
2593 return ok();
Victor Hsieh99de5162017-10-06 14:44:14 -07002594}
2595
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002596binder::Status InstalldNativeService::assertFsverityRootHashMatches(const std::string& filePath,
2597 const std::vector<uint8_t>& expectedHash) {
2598 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002599 CHECK_ARGUMENT_PATH(filePath);
2600 std::lock_guard<std::recursive_mutex> lock(mLock);
2601
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002602 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2603 return ok();
2604 }
2605 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2606 if (expectedHash.size() != kSha256Size) {
2607 return error("verity hash size should be " + std::to_string(kSha256Size) + " but is " +
2608 std::to_string(expectedHash.size()));
2609 }
2610
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002611 ::android::base::unique_fd fd(open(filePath.c_str(), O_RDONLY));
2612 if (fd.get() < 0) {
2613 return error("Failed to open " + filePath + ": " + strerror(errno));
2614 }
2615
Victor Hsieh18ac0272018-03-12 16:03:02 -07002616 unsigned int buffer_size = sizeof(fsverity_measurement) + kSha256Size;
2617 std::vector<char> buffer(buffer_size, 0);
2618
2619 fsverity_measurement* config = reinterpret_cast<fsverity_measurement*>(buffer.data());
2620 config->digest_algorithm = FS_VERITY_ALG_SHA256;
2621 config->digest_size = kSha256Size;
2622 memcpy(config->digest, expectedHash.data(), kSha256Size);
2623 if (ioctl(fd.get(), FS_IOC_SET_VERITY_MEASUREMENT, config) < 0) {
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002624 // This includes an expected failure case with no FSVerity setup. It normally happens when
2625 // the apk does not contains the Merkle tree root hash.
2626 return error("Failed to measure fsverity on " + filePath + ": " + strerror(errno));
2627 }
2628 return ok(); // hashes match
2629}
2630
Calin Juravlebd968362017-01-25 01:17:17 -08002631binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2632 const std::string& dexPath, const std::string& packageName, int32_t uid,
2633 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2634 int32_t storage_flag, bool* _aidl_return) {
2635 ENFORCE_UID(AID_SYSTEM);
2636 CHECK_ARGUMENT_UUID(volumeUuid);
2637 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002638 CHECK_ARGUMENT_PATH(dexPath);
Calin Juravlebd968362017-01-25 01:17:17 -08002639 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey53594302018-02-24 18:59:39 -07002640
Calin Juravlebd968362017-01-25 01:17:17 -08002641 bool result = android::installd::reconcile_secondary_dex_file(
2642 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2643 return result ? ok() : error();
2644}
2645
Alan Stokes753dc712017-10-16 10:56:00 +01002646binder::Status InstalldNativeService::hashSecondaryDexFile(
2647 const std::string& dexPath, const std::string& packageName, int32_t uid,
2648 const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
2649 std::vector<uint8_t>* _aidl_return) {
2650 ENFORCE_UID(AID_SYSTEM);
2651 CHECK_ARGUMENT_UUID(volumeUuid);
2652 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002653 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01002654
2655 // mLock is not taken here since we will never modify the file system.
2656 // If a file is modified just as we are reading it this may result in an
2657 // anomalous hash, but that's ok.
2658 bool result = android::installd::hash_secondary_dex_file(
2659 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
2660 return result ? ok() : error();
2661}
2662
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002663binder::Status InstalldNativeService::invalidateMounts() {
2664 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002665 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002666
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002667 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06002668
2669#if !BYPASS_QUOTA
2670 if (!InvalidateQuotaMounts()) {
2671 return error("Failed to read mounts");
2672 }
2673#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002674
2675 std::ifstream in("/proc/mounts");
2676 if (!in.is_open()) {
2677 return error("Failed to read mounts");
2678 }
2679
2680 std::string source;
2681 std::string target;
2682 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002683 while (!in.eof()) {
2684 std::getline(in, source, ' ');
2685 std::getline(in, target, ' ');
2686 std::getline(in, ignored);
2687
Zim0ce832d2019-12-03 17:03:58 +00002688 if (android::base::GetBoolProperty(kFuseProp, false)) {
Zimd4de6362019-12-12 16:22:27 +00002689 // TODO(b/146139106): Use sdcardfs mounts on devices running sdcardfs so we don't bypass
2690 // it's VFS cache
Zim0ce832d2019-12-03 17:03:58 +00002691 if (target.compare(0, 17, "/mnt/pass_through") == 0) {
2692 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2693 mStorageMounts[source] = target;
2694 }
2695 } else {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002696#if !BYPASS_SDCARDFS
Zim0ce832d2019-12-03 17:03:58 +00002697 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2698 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2699 mStorageMounts[source] = target;
2700 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002701#endif
Zim0ce832d2019-12-03 17:03:58 +00002702 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002703 }
2704 return ok();
2705}
2706
Ricky Waiff9d3ea2019-11-18 18:18:24 +00002707// Mount volume's CE and DE storage to mirror
2708binder::Status InstalldNativeService::onPrivateVolumeMounted(
2709 const std::unique_ptr<std::string>& uuid) {
2710 ENFORCE_UID(AID_SYSTEM);
2711 CHECK_ARGUMENT_UUID(uuid);
2712 if (!sAppDataIsolationEnabled) {
2713 return ok();
2714 }
2715 if (!uuid) {
2716 return error("Should not happen, mounting uuid == null");
2717 }
2718
2719 const char* uuid_ = uuid->c_str();
2720 // Mount CE mirror
2721 std::string mirrorVolCePath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
2722 std::lock_guard<std::recursive_mutex> lock(mLock);
2723 if (fs_prepare_dir(mirrorVolCePath.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
2724 return error("Failed to create CE mirror");
2725 }
2726 auto cePath = StringPrintf("%s/user_ce", create_data_path(uuid_).c_str());
2727 if (TEMP_FAILURE_RETRY(mount(cePath.c_str(), mirrorVolCePath.c_str(), NULL,
2728 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
2729 return error("Failed to mount " + mirrorVolCePath);
2730 }
2731
2732 // Mount DE mirror
2733 std::string mirrorVolDePath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
2734 if (fs_prepare_dir(mirrorVolDePath.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
2735 return error("Failed to create DE mirror");
2736 }
2737 auto dePath = StringPrintf("%s/user_de", create_data_path(uuid_).c_str());
2738 if (TEMP_FAILURE_RETRY(mount(dePath.c_str(), mirrorVolDePath.c_str(), NULL,
2739 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
2740 return error("Failed to mount " + mirrorVolDePath);
2741 }
2742 return ok();
2743}
2744
2745// Unmount volume's CE and DE storage from mirror
2746binder::Status InstalldNativeService::onPrivateVolumeRemoved(
2747 const std::unique_ptr<std::string>& uuid) {
2748 ENFORCE_UID(AID_SYSTEM);
2749 CHECK_ARGUMENT_UUID(uuid);
2750 if (!sAppDataIsolationEnabled) {
2751 return ok();
2752 }
2753 if (!uuid) {
2754 // It happens when private volume failed to mount.
2755 LOG(INFO) << "Ignore unmount uuid=null";
2756 return ok();
2757 }
2758 const char* uuid_ = uuid->c_str();
2759
2760 binder::Status res = ok();
2761
2762 std::string mirrorCeVolPath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
2763 std::string mirrorDeVolPath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
2764
2765 // Unmount CE storage
2766 std::lock_guard<std::recursive_mutex> lock(mLock);
2767 if (TEMP_FAILURE_RETRY(umount(mirrorCeVolPath.c_str())) != 0) {
2768 if (errno != ENOENT) {
2769 res = error(StringPrintf("Failed to umount %s %s", mirrorCeVolPath.c_str(),
2770 strerror(errno)));
2771 }
2772 }
2773 if (delete_dir_contents_and_dir(mirrorCeVolPath, true) != 0) {
2774 res = error("Failed to delete " + mirrorCeVolPath);
2775 }
2776
2777 // Unmount DE storage
2778 if (TEMP_FAILURE_RETRY(umount(mirrorDeVolPath.c_str())) != 0) {
2779 if (errno != ENOENT) {
2780 res = error(StringPrintf("Failed to umount %s %s", mirrorDeVolPath.c_str(),
2781 strerror(errno)));
2782 }
2783 }
2784 if (delete_dir_contents_and_dir(mirrorDeVolPath, true) != 0) {
2785 res = error("Failed to delete " + mirrorDeVolPath);
2786 }
2787 return res;
2788}
2789
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002790std::string InstalldNativeService::findDataMediaPath(
2791 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2792 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2793 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2794 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
Zimd4de6362019-12-12 16:22:27 +00002795 if (android::base::GetBoolProperty(kFuseProp, false)) {
2796 // TODO(b/146139106): This is only safe on devices not running sdcardfs where there is no
2797 // risk of bypassing the sdcardfs VFS cache
2798
2799 // Always use the lower filesystem path on FUSE enabled devices not running sdcardfs
2800 // The upper filesystem path, /mnt/pass_through/<userid>/<vol>/ which was a bind mount
2801 // to the lower filesytem may have been unmounted already when a user is
2802 // removed and the path will now be pointing to a tmpfs without content
2803 return StringPrintf("%s/%u", path.c_str(), userid);
2804 }
2805
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002806 auto resolved = mStorageMounts[path];
2807 if (resolved.empty()) {
2808 LOG(WARNING) << "Failed to find storage mount for " << path;
2809 resolved = path;
2810 }
2811 return StringPrintf("%s/%u", resolved.c_str(), userid);
2812}
2813
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002814binder::Status InstalldNativeService::isQuotaSupported(
Risan5f308262018-10-26 12:06:58 -06002815 const std::unique_ptr<std::string>& uuid, bool* _aidl_return) {
2816 auto uuidString = uuid ? *uuid : "";
2817 *_aidl_return = IsQuotaSupported(uuidString);
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002818 return ok();
2819}
2820
Calin Juravlebc5ab872018-01-18 22:32:58 -08002821binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
2822 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
2823 const std::unique_ptr<std::string>& dexMetadata, bool* _aidl_return) {
2824 ENFORCE_UID(AID_SYSTEM);
2825 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002826 CHECK_ARGUMENT_PATH(codePath);
Calin Juravlebc5ab872018-01-18 22:32:58 -08002827 std::lock_guard<std::recursive_mutex> lock(mLock);
2828
2829 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
2830 dexMetadata);
2831 return ok();
2832}
2833
Narayan Kamath28ab93b2019-05-15 18:29:44 +01002834binder::Status InstalldNativeService::migrateLegacyObbData() {
2835 ENFORCE_UID(AID_SYSTEM);
2836 // NOTE: The lint warning doesn't apply to the use of system(3) with
2837 // absolute parse and no command line arguments.
2838 if (system("/system/bin/migrate_legacy_obb_data.sh") != 0) { // NOLINT(cert-env33-c)
2839 LOG(ERROR) << "Unable to migrate legacy obb data";
2840 }
2841
2842 return ok();
2843}
2844
Andreas Gampe02d0de52015-11-11 20:43:16 -08002845} // namespace installd
2846} // namespace android