blob: b23d69c52f1db1aee5793a3d38c4b9e0139ba504 [file] [log] [blame]
Mike Lockwood94afecf2012-10-24 10:45:23 -07001/*
2** Copyright 2008, The Android Open Source Project
3**
Dave Allisond9370732014-01-30 14:19:23 -08004** Licensed under the Apache License, Version 2.0 (the "License");
5** you may not use this file except in compliance with the License.
6** You may obtain a copy of the License at
Mike Lockwood94afecf2012-10-24 10:45:23 -07007**
Dave Allisond9370732014-01-30 14:19:23 -08008** http://www.apache.org/licenses/LICENSE-2.0
Mike Lockwood94afecf2012-10-24 10:45:23 -07009**
Dave Allisond9370732014-01-30 14:19:23 -080010** Unless required by applicable law or agreed to in writing, software
11** distributed under the License is distributed on an "AS IS" BASIS,
12** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13** See the License for the specific language governing permissions and
Mike Lockwood94afecf2012-10-24 10:45:23 -070014** limitations under the License.
15*/
16
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070017#include "InstalldNativeService.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080018
Jeff Sharkey466459b2017-01-17 15:25:01 -070019#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
20
Victor Hsiehc6d738a2018-01-20 15:06:39 -080021#include <algorithm>
Andreas Gampe02d0de52015-11-11 20:43:16 -080022#include <errno.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070023#include <fstream>
24#include <fts.h>
Victor Hsieh18ac0272018-03-12 16:03:02 -070025#include <functional>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080026#include <inttypes.h>
Andreas Gampe0354bd02016-06-27 14:25:30 -070027#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070029#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080030#include <sys/capability.h>
31#include <sys/file.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080032#include <sys/ioctl.h>
33#include <sys/mman.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080034#include <sys/resource.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070036#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070037#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000038#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070039#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080040#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070041
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000042#include <android-base/file.h>
Andreas Gampeafa58d12016-06-03 16:09:32 -070043#include <android-base/logging.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070044#include <android-base/properties.h>
Narayan Kamathe63ca7d2019-01-14 15:21:52 +000045#include <android-base/scopeguard.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080046#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070047#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010048#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080049#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080050#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070051#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070052#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070053#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070054#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080055#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070056#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080057#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070058#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070059
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070060#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070061#include "globals.h"
62#include "installd_deps.h"
63#include "otapreopt_utils.h"
64#include "utils.h"
Eric Holk0ebbe0f2019-01-09 18:17:27 -080065#include "view_compiler.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070066
Jeff Sharkey88ddd942017-01-17 18:05:54 -070067#include "CacheTracker.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070068#include "MatchExtensionGen.h"
Risan5f308262018-10-26 12:06:58 -060069#include "QuotaUtils.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070070
Andreas Gampe02d0de52015-11-11 20:43:16 -080071#ifndef LOG_TAG
72#define LOG_TAG "installd"
73#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070074
75using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070076using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070077
Andreas Gampe02d0de52015-11-11 20:43:16 -080078namespace android {
79namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070080
Nikita Ioffe8e4d3462019-01-21 17:56:03 +000081// An uuid used in unit tests.
82static constexpr const char* kTestUuid = "TEST";
83
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000084static constexpr const mode_t kRollbackFolderMode = 0700;
85
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070086static constexpr const char* kCpPath = "/system/bin/cp";
87static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070088
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070089static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000090
Andreas Gampe0354bd02016-06-27 14:25:30 -070091static constexpr const char* PKG_LIB_POSTFIX = "/lib";
92static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
93static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
94
Jaekyun Seok5cb903e2017-05-18 00:13:44 +090095static constexpr const char *kIdMapPath = "/system/bin/idmap";
Andreas Gampe0354bd02016-06-27 14:25:30 -070096static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
97static constexpr const char* IDMAP_SUFFIX = "@idmap";
98
Victor Hsieh3f16dd62018-01-13 13:43:11 -080099// fsverity assumes the page size is always 4096. If not, the feature can not be
100// enabled.
101static constexpr int kVerityPageSize = 4096;
Victor Hsiehc6d738a2018-01-20 15:06:39 -0800102static constexpr size_t kSha256Size = 32;
Victor Hsieh99de5162017-10-06 14:44:14 -0700103static constexpr const char* kPropApkVerityMode = "ro.apk_verity.mode";
Zim0ce832d2019-12-03 17:03:58 +0000104static constexpr const char* kFuseProp = "persist.sys.fuse";
Victor Hsieh99de5162017-10-06 14:44:14 -0700105
Jeff Sharkey0274c972016-12-06 09:32:04 -0700106namespace {
107
108constexpr const char* kDump = "android.permission.DUMP";
109
Jeff Sharkey423e7462016-12-09 18:18:43 -0700110static binder::Status ok() {
111 return binder::Status::ok();
112}
113
114static binder::Status exception(uint32_t code, const std::string& msg) {
Jeff Sharkey8e9bf352018-02-27 11:40:45 -0700115 LOG(ERROR) << msg << " (" << code << ")";
Jeff Sharkey423e7462016-12-09 18:18:43 -0700116 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
117}
118
119static binder::Status error() {
120 return binder::Status::fromServiceSpecificError(errno);
121}
122
123static binder::Status error(const std::string& msg) {
124 PLOG(ERROR) << msg;
125 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
126}
127
128static binder::Status error(uint32_t code, const std::string& msg) {
129 LOG(ERROR) << msg << " (" << code << ")";
130 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
131}
132
Jeff Sharkey0274c972016-12-06 09:32:04 -0700133binder::Status checkPermission(const char* permission) {
134 pid_t pid;
135 uid_t uid;
136
137 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
138 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700139 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700140 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700141 return exception(binder::Status::EX_SECURITY,
142 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700143 }
144}
145
146binder::Status checkUid(uid_t expectedUid) {
147 uid_t uid = IPCThreadState::self()->getCallingUid();
148 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700149 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700150 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700151 return exception(binder::Status::EX_SECURITY,
152 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
153 }
154}
155
156binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
157 if (!uuid || is_valid_filename(*uuid)) {
158 return ok();
159 } else {
160 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
161 StringPrintf("UUID %s is malformed", uuid->c_str()));
162 }
163}
164
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000165binder::Status checkArgumentUuidTestOrNull(const std::unique_ptr<std::string>& uuid) {
166 if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
167 return ok();
168 } else {
169 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
170 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
171 }
172}
173
Jeff Sharkey423e7462016-12-09 18:18:43 -0700174binder::Status checkArgumentPackageName(const std::string& packageName) {
Greg Kaiser6d758fc2019-03-26 08:55:32 -0700175 if (is_valid_package_name(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700176 return ok();
177 } else {
178 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
179 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700180 }
181}
182
Jeff Sharkey53594302018-02-24 18:59:39 -0700183binder::Status checkArgumentPath(const std::string& path) {
184 if (path.empty()) {
185 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
186 }
187 if (path[0] != '/') {
188 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
189 StringPrintf("Path %s is relative", path.c_str()));
190 }
191 if ((path + '/').find("/../") != std::string::npos) {
192 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
193 StringPrintf("Path %s is shady", path.c_str()));
194 }
195 for (const char& c : path) {
196 if (c == '\0' || c == '\n') {
197 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
198 StringPrintf("Path %s is malformed", path.c_str()));
199 }
200 }
201 return ok();
202}
203
204binder::Status checkArgumentPath(const std::unique_ptr<std::string>& path) {
205 if (path) {
206 return checkArgumentPath(*path);
207 } else {
208 return ok();
209 }
210}
211
Jeff Sharkey0274c972016-12-06 09:32:04 -0700212#define ENFORCE_UID(uid) { \
213 binder::Status status = checkUid((uid)); \
214 if (!status.isOk()) { \
215 return status; \
216 } \
217}
218
Jeff Sharkey423e7462016-12-09 18:18:43 -0700219#define CHECK_ARGUMENT_UUID(uuid) { \
220 binder::Status status = checkArgumentUuid((uuid)); \
221 if (!status.isOk()) { \
222 return status; \
223 } \
224}
225
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000226#define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) { \
227 auto status = checkArgumentUuidTestOrNull(uuid); \
228 if (!status.isOk()) { \
229 return status; \
230 } \
231} \
232
Jeff Sharkey423e7462016-12-09 18:18:43 -0700233#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
234 binder::Status status = \
235 checkArgumentPackageName((packageName)); \
236 if (!status.isOk()) { \
237 return status; \
238 } \
239}
240
Jeff Sharkey53594302018-02-24 18:59:39 -0700241#define CHECK_ARGUMENT_PATH(path) { \
242 binder::Status status = checkArgumentPath((path)); \
243 if (!status.isOk()) { \
244 return status; \
245 } \
246}
247
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800248#define ASSERT_PAGE_SIZE_4K() { \
249 if (getpagesize() != kVerityPageSize) { \
Victor Hsieh7ebd5132018-01-23 07:52:17 -0800250 return error("FSVerity only supports 4K pages"); \
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800251 } \
252}
253
Jeff Sharkey0274c972016-12-06 09:32:04 -0700254} // namespace
255
256status_t InstalldNativeService::start() {
257 IPCThreadState::self()->disableBackgroundScheduling(true);
258 status_t ret = BinderService<InstalldNativeService>::publish();
259 if (ret != android::OK) {
260 return ret;
261 }
262 sp<ProcessState> ps(ProcessState::self());
263 ps->startThreadPool();
264 ps->giveThreadPoolName();
265 return android::OK;
266}
267
268status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700269 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700270 const binder::Status dump_permission = checkPermission(kDump);
271 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700272 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700273 return PERMISSION_DENIED;
274 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700275 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700276
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700277 out << "installd is happy!" << endl;
278
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700279 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600280 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
281 out << endl << "Storage mounts:" << endl;
282 for (const auto& n : mStorageMounts) {
283 out << " " << n.first << " = " << n.second << endl;
284 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700285 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700286
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700287 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600288 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700289 out << endl << "Per-UID cache quotas:" << endl;
290 for (const auto& n : mCacheQuotas) {
291 out << " " << n.first << " = " << n.second << endl;
292 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700293 }
294
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700295 out << endl;
296 out.flush();
297
Jeff Sharkey0274c972016-12-06 09:32:04 -0700298 return NO_ERROR;
299}
300
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600301/**
302 * Perform restorecon of the given path, but only perform recursive restorecon
303 * if the label of that top-level file actually changed. This can save us
304 * significant time by avoiding no-op traversals of large filesystem trees.
305 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700306static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
307 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600308 int res = 0;
309 char* before = nullptr;
310 char* after = nullptr;
311
312 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
313 // libselinux. Not needed here.
314
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600315 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600316 PLOG(ERROR) << "Failed before getfilecon for " << path;
317 goto fail;
318 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700319 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600320 PLOG(ERROR) << "Failed top-level restorecon for " << path;
321 goto fail;
322 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600323 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600324 PLOG(ERROR) << "Failed after getfilecon for " << path;
325 goto fail;
326 }
327
328 // If the initial top-level restorecon above changed the label, then go
329 // back and restorecon everything recursively
330 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700331 if (existing) {
332 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
333 << path << "; running recursive restorecon";
334 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700335 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600336 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
337 PLOG(ERROR) << "Failed recursive restorecon for " << path;
338 goto fail;
339 }
340 }
341
342 goto done;
343fail:
344 res = -1;
345done:
346 free(before);
347 free(after);
348 return res;
349}
350
Jeff Sharkey0274c972016-12-06 09:32:04 -0700351static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700352 const std::string& seInfo, uid_t uid, bool existing) {
353 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
354 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600355}
356
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600357static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600358 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
359 PLOG(ERROR) << "Failed to prepare " << path;
360 return -1;
361 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600362 return 0;
363}
364
Calin Juravled2affb82017-11-28 17:41:43 -0800365static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
366 if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
367 return true;
368 }
369
370 int32_t uid = multiuser_get_uid(userId, appId);
371 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
372 if (shared_app_gid == -1) {
373 // TODO(calin): this should no longer be possible but do not continue if we don't get
374 // a valid shared gid.
375 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
376 return true;
377 }
378
379 const std::string profile_dir =
380 create_primary_current_profile_package_dir_path(userId, packageName);
381 // read-write-execute only for the app user.
382 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
383 PLOG(ERROR) << "Failed to prepare " << profile_dir;
384 return false;
385 }
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800386
Calin Juravled2affb82017-11-28 17:41:43 -0800387 const std::string ref_profile_path =
388 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800389
390 // Prepare the reference profile directory. Note that we use the non strict version of
391 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
392 // This is particularly important given that in O there were some fixes for how the
393 // shared_app_gid is computed.
394 //
395 // Note that by the time we get here we know that we are using a correct uid (otherwise
396 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
397 // are sure that the gid being used belongs to the owning app and not someone else.
398 //
399 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
400 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800401 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
402 return false;
403 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800404
Calin Juravled2affb82017-11-28 17:41:43 -0800405 return true;
406}
407
Jeff Sharkey0274c972016-12-06 09:32:04 -0700408binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
409 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700410 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700411 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700412 CHECK_ARGUMENT_UUID(uuid);
413 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700414 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700415
416 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
417 const char* pkgname = packageName.c_str();
418
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700419 // Assume invalid inode unless filled in below
420 if (_aidl_return != nullptr) *_aidl_return = -1;
421
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700422 int32_t uid = multiuser_get_uid(userId, appId);
423 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700424 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
425
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700426 // If UID doesn't have a specific cache GID, use UID value
427 if (cacheGid == -1) {
428 cacheGid = uid;
429 }
430
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700431 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700432 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700433 bool existing = (access(path.c_str(), F_OK) == 0);
434
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700435 if (prepare_app_dir(path, targetMode, uid) ||
436 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
437 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700438 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600439 }
440
441 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700442 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
443 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
444 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700445 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700446 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600447
448 // Remember inode numbers of cache directories so that we can clear
449 // contents while CE storage is locked
450 if (write_path_inode(path, "cache", kXattrInodeCache) ||
451 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700452 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700453 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700454
455 // And return the CE inode of the top-level data directory so we can
456 // clear contents while CE storage is locked
457 if ((_aidl_return != nullptr)
458 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
459 return error("Failed to get_path_inode for " + path);
460 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700461 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700462 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700463 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700464 bool existing = (access(path.c_str(), F_OK) == 0);
465
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700466 if (prepare_app_dir(path, targetMode, uid) ||
467 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
468 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700469 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700470 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000471
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600472 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600473 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
474 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
475 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700476 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600477 }
478
Calin Juravled2affb82017-11-28 17:41:43 -0800479 if (!prepare_app_profile_dir(packageName, appId, userId)) {
480 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000481 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700482 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700483 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700484}
485
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700486binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
487 const std::string& packageName, int32_t userId, int32_t flags) {
488 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700489 CHECK_ARGUMENT_UUID(uuid);
490 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700491 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700492
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700493 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
494 const char* pkgname = packageName.c_str();
495
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700496 // This method only exists to upgrade system apps that have requested
497 // forceDeviceEncrypted, so their default storage always lives in a
498 // consistent location. This only works on non-FBE devices, since we
499 // never want to risk exposing data on a device with real CE/DE storage.
500
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700501 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
502 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700503
504 // If neither directory is marked as default, assume CE is default
505 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
506 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
507 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700508 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700509 }
510 }
511
512 // Migrate default data location if needed
513 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
514 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
515
516 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
517 LOG(WARNING) << "Requested default storage " << target
518 << " is not active; migrating from " << source;
519 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700520 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700521 }
522 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700523 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700524 }
525 }
526
Jeff Sharkey423e7462016-12-09 18:18:43 -0700527 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700528}
529
Calin Juravle6a1648e2016-02-01 12:12:16 +0000530
Calin Juravle562de812018-01-20 23:34:18 -0800531binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
532 const std::string& profileName) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700533 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700534 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700535 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700536
Jeff Sharkey423e7462016-12-09 18:18:43 -0700537 binder::Status res = ok();
Calin Juravle562de812018-01-20 23:34:18 -0800538 if (!clear_primary_reference_profile(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700539 res = error("Failed to clear reference profile for " + packageName);
540 }
Calin Juravle562de812018-01-20 23:34:18 -0800541 if (!clear_primary_current_profiles(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700542 res = error("Failed to clear current profiles for " + packageName);
543 }
544 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000545}
546
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700547binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
548 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
549 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700550 CHECK_ARGUMENT_UUID(uuid);
551 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700552 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700553
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700554 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
555 const char* pkgname = packageName.c_str();
556
Jeff Sharkey423e7462016-12-09 18:18:43 -0700557 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700558 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700559 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600560 if (flags & FLAG_CLEAR_CACHE_ONLY) {
561 path = read_path_inode(path, "cache", kXattrInodeCache);
562 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
563 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
564 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700565 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700566 if (delete_dir_contents(path) != 0) {
567 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900568 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
569 remove_path_xattr(path, kXattrInodeCache);
570 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700571 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700572 }
573 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700574 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600575 std::string suffix = "";
576 bool only_cache = false;
577 if (flags & FLAG_CLEAR_CACHE_ONLY) {
578 suffix = CACHE_DIR_POSTFIX;
579 only_cache = true;
580 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
581 suffix = CODE_CACHE_DIR_POSTFIX;
582 only_cache = true;
583 }
584
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700585 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700586 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700587 if (delete_dir_contents(path) != 0) {
588 res = error("Failed to delete contents of " + path);
589 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700590 }
591 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600592 if (flags & FLAG_STORAGE_EXTERNAL) {
593 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
594 for (const auto& n : mStorageMounts) {
595 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +0000596
597 if (android::base::GetBoolProperty(kFuseProp, false)) {
598 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
599 if (std::regex_match(extPath, re)) {
600 extPath += "/" + std::to_string(userId);
601 }
602 } else {
603 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
604 extPath += StringPrintf("/%d", userId);
605 } else if (userId != 0) {
606 // TODO: support devices mounted under secondary users
607 continue;
608 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600609 }
Zim0ce832d2019-12-03 17:03:58 +0000610
Jeff Sharkey6e175692019-05-14 14:55:33 -0600611 if (flags & FLAG_CLEAR_CACHE_ONLY) {
612 // Clear only cached data from shared storage
613 auto path = StringPrintf("%s/Android/data/%s/cache", extPath.c_str(), pkgname);
614 if (delete_dir_contents(path, true) != 0) {
615 res = error("Failed to delete contents of " + path);
616 }
617 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
618 // No code cache on shared storage
619 } else {
620 // Clear everything on shared storage
621 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
622 if (delete_dir_contents(path, true) != 0) {
623 res = error("Failed to delete contents of " + path);
624 }
625 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
626 if (delete_dir_contents(path, true) != 0) {
627 res = error("Failed to delete contents of " + path);
628 }
629 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
630 if (delete_dir_contents(path, true) != 0) {
631 res = error("Failed to delete contents of " + path);
632 }
633 }
634 }
635 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700636 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700637}
638
Calin Juravle76268c52017-03-09 13:19:42 -0800639static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100640 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800641 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100642 /*ignore_if_missing*/ true);
643}
644
Calin Juravle76268c52017-03-09 13:19:42 -0800645static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100646 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800647 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100648 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000649}
650
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700651binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
652 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700653 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700654 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700655
Jeff Sharkey423e7462016-12-09 18:18:43 -0700656 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000657 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
658 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800659 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700660 res = error("Failed to destroy current profiles for " + packageName);
661 }
Calin Juravleedae6692016-03-23 13:55:31 +0000662 }
Calin Juravle76268c52017-03-09 13:19:42 -0800663 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700664 res = error("Failed to destroy reference profile for " + packageName);
665 }
666 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000667}
668
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700669binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
670 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
671 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700672 CHECK_ARGUMENT_UUID(uuid);
673 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700674 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700675
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700676 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
677 const char* pkgname = packageName.c_str();
678
Jeff Sharkey423e7462016-12-09 18:18:43 -0700679 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700680 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700681 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
682 if (delete_dir_contents_and_dir(path) != 0) {
683 res = error("Failed to delete " + path);
684 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700685 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700686 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700687 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
688 if (delete_dir_contents_and_dir(path) != 0) {
689 res = error("Failed to delete " + path);
690 }
Calin Juravle76268c52017-03-09 13:19:42 -0800691 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100692 // TODO(calin): If the package is still installed by other users it's probably
693 // beneficial to keep the reference profile around.
694 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800695 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700696 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600697 if (flags & FLAG_STORAGE_EXTERNAL) {
698 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
699 for (const auto& n : mStorageMounts) {
700 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +0000701
702 if (android::base::GetBoolProperty(kFuseProp, false)) {
703 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
704 if (std::regex_match(extPath, re)) {
705 extPath += "/" + std::to_string(userId);
706 }
707 } else {
708 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
709 extPath += StringPrintf("/%d", userId);
710 } else if (userId != 0) {
711 // TODO: support devices mounted under secondary users
712 continue;
713 }
Jeff Sharkey6e175692019-05-14 14:55:33 -0600714 }
Zim0ce832d2019-12-03 17:03:58 +0000715
Jeff Sharkey6e175692019-05-14 14:55:33 -0600716 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
717 if (delete_dir_contents_and_dir(path, true) != 0) {
718 res = error("Failed to delete contents of " + path);
719 }
Zim0ce832d2019-12-03 17:03:58 +0000720
Jeff Sharkey6e175692019-05-14 14:55:33 -0600721 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
722 if (delete_dir_contents_and_dir(path, true) != 0) {
723 res = error("Failed to delete contents of " + path);
724 }
725 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
726 if (delete_dir_contents_and_dir(path, true) != 0) {
727 res = error("Failed to delete contents of " + path);
728 }
729 }
730 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700731 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700732}
733
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600734static gid_t get_cache_gid(uid_t uid) {
735 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
736 return (gid != -1) ? gid : uid;
737}
738
739binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
740 int32_t flags) {
741 ENFORCE_UID(AID_SYSTEM);
742 CHECK_ARGUMENT_UUID(uuid);
743 std::lock_guard<std::recursive_mutex> lock(mLock);
744
745 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
746 for (auto user : get_known_users(uuid_)) {
747 ATRACE_BEGIN("fixup user");
748 FTS* fts;
749 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600750 auto ce_path = create_data_user_ce_path(uuid_, user);
751 auto de_path = create_data_user_de_path(uuid_, user);
752 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -0700753 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600754 return error("Failed to fts_open");
755 }
756 while ((p = fts_read(fts)) != nullptr) {
757 if (p->fts_info == FTS_D && p->fts_level == 1) {
758 // Track down inodes of cache directories
759 uint64_t raw = 0;
760 ino_t inode_cache = 0;
761 ino_t inode_code_cache = 0;
762 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
763 inode_cache = raw;
764 }
765 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
766 inode_code_cache = raw;
767 }
768
769 // Figure out expected GID of each child
770 FTSENT* child = fts_children(fts, 0);
771 while (child != nullptr) {
772 if ((child->fts_statp->st_ino == inode_cache)
773 || (child->fts_statp->st_ino == inode_code_cache)
774 || !strcmp(child->fts_name, "cache")
775 || !strcmp(child->fts_name, "code_cache")) {
776 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
777 } else {
778 child->fts_number = p->fts_statp->st_uid;
779 }
780 child = child->fts_link;
781 }
782 } else if (p->fts_level >= 2) {
783 if (p->fts_level > 2) {
784 // Inherit GID from parent once we're deeper into tree
785 p->fts_number = p->fts_parent->fts_number;
786 }
787
788 uid_t uid = p->fts_parent->fts_statp->st_uid;
789 gid_t cache_gid = get_cache_gid(uid);
790 gid_t expected = p->fts_number;
791 gid_t actual = p->fts_statp->st_gid;
792 if (actual == expected) {
793#if FIXUP_DEBUG
794 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
795#endif
796 if (!(flags & FLAG_FORCE)) {
797 fts_set(fts, p, FTS_SKIP);
798 }
799 } else if ((actual == uid) || (actual == cache_gid)) {
800 // Only consider fixing up when current GID belongs to app
801 if (p->fts_info != FTS_D) {
802 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
803 << " instead of " << expected;
804 }
805 switch (p->fts_info) {
806 case FTS_DP:
807 // If we're moving towards cache GID, we need to set S_ISGID
808 if (expected == cache_gid) {
809 if (chmod(p->fts_path, 02771) != 0) {
810 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
811 }
812 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -0700813 [[fallthrough]]; // also set GID
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600814 case FTS_F:
815 if (chown(p->fts_path, -1, expected) != 0) {
816 PLOG(WARNING) << "Failed to chown " << p->fts_path;
817 }
818 break;
819 case FTS_SL:
820 case FTS_SLNONE:
821 if (lchown(p->fts_path, -1, expected) != 0) {
822 PLOG(WARNING) << "Failed to chown " << p->fts_path;
823 }
824 break;
825 }
826 } else {
827 // Ignore all other GID transitions, since they're kinda shady
828 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
829 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -0600830 if (!(flags & FLAG_FORCE)) {
831 fts_set(fts, p, FTS_SKIP);
832 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600833 }
834 }
835 }
836 fts_close(fts);
837 ATRACE_END();
838 }
839 return ok();
840}
841
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000842static int32_t copy_directory_recursive(const char* from, const char* to) {
843 char *argv[] = {
844 (char*) kCpPath,
845 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
846 (char*) "-p", /* preserve timestamps, ownership, and permissions */
847 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
848 (char*) "-P", /* Do not follow symlinks [default] */
849 (char*) "-d", /* don't dereference symlinks */
850 (char*) from,
851 (char*) to
852 };
853
854 LOG(DEBUG) << "Copying " << from << " to " << to;
Tom Cherrye79cde52019-09-25 16:51:56 -0700855 return logwrap_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, LOG_ALOG, false, nullptr);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000856}
857
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000858binder::Status InstalldNativeService::snapshotAppData(
859 const std::unique_ptr<std::string>& volumeUuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000860 const std::string& packageName, int32_t user, int32_t snapshotId,
861 int32_t storageFlags, int64_t* _aidl_return) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000862 ENFORCE_UID(AID_SYSTEM);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000863 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000864 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
865 std::lock_guard<std::recursive_mutex> lock(mLock);
866
867 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
868 const char* package_name = packageName.c_str();
869
870 binder::Status res = ok();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000871 // Default result to 0, it will be populated with inode of ce data snapshot
872 // if FLAG_STORAGE_CE has been passed.
873 if (_aidl_return != nullptr) *_aidl_return = 0;
874
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000875 bool clear_ce_on_exit = false;
876 bool clear_de_on_exit = false;
877
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000878 auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &user, &package_name,
879 &snapshotId] {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000880 if (clear_de_on_exit) {
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000881 auto to = create_data_misc_de_rollback_package_path(volume_uuid, user, snapshotId,
882 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000883 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
884 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
885 }
886 }
887
888 if (clear_ce_on_exit) {
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000889 auto to = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshotId,
890 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000891 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
892 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
893 }
894 }
895 };
896
897 auto scope_guard = android::base::make_scope_guard(deleter);
898
899 // The app may not have any data at all, in which case it's OK to skip here.
900 auto from_ce = create_data_user_ce_package_path(volume_uuid, user, package_name);
901 if (access(from_ce.c_str(), F_OK) != 0) {
902 LOG(INFO) << "Missing source " << from_ce;
903 return ok();
904 }
905
Nikita Ioffe900b3c22019-01-23 14:32:48 +0000906 // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
907 binder::Status clear_cache_result = clearAppData(volumeUuid, packageName, user,
908 storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
909 if (!clear_cache_result.isOk()) {
910 // It should be fine to continue snapshot if we for some reason failed
911 // to clear cache.
912 LOG(WARNING) << "Failed to clear cache of app " << packageName;
913 }
914
915 // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
916 binder::Status clear_code_cache_result = clearAppData(volumeUuid, packageName, user,
917 storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY, 0);
918 if (!clear_code_cache_result.isOk()) {
919 // It should be fine to continue snapshot if we for some reason failed
920 // to clear code_cache.
921 LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
922 }
923
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000924 if (storageFlags & FLAG_STORAGE_DE) {
925 auto from = create_data_user_de_package_path(volume_uuid, user, package_name);
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000926 auto to = create_data_misc_de_rollback_path(volume_uuid, user, snapshotId);
927 auto rollback_package_path = create_data_misc_de_rollback_package_path(volume_uuid, user,
928 snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000929
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000930 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
931 if (rc != 0) {
932 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000933 }
934
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000935 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
936 if (rc != 0) {
937 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
938 }
939
940 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000941 if (rc != 0) {
942 res = error(rc, "Failed copying " + from + " to " + to);
943 clear_de_on_exit = true;
944 return res;
945 }
946 }
947
948 if (storageFlags & FLAG_STORAGE_CE) {
949 auto from = create_data_user_ce_package_path(volume_uuid, user, package_name);
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000950 auto to = create_data_misc_ce_rollback_path(volume_uuid, user, snapshotId);
951 auto rollback_package_path = create_data_misc_ce_rollback_package_path(volume_uuid, user,
952 snapshotId, package_name);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000953
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000954 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
955 if (rc != 0) {
956 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +0000957 }
958
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000959 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
960 if (rc != 0) {
961 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
962 }
963
964 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000965 if (rc != 0) {
966 res = error(rc, "Failed copying " + from + " to " + to);
967 clear_ce_on_exit = true;
968 return res;
969 }
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000970 if (_aidl_return != nullptr) {
971 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid, user,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000972 snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000973 rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
974 if (rc != 0) {
975 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
976 clear_ce_on_exit = true;
977 return res;
978 }
979 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000980 }
981
982 return res;
983}
984
985binder::Status InstalldNativeService::restoreAppDataSnapshot(
986 const std::unique_ptr<std::string>& volumeUuid, const std::string& packageName,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000987 const int32_t appId, const std::string& seInfo, const int32_t user,
988 const int32_t snapshotId, int32_t storageFlags) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000989 ENFORCE_UID(AID_SYSTEM);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000990 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000991 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
992 std::lock_guard<std::recursive_mutex> lock(mLock);
993
994 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
995 const char* package_name = packageName.c_str();
996
997 auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000998 user, snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +0000999 auto from_de = create_data_misc_de_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001000 user, snapshotId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001001
1002 const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
1003 (access(from_ce.c_str(), F_OK) == 0);
1004 const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
1005 (access(from_de.c_str(), F_OK) == 0);
1006
1007 if (!needs_ce_rollback && !needs_de_rollback) {
1008 return ok();
1009 }
1010
1011 // We know we're going to rollback one of the CE or DE data, so we clear
1012 // application data first. Note that it's possible that we're asked to
1013 // restore both CE & DE data but that one of the restores fail. Leaving the
1014 // app with no data in those cases is arguably better than leaving the app
1015 // with mismatched / stale data.
1016 LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001017 // It's fine to pass 0 as ceDataInode here, because restoreAppDataSnapshot
1018 // can only be called when user unlocks the phone, meaning that CE user data
1019 // is decrypted.
1020 binder::Status res = clearAppData(volumeUuid, packageName, user, storageFlags,
1021 0 /* ceDataInode */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001022 if (!res.isOk()) {
1023 return res;
1024 }
1025
1026 if (needs_ce_rollback) {
1027 auto to_ce = create_data_user_ce_path(volume_uuid, user);
1028 int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
1029 if (rc != 0) {
1030 res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
1031 return res;
1032 }
1033 }
1034
1035 if (needs_de_rollback) {
1036 auto to_de = create_data_user_de_path(volume_uuid, user);
1037 int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
1038 if (rc != 0) {
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001039 if (needs_ce_rollback) {
1040 auto ce_data = create_data_user_ce_package_path(volume_uuid, user, package_name);
1041 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
1042 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
1043 LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
1044 }
1045 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001046 res = error(rc, "Failed copying " + from_de + " to " + to_de);
1047 return res;
1048 }
1049 }
1050
1051 // Finally, restore the SELinux label on the app data.
1052 return restoreconAppData(volumeUuid, packageName, user, storageFlags, appId, seInfo);
1053}
1054
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001055binder::Status InstalldNativeService::destroyAppDataSnapshot(
1056 const std::unique_ptr<std::string> &volumeUuid, const std::string& packageName,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001057 const int32_t user, const int64_t ceSnapshotInode, const int32_t snapshotId,
1058 int32_t storageFlags) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001059 ENFORCE_UID(AID_SYSTEM);
1060 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1061 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1062 std::lock_guard<std::recursive_mutex> lock(mLock);
1063
1064 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1065 const char* package_name = packageName.c_str();
1066
1067 if (storageFlags & FLAG_STORAGE_DE) {
1068 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001069 user, snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001070
1071 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
1072 if (res != 0) {
1073 return error(res, "Failed clearing snapshot " + de_snapshot_path);
1074 }
1075 }
1076
1077 if (storageFlags & FLAG_STORAGE_CE) {
1078 auto ce_snapshot_path = create_data_misc_ce_rollback_package_path(volume_uuid,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001079 user, snapshotId, package_name, ceSnapshotInode);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001080 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
1081 if (res != 0) {
1082 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
1083 }
1084 }
1085 return ok();
1086}
1087
1088
Jeff Sharkey0274c972016-12-06 09:32:04 -07001089binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
1090 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
1091 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
1092 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001093 ENFORCE_UID(AID_SYSTEM);
1094 CHECK_ARGUMENT_UUID(fromUuid);
1095 CHECK_ARGUMENT_UUID(toUuid);
1096 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001097 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -07001098
1099 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1100 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1101 const char* package_name = packageName.c_str();
1102 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001103
Jeff Sharkey423e7462016-12-09 18:18:43 -07001104 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001105 std::vector<userid_t> users = get_known_users(from_uuid);
1106
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001107 // Copy app
1108 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001109 auto from = create_data_app_package_path(from_uuid, data_app_name);
1110 auto to = create_data_app_package_path(to_uuid, data_app_name);
1111 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001112
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001113 int rc = copy_directory_recursive(from.c_str(), to_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001114 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001115 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001116 goto fail;
1117 }
1118
1119 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001120 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001121 goto fail;
1122 }
1123 }
1124
1125 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -07001126 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -07001127
1128 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -06001129 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
1130 if (access(from_ce.c_str(), F_OK) != 0) {
1131 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001132 continue;
1133 }
1134
Jeff Sharkey0274c972016-12-06 09:32:04 -07001135 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -07001136 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001137 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001138 goto fail;
1139 }
1140
Jeff Sharkey51c94492016-05-10 17:46:39 -06001141 {
1142 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
1143 auto to = create_data_user_de_path(to_uuid, user);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001144
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001145 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001146 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001147 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001148 goto fail;
1149 }
1150 }
1151 {
1152 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
1153 auto to = create_data_user_ce_path(to_uuid, user);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001154
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001155 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001156 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001157 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001158 goto fail;
1159 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001160 }
1161
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001162 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1163 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001164 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001165 goto fail;
1166 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001167 }
1168
Jeff Sharkey31f08982015-07-07 13:31:37 -07001169 // We let the framework scan the new location and persist that before
1170 // deleting the data in the old location; this ordering ensures that
1171 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001172 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001173
1174fail:
1175 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001176 {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001177 auto to = create_data_app_package_path(to_uuid, data_app_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001178 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001179 LOG(WARNING) << "Failed to rollback " << to;
1180 }
1181 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001182 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001183 {
1184 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001185 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001186 LOG(WARNING) << "Failed to rollback " << to;
1187 }
1188 }
1189 {
1190 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001191 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001192 LOG(WARNING) << "Failed to rollback " << to;
1193 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001194 }
1195 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001196 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001197}
1198
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001199binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
1200 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
1201 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001202 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001203 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001204
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001205 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001206 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001207 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001208 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001209 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07001210 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001211 }
1212 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001213
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001214 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001215}
1216
1217binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
1218 int32_t userId, int32_t flags) {
1219 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001220 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001221 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001222
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001223 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001224 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001225 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001226 auto path = create_data_user_de_path(uuid_, userId);
1227 if (delete_dir_contents_and_dir(path, true) != 0) {
1228 res = error("Failed to delete " + path);
1229 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001230 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001231 path = create_data_misc_legacy_path(userId);
1232 if (delete_dir_contents_and_dir(path, true) != 0) {
1233 res = error("Failed to delete " + path);
1234 }
Calin Juravle114f0812017-03-08 19:05:07 -08001235 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001236 if (delete_dir_contents_and_dir(path, true) != 0) {
1237 res = error("Failed to delete " + path);
1238 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001239 }
Robin Lee095c7632014-04-25 15:05:19 +01001240 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001241 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001242 auto path = create_data_user_ce_path(uuid_, userId);
1243 if (delete_dir_contents_and_dir(path, true) != 0) {
1244 res = error("Failed to delete " + path);
1245 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001246 path = findDataMediaPath(uuid, 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 Sharkey379a12b2016-04-14 20:45:06 -06001250 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001251 return res;
Robin Lee095c7632014-04-25 15:05:19 +01001252}
1253
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001254binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001255 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001256 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001257 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001258 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001259
Risan5f308262018-10-26 12:06:58 -06001260 auto uuidString = uuid ? *uuid : "";
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001261 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001262 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001263 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001264
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001265 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001266 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001267 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001268 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001269
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001270 int64_t cleared = 0;
1271 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001272 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001273 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001274
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001275 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001276 return ok();
1277 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001278
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001279 if (flags & FLAG_FREE_CACHE_V2) {
1280 // This new cache strategy fairly removes files from UIDs by deleting
1281 // files from the UIDs which are most over their allocated quota
1282
1283 // 1. Create trackers for every known UID
1284 ATRACE_BEGIN("create");
1285 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
1286 for (auto user : get_known_users(uuid_)) {
1287 FTS *fts;
1288 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001289 auto ce_path = create_data_user_ce_path(uuid_, user);
1290 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001291 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
1292 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
1293 (char*) media_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001294 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001295 return error("Failed to fts_open");
1296 }
Yi Konge7bf3772018-07-17 16:16:24 -07001297 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001298 if (p->fts_info == FTS_D && p->fts_level == 1) {
1299 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001300 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
1301 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
1302 + AID_APP_START;
1303 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001304 auto search = trackers.find(uid);
1305 if (search != trackers.end()) {
1306 search->second->addDataPath(p->fts_path);
1307 } else {
1308 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06001309 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001310 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001311 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001312 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001313 tracker->cacheQuota = mCacheQuotas[uid];
1314 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001315 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001316#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001317 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001318#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001319 tracker->cacheQuota = 67108864;
1320 }
1321 trackers[uid] = tracker;
1322 }
1323 fts_set(fts, p, FTS_SKIP);
1324 }
1325 }
1326 fts_close(fts);
1327 }
1328 ATRACE_END();
1329
1330 // 2. Populate tracker stats and insert into priority queue
1331 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001332 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001333 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1334 return (left->getCacheRatio() < right->getCacheRatio());
1335 };
1336 std::priority_queue<std::shared_ptr<CacheTracker>,
1337 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1338 for (const auto& it : trackers) {
1339 it.second->loadStats();
1340 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001341 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001342 }
1343 ATRACE_END();
1344
1345 // 3. Bounce across the queue, freeing items from whichever tracker is
1346 // the most over their assigned quota
1347 ATRACE_BEGIN("bounce");
1348 std::shared_ptr<CacheTracker> active;
1349 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001350 // Only look at apps under quota when explicitly requested
1351 if (active && (active->getCacheRatio() < 10000)
1352 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1353 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1354 << " isn't over quota, and defy not requested";
1355 break;
1356 }
1357
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001358 // Only keep clearing when we haven't pushed into reserved area
1359 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1360 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1361 break;
1362 }
1363
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001364 // Find the best tracker to work with; this might involve swapping
1365 // if the active tracker is no longer the most over quota
1366 bool nextBetter = active && !queue.empty()
1367 && active->getCacheRatio() < queue.top()->getCacheRatio();
1368 if (!active || nextBetter) {
1369 if (active) {
1370 // Current tracker still has items, so we'll consider it
1371 // again later once it bubbles up to surface
1372 queue.push(active);
1373 }
1374 active = queue.top(); queue.pop();
1375 active->ensureItems();
1376 continue;
1377 }
1378
1379 // If no items remain, go find another tracker
1380 if (active->items.empty()) {
1381 active = nullptr;
1382 continue;
1383 } else {
1384 auto item = active->items.back();
1385 active->items.pop_back();
1386
1387 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1388 if (!noop) {
1389 item->purge();
1390 }
1391 active->cacheUsed -= item->size;
1392 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001393 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001394 }
1395
1396 // Verify that we're actually done before bailing, since sneaky
1397 // apps might be using hardlinks
1398 if (needed <= 0) {
1399 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001400 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001401 if (needed <= 0) {
1402 break;
1403 } else {
1404 LOG(WARNING) << "Expected to be done but still need " << needed;
1405 }
1406 }
1407 }
1408 ATRACE_END();
1409
1410 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001411 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001412 }
1413
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001414 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001415 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001416 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001417 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001418 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001419 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001420 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001421}
1422
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001423binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1424 const std::string& instructionSet) {
1425 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07001426 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001427 std::lock_guard<std::recursive_mutex> lock(mLock);
1428
Mike Lockwood94afecf2012-10-24 10:45:23 -07001429 char dex_path[PKG_PATH_MAX];
1430
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001431 const char* path = codePath.c_str();
1432 const char* instruction_set = instructionSet.c_str();
1433
Jeff Sharkey770180a2014-09-08 17:14:26 -07001434 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001435 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001436 }
1437
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001438 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001439 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001440 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001441
1442 ALOGV("unlink %s\n", dex_path);
1443 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001444 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1445 // but could not be unlinked.
1446 if (errno != ENOENT) {
1447 return error(StringPrintf("Failed to unlink %s", dex_path));
1448 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001449 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001450 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001451}
1452
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001453struct stats {
1454 int64_t codeSize;
1455 int64_t dataSize;
1456 int64_t cacheSize;
1457};
1458
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001459#if MEASURE_DEBUG
1460static std::string toString(std::vector<int64_t> values) {
1461 std::stringstream res;
1462 res << "[";
1463 for (size_t i = 0; i < values.size(); i++) {
1464 res << values[i];
1465 if (i < values.size() - 1) {
1466 res << ",";
1467 }
1468 }
1469 res << "]";
1470 return res.str();
1471}
1472#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001473
Risan5f308262018-10-26 12:06:58 -06001474static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001475 int32_t appId, struct stats* stats, struct stats* extStats) {
Risan5f308262018-10-26 12:06:58 -06001476 int64_t space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001477 if (stats != nullptr) {
1478 uid_t uid = multiuser_get_uid(userId, appId);
Risan5f308262018-10-26 12:06:58 -06001479 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
1480 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001481 }
1482
1483 int cacheGid = multiuser_get_cache_gid(userId, appId);
1484 if (cacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001485 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
1486 stats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001487 }
1488 }
1489
1490 int sharedGid = multiuser_get_shared_gid(0, appId);
1491 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001492 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
1493 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001494 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001495 }
1496 }
1497
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001498 if (extStats != nullptr) {
1499 int extGid = multiuser_get_ext_gid(userId, appId);
1500 if (extGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001501 if ((space = GetOccupiedSpaceForGid(uuid, extGid)) != -1) {
1502 extStats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001503 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001504 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001505
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001506 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1507 if (extCacheGid != -1) {
Risan5f308262018-10-26 12:06:58 -06001508 if ((space = GetOccupiedSpaceForGid(uuid, extCacheGid)) != -1) {
1509 extStats->dataSize += space;
1510 extStats->cacheSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001511 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001512 }
1513 }
1514}
1515
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001516static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001517 DIR *d;
1518 int dfd;
1519 struct dirent *de;
1520 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001521
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001522 d = opendir(path.c_str());
1523 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001524 if (errno != ENOENT) {
1525 PLOG(WARNING) << "Failed to open " << path;
1526 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001527 return;
1528 }
1529 dfd = dirfd(d);
1530 while ((de = readdir(d))) {
1531 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001532
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001533 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001534 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001535 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001536 }
1537
1538 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001539 if (!strcmp(name, ".")) {
1540 // Don't recurse, but still count node size
1541 } else if (!strcmp(name, "..")) {
1542 // Don't recurse or count node size
1543 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001544 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001545 // Measure all children nodes
1546 size = 0;
1547 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001548 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001549
1550 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1551 stats->cacheSize += size;
1552 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001553 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001554
1555 // Legacy symlink isn't owned by app
1556 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1557 continue;
1558 }
1559
1560 // Everything found inside is considered data
1561 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001562 }
1563 closedir(d);
1564}
1565
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001566static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1567 bool exclude_apps = false) {
1568 DIR *d;
1569 int dfd;
1570 struct dirent *de;
1571 struct stat s;
1572
1573 d = opendir(path.c_str());
1574 if (d == nullptr) {
1575 if (errno != ENOENT) {
1576 PLOG(WARNING) << "Failed to open " << path;
1577 }
1578 return;
1579 }
1580 dfd = dirfd(d);
1581 while ((de = readdir(d))) {
1582 if (de->d_type == DT_DIR) {
1583 const char *name = de->d_name;
1584 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1585 continue;
1586 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001587 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001588 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1589 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001590 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001591 continue;
1592 } else {
1593 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1594 }
1595 }
1596 }
1597 closedir(d);
1598}
1599
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001600static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1601 FTS *fts;
1602 FTSENT *p;
1603 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001604 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001605 PLOG(ERROR) << "Failed to fts_open " << path;
1606 return;
1607 }
Yi Konge7bf3772018-07-17 16:16:24 -07001608 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001609 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001610 switch (p->fts_info) {
1611 case FTS_D:
1612 if (p->fts_level == 4
1613 && !strcmp(p->fts_name, "cache")
1614 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1615 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1616 p->fts_number = 1;
1617 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001618 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001619 case FTS_DEFAULT:
1620 case FTS_F:
1621 case FTS_SL:
1622 case FTS_SLNONE:
1623 int64_t size = (p->fts_statp->st_blocks * 512);
1624 if (p->fts_number == 1) {
1625 stats->cacheSize += size;
1626 }
1627 stats->dataSize += size;
1628 break;
1629 }
1630 }
1631 fts_close(fts);
1632}
1633
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001634binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001635 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1636 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1637 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001638 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001639 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001640 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001641 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1642 }
Jeff Sharkey53594302018-02-24 18:59:39 -07001643 for (const auto& codePath : codePaths) {
1644 CHECK_ARGUMENT_PATH(codePath);
1645 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001646 // NOTE: Locking is relaxed on this method, since it's limited to
1647 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001648
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001649 // When modifying this logic, always verify using tests:
1650 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1651
1652#if MEASURE_DEBUG
1653 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1654#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001655
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001656 // Here's a summary of the common storage locations across the platform,
1657 // and how they're each tagged:
1658 //
1659 // /data/app/com.example UID system
1660 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001661 // /data/user/0/com.example UID u0_a10 GID u0_a10
1662 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1663 // /data/media/0/foo.txt UID u0_media_rw
1664 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1665 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1666 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1667 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001668
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001669 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001670 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001671 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001672 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001673
Risan5f308262018-10-26 12:06:58 -06001674 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001675 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001676
Risan5f308262018-10-26 12:06:58 -06001677 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001678 flags &= ~FLAG_USE_QUOTA;
1679 }
1680
Jeff Sharkey466459b2017-01-17 15:25:01 -07001681 ATRACE_BEGIN("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001682 for (const auto& packageName : packageNames) {
Jeff Sharkey6d775c52019-03-22 13:46:20 -06001683 auto obbCodePath = create_data_media_package_path(uuid_, userId,
1684 "obb", packageName.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001685 calculate_tree_size(obbCodePath, &extStats.codeSize);
1686 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001687 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001688
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001689 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001690 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001691 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001692 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001693 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001694 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001695 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001696
Jeff Sharkey466459b2017-01-17 15:25:01 -07001697 ATRACE_BEGIN("quota");
Risan5f308262018-10-26 12:06:58 -06001698 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001699 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001700 } else {
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);
1704 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001705 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001706
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001707 for (size_t i = 0; i < packageNames.size(); i++) {
1708 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001709
Jeff Sharkey466459b2017-01-17 15:25:01 -07001710 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001711 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1712 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001713 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1714 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001715 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001716
Jeff Sharkey06a61842017-04-15 12:03:31 -06001717 if (!uuid) {
1718 ATRACE_BEGIN("profiles");
1719 calculate_tree_size(
1720 create_primary_current_profile_package_dir_path(userId, pkgname),
1721 &stats.dataSize);
1722 calculate_tree_size(
1723 create_primary_reference_profile_package_dir_path(pkgname),
1724 &stats.codeSize);
1725 ATRACE_END();
1726 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001727
Jeff Sharkey466459b2017-01-17 15:25:01 -07001728 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001729 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001730 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001731 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001732 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001733 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001734 }
1735
Jeff Sharkey06a61842017-04-15 12:03:31 -06001736 if (!uuid) {
1737 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001738 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001739 if (sharedGid != -1) {
1740 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1741 sharedGid, -1);
1742 }
1743 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001744 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001745 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001746
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001747 std::vector<int64_t> ret;
1748 ret.push_back(stats.codeSize);
1749 ret.push_back(stats.dataSize);
1750 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001751 ret.push_back(extStats.codeSize);
1752 ret.push_back(extStats.dataSize);
1753 ret.push_back(extStats.cacheSize);
1754#if MEASURE_DEBUG
1755 LOG(DEBUG) << "Final result " << toString(ret);
1756#endif
1757 *_aidl_return = ret;
1758 return ok();
1759}
1760
1761binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1762 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1763 std::vector<int64_t>* _aidl_return) {
1764 ENFORCE_UID(AID_SYSTEM);
1765 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001766 // NOTE: Locking is relaxed on this method, since it's limited to
1767 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001768
1769 // When modifying this logic, always verify using tests:
1770 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1771
1772#if MEASURE_DEBUG
1773 LOG(INFO) << "Measuring user " << userId;
1774#endif
1775
1776 struct stats stats;
1777 struct stats extStats;
1778 memset(&stats, 0, sizeof(stats));
1779 memset(&extStats, 0, sizeof(extStats));
1780
Risan5f308262018-10-26 12:06:58 -06001781 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001782 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1783
Risan5f308262018-10-26 12:06:58 -06001784 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001785 flags &= ~FLAG_USE_QUOTA;
1786 }
1787
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001788 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001789 int64_t space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001790
1791 ATRACE_BEGIN("obb");
Risan5f308262018-10-26 12:06:58 -06001792 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1793 extStats.codeSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001794 }
1795 ATRACE_END();
1796
Jeff Sharkey466459b2017-01-17 15:25:01 -07001797 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001798 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001799 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001800
Jeff Sharkey466459b2017-01-17 15:25:01 -07001801 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001802 auto cePath = create_data_user_ce_path(uuid_, userId);
1803 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001804 auto dePath = create_data_user_de_path(uuid_, userId);
1805 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001806 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001807
Jeff Sharkey06a61842017-04-15 12:03:31 -06001808 if (!uuid) {
1809 ATRACE_BEGIN("profile");
1810 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1811 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1812 auto refProfilePath = create_primary_ref_profile_dir_path();
1813 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1814 ATRACE_END();
1815 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001816
Jeff Sharkey466459b2017-01-17 15:25:01 -07001817 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001818 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001819 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1820 extStats.dataSize += space;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001821 }
1822 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001823
Jeff Sharkey06a61842017-04-15 12:03:31 -06001824 if (!uuid) {
1825 ATRACE_BEGIN("dalvik");
1826 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1827 -1, -1, true);
1828 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1829 -1, -1, true);
1830 ATRACE_END();
1831 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001832
Jeff Sharkey466459b2017-01-17 15:25:01 -07001833 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001834 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001835 for (auto appId : appIds) {
1836 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001837 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001838
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001839#if MEASURE_DEBUG
1840 // Sleep to make sure we don't lose logs
1841 usleep(1);
1842#endif
1843 }
1844 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001845 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001846 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001847 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001848 ATRACE_BEGIN("obb");
1849 auto obbPath = create_data_path(uuid_) + "/media/obb";
1850 calculate_tree_size(obbPath, &extStats.codeSize);
1851 ATRACE_END();
1852
Jeff Sharkey466459b2017-01-17 15:25:01 -07001853 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001854 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001855 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001856
Jeff Sharkey466459b2017-01-17 15:25:01 -07001857 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001858 auto cePath = create_data_user_ce_path(uuid_, userId);
1859 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001860 auto dePath = create_data_user_de_path(uuid_, userId);
1861 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001862 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001863
Jeff Sharkey06a61842017-04-15 12:03:31 -06001864 if (!uuid) {
1865 ATRACE_BEGIN("profile");
1866 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1867 calculate_tree_size(userProfilePath, &stats.dataSize);
1868 auto refProfilePath = create_primary_ref_profile_dir_path();
1869 calculate_tree_size(refProfilePath, &stats.codeSize);
1870 ATRACE_END();
1871 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001872
Jeff Sharkey466459b2017-01-17 15:25:01 -07001873 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001874 auto dataMediaPath = create_data_media_path(uuid_, userId);
1875 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1876#if MEASURE_DEBUG
1877 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1878 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001879#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001880 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001881
Jeff Sharkey06a61842017-04-15 12:03:31 -06001882 if (!uuid) {
1883 ATRACE_BEGIN("dalvik");
1884 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1885 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1886 ATRACE_END();
1887 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001888 }
1889
1890 std::vector<int64_t> ret;
1891 ret.push_back(stats.codeSize);
1892 ret.push_back(stats.dataSize);
1893 ret.push_back(stats.cacheSize);
1894 ret.push_back(extStats.codeSize);
1895 ret.push_back(extStats.dataSize);
1896 ret.push_back(extStats.cacheSize);
1897#if MEASURE_DEBUG
1898 LOG(DEBUG) << "Final result " << toString(ret);
1899#endif
1900 *_aidl_return = ret;
1901 return ok();
1902}
1903
1904binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001905 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1906 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001907 ENFORCE_UID(AID_SYSTEM);
1908 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001909 // NOTE: Locking is relaxed on this method, since it's limited to
1910 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001911
1912 // When modifying this logic, always verify using tests:
1913 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1914
1915#if MEASURE_DEBUG
1916 LOG(INFO) << "Measuring external " << userId;
1917#endif
1918
Risan5f308262018-10-26 12:06:58 -06001919 auto uuidString = uuid ? *uuid : "";
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001920 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1921
1922 int64_t totalSize = 0;
1923 int64_t audioSize = 0;
1924 int64_t videoSize = 0;
1925 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001926 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001927 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001928
Risan5f308262018-10-26 12:06:58 -06001929 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001930 flags &= ~FLAG_USE_QUOTA;
1931 }
1932
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001933 if (flags & FLAG_USE_QUOTA) {
Risan5f308262018-10-26 12:06:58 -06001934 int64_t space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001935
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001936 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001937 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
Risan5f308262018-10-26 12:06:58 -06001938 if ((space = GetOccupiedSpaceForUid(uuidString, uid)) != -1) {
1939 totalSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001940 }
1941
1942 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
Risan5f308262018-10-26 12:06:58 -06001943 if ((space = GetOccupiedSpaceForGid(uuidString, audioGid)) != -1) {
1944 audioSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001945 }
1946 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
Risan5f308262018-10-26 12:06:58 -06001947 if ((space = GetOccupiedSpaceForGid(uuidString, videoGid)) != -1) {
1948 videoSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001949 }
1950 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
Risan5f308262018-10-26 12:06:58 -06001951 if ((space = GetOccupiedSpaceForGid(uuidString, imageGid)) != -1) {
1952 imageSize = space;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001953 }
Risan5f308262018-10-26 12:06:58 -06001954 if ((space = GetOccupiedSpaceForGid(uuidString, AID_MEDIA_OBB)) != -1) {
1955 obbSize = space;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001956 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001957 ATRACE_END();
1958
1959 ATRACE_BEGIN("apps");
1960 struct stats extStats;
1961 memset(&extStats, 0, sizeof(extStats));
1962 for (auto appId : appIds) {
1963 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06001964 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001965 }
1966 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001967 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001968 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001969 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001970 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001971 FTS *fts;
1972 FTSENT *p;
1973 auto path = create_data_media_path(uuid_, userId);
1974 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001975 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001976 return error("Failed to fts_open " + path);
1977 }
Yi Konge7bf3772018-07-17 16:16:24 -07001978 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001979 char* ext;
1980 int64_t size = (p->fts_statp->st_blocks * 512);
1981 switch (p->fts_info) {
1982 case FTS_F:
1983 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001984 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001985 ext = strrchr(p->fts_name, '.');
1986 if (ext != nullptr) {
1987 switch (MatchExtension(++ext)) {
1988 case AID_MEDIA_AUDIO: audioSize += size; break;
1989 case AID_MEDIA_VIDEO: videoSize += size; break;
1990 case AID_MEDIA_IMAGE: imageSize += size; break;
1991 }
1992 }
1993 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001994 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001995 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001996 // Ignore data belonging to specific apps
1997 p->fts_number = p->fts_parent->fts_number;
1998 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1999 p->fts_number = 1;
2000 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002001 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002002 case FTS_DEFAULT:
2003 case FTS_SL:
2004 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002005 if (p->fts_parent->fts_number == 1) {
2006 appSize += size;
2007 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002008 totalSize += size;
2009 break;
2010 }
2011 }
2012 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002013 ATRACE_END();
Jeff Sharkeya0136982017-07-06 11:29:37 -06002014
2015 ATRACE_BEGIN("obb");
Jeff Sharkey6d775c52019-03-22 13:46:20 -06002016 auto obbPath = StringPrintf("%s/Android/obb",
2017 create_data_media_path(uuid_, userId).c_str());
Jeff Sharkeya0136982017-07-06 11:29:37 -06002018 calculate_tree_size(obbPath, &obbSize);
2019 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002020 }
2021
2022 std::vector<int64_t> ret;
2023 ret.push_back(totalSize);
2024 ret.push_back(audioSize);
2025 ret.push_back(videoSize);
2026 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002027 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06002028 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002029#if MEASURE_DEBUG
2030 LOG(DEBUG) << "Final result " << toString(ret);
2031#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002032 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002033 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002034}
2035
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002036binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
2037 int32_t userId, int32_t appId, int64_t cacheQuota) {
2038 ENFORCE_UID(AID_SYSTEM);
2039 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002040 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002041
2042 int32_t uid = multiuser_get_uid(userId, appId);
2043 mCacheQuotas[uid] = cacheQuota;
2044
2045 return ok();
2046}
2047
David Sehr6727c2d2016-05-17 16:06:22 -07002048// Dumps the contents of a profile file, using pkgname's dex files for pretty
2049// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002050binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08002051 const std::string& profileName, const std::string& codePath, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002052 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002053 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002054 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002055 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002056
Calin Juravle562de812018-01-20 23:34:18 -08002057 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002058 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07002059}
2060
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002061// Copy the contents of a system profile over the data profile.
2062binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08002063 int32_t packageUid, const std::string& packageName, const std::string& profileName,
2064 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002065 ENFORCE_UID(AID_SYSTEM);
2066 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2067 std::lock_guard<std::recursive_mutex> lock(mLock);
Calin Juravle562de812018-01-20 23:34:18 -08002068 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07002069 return ok();
2070}
2071
Andreas Gampe4d0f8252016-03-20 11:30:28 -07002072// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002073binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle562de812018-01-20 23:34:18 -08002074 const std::string& profileName, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002075 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002076 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002077 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002078
Calin Juravle562de812018-01-20 23:34:18 -08002079 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002080 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07002081}
2082
Calin Juravlec41dac22017-12-05 12:29:15 -08002083binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08002084 const std::string& packageName, const std::string& profileName,
2085 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08002086 ENFORCE_UID(AID_SYSTEM);
2087 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2088 std::lock_guard<std::recursive_mutex> lock(mLock);
2089
Calin Juravlee61189e2018-01-23 19:54:11 -08002090 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08002091 return ok();
2092}
2093
2094binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002095 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08002096 ENFORCE_UID(AID_SYSTEM);
2097 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2098 std::lock_guard<std::recursive_mutex> lock(mLock);
2099
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002100 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002101 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08002102 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08002103 }
2104 return ok();
2105}
2106
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002107static const char* getCStr(const std::unique_ptr<std::string>& data,
2108 const char* default_value = nullptr) {
2109 return data == nullptr ? default_value : data->c_str();
2110}
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002111binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
2112 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
2113 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
2114 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle1d667612017-07-13 22:50:21 -07002115 const std::unique_ptr<std::string>& classLoaderContext,
Calin Juravle562de812018-01-20 23:34:18 -08002116 const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002117 const std::unique_ptr<std::string>& profileName,
Calin Juravledcccd832018-02-13 18:31:32 -08002118 const std::unique_ptr<std::string>& dexMetadataPath,
2119 const std::unique_ptr<std::string>& compilationReason) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002120 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002121 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07002122 CHECK_ARGUMENT_PATH(apkPath);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002123 if (packageName && *packageName != "*") {
2124 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
2125 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002126 CHECK_ARGUMENT_PATH(outputPath);
2127 CHECK_ARGUMENT_PATH(dexMetadataPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002128 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002129
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07002130 const char* oat_dir = getCStr(outputPath);
2131 const char* instruction_set = instructionSet.c_str();
2132 if (oat_dir != nullptr && !createOatDir(oat_dir, instruction_set).isOk()) {
2133 // Can't create oat dir - let dexopt use cache dir.
2134 oat_dir = nullptr;
2135 }
2136
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002137 const char* apk_path = apkPath.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002138 const char* pkgname = getCStr(packageName, "*");
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002139 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00002140 const char* volume_uuid = getCStr(uuid);
2141 const char* class_loader_context = getCStr(classLoaderContext);
2142 const char* se_info = getCStr(seInfo);
2143 const char* profile_name = getCStr(profileName);
2144 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08002145 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08002146 std::string error_msg;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002147 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07002148 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Andreas Gampe023b2242018-02-28 16:03:25 -08002149 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg);
2150 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002151}
2152
Eric Holk0ebbe0f2019-01-09 18:17:27 -08002153binder::Status InstalldNativeService::compileLayouts(const std::string& apkPath,
2154 const std::string& packageName,
2155 const std ::string& outDexFile, int uid,
2156 bool* _aidl_return) {
2157 const char* apk_path = apkPath.c_str();
2158 const char* package_name = packageName.c_str();
2159 const char* out_dex_file = outDexFile.c_str();
2160 *_aidl_return = android::installd::view_compiler(apk_path, package_name, out_dex_file, uid);
2161 return *_aidl_return ? ok() : error("viewcompiler failed");
2162}
2163
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002164binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
2165 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002166 std::lock_guard<std::recursive_mutex> lock(mLock);
2167
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002168 const char* instruction_set = instructionSet.c_str();
2169
2170 char boot_marker_path[PKG_PATH_MAX];
2171 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08002172 "%s/%s/%s/.booting",
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -06002173 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08002174 DALVIK_CACHE,
2175 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00002176
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002177 ALOGV("mark_boot_complete : %s", boot_marker_path);
2178 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002179 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002180 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002181 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00002182}
2183
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002184binder::Status InstalldNativeService::linkNativeLibraryDirectory(
2185 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
2186 const std::string& nativeLibPath32, int32_t userId) {
2187 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002188 CHECK_ARGUMENT_UUID(uuid);
2189 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002190 CHECK_ARGUMENT_PATH(nativeLibPath32);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002191 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002192
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002193 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2194 const char* pkgname = packageName.c_str();
2195 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002196 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002197 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002198
Jeff Sharkey423e7462016-12-09 18:18:43 -07002199 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
2200 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07002201
2202 const char* pkgdir = _pkgdir.c_str();
2203 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002204
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002205 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002206 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002207 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002208
Nick Kralevich85958b62019-01-30 12:32:21 -08002209 char *con = nullptr;
2210 if (lgetfilecon(pkgdir, &con) < 0) {
2211 return error("Failed to lgetfilecon " + _pkgdir);
2212 }
2213
Mike Lockwood94afecf2012-10-24 10:45:23 -07002214 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08002215 res = error("Failed to chown " + _pkgdir);
2216 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002217 }
2218
2219 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002220 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002221 goto out;
2222 }
2223
2224 if (lstat(libsymlink, &libStat) < 0) {
2225 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002226 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002227 goto out;
2228 }
2229 } else {
2230 if (S_ISDIR(libStat.st_mode)) {
Yi Konge7bf3772018-07-17 16:16:24 -07002231 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002232 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002233 goto out;
2234 }
2235 } else if (S_ISLNK(libStat.st_mode)) {
2236 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002237 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002238 goto out;
2239 }
2240 }
2241 }
2242
2243 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002244 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002245 goto out;
2246 }
2247
Nick Kralevich85958b62019-01-30 12:32:21 -08002248 if (lsetfilecon(libsymlink, con) < 0) {
2249 res = error("Failed to lsetfilecon " + _libsymlink);
2250 goto out;
2251 }
2252
Mike Lockwood94afecf2012-10-24 10:45:23 -07002253out:
Nick Kralevich85958b62019-01-30 12:32:21 -08002254 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002255 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002256 auto msg = "Failed to cleanup chmod " + _pkgdir;
2257 if (res.isOk()) {
2258 res = error(msg);
2259 } else {
2260 PLOG(ERROR) << msg;
2261 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002262 }
2263
2264 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002265 auto msg = "Failed to cleanup chown " + _pkgdir;
2266 if (res.isOk()) {
2267 res = error(msg);
2268 } else {
2269 PLOG(ERROR) << msg;
2270 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002271 }
2272
Jeff Sharkey423e7462016-12-09 18:18:43 -07002273 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002274}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002275
2276static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2277{
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002278 execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
Yi Konge7bf3772018-07-17 16:16:24 -07002279 StringPrintf("%d", idmap_fd).c_str(), (char*)nullptr);
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002280 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2281}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002282
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002283static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2284{
2285 execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
Yi Konge7bf3772018-07-17 16:16:24 -07002286 StringPrintf("%d", idmap_fd).c_str(), (char*)nullptr);
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002287 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2288}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002289
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002290static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
2291 const char* idmap_path, int32_t uid) {
2292 int idmap_fd = open(idmap_path, O_RDWR);
2293 if (idmap_fd < 0) {
2294 PLOG(ERROR) << "idmap open failed: " << idmap_path;
2295 unlink(idmap_path);
2296 return true;
2297 }
2298
2299 pid_t pid;
2300 pid = fork();
2301 if (pid == 0) {
2302 /* child -- drop privileges before continuing */
2303 if (setgid(uid) != 0) {
2304 LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
2305 exit(1);
2306 }
2307 if (setuid(uid) != 0) {
2308 LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
2309 exit(1);
2310 }
2311 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2312 PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
2313 exit(1);
2314 }
2315
2316 run_verify_idmap(target_apk, overlay_apk, idmap_fd);
2317 exit(1); /* only if exec call to deleting stale idmap failed */
2318 } else {
2319 int status = wait_child(pid);
2320 close(idmap_fd);
2321
2322 if (status != 0) {
2323 // Failed on verifying if idmap is made from target_apk and overlay_apk.
2324 LOG(DEBUG) << "delete stale idmap: " << idmap_path;
2325 unlink(idmap_path);
2326 return true;
2327 }
2328 }
2329 return false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002330}
2331
2332// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2333// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2334static int flatten_path(const char *prefix, const char *suffix,
2335 const char *overlay_path, char *idmap_path, size_t N)
2336{
Yi Konge7bf3772018-07-17 16:16:24 -07002337 if (overlay_path == nullptr || idmap_path == nullptr) {
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002338 return -1;
2339 }
2340 const size_t len_overlay_path = strlen(overlay_path);
2341 // will access overlay_path + 1 further below; requires absolute path
2342 if (len_overlay_path < 2 || *overlay_path != '/') {
2343 return -1;
2344 }
2345 const size_t len_idmap_root = strlen(prefix);
2346 const size_t len_suffix = strlen(suffix);
2347 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2348 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2349 // additions below would cause overflow
2350 return -1;
2351 }
2352 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2353 return -1;
2354 }
2355 memset(idmap_path, 0, N);
2356 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2357 char *ch = idmap_path + len_idmap_root;
2358 while (*ch != '\0') {
2359 if (*ch == '/') {
2360 *ch = '@';
2361 }
2362 ++ch;
2363 }
2364 return 0;
2365}
2366
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002367binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2368 const std::string& overlayApkPath, int32_t uid) {
2369 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002370 CHECK_ARGUMENT_PATH(targetApkPath);
2371 CHECK_ARGUMENT_PATH(overlayApkPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002372 std::lock_guard<std::recursive_mutex> lock(mLock);
2373
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002374 const char* target_apk = targetApkPath.c_str();
2375 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002376 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2377
2378 int idmap_fd = -1;
2379 char idmap_path[PATH_MAX];
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002380 struct stat idmap_stat;
2381 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002382
2383 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2384 idmap_path, sizeof(idmap_path)) == -1) {
2385 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2386 goto fail;
2387 }
2388
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002389 if (stat(idmap_path, &idmap_stat) < 0) {
2390 outdated = true;
2391 } else {
2392 outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2393 }
2394
2395 if (outdated) {
2396 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2397 } else {
2398 idmap_fd = open(idmap_path, O_RDWR);
2399 }
2400
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002401 if (idmap_fd < 0) {
2402 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2403 goto fail;
2404 }
2405 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2406 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2407 goto fail;
2408 }
2409 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2410 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2411 goto fail;
2412 }
2413
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002414 if (!outdated) {
2415 close(idmap_fd);
2416 return ok();
2417 }
2418
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002419 pid_t pid;
2420 pid = fork();
2421 if (pid == 0) {
2422 /* child -- drop privileges before continuing */
2423 if (setgid(uid) != 0) {
2424 ALOGE("setgid(%d) failed during idmap\n", uid);
2425 exit(1);
2426 }
2427 if (setuid(uid) != 0) {
2428 ALOGE("setuid(%d) failed during idmap\n", uid);
2429 exit(1);
2430 }
2431 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2432 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2433 exit(1);
2434 }
2435
2436 run_idmap(target_apk, overlay_apk, idmap_fd);
2437 exit(1); /* only if exec call to idmap failed */
2438 } else {
2439 int status = wait_child(pid);
2440 if (status != 0) {
2441 ALOGE("idmap failed, status=0x%04x\n", status);
2442 goto fail;
2443 }
2444 }
2445
2446 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002447 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002448fail:
2449 if (idmap_fd >= 0) {
2450 close(idmap_fd);
2451 unlink(idmap_path);
2452 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002453 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002454}
Robert Craige9887e42014-02-20 10:25:56 -05002455
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002456binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
Jeff Sharkey53594302018-02-24 18:59:39 -07002457 ENFORCE_UID(AID_SYSTEM);
2458 CHECK_ARGUMENT_PATH(overlayApkPath);
2459 std::lock_guard<std::recursive_mutex> lock(mLock);
2460
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002461 const char* overlay_apk = overlayApkPath.c_str();
2462 char idmap_path[PATH_MAX];
2463
2464 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2465 idmap_path, sizeof(idmap_path)) == -1) {
2466 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2467 return error();
2468 }
2469 if (unlink(idmap_path) < 0) {
2470 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2471 return error();
2472 }
2473 return ok();
2474}
2475
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002476binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2477 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2478 const std::string& seInfo) {
2479 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002480 CHECK_ARGUMENT_UUID(uuid);
2481 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002482 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002483
2484 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002485
Robert Craigda30dc72014-03-27 10:21:12 -04002486 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002487 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002488 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2489 const char* pkgName = packageName.c_str();
2490 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002491
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002492 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002493 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002494 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002495 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002496 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002497 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002498 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002499 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002500 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002501 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002502 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002503 }
Robert Craige9887e42014-02-20 10:25:56 -05002504 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002505 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002506}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002507
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002508binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2509 const std::string& instructionSet) {
2510 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002511 CHECK_ARGUMENT_PATH(oatDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002512 std::lock_guard<std::recursive_mutex> lock(mLock);
2513
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002514 const char* oat_dir = oatDir.c_str();
2515 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002516 char oat_instr_dir[PKG_PATH_MAX];
2517
2518 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002519 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002520 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002521 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002522 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002523 }
2524 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002525 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002526 }
2527 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002528 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002529 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002530 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002531 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002532}
2533
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002534binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2535 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002536 CHECK_ARGUMENT_PATH(packageDir);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002537 std::lock_guard<std::recursive_mutex> lock(mLock);
2538
Jeff Sharkey423e7462016-12-09 18:18:43 -07002539 if (validate_apk_path(packageDir.c_str())) {
2540 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002541 }
Oleksandr Peletskyid2be6322019-01-24 17:59:45 +01002542 if (rm_package_dir(packageDir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002543 return error("Failed to delete " + packageDir);
2544 }
2545 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002546}
2547
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002548binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2549 const std::string& fromBase, const std::string& toBase) {
2550 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002551 CHECK_ARGUMENT_PATH(fromBase);
2552 CHECK_ARGUMENT_PATH(toBase);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002553 std::lock_guard<std::recursive_mutex> lock(mLock);
2554
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002555 const char* relative_path = relativePath.c_str();
2556 const char* from_base = fromBase.c_str();
2557 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002558 char from_path[PKG_PATH_MAX];
2559 char to_path[PKG_PATH_MAX];
2560 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2561 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2562
2563 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002564 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002565 }
2566
2567 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002568 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002569 }
2570
Jeff Sharkey423e7462016-12-09 18:18:43 -07002571 if (link(from_path, to_path) < 0) {
2572 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002573 }
2574
Jeff Sharkey423e7462016-12-09 18:18:43 -07002575 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002576}
2577
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002578binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2579 const std::string& instructionSet, const std::string& outputPath) {
2580 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002581 CHECK_ARGUMENT_PATH(apkPath);
2582 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002583 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002584
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002585 const char* apk_path = apkPath.c_str();
2586 const char* instruction_set = instructionSet.c_str();
2587 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002588
Jeff Sharkey90aff262016-12-12 14:28:24 -07002589 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002590 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002591}
2592
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002593binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002594 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002595 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002596 CHECK_ARGUMENT_PATH(apkPath);
2597 CHECK_ARGUMENT_PATH(outputPath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002598 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002599
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002600 const char* apk_path = apkPath.c_str();
2601 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002602 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002603
Jeff Sharkey90aff262016-12-12 14:28:24 -07002604 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2605 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002606}
2607
Victor Hsieh7ebd5132018-01-23 07:52:17 -08002608// This kernel feature is experimental.
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002609// TODO: remove local definition once upstreamed
Victor Hsieh18ac0272018-03-12 16:03:02 -07002610#ifndef FS_IOC_ENABLE_VERITY
2611
2612#define FS_IOC_ENABLE_VERITY _IO('f', 133)
2613#define FS_IOC_SET_VERITY_MEASUREMENT _IOW('f', 134, struct fsverity_measurement)
2614
2615#define FS_VERITY_ALG_SHA256 1
2616
2617struct fsverity_measurement {
2618 __u16 digest_algorithm;
2619 __u16 digest_size;
2620 __u32 reserved1;
2621 __u64 reserved2[3];
2622 __u8 digest[];
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002623};
2624
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002625#endif
2626
2627binder::Status InstalldNativeService::installApkVerity(const std::string& filePath,
Victor Hsieh18ac0272018-03-12 16:03:02 -07002628 const ::android::base::unique_fd& verityInputAshmem, int32_t contentSize) {
Victor Hsieh99de5162017-10-06 14:44:14 -07002629 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002630 CHECK_ARGUMENT_PATH(filePath);
2631 std::lock_guard<std::recursive_mutex> lock(mLock);
2632
Victor Hsieh99de5162017-10-06 14:44:14 -07002633 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2634 return ok();
2635 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002636#ifndef NDEBUG
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002637 ASSERT_PAGE_SIZE_4K();
2638#endif
2639 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2640 // TODO: change ashmem to some temporary file to support huge apk.
2641 if (!ashmem_valid(verityInputAshmem.get())) {
2642 return error("FD is not an ashmem");
2643 }
2644
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002645 // 1. Seek to the next page boundary beyond the end of the file.
Victor Hsieh93a98052018-01-24 14:56:32 -08002646 ::android::base::unique_fd wfd(open(filePath.c_str(), O_WRONLY));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002647 if (wfd.get() < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002648 return error("Failed to open " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002649 }
2650 struct stat st;
2651 if (fstat(wfd.get(), &st) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002652 return error("Failed to stat " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002653 }
2654 // fsverity starts from the block boundary.
Victor Hsieh93a98052018-01-24 14:56:32 -08002655 off_t padding = kVerityPageSize - st.st_size % kVerityPageSize;
2656 if (padding == kVerityPageSize) {
2657 padding = 0;
2658 }
2659 if (lseek(wfd.get(), st.st_size + padding, SEEK_SET) < 0) {
Victor Hsieh18ac0272018-03-12 16:03:02 -07002660 return error("Failed to lseek " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002661 }
2662
Victor Hsieh18ac0272018-03-12 16:03:02 -07002663 // 2. Write everything in the ashmem to the file. Note that allocated
2664 // ashmem size is multiple of page size, which is different from the
2665 // actual content size.
2666 int shmSize = ashmem_get_size_region(verityInputAshmem.get());
2667 if (shmSize < 0) {
2668 return error("Failed to get ashmem size: " + std::to_string(shmSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002669 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002670 if (contentSize < 0) {
2671 return error("Invalid content size: " + std::to_string(contentSize));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002672 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002673 if (contentSize > shmSize) {
2674 return error("Content size overflow: " + std::to_string(contentSize) + " > " +
2675 std::to_string(shmSize));
2676 }
2677 auto data = std::unique_ptr<void, std::function<void (void *)>>(
Yi Konge7bf3772018-07-17 16:16:24 -07002678 mmap(nullptr, contentSize, PROT_READ, MAP_SHARED, verityInputAshmem.get(), 0),
Victor Hsieh18ac0272018-03-12 16:03:02 -07002679 [contentSize] (void* ptr) {
2680 if (ptr != MAP_FAILED) {
2681 munmap(ptr, contentSize);
2682 }
2683 });
2684
2685 if (data.get() == MAP_FAILED) {
2686 return error("Failed to mmap the ashmem");
2687 }
2688 char* cursor = reinterpret_cast<char*>(data.get());
2689 int remaining = contentSize;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002690 while (remaining > 0) {
Victor Hsieh93a98052018-01-24 14:56:32 -08002691 int ret = TEMP_FAILURE_RETRY(write(wfd.get(), cursor, remaining));
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002692 if (ret < 0) {
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002693 return error("Failed to write to " + filePath + " (" + std::to_string(remaining) +
Victor Hsieh18ac0272018-03-12 16:03:02 -07002694 + "/" + std::to_string(contentSize) + ")");
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002695 }
Victor Hsieh93a98052018-01-24 14:56:32 -08002696 cursor += ret;
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002697 remaining -= ret;
2698 }
Victor Hsieh18ac0272018-03-12 16:03:02 -07002699 wfd.reset();
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002700
Victor Hsieh18ac0272018-03-12 16:03:02 -07002701 // 3. Enable fsverity (needs readonly fd. Once it's done, the file becomes immutable.
2702 ::android::base::unique_fd rfd(open(filePath.c_str(), O_RDONLY));
2703 if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, nullptr) < 0) {
2704 return error("Failed to enable fsverity on " + filePath);
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002705 }
2706 return ok();
Victor Hsieh99de5162017-10-06 14:44:14 -07002707}
2708
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002709binder::Status InstalldNativeService::assertFsverityRootHashMatches(const std::string& filePath,
2710 const std::vector<uint8_t>& expectedHash) {
2711 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002712 CHECK_ARGUMENT_PATH(filePath);
2713 std::lock_guard<std::recursive_mutex> lock(mLock);
2714
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002715 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2716 return ok();
2717 }
2718 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2719 if (expectedHash.size() != kSha256Size) {
2720 return error("verity hash size should be " + std::to_string(kSha256Size) + " but is " +
2721 std::to_string(expectedHash.size()));
2722 }
2723
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002724 ::android::base::unique_fd fd(open(filePath.c_str(), O_RDONLY));
2725 if (fd.get() < 0) {
2726 return error("Failed to open " + filePath + ": " + strerror(errno));
2727 }
2728
Victor Hsieh18ac0272018-03-12 16:03:02 -07002729 unsigned int buffer_size = sizeof(fsverity_measurement) + kSha256Size;
2730 std::vector<char> buffer(buffer_size, 0);
2731
2732 fsverity_measurement* config = reinterpret_cast<fsverity_measurement*>(buffer.data());
2733 config->digest_algorithm = FS_VERITY_ALG_SHA256;
2734 config->digest_size = kSha256Size;
2735 memcpy(config->digest, expectedHash.data(), kSha256Size);
2736 if (ioctl(fd.get(), FS_IOC_SET_VERITY_MEASUREMENT, config) < 0) {
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002737 // This includes an expected failure case with no FSVerity setup. It normally happens when
2738 // the apk does not contains the Merkle tree root hash.
2739 return error("Failed to measure fsverity on " + filePath + ": " + strerror(errno));
2740 }
2741 return ok(); // hashes match
2742}
2743
Calin Juravlebd968362017-01-25 01:17:17 -08002744binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2745 const std::string& dexPath, const std::string& packageName, int32_t uid,
2746 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2747 int32_t storage_flag, bool* _aidl_return) {
2748 ENFORCE_UID(AID_SYSTEM);
2749 CHECK_ARGUMENT_UUID(volumeUuid);
2750 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002751 CHECK_ARGUMENT_PATH(dexPath);
Calin Juravlebd968362017-01-25 01:17:17 -08002752 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey53594302018-02-24 18:59:39 -07002753
Calin Juravlebd968362017-01-25 01:17:17 -08002754 bool result = android::installd::reconcile_secondary_dex_file(
2755 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2756 return result ? ok() : error();
2757}
2758
Alan Stokes753dc712017-10-16 10:56:00 +01002759binder::Status InstalldNativeService::hashSecondaryDexFile(
2760 const std::string& dexPath, const std::string& packageName, int32_t uid,
2761 const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
2762 std::vector<uint8_t>* _aidl_return) {
2763 ENFORCE_UID(AID_SYSTEM);
2764 CHECK_ARGUMENT_UUID(volumeUuid);
2765 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002766 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01002767
2768 // mLock is not taken here since we will never modify the file system.
2769 // If a file is modified just as we are reading it this may result in an
2770 // anomalous hash, but that's ok.
2771 bool result = android::installd::hash_secondary_dex_file(
2772 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
2773 return result ? ok() : error();
2774}
2775
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002776binder::Status InstalldNativeService::invalidateMounts() {
2777 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002778 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002779
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002780 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06002781
2782#if !BYPASS_QUOTA
2783 if (!InvalidateQuotaMounts()) {
2784 return error("Failed to read mounts");
2785 }
2786#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002787
2788 std::ifstream in("/proc/mounts");
2789 if (!in.is_open()) {
2790 return error("Failed to read mounts");
2791 }
2792
2793 std::string source;
2794 std::string target;
2795 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002796 while (!in.eof()) {
2797 std::getline(in, source, ' ');
2798 std::getline(in, target, ' ');
2799 std::getline(in, ignored);
2800
Zim0ce832d2019-12-03 17:03:58 +00002801 if (android::base::GetBoolProperty(kFuseProp, false)) {
2802 if (target.compare(0, 17, "/mnt/pass_through") == 0) {
2803 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2804 mStorageMounts[source] = target;
2805 }
2806 } else {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002807#if !BYPASS_SDCARDFS
Zim0ce832d2019-12-03 17:03:58 +00002808 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2809 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2810 mStorageMounts[source] = target;
2811 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002812#endif
Zim0ce832d2019-12-03 17:03:58 +00002813 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002814 }
2815 return ok();
2816}
2817
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002818std::string InstalldNativeService::findDataMediaPath(
2819 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2820 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2821 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2822 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2823 auto resolved = mStorageMounts[path];
2824 if (resolved.empty()) {
2825 LOG(WARNING) << "Failed to find storage mount for " << path;
2826 resolved = path;
2827 }
2828 return StringPrintf("%s/%u", resolved.c_str(), userid);
2829}
2830
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002831binder::Status InstalldNativeService::isQuotaSupported(
Risan5f308262018-10-26 12:06:58 -06002832 const std::unique_ptr<std::string>& uuid, bool* _aidl_return) {
2833 auto uuidString = uuid ? *uuid : "";
2834 *_aidl_return = IsQuotaSupported(uuidString);
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002835 return ok();
2836}
2837
Calin Juravlebc5ab872018-01-18 22:32:58 -08002838binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
2839 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
2840 const std::unique_ptr<std::string>& dexMetadata, bool* _aidl_return) {
2841 ENFORCE_UID(AID_SYSTEM);
2842 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07002843 CHECK_ARGUMENT_PATH(codePath);
Calin Juravlebc5ab872018-01-18 22:32:58 -08002844 std::lock_guard<std::recursive_mutex> lock(mLock);
2845
2846 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
2847 dexMetadata);
2848 return ok();
2849}
2850
Narayan Kamath28ab93b2019-05-15 18:29:44 +01002851binder::Status InstalldNativeService::migrateLegacyObbData() {
2852 ENFORCE_UID(AID_SYSTEM);
2853 // NOTE: The lint warning doesn't apply to the use of system(3) with
2854 // absolute parse and no command line arguments.
2855 if (system("/system/bin/migrate_legacy_obb_data.sh") != 0) { // NOLINT(cert-env33-c)
2856 LOG(ERROR) << "Unable to migrate legacy obb data";
2857 }
2858
2859 return ok();
2860}
2861
Andreas Gampe02d0de52015-11-11 20:43:16 -08002862} // namespace installd
2863} // namespace android