blob: bc91285ef45f8a1f0161ee5d75d764bbad8e5401 [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 Hsieh3f16dd62018-01-13 13:43:11 -080025#include <inttypes.h>
Andreas Gampe0354bd02016-06-27 14:25:30 -070026#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080027#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070028#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080029#include <sys/capability.h>
30#include <sys/file.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080031#include <sys/ioctl.h>
32#include <sys/mman.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070033#include <sys/quota.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080034#include <sys/resource.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070036#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070037#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000038#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070039#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080040#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070041
Andreas Gampeafa58d12016-06-03 16:09:32 -070042#include <android-base/logging.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070043#include <android-base/properties.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080044#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070045#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010046#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080047#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080048#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070049#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070050#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070051#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070052#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080053#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070054#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080055#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070056#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070057
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070058#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070059#include "globals.h"
60#include "installd_deps.h"
61#include "otapreopt_utils.h"
62#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070063
Jeff Sharkey88ddd942017-01-17 18:05:54 -070064#include "CacheTracker.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070065#include "MatchExtensionGen.h"
66
Andreas Gampe02d0de52015-11-11 20:43:16 -080067#ifndef LOG_TAG
68#define LOG_TAG "installd"
69#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070070
71using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070072using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070073
Andreas Gampe02d0de52015-11-11 20:43:16 -080074namespace android {
75namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070076
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070077static constexpr const char* kCpPath = "/system/bin/cp";
78static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070079static constexpr const char* kPropHasReserved = "vold.has_reserved";
Jeff Sharkeye3637242015-04-08 20:56:42 -070080
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070081static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000082
Andreas Gampe0354bd02016-06-27 14:25:30 -070083static constexpr const char* PKG_LIB_POSTFIX = "/lib";
84static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
85static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
86
Jaekyun Seok5cb903e2017-05-18 00:13:44 +090087static constexpr const char *kIdMapPath = "/system/bin/idmap";
Andreas Gampe0354bd02016-06-27 14:25:30 -070088static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
89static constexpr const char* IDMAP_SUFFIX = "@idmap";
90
Victor Hsieh3f16dd62018-01-13 13:43:11 -080091// fsverity assumes the page size is always 4096. If not, the feature can not be
92// enabled.
93static constexpr int kVerityPageSize = 4096;
Victor Hsiehc6d738a2018-01-20 15:06:39 -080094static constexpr size_t kSha256Size = 32;
Victor Hsieh99de5162017-10-06 14:44:14 -070095static constexpr const char* kPropApkVerityMode = "ro.apk_verity.mode";
96
Andreas Gampe0354bd02016-06-27 14:25:30 -070097// NOTE: keep in sync with Installer
98static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
99static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700100static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700101static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700102static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
103static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600104static constexpr int FLAG_FORCE = 1 << 16;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000105
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) {
115 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
116}
117
118static binder::Status error() {
119 return binder::Status::fromServiceSpecificError(errno);
120}
121
122static binder::Status error(const std::string& msg) {
123 PLOG(ERROR) << msg;
124 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
125}
126
127static binder::Status error(uint32_t code, const std::string& msg) {
128 LOG(ERROR) << msg << " (" << code << ")";
129 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
130}
131
Jeff Sharkey0274c972016-12-06 09:32:04 -0700132binder::Status checkPermission(const char* permission) {
133 pid_t pid;
134 uid_t uid;
135
136 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
137 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700138 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700139 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700140 return exception(binder::Status::EX_SECURITY,
141 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700142 }
143}
144
145binder::Status checkUid(uid_t expectedUid) {
146 uid_t uid = IPCThreadState::self()->getCallingUid();
147 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700148 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700149 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700150 return exception(binder::Status::EX_SECURITY,
151 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
152 }
153}
154
155binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
156 if (!uuid || is_valid_filename(*uuid)) {
157 return ok();
158 } else {
159 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
160 StringPrintf("UUID %s is malformed", uuid->c_str()));
161 }
162}
163
164binder::Status checkArgumentPackageName(const std::string& packageName) {
165 if (is_valid_package_name(packageName.c_str())) {
166 return ok();
167 } else {
168 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
169 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700170 }
171}
172
173#define ENFORCE_UID(uid) { \
174 binder::Status status = checkUid((uid)); \
175 if (!status.isOk()) { \
176 return status; \
177 } \
178}
179
Jeff Sharkey423e7462016-12-09 18:18:43 -0700180#define CHECK_ARGUMENT_UUID(uuid) { \
181 binder::Status status = checkArgumentUuid((uuid)); \
182 if (!status.isOk()) { \
183 return status; \
184 } \
185}
186
187#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
188 binder::Status status = \
189 checkArgumentPackageName((packageName)); \
190 if (!status.isOk()) { \
191 return status; \
192 } \
193}
194
Victor Hsieh3f16dd62018-01-13 13:43:11 -0800195#define ASSERT_PAGE_SIZE_4K() { \
196 if (getpagesize() != kVerityPageSize) { \
197 return error("FSVerity only supports 4K page"); \
198 } \
199}
200
Jeff Sharkey0274c972016-12-06 09:32:04 -0700201} // namespace
202
203status_t InstalldNativeService::start() {
204 IPCThreadState::self()->disableBackgroundScheduling(true);
205 status_t ret = BinderService<InstalldNativeService>::publish();
206 if (ret != android::OK) {
207 return ret;
208 }
209 sp<ProcessState> ps(ProcessState::self());
210 ps->startThreadPool();
211 ps->giveThreadPoolName();
212 return android::OK;
213}
214
215status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700216 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700217 const binder::Status dump_permission = checkPermission(kDump);
218 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700219 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700220 return PERMISSION_DENIED;
221 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700222 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700223
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700224 out << "installd is happy!" << endl;
225
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700226 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600227 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
228 out << endl << "Storage mounts:" << endl;
229 for (const auto& n : mStorageMounts) {
230 out << " " << n.first << " = " << n.second << endl;
231 }
232
233 out << endl << "Quota reverse mounts:" << endl;
234 for (const auto& n : mQuotaReverseMounts) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700235 out << " " << n.first << " = " << n.second << endl;
236 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700237 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700238
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700239 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600240 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700241 out << endl << "Per-UID cache quotas:" << endl;
242 for (const auto& n : mCacheQuotas) {
243 out << " " << n.first << " = " << n.second << endl;
244 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700245 }
246
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700247 out << endl;
248 out.flush();
249
Jeff Sharkey0274c972016-12-06 09:32:04 -0700250 return NO_ERROR;
251}
252
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600253/**
254 * Perform restorecon of the given path, but only perform recursive restorecon
255 * if the label of that top-level file actually changed. This can save us
256 * significant time by avoiding no-op traversals of large filesystem trees.
257 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700258static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
259 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600260 int res = 0;
261 char* before = nullptr;
262 char* after = nullptr;
263
264 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
265 // libselinux. Not needed here.
266
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600267 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600268 PLOG(ERROR) << "Failed before getfilecon for " << path;
269 goto fail;
270 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700271 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600272 PLOG(ERROR) << "Failed top-level restorecon for " << path;
273 goto fail;
274 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600275 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600276 PLOG(ERROR) << "Failed after getfilecon for " << path;
277 goto fail;
278 }
279
280 // If the initial top-level restorecon above changed the label, then go
281 // back and restorecon everything recursively
282 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700283 if (existing) {
284 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
285 << path << "; running recursive restorecon";
286 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700287 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600288 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
289 PLOG(ERROR) << "Failed recursive restorecon for " << path;
290 goto fail;
291 }
292 }
293
294 goto done;
295fail:
296 res = -1;
297done:
298 free(before);
299 free(after);
300 return res;
301}
302
Jeff Sharkey0274c972016-12-06 09:32:04 -0700303static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700304 const std::string& seInfo, uid_t uid, bool existing) {
305 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
306 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600307}
308
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600309static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600310 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
311 PLOG(ERROR) << "Failed to prepare " << path;
312 return -1;
313 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600314 return 0;
315}
316
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600317/**
318 * Ensure that we have a hard-limit quota to protect against abusive apps;
319 * they should never use more than 90% of blocks or 50% of inodes.
320 */
321static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
322 uid_t uid) {
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -0700323 // Skip when reserved blocks are protecting us against abusive apps
324 if (android::base::GetBoolProperty(kPropHasReserved, false)) return 0;
325 // Skip when device no quotas present
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600326 if (device.empty()) return 0;
327
328 struct dqblk dq;
329 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
330 reinterpret_cast<char*>(&dq)) != 0) {
331 PLOG(WARNING) << "Failed to find quota for " << uid;
332 return -1;
333 }
334
Jeff Sharkeybdd4de82017-08-11 15:13:31 -0600335#if APPLY_HARD_QUOTAS
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600336 if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
337 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
338 struct statvfs stat;
339 if (statvfs(path.c_str(), &stat) != 0) {
340 PLOG(WARNING) << "Failed to statvfs " << path;
341 return -1;
342 }
343
344 dq.dqb_valid = QIF_LIMITS;
Jerry Wongbcb87472017-07-28 15:54:58 -0700345 dq.dqb_bhardlimit =
346 (((static_cast<uint64_t>(stat.f_blocks) * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600347 dq.dqb_ihardlimit = (stat.f_files / 2);
348 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
349 reinterpret_cast<char*>(&dq)) != 0) {
350 PLOG(WARNING) << "Failed to set hard quota for " << uid;
351 return -1;
352 } else {
353 LOG(DEBUG) << "Applied hard quotas for " << uid;
354 return 0;
355 }
356 } else {
357 // Hard quota already set; assume it's reasonable
358 return 0;
359 }
Jeff Sharkeybdd4de82017-08-11 15:13:31 -0600360#else
361 // Hard quotas disabled
362 return 0;
363#endif
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600364}
365
Calin Juravled2affb82017-11-28 17:41:43 -0800366static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
367 if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
368 return true;
369 }
370
371 int32_t uid = multiuser_get_uid(userId, appId);
372 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
373 if (shared_app_gid == -1) {
374 // TODO(calin): this should no longer be possible but do not continue if we don't get
375 // a valid shared gid.
376 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
377 return true;
378 }
379
380 const std::string profile_dir =
381 create_primary_current_profile_package_dir_path(userId, packageName);
382 // read-write-execute only for the app user.
383 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
384 PLOG(ERROR) << "Failed to prepare " << profile_dir;
385 return false;
386 }
387 const std::string profile_file = create_current_profile_path(userId, packageName,
388 /*is_secondary_dex*/false);
389 // read-write only for the app user.
390 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
391 PLOG(ERROR) << "Failed to prepare " << profile_file;
392 return false;
393 }
394
395 const std::string ref_profile_path =
396 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800397
398 // Prepare the reference profile directory. Note that we use the non strict version of
399 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
400 // This is particularly important given that in O there were some fixes for how the
401 // shared_app_gid is computed.
402 //
403 // Note that by the time we get here we know that we are using a correct uid (otherwise
404 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
405 // are sure that the gid being used belongs to the owning app and not someone else.
406 //
407 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
408 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800409 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
410 return false;
411 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800412
Calin Juravled2affb82017-11-28 17:41:43 -0800413 return true;
414}
415
Jeff Sharkey0274c972016-12-06 09:32:04 -0700416binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
417 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700418 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700419 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700420 CHECK_ARGUMENT_UUID(uuid);
421 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700422 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700423
424 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
425 const char* pkgname = packageName.c_str();
426
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700427 // Assume invalid inode unless filled in below
428 if (_aidl_return != nullptr) *_aidl_return = -1;
429
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700430 int32_t uid = multiuser_get_uid(userId, appId);
431 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700432 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
433
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700434 // If UID doesn't have a specific cache GID, use UID value
435 if (cacheGid == -1) {
436 cacheGid = uid;
437 }
438
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700439 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700440 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700441 bool existing = (access(path.c_str(), F_OK) == 0);
442
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700443 if (prepare_app_dir(path, targetMode, uid) ||
444 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
445 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700446 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600447 }
448
449 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700450 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
451 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
452 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700453 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700454 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600455
456 // Remember inode numbers of cache directories so that we can clear
457 // contents while CE storage is locked
458 if (write_path_inode(path, "cache", kXattrInodeCache) ||
459 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700460 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700461 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700462
463 // And return the CE inode of the top-level data directory so we can
464 // clear contents while CE storage is locked
465 if ((_aidl_return != nullptr)
466 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
467 return error("Failed to get_path_inode for " + path);
468 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700469 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700470 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700471 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700472 bool existing = (access(path.c_str(), F_OK) == 0);
473
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700474 if (prepare_app_dir(path, targetMode, uid) ||
475 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
476 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700477 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700478 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000479
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600480 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600481 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
482 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
483 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700484 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600485 }
486
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600487 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
488 return error("Failed to set hard quota " + path);
489 }
490
Calin Juravled2affb82017-11-28 17:41:43 -0800491 if (!prepare_app_profile_dir(packageName, appId, userId)) {
492 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000493 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700494 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700495 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700496}
497
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700498binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
499 const std::string& packageName, int32_t userId, int32_t flags) {
500 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700501 CHECK_ARGUMENT_UUID(uuid);
502 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700503 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700504
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700505 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
506 const char* pkgname = packageName.c_str();
507
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700508 // This method only exists to upgrade system apps that have requested
509 // forceDeviceEncrypted, so their default storage always lives in a
510 // consistent location. This only works on non-FBE devices, since we
511 // never want to risk exposing data on a device with real CE/DE storage.
512
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700513 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
514 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700515
516 // If neither directory is marked as default, assume CE is default
517 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
518 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
519 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700520 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700521 }
522 }
523
524 // Migrate default data location if needed
525 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
526 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
527
528 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
529 LOG(WARNING) << "Requested default storage " << target
530 << " is not active; migrating from " << source;
531 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700532 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700533 }
534 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700535 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700536 }
537 }
538
Jeff Sharkey423e7462016-12-09 18:18:43 -0700539 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700540}
541
Calin Juravle6a1648e2016-02-01 12:12:16 +0000542
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700543binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
544 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700545 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700546 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547
Jeff Sharkey423e7462016-12-09 18:18:43 -0700548 binder::Status res = ok();
Calin Juravle114f0812017-03-08 19:05:07 -0800549 if (!clear_primary_reference_profile(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700550 res = error("Failed to clear reference profile for " + packageName);
551 }
Calin Juravle114f0812017-03-08 19:05:07 -0800552 if (!clear_primary_current_profiles(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700553 res = error("Failed to clear current profiles for " + packageName);
554 }
555 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000556}
557
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700558binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
559 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
560 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700561 CHECK_ARGUMENT_UUID(uuid);
562 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700563 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700564
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700565 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
566 const char* pkgname = packageName.c_str();
567
Jeff Sharkey423e7462016-12-09 18:18:43 -0700568 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700569 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700570 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600571 if (flags & FLAG_CLEAR_CACHE_ONLY) {
572 path = read_path_inode(path, "cache", kXattrInodeCache);
573 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
574 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
575 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700576 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700577 if (delete_dir_contents(path) != 0) {
578 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900579 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
580 remove_path_xattr(path, kXattrInodeCache);
581 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700582 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700583 }
584 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700585 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600586 std::string suffix = "";
587 bool only_cache = false;
588 if (flags & FLAG_CLEAR_CACHE_ONLY) {
589 suffix = CACHE_DIR_POSTFIX;
590 only_cache = true;
591 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
592 suffix = CODE_CACHE_DIR_POSTFIX;
593 only_cache = true;
594 }
595
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700596 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700597 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700598 if (delete_dir_contents(path) != 0) {
599 res = error("Failed to delete contents of " + path);
600 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700601 }
Calin Juravleedae6692016-03-23 13:55:31 +0000602 if (!only_cache) {
Calin Juravle114f0812017-03-08 19:05:07 -0800603 if (!clear_primary_current_profile(packageName, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700604 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000605 }
606 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700607 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700608 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700609}
610
Calin Juravle76268c52017-03-09 13:19:42 -0800611static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100612 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800613 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100614 /*ignore_if_missing*/ true);
615}
616
Calin Juravle76268c52017-03-09 13:19:42 -0800617static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100618 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800619 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100620 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000621}
622
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700623binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
624 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700625 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700626 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700627
Jeff Sharkey423e7462016-12-09 18:18:43 -0700628 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000629 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
630 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800631 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700632 res = error("Failed to destroy current profiles for " + packageName);
633 }
Calin Juravleedae6692016-03-23 13:55:31 +0000634 }
Calin Juravle76268c52017-03-09 13:19:42 -0800635 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700636 res = error("Failed to destroy reference profile for " + packageName);
637 }
638 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000639}
640
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700641binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
642 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
643 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700644 CHECK_ARGUMENT_UUID(uuid);
645 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700646 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700647
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700648 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
649 const char* pkgname = packageName.c_str();
650
Jeff Sharkey423e7462016-12-09 18:18:43 -0700651 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700652 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700653 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
654 if (delete_dir_contents_and_dir(path) != 0) {
655 res = error("Failed to delete " + path);
656 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700657 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700658 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700659 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
660 if (delete_dir_contents_and_dir(path) != 0) {
661 res = error("Failed to delete " + path);
662 }
Calin Juravle76268c52017-03-09 13:19:42 -0800663 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100664 // TODO(calin): If the package is still installed by other users it's probably
665 // beneficial to keep the reference profile around.
666 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800667 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700668 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700669 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700670}
671
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600672static gid_t get_cache_gid(uid_t uid) {
673 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
674 return (gid != -1) ? gid : uid;
675}
676
677binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
678 int32_t flags) {
679 ENFORCE_UID(AID_SYSTEM);
680 CHECK_ARGUMENT_UUID(uuid);
681 std::lock_guard<std::recursive_mutex> lock(mLock);
682
683 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
684 for (auto user : get_known_users(uuid_)) {
685 ATRACE_BEGIN("fixup user");
686 FTS* fts;
687 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600688 auto ce_path = create_data_user_ce_path(uuid_, user);
689 auto de_path = create_data_user_de_path(uuid_, user);
690 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600691 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
692 return error("Failed to fts_open");
693 }
694 while ((p = fts_read(fts)) != nullptr) {
695 if (p->fts_info == FTS_D && p->fts_level == 1) {
696 // Track down inodes of cache directories
697 uint64_t raw = 0;
698 ino_t inode_cache = 0;
699 ino_t inode_code_cache = 0;
700 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
701 inode_cache = raw;
702 }
703 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
704 inode_code_cache = raw;
705 }
706
707 // Figure out expected GID of each child
708 FTSENT* child = fts_children(fts, 0);
709 while (child != nullptr) {
710 if ((child->fts_statp->st_ino == inode_cache)
711 || (child->fts_statp->st_ino == inode_code_cache)
712 || !strcmp(child->fts_name, "cache")
713 || !strcmp(child->fts_name, "code_cache")) {
714 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
715 } else {
716 child->fts_number = p->fts_statp->st_uid;
717 }
718 child = child->fts_link;
719 }
720 } else if (p->fts_level >= 2) {
721 if (p->fts_level > 2) {
722 // Inherit GID from parent once we're deeper into tree
723 p->fts_number = p->fts_parent->fts_number;
724 }
725
726 uid_t uid = p->fts_parent->fts_statp->st_uid;
727 gid_t cache_gid = get_cache_gid(uid);
728 gid_t expected = p->fts_number;
729 gid_t actual = p->fts_statp->st_gid;
730 if (actual == expected) {
731#if FIXUP_DEBUG
732 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
733#endif
734 if (!(flags & FLAG_FORCE)) {
735 fts_set(fts, p, FTS_SKIP);
736 }
737 } else if ((actual == uid) || (actual == cache_gid)) {
738 // Only consider fixing up when current GID belongs to app
739 if (p->fts_info != FTS_D) {
740 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
741 << " instead of " << expected;
742 }
743 switch (p->fts_info) {
744 case FTS_DP:
745 // If we're moving towards cache GID, we need to set S_ISGID
746 if (expected == cache_gid) {
747 if (chmod(p->fts_path, 02771) != 0) {
748 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
749 }
750 }
751 // Intentional fall through to also set GID
752 case FTS_F:
753 if (chown(p->fts_path, -1, expected) != 0) {
754 PLOG(WARNING) << "Failed to chown " << p->fts_path;
755 }
756 break;
757 case FTS_SL:
758 case FTS_SLNONE:
759 if (lchown(p->fts_path, -1, expected) != 0) {
760 PLOG(WARNING) << "Failed to chown " << p->fts_path;
761 }
762 break;
763 }
764 } else {
765 // Ignore all other GID transitions, since they're kinda shady
766 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
767 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -0600768 if (!(flags & FLAG_FORCE)) {
769 fts_set(fts, p, FTS_SKIP);
770 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600771 }
772 }
773 }
774 fts_close(fts);
775 ATRACE_END();
776 }
777 return ok();
778}
779
Jeff Sharkey0274c972016-12-06 09:32:04 -0700780binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
781 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
782 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
783 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700784 ENFORCE_UID(AID_SYSTEM);
785 CHECK_ARGUMENT_UUID(fromUuid);
786 CHECK_ARGUMENT_UUID(toUuid);
787 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700788 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700789
790 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
791 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
792 const char* package_name = packageName.c_str();
793 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700794
Jeff Sharkey423e7462016-12-09 18:18:43 -0700795 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700796 std::vector<userid_t> users = get_known_users(from_uuid);
797
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700798 // Copy app
799 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600800 auto from = create_data_app_package_path(from_uuid, data_app_name);
801 auto to = create_data_app_package_path(to_uuid, data_app_name);
802 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700803
804 char *argv[] = {
805 (char*) kCpPath,
806 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
807 (char*) "-p", /* preserve timestamps, ownership, and permissions */
808 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
809 (char*) "-P", /* Do not follow symlinks [default] */
810 (char*) "-d", /* don't dereference symlinks */
811 (char*) from.c_str(),
812 (char*) to_parent.c_str()
813 };
814
815 LOG(DEBUG) << "Copying " << from << " to " << to;
816 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700817 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700818 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700819 goto fail;
820 }
821
822 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700823 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700824 goto fail;
825 }
826 }
827
828 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700829 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700830
831 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600832 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
833 if (access(from_ce.c_str(), F_OK) != 0) {
834 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700835 continue;
836 }
837
Jeff Sharkey0274c972016-12-06 09:32:04 -0700838 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700839 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700840 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700841 goto fail;
842 }
843
844 char *argv[] = {
845 (char*) kCpPath,
846 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
847 (char*) "-p", /* preserve timestamps, ownership, and permissions */
848 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
849 (char*) "-P", /* Do not follow symlinks [default] */
850 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600851 nullptr,
852 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700853 };
854
Jeff Sharkey51c94492016-05-10 17:46:39 -0600855 {
856 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
857 auto to = create_data_user_de_path(to_uuid, user);
858 argv[6] = (char*) from.c_str();
859 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700860
Jeff Sharkey51c94492016-05-10 17:46:39 -0600861 LOG(DEBUG) << "Copying " << from << " to " << to;
862 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
863 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700864 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600865 goto fail;
866 }
867 }
868 {
869 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
870 auto to = create_data_user_ce_path(to_uuid, user);
871 argv[6] = (char*) from.c_str();
872 argv[7] = (char*) to.c_str();
873
874 LOG(DEBUG) << "Copying " << from << " to " << to;
875 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
876 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700877 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600878 goto fail;
879 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700880 }
881
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700882 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
883 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700884 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700885 goto fail;
886 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700887 }
888
Jeff Sharkey31f08982015-07-07 13:31:37 -0700889 // We let the framework scan the new location and persist that before
890 // deleting the data in the old location; this ordering ensures that
891 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700892 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700893
894fail:
895 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700896 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600897 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700898 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
899 LOG(WARNING) << "Failed to rollback " << to;
900 }
901 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700902 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600903 {
904 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
905 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
906 LOG(WARNING) << "Failed to rollback " << to;
907 }
908 }
909 {
910 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
911 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
912 LOG(WARNING) << "Failed to rollback " << to;
913 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700914 }
915 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700916 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700917}
918
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700919binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
920 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
921 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700922 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700923 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700924
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700925 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600926 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700927 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700928 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700929 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700930 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700931 }
932 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600933
934 // Data under /data/media doesn't have an app, but we still want
935 // to limit it to prevent abuse.
936 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
937 multiuser_get_uid(userId, AID_MEDIA_RW))) {
938 return error("Failed to set hard quota for media_rw");
939 }
940
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700941 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700942}
943
944binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
945 int32_t userId, int32_t flags) {
946 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700947 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700948 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700949
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700950 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700951 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700952 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700953 auto path = create_data_user_de_path(uuid_, userId);
954 if (delete_dir_contents_and_dir(path, true) != 0) {
955 res = error("Failed to delete " + path);
956 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700957 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700958 path = create_data_misc_legacy_path(userId);
959 if (delete_dir_contents_and_dir(path, true) != 0) {
960 res = error("Failed to delete " + path);
961 }
Calin Juravle114f0812017-03-08 19:05:07 -0800962 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700963 if (delete_dir_contents_and_dir(path, true) != 0) {
964 res = error("Failed to delete " + path);
965 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700966 }
Robin Lee095c7632014-04-25 15:05:19 +0100967 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600968 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700969 auto path = create_data_user_ce_path(uuid_, userId);
970 if (delete_dir_contents_and_dir(path, true) != 0) {
971 res = error("Failed to delete " + path);
972 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600973 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700974 if (delete_dir_contents_and_dir(path, true) != 0) {
975 res = error("Failed to delete " + path);
976 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600977 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700978 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100979}
980
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700981binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600982 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700983 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700984 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700985 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700986
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700987 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700988 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700989 auto device = findQuotaDeviceForUuid(uuid);
990 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700991
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700992 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700993 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700994 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700995 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700996
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600997 int64_t cleared = 0;
998 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600999 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001000 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001001
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001002 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001003 return ok();
1004 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001005
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001006 if (flags & FLAG_FREE_CACHE_V2) {
1007 // This new cache strategy fairly removes files from UIDs by deleting
1008 // files from the UIDs which are most over their allocated quota
1009
1010 // 1. Create trackers for every known UID
1011 ATRACE_BEGIN("create");
1012 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
1013 for (auto user : get_known_users(uuid_)) {
1014 FTS *fts;
1015 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001016 auto ce_path = create_data_user_ce_path(uuid_, user);
1017 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001018 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
1019 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
1020 (char*) media_path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001021 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001022 return error("Failed to fts_open");
1023 }
1024 while ((p = fts_read(fts)) != NULL) {
1025 if (p->fts_info == FTS_D && p->fts_level == 1) {
1026 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001027 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
1028 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
1029 + AID_APP_START;
1030 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001031 auto search = trackers.find(uid);
1032 if (search != trackers.end()) {
1033 search->second->addDataPath(p->fts_path);
1034 } else {
1035 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
1036 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
1037 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001038 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001039 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001040 tracker->cacheQuota = mCacheQuotas[uid];
1041 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001042 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001043#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001044 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001045#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001046 tracker->cacheQuota = 67108864;
1047 }
1048 trackers[uid] = tracker;
1049 }
1050 fts_set(fts, p, FTS_SKIP);
1051 }
1052 }
1053 fts_close(fts);
1054 }
1055 ATRACE_END();
1056
1057 // 2. Populate tracker stats and insert into priority queue
1058 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001059 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001060 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1061 return (left->getCacheRatio() < right->getCacheRatio());
1062 };
1063 std::priority_queue<std::shared_ptr<CacheTracker>,
1064 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1065 for (const auto& it : trackers) {
1066 it.second->loadStats();
1067 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001068 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001069 }
1070 ATRACE_END();
1071
1072 // 3. Bounce across the queue, freeing items from whichever tracker is
1073 // the most over their assigned quota
1074 ATRACE_BEGIN("bounce");
1075 std::shared_ptr<CacheTracker> active;
1076 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001077 // Only look at apps under quota when explicitly requested
1078 if (active && (active->getCacheRatio() < 10000)
1079 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1080 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1081 << " isn't over quota, and defy not requested";
1082 break;
1083 }
1084
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001085 // Only keep clearing when we haven't pushed into reserved area
1086 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1087 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1088 break;
1089 }
1090
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001091 // Find the best tracker to work with; this might involve swapping
1092 // if the active tracker is no longer the most over quota
1093 bool nextBetter = active && !queue.empty()
1094 && active->getCacheRatio() < queue.top()->getCacheRatio();
1095 if (!active || nextBetter) {
1096 if (active) {
1097 // Current tracker still has items, so we'll consider it
1098 // again later once it bubbles up to surface
1099 queue.push(active);
1100 }
1101 active = queue.top(); queue.pop();
1102 active->ensureItems();
1103 continue;
1104 }
1105
1106 // If no items remain, go find another tracker
1107 if (active->items.empty()) {
1108 active = nullptr;
1109 continue;
1110 } else {
1111 auto item = active->items.back();
1112 active->items.pop_back();
1113
1114 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1115 if (!noop) {
1116 item->purge();
1117 }
1118 active->cacheUsed -= item->size;
1119 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001120 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001121 }
1122
1123 // Verify that we're actually done before bailing, since sneaky
1124 // apps might be using hardlinks
1125 if (needed <= 0) {
1126 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001127 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001128 if (needed <= 0) {
1129 break;
1130 } else {
1131 LOG(WARNING) << "Expected to be done but still need " << needed;
1132 }
1133 }
1134 }
1135 ATRACE_END();
1136
1137 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001138 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001139 }
1140
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001141 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001142 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001143 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001144 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001145 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001146 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001147 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001148}
1149
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001150binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1151 const std::string& instructionSet) {
1152 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001153 std::lock_guard<std::recursive_mutex> lock(mLock);
1154
Mike Lockwood94afecf2012-10-24 10:45:23 -07001155 char dex_path[PKG_PATH_MAX];
1156
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001157 const char* path = codePath.c_str();
1158 const char* instruction_set = instructionSet.c_str();
1159
Jeff Sharkey770180a2014-09-08 17:14:26 -07001160 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001161 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001162 }
1163
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001164 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001165 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001166 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001167
1168 ALOGV("unlink %s\n", dex_path);
1169 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001170 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1171 // but could not be unlinked.
1172 if (errno != ENOENT) {
1173 return error(StringPrintf("Failed to unlink %s", dex_path));
1174 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001175 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001176 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001177}
1178
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001179struct stats {
1180 int64_t codeSize;
1181 int64_t dataSize;
1182 int64_t cacheSize;
1183};
1184
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001185#if MEASURE_DEBUG
1186static std::string toString(std::vector<int64_t> values) {
1187 std::stringstream res;
1188 res << "[";
1189 for (size_t i = 0; i < values.size(); i++) {
1190 res << values[i];
1191 if (i < values.size() - 1) {
1192 res << ",";
1193 }
1194 }
1195 res << "]";
1196 return res.str();
1197}
1198#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001199
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001200static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001201 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001202 if (device.empty()) return;
1203
1204 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001205
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001206 if (stats != nullptr) {
1207 uid_t uid = multiuser_get_uid(userId, appId);
1208 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001209 reinterpret_cast<char*>(&dq)) != 0) {
1210 if (errno != ESRCH) {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001211 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001212 }
1213 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001214#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001215 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001216#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001217 stats->dataSize += dq.dqb_curspace;
1218 }
1219
1220 int cacheGid = multiuser_get_cache_gid(userId, appId);
1221 if (cacheGid != -1) {
1222 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1223 reinterpret_cast<char*>(&dq)) != 0) {
1224 if (errno != ESRCH) {
1225 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1226 }
1227 } else {
1228#if MEASURE_DEBUG
1229 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1230#endif
1231 stats->cacheSize += dq.dqb_curspace;
1232 }
1233 }
1234
1235 int sharedGid = multiuser_get_shared_gid(0, appId);
1236 if (sharedGid != -1) {
1237 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1238 reinterpret_cast<char*>(&dq)) != 0) {
1239 if (errno != ESRCH) {
1240 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1241 }
1242 } else {
1243#if MEASURE_DEBUG
1244 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1245#endif
1246 stats->codeSize += dq.dqb_curspace;
1247 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001248 }
1249 }
1250
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001251 if (extStats != nullptr) {
1252 int extGid = multiuser_get_ext_gid(userId, appId);
1253 if (extGid != -1) {
1254 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1255 reinterpret_cast<char*>(&dq)) != 0) {
1256 if (errno != ESRCH) {
1257 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1258 }
1259 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001260#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001261 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001262#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001263 extStats->dataSize += dq.dqb_curspace;
1264 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001265 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001266
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001267 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1268 if (extCacheGid != -1) {
1269 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extCacheGid,
1270 reinterpret_cast<char*>(&dq)) != 0) {
1271 if (errno != ESRCH) {
1272 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extCacheGid;
1273 }
1274 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001275#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001276 LOG(DEBUG) << "quotactl() for GID " << extCacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001277#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001278 extStats->dataSize += dq.dqb_curspace;
1279 extStats->cacheSize += dq.dqb_curspace;
1280 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001281 }
1282 }
1283}
1284
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001285static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001286 DIR *d;
1287 int dfd;
1288 struct dirent *de;
1289 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001290
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001291 d = opendir(path.c_str());
1292 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001293 if (errno != ENOENT) {
1294 PLOG(WARNING) << "Failed to open " << path;
1295 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001296 return;
1297 }
1298 dfd = dirfd(d);
1299 while ((de = readdir(d))) {
1300 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001301
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001302 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001303 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001304 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001305 }
1306
1307 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001308 if (!strcmp(name, ".")) {
1309 // Don't recurse, but still count node size
1310 } else if (!strcmp(name, "..")) {
1311 // Don't recurse or count node size
1312 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001313 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001314 // Measure all children nodes
1315 size = 0;
1316 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001317 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001318
1319 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1320 stats->cacheSize += size;
1321 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001322 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001323
1324 // Legacy symlink isn't owned by app
1325 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1326 continue;
1327 }
1328
1329 // Everything found inside is considered data
1330 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001331 }
1332 closedir(d);
1333}
1334
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001335static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1336 bool exclude_apps = false) {
1337 DIR *d;
1338 int dfd;
1339 struct dirent *de;
1340 struct stat s;
1341
1342 d = opendir(path.c_str());
1343 if (d == nullptr) {
1344 if (errno != ENOENT) {
1345 PLOG(WARNING) << "Failed to open " << path;
1346 }
1347 return;
1348 }
1349 dfd = dirfd(d);
1350 while ((de = readdir(d))) {
1351 if (de->d_type == DT_DIR) {
1352 const char *name = de->d_name;
1353 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1354 continue;
1355 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001356 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001357 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1358 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001359 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001360 continue;
1361 } else {
1362 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1363 }
1364 }
1365 }
1366 closedir(d);
1367}
1368
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001369static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1370 FTS *fts;
1371 FTSENT *p;
1372 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001373 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001374 PLOG(ERROR) << "Failed to fts_open " << path;
1375 return;
1376 }
1377 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001378 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001379 switch (p->fts_info) {
1380 case FTS_D:
1381 if (p->fts_level == 4
1382 && !strcmp(p->fts_name, "cache")
1383 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1384 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1385 p->fts_number = 1;
1386 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001387 // Fall through to count the directory
1388 case FTS_DEFAULT:
1389 case FTS_F:
1390 case FTS_SL:
1391 case FTS_SLNONE:
1392 int64_t size = (p->fts_statp->st_blocks * 512);
1393 if (p->fts_number == 1) {
1394 stats->cacheSize += size;
1395 }
1396 stats->dataSize += size;
1397 break;
1398 }
1399 }
1400 fts_close(fts);
1401}
1402
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001403binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001404 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1405 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1406 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001407 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001408 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001409 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001410 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1411 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001412 // NOTE: Locking is relaxed on this method, since it's limited to
1413 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001414
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001415 // When modifying this logic, always verify using tests:
1416 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1417
1418#if MEASURE_DEBUG
1419 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1420#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001421
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001422 // Here's a summary of the common storage locations across the platform,
1423 // and how they're each tagged:
1424 //
1425 // /data/app/com.example UID system
1426 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001427 // /data/user/0/com.example UID u0_a10 GID u0_a10
1428 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1429 // /data/media/0/foo.txt UID u0_media_rw
1430 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1431 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1432 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1433 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001434
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001435 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001436 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001437 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001438 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001439
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001440 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001441
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001442 auto device = findQuotaDeviceForUuid(uuid);
1443 if (device.empty()) {
1444 flags &= ~FLAG_USE_QUOTA;
1445 }
1446
Jeff Sharkey466459b2017-01-17 15:25:01 -07001447 ATRACE_BEGIN("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001448 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001449 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1450 calculate_tree_size(obbCodePath, &extStats.codeSize);
1451 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001452 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001453
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001454 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001455 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001456 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001457 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001458 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001459 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001460 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001461
Jeff Sharkey466459b2017-01-17 15:25:01 -07001462 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001463 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001464 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001465 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001466 ATRACE_BEGIN("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07001467 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001468 calculate_tree_size(codePath, &stats.codeSize);
1469 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001470 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001471
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001472 for (size_t i = 0; i < packageNames.size(); i++) {
1473 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001474
Jeff Sharkey466459b2017-01-17 15:25:01 -07001475 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001476 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1477 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001478 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1479 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001480 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001481
Jeff Sharkey06a61842017-04-15 12:03:31 -06001482 if (!uuid) {
1483 ATRACE_BEGIN("profiles");
1484 calculate_tree_size(
1485 create_primary_current_profile_package_dir_path(userId, pkgname),
1486 &stats.dataSize);
1487 calculate_tree_size(
1488 create_primary_reference_profile_package_dir_path(pkgname),
1489 &stats.codeSize);
1490 ATRACE_END();
1491 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001492
Jeff Sharkey466459b2017-01-17 15:25:01 -07001493 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001494 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001495 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001496 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001497 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001498 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001499 }
1500
Jeff Sharkey06a61842017-04-15 12:03:31 -06001501 if (!uuid) {
1502 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001503 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001504 if (sharedGid != -1) {
1505 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1506 sharedGid, -1);
1507 }
1508 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001509 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001510 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001511
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001512 std::vector<int64_t> ret;
1513 ret.push_back(stats.codeSize);
1514 ret.push_back(stats.dataSize);
1515 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001516 ret.push_back(extStats.codeSize);
1517 ret.push_back(extStats.dataSize);
1518 ret.push_back(extStats.cacheSize);
1519#if MEASURE_DEBUG
1520 LOG(DEBUG) << "Final result " << toString(ret);
1521#endif
1522 *_aidl_return = ret;
1523 return ok();
1524}
1525
1526binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1527 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1528 std::vector<int64_t>* _aidl_return) {
1529 ENFORCE_UID(AID_SYSTEM);
1530 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001531 // NOTE: Locking is relaxed on this method, since it's limited to
1532 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001533
1534 // When modifying this logic, always verify using tests:
1535 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1536
1537#if MEASURE_DEBUG
1538 LOG(INFO) << "Measuring user " << userId;
1539#endif
1540
1541 struct stats stats;
1542 struct stats extStats;
1543 memset(&stats, 0, sizeof(stats));
1544 memset(&extStats, 0, sizeof(extStats));
1545
1546 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1547
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001548 auto device = findQuotaDeviceForUuid(uuid);
1549 if (device.empty()) {
1550 flags &= ~FLAG_USE_QUOTA;
1551 }
1552
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001553 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001554 struct dqblk dq;
1555
1556 ATRACE_BEGIN("obb");
1557 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1558 reinterpret_cast<char*>(&dq)) != 0) {
1559 if (errno != ESRCH) {
1560 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1561 }
1562 } else {
1563#if MEASURE_DEBUG
1564 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1565#endif
1566 extStats.codeSize += dq.dqb_curspace;
1567 }
1568 ATRACE_END();
1569
Jeff Sharkey466459b2017-01-17 15:25:01 -07001570 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001571 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001572 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001573
Jeff Sharkey466459b2017-01-17 15:25:01 -07001574 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001575 auto cePath = create_data_user_ce_path(uuid_, userId);
1576 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001577 auto dePath = create_data_user_de_path(uuid_, userId);
1578 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001579 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001580
Jeff Sharkey06a61842017-04-15 12:03:31 -06001581 if (!uuid) {
1582 ATRACE_BEGIN("profile");
1583 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1584 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1585 auto refProfilePath = create_primary_ref_profile_dir_path();
1586 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1587 ATRACE_END();
1588 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001589
Jeff Sharkey466459b2017-01-17 15:25:01 -07001590 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001591 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1592 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1593 reinterpret_cast<char*>(&dq)) != 0) {
1594 if (errno != ESRCH) {
1595 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1596 }
1597 } else {
1598#if MEASURE_DEBUG
1599 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001600#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001601 extStats.dataSize += dq.dqb_curspace;
1602 }
1603 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001604
Jeff Sharkey06a61842017-04-15 12:03:31 -06001605 if (!uuid) {
1606 ATRACE_BEGIN("dalvik");
1607 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1608 -1, -1, true);
1609 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1610 -1, -1, true);
1611 ATRACE_END();
1612 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001613
Jeff Sharkey466459b2017-01-17 15:25:01 -07001614 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001615 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001616 for (auto appId : appIds) {
1617 if (appId >= AID_APP_START) {
1618 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001619
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001620#if MEASURE_DEBUG
1621 // Sleep to make sure we don't lose logs
1622 usleep(1);
1623#endif
1624 }
1625 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001626 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001627 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001628 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001629 ATRACE_BEGIN("obb");
1630 auto obbPath = create_data_path(uuid_) + "/media/obb";
1631 calculate_tree_size(obbPath, &extStats.codeSize);
1632 ATRACE_END();
1633
Jeff Sharkey466459b2017-01-17 15:25:01 -07001634 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001635 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001636 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001637
Jeff Sharkey466459b2017-01-17 15:25:01 -07001638 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001639 auto cePath = create_data_user_ce_path(uuid_, userId);
1640 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001641 auto dePath = create_data_user_de_path(uuid_, userId);
1642 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001643 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001644
Jeff Sharkey06a61842017-04-15 12:03:31 -06001645 if (!uuid) {
1646 ATRACE_BEGIN("profile");
1647 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1648 calculate_tree_size(userProfilePath, &stats.dataSize);
1649 auto refProfilePath = create_primary_ref_profile_dir_path();
1650 calculate_tree_size(refProfilePath, &stats.codeSize);
1651 ATRACE_END();
1652 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001653
Jeff Sharkey466459b2017-01-17 15:25:01 -07001654 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001655 auto dataMediaPath = create_data_media_path(uuid_, userId);
1656 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1657#if MEASURE_DEBUG
1658 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1659 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001660#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001661 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001662
Jeff Sharkey06a61842017-04-15 12:03:31 -06001663 if (!uuid) {
1664 ATRACE_BEGIN("dalvik");
1665 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1666 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1667 ATRACE_END();
1668 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001669 }
1670
1671 std::vector<int64_t> ret;
1672 ret.push_back(stats.codeSize);
1673 ret.push_back(stats.dataSize);
1674 ret.push_back(stats.cacheSize);
1675 ret.push_back(extStats.codeSize);
1676 ret.push_back(extStats.dataSize);
1677 ret.push_back(extStats.cacheSize);
1678#if MEASURE_DEBUG
1679 LOG(DEBUG) << "Final result " << toString(ret);
1680#endif
1681 *_aidl_return = ret;
1682 return ok();
1683}
1684
1685binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001686 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1687 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001688 ENFORCE_UID(AID_SYSTEM);
1689 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001690 // NOTE: Locking is relaxed on this method, since it's limited to
1691 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001692
1693 // When modifying this logic, always verify using tests:
1694 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1695
1696#if MEASURE_DEBUG
1697 LOG(INFO) << "Measuring external " << userId;
1698#endif
1699
1700 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1701
1702 int64_t totalSize = 0;
1703 int64_t audioSize = 0;
1704 int64_t videoSize = 0;
1705 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001706 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06001707 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001708
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001709 auto device = findQuotaDeviceForUuid(uuid);
1710 if (device.empty()) {
1711 flags &= ~FLAG_USE_QUOTA;
1712 }
1713
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001714 if (flags & FLAG_USE_QUOTA) {
1715 struct dqblk dq;
1716
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001717 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001718 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1719 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1720 reinterpret_cast<char*>(&dq)) != 0) {
1721 if (errno != ESRCH) {
1722 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1723 }
1724 } else {
1725#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001726 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001727#endif
1728 totalSize = dq.dqb_curspace;
1729 }
1730
1731 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1732 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1733 reinterpret_cast<char*>(&dq)) == 0) {
1734#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001735 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001736#endif
1737 audioSize = dq.dqb_curspace;
1738 }
1739 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1740 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1741 reinterpret_cast<char*>(&dq)) == 0) {
1742#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001743 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001744#endif
1745 videoSize = dq.dqb_curspace;
1746 }
1747 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1748 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1749 reinterpret_cast<char*>(&dq)) == 0) {
1750#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001751 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001752#endif
1753 imageSize = dq.dqb_curspace;
1754 }
Jeff Sharkeya0136982017-07-06 11:29:37 -06001755 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1756 reinterpret_cast<char*>(&dq)) == 0) {
1757#if MEASURE_DEBUG
1758 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1759#endif
1760 obbSize = dq.dqb_curspace;
1761 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001762 ATRACE_END();
1763
1764 ATRACE_BEGIN("apps");
1765 struct stats extStats;
1766 memset(&extStats, 0, sizeof(extStats));
1767 for (auto appId : appIds) {
1768 if (appId >= AID_APP_START) {
1769 collectQuotaStats(device, userId, appId, nullptr, &extStats);
1770 }
1771 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001772 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001773 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001774 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001775 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001776 FTS *fts;
1777 FTSENT *p;
1778 auto path = create_data_media_path(uuid_, userId);
1779 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001780 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001781 return error("Failed to fts_open " + path);
1782 }
1783 while ((p = fts_read(fts)) != NULL) {
1784 char* ext;
1785 int64_t size = (p->fts_statp->st_blocks * 512);
1786 switch (p->fts_info) {
1787 case FTS_F:
1788 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001789 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001790 ext = strrchr(p->fts_name, '.');
1791 if (ext != nullptr) {
1792 switch (MatchExtension(++ext)) {
1793 case AID_MEDIA_AUDIO: audioSize += size; break;
1794 case AID_MEDIA_VIDEO: videoSize += size; break;
1795 case AID_MEDIA_IMAGE: imageSize += size; break;
1796 }
1797 }
1798 }
1799 // Fall through to always count against total
1800 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001801 // Ignore data belonging to specific apps
1802 p->fts_number = p->fts_parent->fts_number;
1803 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1804 p->fts_number = 1;
1805 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001806 case FTS_DEFAULT:
1807 case FTS_SL:
1808 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001809 if (p->fts_parent->fts_number == 1) {
1810 appSize += size;
1811 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001812 totalSize += size;
1813 break;
1814 }
1815 }
1816 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001817 ATRACE_END();
Jeff Sharkeya0136982017-07-06 11:29:37 -06001818
1819 ATRACE_BEGIN("obb");
1820 auto obbPath = create_data_media_obb_path(uuid_, "");
1821 calculate_tree_size(obbPath, &obbSize);
1822 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001823 }
1824
1825 std::vector<int64_t> ret;
1826 ret.push_back(totalSize);
1827 ret.push_back(audioSize);
1828 ret.push_back(videoSize);
1829 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001830 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06001831 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001832#if MEASURE_DEBUG
1833 LOG(DEBUG) << "Final result " << toString(ret);
1834#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001835 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001836 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001837}
1838
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001839binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1840 int32_t userId, int32_t appId, int64_t cacheQuota) {
1841 ENFORCE_UID(AID_SYSTEM);
1842 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001843 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001844
1845 int32_t uid = multiuser_get_uid(userId, appId);
1846 mCacheQuotas[uid] = cacheQuota;
1847
1848 return ok();
1849}
1850
David Sehr6727c2d2016-05-17 16:06:22 -07001851// Dumps the contents of a profile file, using pkgname's dex files for pretty
1852// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001853binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1854 const std::string& codePaths, bool* _aidl_return) {
1855 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001856 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001857 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001858
1859 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001860 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001861
Jeff Sharkey90aff262016-12-12 14:28:24 -07001862 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001863 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001864}
1865
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001866// Copy the contents of a system profile over the data profile.
1867binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
1868 int32_t packageUid, const std::string& packageName, bool* _aidl_return) {
1869 ENFORCE_UID(AID_SYSTEM);
1870 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1871 std::lock_guard<std::recursive_mutex> lock(mLock);
1872 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName);
1873 return ok();
1874}
1875
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001876// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001877binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001878 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001879 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001880 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001881 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001882
Calin Juravle114f0812017-03-08 19:05:07 -08001883 *_aidl_return = analyze_primary_profiles(uid, packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001884 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001885}
1886
Calin Juravlec41dac22017-12-05 12:29:15 -08001887binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
1888 const std::string& packageName, const std::string& codePath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08001889 ENFORCE_UID(AID_SYSTEM);
1890 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1891 std::lock_guard<std::recursive_mutex> lock(mLock);
1892
Calin Juravlec41dac22017-12-05 12:29:15 -08001893 *_aidl_return = create_profile_snapshot(appId, packageName, codePath);
Calin Juravle29591732017-11-20 17:46:19 -08001894 return ok();
1895}
1896
1897binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
1898 const std::string& codePath) {
1899 ENFORCE_UID(AID_SYSTEM);
1900 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1901 std::lock_guard<std::recursive_mutex> lock(mLock);
1902
1903 std::string snapshot = create_snapshot_profile_path(packageName, codePath);
1904 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
1905 return error("Failed to destroy profile snapshot for " + packageName + ":" + codePath);
1906 }
1907 return ok();
1908}
1909
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001910binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1911 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1912 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1913 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle1d667612017-07-13 22:50:21 -07001914 const std::unique_ptr<std::string>& classLoaderContext,
David Brazdil570d3982018-01-16 20:15:43 +00001915 const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001916 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001917 CHECK_ARGUMENT_UUID(uuid);
1918 if (packageName && *packageName != "*") {
1919 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1920 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001921 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001922
1923 const char* apk_path = apkPath.c_str();
1924 const char* pkgname = packageName ? packageName->c_str() : "*";
1925 const char* instruction_set = instructionSet.c_str();
1926 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1927 const char* compiler_filter = compilerFilter.c_str();
1928 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
Calin Juravle1d667612017-07-13 22:50:21 -07001929 const char* class_loader_context = classLoaderContext ? classLoaderContext->c_str() : nullptr;
Calin Juravlecb556e32017-04-04 20:22:50 -07001930 const char* se_info = seInfo ? seInfo->c_str() : nullptr;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001931 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07001932 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
David Brazdil570d3982018-01-16 20:15:43 +00001933 downgrade, targetSdkVersion);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001934 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001935}
1936
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001937binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1938 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001939 std::lock_guard<std::recursive_mutex> lock(mLock);
1940
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001941 const char* instruction_set = instructionSet.c_str();
1942
1943 char boot_marker_path[PKG_PATH_MAX];
1944 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001945 "%s/%s/%s/.booting",
Jeff Sharkey1b9d9a62017-09-21 14:51:09 -06001946 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08001947 DALVIK_CACHE,
1948 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001949
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001950 ALOGV("mark_boot_complete : %s", boot_marker_path);
1951 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001952 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001953 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001954 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001955}
1956
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001957binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1958 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1959 const std::string& nativeLibPath32, int32_t userId) {
1960 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001961 CHECK_ARGUMENT_UUID(uuid);
1962 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001963 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001964
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001965 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1966 const char* pkgname = packageName.c_str();
1967 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001968 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001969 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001970
Jeff Sharkey423e7462016-12-09 18:18:43 -07001971 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1972 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001973
1974 const char* pkgdir = _pkgdir.c_str();
1975 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001976
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001977 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001978 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001979 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001980
1981 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001982 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001983 }
1984
1985 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001986 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001987 goto out;
1988 }
1989
1990 if (lstat(libsymlink, &libStat) < 0) {
1991 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001992 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001993 goto out;
1994 }
1995 } else {
1996 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001997 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001998 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001999 goto out;
2000 }
2001 } else if (S_ISLNK(libStat.st_mode)) {
2002 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002003 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002004 goto out;
2005 }
2006 }
2007 }
2008
2009 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002010 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002011 goto out;
2012 }
2013
2014out:
2015 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002016 auto msg = "Failed to cleanup chmod " + _pkgdir;
2017 if (res.isOk()) {
2018 res = error(msg);
2019 } else {
2020 PLOG(ERROR) << msg;
2021 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002022 }
2023
2024 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002025 auto msg = "Failed to cleanup chown " + _pkgdir;
2026 if (res.isOk()) {
2027 res = error(msg);
2028 } else {
2029 PLOG(ERROR) << msg;
2030 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002031 }
2032
Jeff Sharkey423e7462016-12-09 18:18:43 -07002033 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002034}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002035
2036static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2037{
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002038 execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
2039 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
2040 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2041}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002042
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002043static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2044{
2045 execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
2046 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
2047 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2048}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002049
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002050static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
2051 const char* idmap_path, int32_t uid) {
2052 int idmap_fd = open(idmap_path, O_RDWR);
2053 if (idmap_fd < 0) {
2054 PLOG(ERROR) << "idmap open failed: " << idmap_path;
2055 unlink(idmap_path);
2056 return true;
2057 }
2058
2059 pid_t pid;
2060 pid = fork();
2061 if (pid == 0) {
2062 /* child -- drop privileges before continuing */
2063 if (setgid(uid) != 0) {
2064 LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
2065 exit(1);
2066 }
2067 if (setuid(uid) != 0) {
2068 LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
2069 exit(1);
2070 }
2071 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2072 PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
2073 exit(1);
2074 }
2075
2076 run_verify_idmap(target_apk, overlay_apk, idmap_fd);
2077 exit(1); /* only if exec call to deleting stale idmap failed */
2078 } else {
2079 int status = wait_child(pid);
2080 close(idmap_fd);
2081
2082 if (status != 0) {
2083 // Failed on verifying if idmap is made from target_apk and overlay_apk.
2084 LOG(DEBUG) << "delete stale idmap: " << idmap_path;
2085 unlink(idmap_path);
2086 return true;
2087 }
2088 }
2089 return false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002090}
2091
2092// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2093// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2094static int flatten_path(const char *prefix, const char *suffix,
2095 const char *overlay_path, char *idmap_path, size_t N)
2096{
2097 if (overlay_path == NULL || idmap_path == NULL) {
2098 return -1;
2099 }
2100 const size_t len_overlay_path = strlen(overlay_path);
2101 // will access overlay_path + 1 further below; requires absolute path
2102 if (len_overlay_path < 2 || *overlay_path != '/') {
2103 return -1;
2104 }
2105 const size_t len_idmap_root = strlen(prefix);
2106 const size_t len_suffix = strlen(suffix);
2107 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2108 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2109 // additions below would cause overflow
2110 return -1;
2111 }
2112 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2113 return -1;
2114 }
2115 memset(idmap_path, 0, N);
2116 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2117 char *ch = idmap_path + len_idmap_root;
2118 while (*ch != '\0') {
2119 if (*ch == '/') {
2120 *ch = '@';
2121 }
2122 ++ch;
2123 }
2124 return 0;
2125}
2126
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002127binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2128 const std::string& overlayApkPath, int32_t uid) {
2129 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002130 std::lock_guard<std::recursive_mutex> lock(mLock);
2131
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002132 const char* target_apk = targetApkPath.c_str();
2133 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002134 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2135
2136 int idmap_fd = -1;
2137 char idmap_path[PATH_MAX];
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002138 struct stat idmap_stat;
2139 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002140
2141 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2142 idmap_path, sizeof(idmap_path)) == -1) {
2143 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2144 goto fail;
2145 }
2146
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002147 if (stat(idmap_path, &idmap_stat) < 0) {
2148 outdated = true;
2149 } else {
2150 outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2151 }
2152
2153 if (outdated) {
2154 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2155 } else {
2156 idmap_fd = open(idmap_path, O_RDWR);
2157 }
2158
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002159 if (idmap_fd < 0) {
2160 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2161 goto fail;
2162 }
2163 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2164 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2165 goto fail;
2166 }
2167 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2168 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2169 goto fail;
2170 }
2171
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002172 if (!outdated) {
2173 close(idmap_fd);
2174 return ok();
2175 }
2176
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002177 pid_t pid;
2178 pid = fork();
2179 if (pid == 0) {
2180 /* child -- drop privileges before continuing */
2181 if (setgid(uid) != 0) {
2182 ALOGE("setgid(%d) failed during idmap\n", uid);
2183 exit(1);
2184 }
2185 if (setuid(uid) != 0) {
2186 ALOGE("setuid(%d) failed during idmap\n", uid);
2187 exit(1);
2188 }
2189 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2190 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2191 exit(1);
2192 }
2193
2194 run_idmap(target_apk, overlay_apk, idmap_fd);
2195 exit(1); /* only if exec call to idmap failed */
2196 } else {
2197 int status = wait_child(pid);
2198 if (status != 0) {
2199 ALOGE("idmap failed, status=0x%04x\n", status);
2200 goto fail;
2201 }
2202 }
2203
2204 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002205 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002206fail:
2207 if (idmap_fd >= 0) {
2208 close(idmap_fd);
2209 unlink(idmap_path);
2210 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002211 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002212}
Robert Craige9887e42014-02-20 10:25:56 -05002213
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002214binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
2215 const char* overlay_apk = overlayApkPath.c_str();
2216 char idmap_path[PATH_MAX];
2217
2218 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2219 idmap_path, sizeof(idmap_path)) == -1) {
2220 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2221 return error();
2222 }
2223 if (unlink(idmap_path) < 0) {
2224 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2225 return error();
2226 }
2227 return ok();
2228}
2229
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002230binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2231 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2232 const std::string& seInfo) {
2233 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002234 CHECK_ARGUMENT_UUID(uuid);
2235 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002236 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002237
2238 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002239
Robert Craigda30dc72014-03-27 10:21:12 -04002240 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002241 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002242 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2243 const char* pkgName = packageName.c_str();
2244 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002245
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002246 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002247 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002248 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002249 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002250 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002251 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002252 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002253 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002254 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002255 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002256 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002257 }
Robert Craige9887e42014-02-20 10:25:56 -05002258 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002259 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002260}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002261
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002262binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2263 const std::string& instructionSet) {
2264 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002265 std::lock_guard<std::recursive_mutex> lock(mLock);
2266
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002267 const char* oat_dir = oatDir.c_str();
2268 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002269 char oat_instr_dir[PKG_PATH_MAX];
2270
2271 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002272 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002273 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002274 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002275 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002276 }
2277 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002278 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002279 }
2280 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002281 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002282 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002283 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002284 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002285}
2286
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002287binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2288 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002289 std::lock_guard<std::recursive_mutex> lock(mLock);
2290
Jeff Sharkey423e7462016-12-09 18:18:43 -07002291 if (validate_apk_path(packageDir.c_str())) {
2292 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002293 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002294 if (delete_dir_contents_and_dir(packageDir) != 0) {
2295 return error("Failed to delete " + packageDir);
2296 }
2297 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002298}
2299
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002300binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2301 const std::string& fromBase, const std::string& toBase) {
2302 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002303 std::lock_guard<std::recursive_mutex> lock(mLock);
2304
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002305 const char* relative_path = relativePath.c_str();
2306 const char* from_base = fromBase.c_str();
2307 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002308 char from_path[PKG_PATH_MAX];
2309 char to_path[PKG_PATH_MAX];
2310 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2311 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2312
2313 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002314 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002315 }
2316
2317 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002318 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002319 }
2320
Jeff Sharkey423e7462016-12-09 18:18:43 -07002321 if (link(from_path, to_path) < 0) {
2322 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002323 }
2324
Jeff Sharkey423e7462016-12-09 18:18:43 -07002325 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002326}
2327
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002328binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2329 const std::string& instructionSet, const std::string& outputPath) {
2330 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002331 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002332
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002333 const char* apk_path = apkPath.c_str();
2334 const char* instruction_set = instructionSet.c_str();
2335 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002336
Jeff Sharkey90aff262016-12-12 14:28:24 -07002337 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002338 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002339}
2340
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002341binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002342 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002343 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002344 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002345
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002346 const char* apk_path = apkPath.c_str();
2347 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002348 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002349
Jeff Sharkey90aff262016-12-12 14:28:24 -07002350 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2351 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002352}
2353
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002354// This kernel feaeture is experimental.
2355// TODO: remove local definition once upstreamed
2356#ifndef FS_IOC_SET_FSVERITY
2357struct fsverity_set {
2358 __u64 offset;
2359 __u64 flags;
2360};
2361
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002362struct fsverity_root_hash {
2363 short root_hash_algorithm;
2364 short flags;
2365 __u8 reserved[4];
2366 __u8 root_hash[64];
2367};
2368
2369#define FS_IOC_MEASURE_FSVERITY _IOW('f', 2733, struct fsverity_root_hash)
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002370#define FS_IOC_SET_FSVERITY _IOW('f', 2734, struct fsverity_set)
2371
2372#define FSVERITY_FLAG_ENABLED 0x0001
2373#endif
2374
2375binder::Status InstalldNativeService::installApkVerity(const std::string& filePath,
2376 const ::android::base::unique_fd& verityInputAshmem) {
Victor Hsieh99de5162017-10-06 14:44:14 -07002377 ENFORCE_UID(AID_SYSTEM);
2378 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2379 return ok();
2380 }
Victor Hsieh3f16dd62018-01-13 13:43:11 -08002381#if DEBUG
2382 ASSERT_PAGE_SIZE_4K();
2383#endif
2384 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2385 // TODO: change ashmem to some temporary file to support huge apk.
2386 if (!ashmem_valid(verityInputAshmem.get())) {
2387 return error("FD is not an ashmem");
2388 }
2389
2390 // TODO(71871109): Validate filePath.
2391 // 1. Seek to the next page boundary beyond the end of the file.
2392 ::android::base::unique_fd wfd(open(filePath.c_str(), O_WRONLY | O_APPEND));
2393 if (wfd.get() < 0) {
2394 return error("Failed to open " + filePath + ": " + strerror(errno));
2395 }
2396 struct stat st;
2397 if (fstat(wfd.get(), &st) < 0) {
2398 return error("Failed to stat " + filePath + ": " + strerror(errno));
2399 }
2400 // fsverity starts from the block boundary.
2401 if (lseek(wfd.get(), (st.st_size + kVerityPageSize - 1) / kVerityPageSize, SEEK_SET) < 0) {
2402 return error("Failed to lseek " + filePath + ": " + strerror(errno));
2403 }
2404
2405 // 2. Write everything in the ashmem to the file.
2406 int size = ashmem_get_size_region(verityInputAshmem.get());
2407 if (size < 0) {
2408 return error("Failed to get ashmem size: " + std::to_string(size));
2409 }
2410 void* data = mmap(NULL, size, PROT_READ, MAP_SHARED, wfd.get(), 0);
2411 if (data == MAP_FAILED) {
2412 return error("Failed to mmap the ashmem: " + std::string(strerror(errno)));
2413 }
2414 int remaining = size;
2415 while (remaining > 0) {
2416 int ret = TEMP_FAILURE_RETRY(write(wfd.get(), data, remaining));
2417 if (ret < 0) {
2418 munmap(data, size);
2419 return error("Failed to write to " + filePath + " (" + std::to_string(remaining) +
2420 + "/" + std::to_string(size) + "): " + strerror(errno));
2421 }
2422 remaining -= ret;
2423 }
2424 munmap(data, size);
2425
2426 // 3. Enable fsverity. Once it's done, the file becomes immutable.
2427 struct fsverity_set config;
2428 config.offset = st.st_size;
2429 config.flags = FSVERITY_FLAG_ENABLED;
2430 if (ioctl(wfd.get(), FS_IOC_SET_FSVERITY, &config) < 0) {
2431 return error("Failed to enable fsverity on " + filePath + ": " + strerror(errno));
2432 }
2433 return ok();
Victor Hsieh99de5162017-10-06 14:44:14 -07002434}
2435
Victor Hsiehc6d738a2018-01-20 15:06:39 -08002436binder::Status InstalldNativeService::assertFsverityRootHashMatches(const std::string& filePath,
2437 const std::vector<uint8_t>& expectedHash) {
2438 ENFORCE_UID(AID_SYSTEM);
2439 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2440 return ok();
2441 }
2442 // TODO: also check fsverity support in the current file system if compiled with DEBUG.
2443 if (expectedHash.size() != kSha256Size) {
2444 return error("verity hash size should be " + std::to_string(kSha256Size) + " but is " +
2445 std::to_string(expectedHash.size()));
2446 }
2447
2448 // TODO(71871109): Validate filePath.
2449 ::android::base::unique_fd fd(open(filePath.c_str(), O_RDONLY));
2450 if (fd.get() < 0) {
2451 return error("Failed to open " + filePath + ": " + strerror(errno));
2452 }
2453
2454 struct fsverity_root_hash config;
2455 memset(&config, 0, sizeof(config));
2456 config.root_hash_algorithm = 0; // SHA256
2457 memcpy(config.root_hash, expectedHash.data(), std::min(sizeof(config.root_hash), kSha256Size));
2458 if (ioctl(fd.get(), FS_IOC_MEASURE_FSVERITY, &config) < 0) {
2459 // This includes an expected failure case with no FSVerity setup. It normally happens when
2460 // the apk does not contains the Merkle tree root hash.
2461 return error("Failed to measure fsverity on " + filePath + ": " + strerror(errno));
2462 }
2463 return ok(); // hashes match
2464}
2465
Calin Juravlebd968362017-01-25 01:17:17 -08002466binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2467 const std::string& dexPath, const std::string& packageName, int32_t uid,
2468 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2469 int32_t storage_flag, bool* _aidl_return) {
2470 ENFORCE_UID(AID_SYSTEM);
2471 CHECK_ARGUMENT_UUID(volumeUuid);
2472 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2473
2474 std::lock_guard<std::recursive_mutex> lock(mLock);
2475 bool result = android::installd::reconcile_secondary_dex_file(
2476 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2477 return result ? ok() : error();
2478}
2479
Alan Stokes753dc712017-10-16 10:56:00 +01002480binder::Status InstalldNativeService::hashSecondaryDexFile(
2481 const std::string& dexPath, const std::string& packageName, int32_t uid,
2482 const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
2483 std::vector<uint8_t>* _aidl_return) {
2484 ENFORCE_UID(AID_SYSTEM);
2485 CHECK_ARGUMENT_UUID(volumeUuid);
2486 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2487
2488 // mLock is not taken here since we will never modify the file system.
2489 // If a file is modified just as we are reading it this may result in an
2490 // anomalous hash, but that's ok.
2491 bool result = android::installd::hash_secondary_dex_file(
2492 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
2493 return result ? ok() : error();
2494}
2495
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002496binder::Status InstalldNativeService::invalidateMounts() {
2497 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002498 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002499
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002500 mStorageMounts.clear();
2501 mQuotaReverseMounts.clear();
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002502
2503 std::ifstream in("/proc/mounts");
2504 if (!in.is_open()) {
2505 return error("Failed to read mounts");
2506 }
2507
2508 std::string source;
2509 std::string target;
2510 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002511 while (!in.eof()) {
2512 std::getline(in, source, ' ');
2513 std::getline(in, target, ' ');
2514 std::getline(in, ignored);
2515
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002516#if !BYPASS_SDCARDFS
2517 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2518 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2519 mStorageMounts[source] = target;
2520 }
2521#endif
2522
2523#if !BYPASS_QUOTA
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002524 if (source.compare(0, 11, "/dev/block/") == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002525 struct dqblk dq;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002526 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2527 reinterpret_cast<char*>(&dq)) == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002528 LOG(DEBUG) << "Found quota mount " << source << " at " << target;
2529 mQuotaReverseMounts[target] = source;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002530
2531 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -07002532 // need to kick it again to enable DQUOT_LIMITS_ENABLED. We
2533 // only need hard limits enabled when we're not being protected
2534 // by reserved blocks.
2535 if (!android::base::GetBoolProperty(kPropHasReserved, false)) {
2536 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1,
2537 nullptr) != 0 && errno != EBUSY) {
2538 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2539 }
2540 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1,
2541 nullptr) != 0 && errno != EBUSY) {
2542 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2543 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002544 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002545 }
2546 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002547#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002548 }
2549 return ok();
2550}
2551
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002552std::string InstalldNativeService::findDataMediaPath(
2553 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2554 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2555 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2556 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2557 auto resolved = mStorageMounts[path];
2558 if (resolved.empty()) {
2559 LOG(WARNING) << "Failed to find storage mount for " << path;
2560 resolved = path;
2561 }
2562 return StringPrintf("%s/%u", resolved.c_str(), userid);
2563}
2564
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002565std::string InstalldNativeService::findQuotaDeviceForUuid(
2566 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002567 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002568 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002569 return mQuotaReverseMounts[path];
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002570}
2571
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002572binder::Status InstalldNativeService::isQuotaSupported(
2573 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2574 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2575 return ok();
2576}
2577
Andreas Gampe02d0de52015-11-11 20:43:16 -08002578} // namespace installd
2579} // namespace android