blob: 9ab54470ae8556a9e7ca112eed924513895f2362 [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
Andreas Gampe02d0de52015-11-11 20:43:16 -080021#include <errno.h>
22#include <inttypes.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070023#include <fstream>
24#include <fts.h>
Andreas Gampe0354bd02016-06-27 14:25:30 -070025#include <regex>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070027#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028#include <sys/capability.h>
29#include <sys/file.h>
30#include <sys/resource.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070031#include <sys/quota.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080032#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070033#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070034#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000035#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070036#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080037#include <unistd.h>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070038
Andreas Gampeafa58d12016-06-03 16:09:32 -070039#include <android-base/logging.h>
Victor Hsieh99de5162017-10-06 14:44:14 -070040#include <android-base/properties.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080041#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070042#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010043#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080044#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070045#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070046#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070047#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070048#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080049#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070050#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080051#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070052#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070053
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070054#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070055#include "globals.h"
56#include "installd_deps.h"
57#include "otapreopt_utils.h"
58#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070059
Jeff Sharkey88ddd942017-01-17 18:05:54 -070060#include "CacheTracker.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070061#include "MatchExtensionGen.h"
62
Andreas Gampe02d0de52015-11-11 20:43:16 -080063#ifndef LOG_TAG
64#define LOG_TAG "installd"
65#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070066
67using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070068using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070069
Andreas Gampe02d0de52015-11-11 20:43:16 -080070namespace android {
71namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070072
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070073static constexpr const char* kCpPath = "/system/bin/cp";
74static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070075
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070076static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000077
Andreas Gampe0354bd02016-06-27 14:25:30 -070078static constexpr const char* PKG_LIB_POSTFIX = "/lib";
79static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
80static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
81
Jaekyun Seok5cb903e2017-05-18 00:13:44 +090082static constexpr const char *kIdMapPath = "/system/bin/idmap";
Andreas Gampe0354bd02016-06-27 14:25:30 -070083static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
84static constexpr const char* IDMAP_SUFFIX = "@idmap";
85
Victor Hsieh99de5162017-10-06 14:44:14 -070086static constexpr const char* kPropApkVerityMode = "ro.apk_verity.mode";
87
Andreas Gampe0354bd02016-06-27 14:25:30 -070088// NOTE: keep in sync with Installer
89static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
90static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070091static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -070092static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
Jeff Sharkey871a8f22017-02-21 18:30:28 -070093static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
94static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
Jeff Sharkeye12d5962017-04-03 16:41:02 -060095static constexpr int FLAG_FORCE = 1 << 16;
Calin Juravle6a1648e2016-02-01 12:12:16 +000096
Jeff Sharkey0274c972016-12-06 09:32:04 -070097namespace {
98
99constexpr const char* kDump = "android.permission.DUMP";
100
Calin Juravle824a64d2018-01-18 20:23:17 -0800101// TODO(calin): We can stop hardcoding this here once the PM passes the profile
102// name for all profile related operations.
103constexpr const char* kPrimaryProfileName = "primary.prof";
104
Jeff Sharkey423e7462016-12-09 18:18:43 -0700105static binder::Status ok() {
106 return binder::Status::ok();
107}
108
109static binder::Status exception(uint32_t code, const std::string& msg) {
110 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
111}
112
113static binder::Status error() {
114 return binder::Status::fromServiceSpecificError(errno);
115}
116
117static binder::Status error(const std::string& msg) {
118 PLOG(ERROR) << msg;
119 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
120}
121
122static binder::Status error(uint32_t code, const std::string& msg) {
123 LOG(ERROR) << msg << " (" << code << ")";
124 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
125}
126
Jeff Sharkey0274c972016-12-06 09:32:04 -0700127binder::Status checkPermission(const char* permission) {
128 pid_t pid;
129 uid_t uid;
130
131 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
132 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700133 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700134 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700135 return exception(binder::Status::EX_SECURITY,
136 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700137 }
138}
139
140binder::Status checkUid(uid_t expectedUid) {
141 uid_t uid = IPCThreadState::self()->getCallingUid();
142 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700143 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700144 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700145 return exception(binder::Status::EX_SECURITY,
146 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
147 }
148}
149
150binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
151 if (!uuid || is_valid_filename(*uuid)) {
152 return ok();
153 } else {
154 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
155 StringPrintf("UUID %s is malformed", uuid->c_str()));
156 }
157}
158
159binder::Status checkArgumentPackageName(const std::string& packageName) {
160 if (is_valid_package_name(packageName.c_str())) {
161 return ok();
162 } else {
163 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
164 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700165 }
166}
167
168#define ENFORCE_UID(uid) { \
169 binder::Status status = checkUid((uid)); \
170 if (!status.isOk()) { \
171 return status; \
172 } \
173}
174
Jeff Sharkey423e7462016-12-09 18:18:43 -0700175#define CHECK_ARGUMENT_UUID(uuid) { \
176 binder::Status status = checkArgumentUuid((uuid)); \
177 if (!status.isOk()) { \
178 return status; \
179 } \
180}
181
182#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
183 binder::Status status = \
184 checkArgumentPackageName((packageName)); \
185 if (!status.isOk()) { \
186 return status; \
187 } \
188}
189
Jeff Sharkey0274c972016-12-06 09:32:04 -0700190} // namespace
191
192status_t InstalldNativeService::start() {
193 IPCThreadState::self()->disableBackgroundScheduling(true);
194 status_t ret = BinderService<InstalldNativeService>::publish();
195 if (ret != android::OK) {
196 return ret;
197 }
198 sp<ProcessState> ps(ProcessState::self());
199 ps->startThreadPool();
200 ps->giveThreadPoolName();
201 return android::OK;
202}
203
204status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700205 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700206 const binder::Status dump_permission = checkPermission(kDump);
207 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700208 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700209 return PERMISSION_DENIED;
210 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700211 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700212
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700213 out << "installd is happy!" << endl;
214
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700215 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600216 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
217 out << endl << "Storage mounts:" << endl;
218 for (const auto& n : mStorageMounts) {
219 out << " " << n.first << " = " << n.second << endl;
220 }
221
222 out << endl << "Quota reverse mounts:" << endl;
223 for (const auto& n : mQuotaReverseMounts) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700224 out << " " << n.first << " = " << n.second << endl;
225 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700226 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700227
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700228 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600229 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700230 out << endl << "Per-UID cache quotas:" << endl;
231 for (const auto& n : mCacheQuotas) {
232 out << " " << n.first << " = " << n.second << endl;
233 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700234 }
235
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700236 out << endl;
237 out.flush();
238
Jeff Sharkey0274c972016-12-06 09:32:04 -0700239 return NO_ERROR;
240}
241
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600242/**
243 * Perform restorecon of the given path, but only perform recursive restorecon
244 * if the label of that top-level file actually changed. This can save us
245 * significant time by avoiding no-op traversals of large filesystem trees.
246 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700247static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
248 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600249 int res = 0;
250 char* before = nullptr;
251 char* after = nullptr;
252
253 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
254 // libselinux. Not needed here.
255
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600256 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600257 PLOG(ERROR) << "Failed before getfilecon for " << path;
258 goto fail;
259 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700260 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600261 PLOG(ERROR) << "Failed top-level restorecon for " << path;
262 goto fail;
263 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600264 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600265 PLOG(ERROR) << "Failed after getfilecon for " << path;
266 goto fail;
267 }
268
269 // If the initial top-level restorecon above changed the label, then go
270 // back and restorecon everything recursively
271 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700272 if (existing) {
273 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
274 << path << "; running recursive restorecon";
275 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700276 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600277 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
278 PLOG(ERROR) << "Failed recursive restorecon for " << path;
279 goto fail;
280 }
281 }
282
283 goto done;
284fail:
285 res = -1;
286done:
287 free(before);
288 free(after);
289 return res;
290}
291
Jeff Sharkey0274c972016-12-06 09:32:04 -0700292static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700293 const std::string& seInfo, uid_t uid, bool existing) {
294 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
295 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600296}
297
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600298static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600299 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
300 PLOG(ERROR) << "Failed to prepare " << path;
301 return -1;
302 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600303 return 0;
304}
305
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600306/**
307 * Ensure that we have a hard-limit quota to protect against abusive apps;
308 * they should never use more than 90% of blocks or 50% of inodes.
309 */
310static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
311 uid_t uid) {
312 if (device.empty()) return 0;
313
314 struct dqblk dq;
315 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
316 reinterpret_cast<char*>(&dq)) != 0) {
317 PLOG(WARNING) << "Failed to find quota for " << uid;
318 return -1;
319 }
320
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600321#if APPLY_HARD_QUOTAS
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600322 if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
323 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
324 struct statvfs stat;
325 if (statvfs(path.c_str(), &stat) != 0) {
326 PLOG(WARNING) << "Failed to statvfs " << path;
327 return -1;
328 }
329
330 dq.dqb_valid = QIF_LIMITS;
Jerry Wonge761ac32017-07-28 15:54:58 -0700331 dq.dqb_bhardlimit =
332 (((static_cast<uint64_t>(stat.f_blocks) * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600333 dq.dqb_ihardlimit = (stat.f_files / 2);
334 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
335 reinterpret_cast<char*>(&dq)) != 0) {
336 PLOG(WARNING) << "Failed to set hard quota for " << uid;
337 return -1;
338 } else {
339 LOG(DEBUG) << "Applied hard quotas for " << uid;
340 return 0;
341 }
342 } else {
343 // Hard quota already set; assume it's reasonable
344 return 0;
345 }
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600346#else
347 // Hard quotas disabled
348 return 0;
349#endif
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600350}
351
Calin Juravled2affb82017-11-28 17:41:43 -0800352static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
353 if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
354 return true;
355 }
356
357 int32_t uid = multiuser_get_uid(userId, appId);
358 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
359 if (shared_app_gid == -1) {
360 // TODO(calin): this should no longer be possible but do not continue if we don't get
361 // a valid shared gid.
362 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
363 return true;
364 }
365
366 const std::string profile_dir =
367 create_primary_current_profile_package_dir_path(userId, packageName);
368 // read-write-execute only for the app user.
369 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
370 PLOG(ERROR) << "Failed to prepare " << profile_dir;
371 return false;
372 }
Calin Juravle824a64d2018-01-18 20:23:17 -0800373
Calin Juravled2affb82017-11-28 17:41:43 -0800374 const std::string profile_file = create_current_profile_path(userId, packageName,
Calin Juravle824a64d2018-01-18 20:23:17 -0800375 kPrimaryProfileName, /*is_secondary_dex*/false);
Calin Juravled2affb82017-11-28 17:41:43 -0800376 // read-write only for the app user.
377 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
378 PLOG(ERROR) << "Failed to prepare " << profile_file;
379 return false;
380 }
381
382 const std::string ref_profile_path =
383 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800384
385 // Prepare the reference profile directory. Note that we use the non strict version of
386 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
387 // This is particularly important given that in O there were some fixes for how the
388 // shared_app_gid is computed.
389 //
390 // Note that by the time we get here we know that we are using a correct uid (otherwise
391 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
392 // are sure that the gid being used belongs to the owning app and not someone else.
393 //
394 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
395 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800396 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
397 return false;
398 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800399
Calin Juravled2affb82017-11-28 17:41:43 -0800400 return true;
401}
402
Jeff Sharkey0274c972016-12-06 09:32:04 -0700403binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
404 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700405 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700406 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700407 CHECK_ARGUMENT_UUID(uuid);
408 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700409 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700410
411 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
412 const char* pkgname = packageName.c_str();
413
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700414 // Assume invalid inode unless filled in below
415 if (_aidl_return != nullptr) *_aidl_return = -1;
416
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700417 int32_t uid = multiuser_get_uid(userId, appId);
418 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700419 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
420
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700421 // If UID doesn't have a specific cache GID, use UID value
422 if (cacheGid == -1) {
423 cacheGid = uid;
424 }
425
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700426 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700427 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700428 bool existing = (access(path.c_str(), F_OK) == 0);
429
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700430 if (prepare_app_dir(path, targetMode, uid) ||
431 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
432 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700433 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600434 }
435
436 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700437 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
438 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
439 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700440 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700441 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600442
443 // Remember inode numbers of cache directories so that we can clear
444 // contents while CE storage is locked
445 if (write_path_inode(path, "cache", kXattrInodeCache) ||
446 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700447 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700448 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700449
450 // And return the CE inode of the top-level data directory so we can
451 // clear contents while CE storage is locked
452 if ((_aidl_return != nullptr)
453 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
454 return error("Failed to get_path_inode for " + path);
455 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700456 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700457 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700458 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700459 bool existing = (access(path.c_str(), F_OK) == 0);
460
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700461 if (prepare_app_dir(path, targetMode, uid) ||
462 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
463 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700464 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700465 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000466
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600467 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600468 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
469 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
470 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700471 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600472 }
473
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600474 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
475 return error("Failed to set hard quota " + path);
476 }
477
Calin Juravled2affb82017-11-28 17:41:43 -0800478 if (!prepare_app_profile_dir(packageName, appId, userId)) {
479 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000480 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700481 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700482 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700483}
484
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700485binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
486 const std::string& packageName, int32_t userId, int32_t flags) {
487 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700488 CHECK_ARGUMENT_UUID(uuid);
489 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700490 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700491
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700492 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
493 const char* pkgname = packageName.c_str();
494
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700495 // This method only exists to upgrade system apps that have requested
496 // forceDeviceEncrypted, so their default storage always lives in a
497 // consistent location. This only works on non-FBE devices, since we
498 // never want to risk exposing data on a device with real CE/DE storage.
499
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700500 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
501 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700502
503 // If neither directory is marked as default, assume CE is default
504 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
505 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
506 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700507 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700508 }
509 }
510
511 // Migrate default data location if needed
512 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
513 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
514
515 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
516 LOG(WARNING) << "Requested default storage " << target
517 << " is not active; migrating from " << source;
518 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700519 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700520 }
521 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700522 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700523 }
524 }
525
Jeff Sharkey423e7462016-12-09 18:18:43 -0700526 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700527}
528
Calin Juravle6a1648e2016-02-01 12:12:16 +0000529
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700530binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
531 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700532 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700533 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700534
Jeff Sharkey423e7462016-12-09 18:18:43 -0700535 binder::Status res = ok();
Calin Juravle824a64d2018-01-18 20:23:17 -0800536 if (!clear_primary_reference_profile(packageName, kPrimaryProfileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700537 res = error("Failed to clear reference profile for " + packageName);
538 }
Calin Juravle824a64d2018-01-18 20:23:17 -0800539 if (!clear_primary_current_profiles(packageName, kPrimaryProfileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700540 res = error("Failed to clear current profiles for " + packageName);
541 }
542 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000543}
544
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700545binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
546 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
547 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700548 CHECK_ARGUMENT_UUID(uuid);
549 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700550 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700551
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700552 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
553 const char* pkgname = packageName.c_str();
554
Jeff Sharkey423e7462016-12-09 18:18:43 -0700555 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700556 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700557 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600558 if (flags & FLAG_CLEAR_CACHE_ONLY) {
559 path = read_path_inode(path, "cache", kXattrInodeCache);
560 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
561 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
562 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700563 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700564 if (delete_dir_contents(path) != 0) {
565 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900566 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
567 remove_path_xattr(path, kXattrInodeCache);
568 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700569 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700570 }
571 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700572 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600573 std::string suffix = "";
574 bool only_cache = false;
575 if (flags & FLAG_CLEAR_CACHE_ONLY) {
576 suffix = CACHE_DIR_POSTFIX;
577 only_cache = true;
578 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
579 suffix = CODE_CACHE_DIR_POSTFIX;
580 only_cache = true;
581 }
582
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700583 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700584 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700585 if (delete_dir_contents(path) != 0) {
586 res = error("Failed to delete contents of " + path);
587 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700588 }
Calin Juravleedae6692016-03-23 13:55:31 +0000589 if (!only_cache) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800590 if (!clear_primary_current_profile(packageName, kPrimaryProfileName, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700591 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000592 }
593 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700594 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700595 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700596}
597
Calin Juravle76268c52017-03-09 13:19:42 -0800598static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100599 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800600 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100601 /*ignore_if_missing*/ true);
602}
603
Calin Juravle76268c52017-03-09 13:19:42 -0800604static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100605 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800606 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100607 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000608}
609
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700610binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
611 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700612 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700613 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700614
Jeff Sharkey423e7462016-12-09 18:18:43 -0700615 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000616 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
617 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800618 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700619 res = error("Failed to destroy current profiles for " + packageName);
620 }
Calin Juravleedae6692016-03-23 13:55:31 +0000621 }
Calin Juravle76268c52017-03-09 13:19:42 -0800622 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700623 res = error("Failed to destroy reference profile for " + packageName);
624 }
625 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000626}
627
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700628binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
629 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
630 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700631 CHECK_ARGUMENT_UUID(uuid);
632 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700633 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700634
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700635 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
636 const char* pkgname = packageName.c_str();
637
Jeff Sharkey423e7462016-12-09 18:18:43 -0700638 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700639 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700640 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
641 if (delete_dir_contents_and_dir(path) != 0) {
642 res = error("Failed to delete " + path);
643 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700644 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700645 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700646 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
647 if (delete_dir_contents_and_dir(path) != 0) {
648 res = error("Failed to delete " + path);
649 }
Calin Juravle76268c52017-03-09 13:19:42 -0800650 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100651 // TODO(calin): If the package is still installed by other users it's probably
652 // beneficial to keep the reference profile around.
653 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800654 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700655 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700656 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700657}
658
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600659static gid_t get_cache_gid(uid_t uid) {
660 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
661 return (gid != -1) ? gid : uid;
662}
663
664binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
665 int32_t flags) {
666 ENFORCE_UID(AID_SYSTEM);
667 CHECK_ARGUMENT_UUID(uuid);
668 std::lock_guard<std::recursive_mutex> lock(mLock);
669
670 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
671 for (auto user : get_known_users(uuid_)) {
672 ATRACE_BEGIN("fixup user");
673 FTS* fts;
674 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600675 auto ce_path = create_data_user_ce_path(uuid_, user);
676 auto de_path = create_data_user_de_path(uuid_, user);
677 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600678 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
679 return error("Failed to fts_open");
680 }
681 while ((p = fts_read(fts)) != nullptr) {
682 if (p->fts_info == FTS_D && p->fts_level == 1) {
683 // Track down inodes of cache directories
684 uint64_t raw = 0;
685 ino_t inode_cache = 0;
686 ino_t inode_code_cache = 0;
687 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
688 inode_cache = raw;
689 }
690 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
691 inode_code_cache = raw;
692 }
693
694 // Figure out expected GID of each child
695 FTSENT* child = fts_children(fts, 0);
696 while (child != nullptr) {
697 if ((child->fts_statp->st_ino == inode_cache)
698 || (child->fts_statp->st_ino == inode_code_cache)
699 || !strcmp(child->fts_name, "cache")
700 || !strcmp(child->fts_name, "code_cache")) {
701 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
702 } else {
703 child->fts_number = p->fts_statp->st_uid;
704 }
705 child = child->fts_link;
706 }
707 } else if (p->fts_level >= 2) {
708 if (p->fts_level > 2) {
709 // Inherit GID from parent once we're deeper into tree
710 p->fts_number = p->fts_parent->fts_number;
711 }
712
713 uid_t uid = p->fts_parent->fts_statp->st_uid;
714 gid_t cache_gid = get_cache_gid(uid);
715 gid_t expected = p->fts_number;
716 gid_t actual = p->fts_statp->st_gid;
717 if (actual == expected) {
718#if FIXUP_DEBUG
719 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
720#endif
721 if (!(flags & FLAG_FORCE)) {
722 fts_set(fts, p, FTS_SKIP);
723 }
724 } else if ((actual == uid) || (actual == cache_gid)) {
725 // Only consider fixing up when current GID belongs to app
726 if (p->fts_info != FTS_D) {
727 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
728 << " instead of " << expected;
729 }
730 switch (p->fts_info) {
731 case FTS_DP:
732 // If we're moving towards cache GID, we need to set S_ISGID
733 if (expected == cache_gid) {
734 if (chmod(p->fts_path, 02771) != 0) {
735 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
736 }
737 }
738 // Intentional fall through to also set GID
739 case FTS_F:
740 if (chown(p->fts_path, -1, expected) != 0) {
741 PLOG(WARNING) << "Failed to chown " << p->fts_path;
742 }
743 break;
744 case FTS_SL:
745 case FTS_SLNONE:
746 if (lchown(p->fts_path, -1, expected) != 0) {
747 PLOG(WARNING) << "Failed to chown " << p->fts_path;
748 }
749 break;
750 }
751 } else {
752 // Ignore all other GID transitions, since they're kinda shady
753 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
754 << " instead of " << expected;
Jeff Sharkeye2cff6a2017-09-21 15:41:37 -0600755 if (!(flags & FLAG_FORCE)) {
756 fts_set(fts, p, FTS_SKIP);
757 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600758 }
759 }
760 }
761 fts_close(fts);
762 ATRACE_END();
763 }
764 return ok();
765}
766
Jeff Sharkey0274c972016-12-06 09:32:04 -0700767binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
768 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
769 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
770 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700771 ENFORCE_UID(AID_SYSTEM);
772 CHECK_ARGUMENT_UUID(fromUuid);
773 CHECK_ARGUMENT_UUID(toUuid);
774 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700775 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700776
777 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
778 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
779 const char* package_name = packageName.c_str();
780 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700781
Jeff Sharkey423e7462016-12-09 18:18:43 -0700782 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700783 std::vector<userid_t> users = get_known_users(from_uuid);
784
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700785 // Copy app
786 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600787 auto from = create_data_app_package_path(from_uuid, data_app_name);
788 auto to = create_data_app_package_path(to_uuid, data_app_name);
789 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700790
791 char *argv[] = {
792 (char*) kCpPath,
793 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
794 (char*) "-p", /* preserve timestamps, ownership, and permissions */
795 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
796 (char*) "-P", /* Do not follow symlinks [default] */
797 (char*) "-d", /* don't dereference symlinks */
798 (char*) from.c_str(),
799 (char*) to_parent.c_str()
800 };
801
802 LOG(DEBUG) << "Copying " << from << " to " << to;
803 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700804 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700805 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700806 goto fail;
807 }
808
809 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700810 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700811 goto fail;
812 }
813 }
814
815 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700816 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700817
818 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600819 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
820 if (access(from_ce.c_str(), F_OK) != 0) {
821 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700822 continue;
823 }
824
Jeff Sharkey0274c972016-12-06 09:32:04 -0700825 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700826 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700827 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700828 goto fail;
829 }
830
831 char *argv[] = {
832 (char*) kCpPath,
833 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
834 (char*) "-p", /* preserve timestamps, ownership, and permissions */
835 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
836 (char*) "-P", /* Do not follow symlinks [default] */
837 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600838 nullptr,
839 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700840 };
841
Jeff Sharkey51c94492016-05-10 17:46:39 -0600842 {
843 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
844 auto to = create_data_user_de_path(to_uuid, user);
845 argv[6] = (char*) from.c_str();
846 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700847
Jeff Sharkey51c94492016-05-10 17:46:39 -0600848 LOG(DEBUG) << "Copying " << from << " to " << to;
849 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
850 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700851 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600852 goto fail;
853 }
854 }
855 {
856 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
857 auto to = create_data_user_ce_path(to_uuid, user);
858 argv[6] = (char*) from.c_str();
859 argv[7] = (char*) to.c_str();
860
861 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 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700867 }
868
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700869 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
870 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700871 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700872 goto fail;
873 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700874 }
875
Jeff Sharkey31f08982015-07-07 13:31:37 -0700876 // We let the framework scan the new location and persist that before
877 // deleting the data in the old location; this ordering ensures that
878 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700879 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700880
881fail:
882 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700883 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600884 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700885 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
886 LOG(WARNING) << "Failed to rollback " << to;
887 }
888 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700889 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600890 {
891 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
892 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
893 LOG(WARNING) << "Failed to rollback " << to;
894 }
895 }
896 {
897 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
898 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
899 LOG(WARNING) << "Failed to rollback " << to;
900 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700901 }
902 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700903 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700904}
905
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700906binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
907 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
908 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700909 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700910 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700911
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700912 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600913 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700914 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700915 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700916 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700917 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700918 }
919 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600920
921 // Data under /data/media doesn't have an app, but we still want
922 // to limit it to prevent abuse.
923 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
924 multiuser_get_uid(userId, AID_MEDIA_RW))) {
925 return error("Failed to set hard quota for media_rw");
926 }
927
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700928 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700929}
930
931binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
932 int32_t userId, int32_t flags) {
933 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700934 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700935 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700936
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700937 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700938 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700939 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700940 auto path = create_data_user_de_path(uuid_, userId);
941 if (delete_dir_contents_and_dir(path, true) != 0) {
942 res = error("Failed to delete " + path);
943 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700944 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700945 path = create_data_misc_legacy_path(userId);
946 if (delete_dir_contents_and_dir(path, true) != 0) {
947 res = error("Failed to delete " + path);
948 }
Calin Juravle114f0812017-03-08 19:05:07 -0800949 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700950 if (delete_dir_contents_and_dir(path, true) != 0) {
951 res = error("Failed to delete " + path);
952 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700953 }
Robin Lee095c7632014-04-25 15:05:19 +0100954 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600955 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700956 auto path = create_data_user_ce_path(uuid_, userId);
957 if (delete_dir_contents_and_dir(path, true) != 0) {
958 res = error("Failed to delete " + path);
959 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600960 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700961 if (delete_dir_contents_and_dir(path, true) != 0) {
962 res = error("Failed to delete " + path);
963 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600964 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700965 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100966}
967
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700968binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600969 int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700970 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700971 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700972 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700973
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700974 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700975 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700976 auto device = findQuotaDeviceForUuid(uuid);
977 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700978
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700979 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700980 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700981 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700982 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700983
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600984 int64_t cleared = 0;
985 int64_t needed = targetFreeBytes - free;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600986 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600987 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600988
Jeff Sharkey60f8a532017-05-30 14:38:42 -0600989 if (free >= targetFreeBytes) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600990 return ok();
991 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700992
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700993 if (flags & FLAG_FREE_CACHE_V2) {
994 // This new cache strategy fairly removes files from UIDs by deleting
995 // files from the UIDs which are most over their allocated quota
996
997 // 1. Create trackers for every known UID
998 ATRACE_BEGIN("create");
999 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
1000 for (auto user : get_known_users(uuid_)) {
1001 FTS *fts;
1002 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001003 auto ce_path = create_data_user_ce_path(uuid_, user);
1004 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001005 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
1006 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
1007 (char*) media_path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001008 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001009 return error("Failed to fts_open");
1010 }
1011 while ((p = fts_read(fts)) != NULL) {
1012 if (p->fts_info == FTS_D && p->fts_level == 1) {
1013 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001014 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
1015 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
1016 + AID_APP_START;
1017 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001018 auto search = trackers.find(uid);
1019 if (search != trackers.end()) {
1020 search->second->addDataPath(p->fts_path);
1021 } else {
1022 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
1023 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
1024 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001025 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001026 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001027 tracker->cacheQuota = mCacheQuotas[uid];
1028 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001029 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001030#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001031 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001032#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001033 tracker->cacheQuota = 67108864;
1034 }
1035 trackers[uid] = tracker;
1036 }
1037 fts_set(fts, p, FTS_SKIP);
1038 }
1039 }
1040 fts_close(fts);
1041 }
1042 ATRACE_END();
1043
1044 // 2. Populate tracker stats and insert into priority queue
1045 ATRACE_BEGIN("populate");
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001046 int64_t cacheTotal = 0;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001047 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1048 return (left->getCacheRatio() < right->getCacheRatio());
1049 };
1050 std::priority_queue<std::shared_ptr<CacheTracker>,
1051 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1052 for (const auto& it : trackers) {
1053 it.second->loadStats();
1054 queue.push(it.second);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001055 cacheTotal += it.second->cacheUsed;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001056 }
1057 ATRACE_END();
1058
1059 // 3. Bounce across the queue, freeing items from whichever tracker is
1060 // the most over their assigned quota
1061 ATRACE_BEGIN("bounce");
1062 std::shared_ptr<CacheTracker> active;
1063 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001064 // Only look at apps under quota when explicitly requested
1065 if (active && (active->getCacheRatio() < 10000)
1066 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1067 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1068 << " isn't over quota, and defy not requested";
1069 break;
1070 }
1071
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001072 // Only keep clearing when we haven't pushed into reserved area
1073 if (cacheReservedBytes > 0 && cleared >= (cacheTotal - cacheReservedBytes)) {
1074 LOG(DEBUG) << "Refusing to clear cached data in reserved space";
1075 break;
1076 }
1077
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001078 // Find the best tracker to work with; this might involve swapping
1079 // if the active tracker is no longer the most over quota
1080 bool nextBetter = active && !queue.empty()
1081 && active->getCacheRatio() < queue.top()->getCacheRatio();
1082 if (!active || nextBetter) {
1083 if (active) {
1084 // Current tracker still has items, so we'll consider it
1085 // again later once it bubbles up to surface
1086 queue.push(active);
1087 }
1088 active = queue.top(); queue.pop();
1089 active->ensureItems();
1090 continue;
1091 }
1092
1093 // If no items remain, go find another tracker
1094 if (active->items.empty()) {
1095 active = nullptr;
1096 continue;
1097 } else {
1098 auto item = active->items.back();
1099 active->items.pop_back();
1100
1101 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1102 if (!noop) {
1103 item->purge();
1104 }
1105 active->cacheUsed -= item->size;
1106 needed -= item->size;
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001107 cleared += item->size;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001108 }
1109
1110 // Verify that we're actually done before bailing, since sneaky
1111 // apps might be using hardlinks
1112 if (needed <= 0) {
1113 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001114 needed = targetFreeBytes - free;
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001115 if (needed <= 0) {
1116 break;
1117 } else {
1118 LOG(WARNING) << "Expected to be done but still need " << needed;
1119 }
1120 }
1121 }
1122 ATRACE_END();
1123
1124 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001125 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001126 }
1127
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001128 free = data_disk_free(data_path);
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001129 if (free >= targetFreeBytes) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001130 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001131 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001132 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001133 targetFreeBytes, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001134 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001135}
1136
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001137binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1138 const std::string& instructionSet) {
1139 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001140 std::lock_guard<std::recursive_mutex> lock(mLock);
1141
Mike Lockwood94afecf2012-10-24 10:45:23 -07001142 char dex_path[PKG_PATH_MAX];
1143
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001144 const char* path = codePath.c_str();
1145 const char* instruction_set = instructionSet.c_str();
1146
Jeff Sharkey770180a2014-09-08 17:14:26 -07001147 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001148 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001149 }
1150
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001151 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001152 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001153 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001154
1155 ALOGV("unlink %s\n", dex_path);
1156 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07001157 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
1158 // but could not be unlinked.
1159 if (errno != ENOENT) {
1160 return error(StringPrintf("Failed to unlink %s", dex_path));
1161 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001162 }
Calin Juravle249f2d32017-05-03 17:22:27 -07001163 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001164}
1165
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001166struct stats {
1167 int64_t codeSize;
1168 int64_t dataSize;
1169 int64_t cacheSize;
1170};
1171
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001172#if MEASURE_DEBUG
1173static std::string toString(std::vector<int64_t> values) {
1174 std::stringstream res;
1175 res << "[";
1176 for (size_t i = 0; i < values.size(); i++) {
1177 res << values[i];
1178 if (i < values.size() - 1) {
1179 res << ",";
1180 }
1181 }
1182 res << "]";
1183 return res.str();
1184}
1185#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001186
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001187static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001188 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001189 if (device.empty()) return;
1190
1191 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001192
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001193 if (stats != nullptr) {
1194 uid_t uid = multiuser_get_uid(userId, appId);
1195 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001196 reinterpret_cast<char*>(&dq)) != 0) {
1197 if (errno != ESRCH) {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001198 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001199 }
1200 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001201#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001202 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001203#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001204 stats->dataSize += dq.dqb_curspace;
1205 }
1206
1207 int cacheGid = multiuser_get_cache_gid(userId, appId);
1208 if (cacheGid != -1) {
1209 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1210 reinterpret_cast<char*>(&dq)) != 0) {
1211 if (errno != ESRCH) {
1212 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1213 }
1214 } else {
1215#if MEASURE_DEBUG
1216 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1217#endif
1218 stats->cacheSize += dq.dqb_curspace;
1219 }
1220 }
1221
1222 int sharedGid = multiuser_get_shared_gid(0, appId);
1223 if (sharedGid != -1) {
1224 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1225 reinterpret_cast<char*>(&dq)) != 0) {
1226 if (errno != ESRCH) {
1227 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1228 }
1229 } else {
1230#if MEASURE_DEBUG
1231 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1232#endif
1233 stats->codeSize += dq.dqb_curspace;
1234 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001235 }
1236 }
1237
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001238 if (extStats != nullptr) {
1239 int extGid = multiuser_get_ext_gid(userId, appId);
1240 if (extGid != -1) {
1241 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1242 reinterpret_cast<char*>(&dq)) != 0) {
1243 if (errno != ESRCH) {
1244 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1245 }
1246 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001247#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001248 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001249#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001250 extStats->dataSize += dq.dqb_curspace;
1251 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001252 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001253
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001254 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1255 if (extCacheGid != -1) {
1256 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extCacheGid,
1257 reinterpret_cast<char*>(&dq)) != 0) {
1258 if (errno != ESRCH) {
1259 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extCacheGid;
1260 }
1261 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001262#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001263 LOG(DEBUG) << "quotactl() for GID " << extCacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001264#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001265 extStats->dataSize += dq.dqb_curspace;
1266 extStats->cacheSize += dq.dqb_curspace;
1267 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001268 }
1269 }
1270}
1271
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001272static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001273 DIR *d;
1274 int dfd;
1275 struct dirent *de;
1276 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001277
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001278 d = opendir(path.c_str());
1279 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001280 if (errno != ENOENT) {
1281 PLOG(WARNING) << "Failed to open " << path;
1282 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001283 return;
1284 }
1285 dfd = dirfd(d);
1286 while ((de = readdir(d))) {
1287 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001288
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001289 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001290 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001291 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001292 }
1293
1294 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001295 if (!strcmp(name, ".")) {
1296 // Don't recurse, but still count node size
1297 } else if (!strcmp(name, "..")) {
1298 // Don't recurse or count node size
1299 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001300 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001301 // Measure all children nodes
1302 size = 0;
1303 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001304 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001305
1306 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1307 stats->cacheSize += size;
1308 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001309 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001310
1311 // Legacy symlink isn't owned by app
1312 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1313 continue;
1314 }
1315
1316 // Everything found inside is considered data
1317 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001318 }
1319 closedir(d);
1320}
1321
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001322static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1323 bool exclude_apps = false) {
1324 DIR *d;
1325 int dfd;
1326 struct dirent *de;
1327 struct stat s;
1328
1329 d = opendir(path.c_str());
1330 if (d == nullptr) {
1331 if (errno != ENOENT) {
1332 PLOG(WARNING) << "Failed to open " << path;
1333 }
1334 return;
1335 }
1336 dfd = dirfd(d);
1337 while ((de = readdir(d))) {
1338 if (de->d_type == DT_DIR) {
1339 const char *name = de->d_name;
1340 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1341 continue;
1342 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001343 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001344 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1345 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001346 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001347 continue;
1348 } else {
1349 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1350 }
1351 }
1352 }
1353 closedir(d);
1354}
1355
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001356static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1357 FTS *fts;
1358 FTSENT *p;
1359 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001360 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001361 PLOG(ERROR) << "Failed to fts_open " << path;
1362 return;
1363 }
1364 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001365 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001366 switch (p->fts_info) {
1367 case FTS_D:
1368 if (p->fts_level == 4
1369 && !strcmp(p->fts_name, "cache")
1370 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1371 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1372 p->fts_number = 1;
1373 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001374 // Fall through to count the directory
1375 case FTS_DEFAULT:
1376 case FTS_F:
1377 case FTS_SL:
1378 case FTS_SLNONE:
1379 int64_t size = (p->fts_statp->st_blocks * 512);
1380 if (p->fts_number == 1) {
1381 stats->cacheSize += size;
1382 }
1383 stats->dataSize += size;
1384 break;
1385 }
1386 }
1387 fts_close(fts);
1388}
1389
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001390binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001391 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1392 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1393 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001394 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001395 CHECK_ARGUMENT_UUID(uuid);
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -07001396 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001397 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1398 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001399 // NOTE: Locking is relaxed on this method, since it's limited to
1400 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001401
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001402 // When modifying this logic, always verify using tests:
1403 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1404
1405#if MEASURE_DEBUG
1406 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1407#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001408
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001409 // Here's a summary of the common storage locations across the platform,
1410 // and how they're each tagged:
1411 //
1412 // /data/app/com.example UID system
1413 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001414 // /data/user/0/com.example UID u0_a10 GID u0_a10
1415 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1416 // /data/media/0/foo.txt UID u0_media_rw
1417 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1418 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1419 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1420 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001421
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001422 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001423 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001424 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001425 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001426
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001427 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001428
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001429 auto device = findQuotaDeviceForUuid(uuid);
1430 if (device.empty()) {
1431 flags &= ~FLAG_USE_QUOTA;
1432 }
1433
Jeff Sharkey466459b2017-01-17 15:25:01 -07001434 ATRACE_BEGIN("obb");
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -07001435 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001436 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1437 calculate_tree_size(obbCodePath, &extStats.codeSize);
1438 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001439 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001440
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001441 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001442 ATRACE_BEGIN("code");
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -07001443 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001444 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001445 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001446 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001447 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001448
Jeff Sharkey466459b2017-01-17 15:25:01 -07001449 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001450 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001451 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001452 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001453 ATRACE_BEGIN("code");
Chih-Hung Hsieh0e1f4ce2017-08-03 15:48:25 -07001454 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001455 calculate_tree_size(codePath, &stats.codeSize);
1456 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001457 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001458
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001459 for (size_t i = 0; i < packageNames.size(); i++) {
1460 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001461
Jeff Sharkey466459b2017-01-17 15:25:01 -07001462 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001463 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1464 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001465 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1466 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001467 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001468
Jeff Sharkey06a61842017-04-15 12:03:31 -06001469 if (!uuid) {
1470 ATRACE_BEGIN("profiles");
1471 calculate_tree_size(
1472 create_primary_current_profile_package_dir_path(userId, pkgname),
1473 &stats.dataSize);
1474 calculate_tree_size(
1475 create_primary_reference_profile_package_dir_path(pkgname),
1476 &stats.codeSize);
1477 ATRACE_END();
1478 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001479
Jeff Sharkey466459b2017-01-17 15:25:01 -07001480 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001481 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001482 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001483 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001484 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001485 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001486 }
1487
Jeff Sharkey06a61842017-04-15 12:03:31 -06001488 if (!uuid) {
1489 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001490 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001491 if (sharedGid != -1) {
1492 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1493 sharedGid, -1);
1494 }
1495 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001496 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001497 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001498
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001499 std::vector<int64_t> ret;
1500 ret.push_back(stats.codeSize);
1501 ret.push_back(stats.dataSize);
1502 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001503 ret.push_back(extStats.codeSize);
1504 ret.push_back(extStats.dataSize);
1505 ret.push_back(extStats.cacheSize);
1506#if MEASURE_DEBUG
1507 LOG(DEBUG) << "Final result " << toString(ret);
1508#endif
1509 *_aidl_return = ret;
1510 return ok();
1511}
1512
1513binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1514 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1515 std::vector<int64_t>* _aidl_return) {
1516 ENFORCE_UID(AID_SYSTEM);
1517 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001518 // NOTE: Locking is relaxed on this method, since it's limited to
1519 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001520
1521 // When modifying this logic, always verify using tests:
1522 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1523
1524#if MEASURE_DEBUG
1525 LOG(INFO) << "Measuring user " << userId;
1526#endif
1527
1528 struct stats stats;
1529 struct stats extStats;
1530 memset(&stats, 0, sizeof(stats));
1531 memset(&extStats, 0, sizeof(extStats));
1532
1533 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1534
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001535 auto device = findQuotaDeviceForUuid(uuid);
1536 if (device.empty()) {
1537 flags &= ~FLAG_USE_QUOTA;
1538 }
1539
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001540 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001541 struct dqblk dq;
1542
1543 ATRACE_BEGIN("obb");
1544 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1545 reinterpret_cast<char*>(&dq)) != 0) {
1546 if (errno != ESRCH) {
1547 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1548 }
1549 } else {
1550#if MEASURE_DEBUG
1551 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1552#endif
1553 extStats.codeSize += dq.dqb_curspace;
1554 }
1555 ATRACE_END();
1556
Jeff Sharkey466459b2017-01-17 15:25:01 -07001557 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001558 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001559 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001560
Jeff Sharkey466459b2017-01-17 15:25:01 -07001561 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001562 auto cePath = create_data_user_ce_path(uuid_, userId);
1563 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001564 auto dePath = create_data_user_de_path(uuid_, userId);
1565 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001566 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001567
Jeff Sharkey06a61842017-04-15 12:03:31 -06001568 if (!uuid) {
1569 ATRACE_BEGIN("profile");
1570 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1571 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1572 auto refProfilePath = create_primary_ref_profile_dir_path();
1573 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1574 ATRACE_END();
1575 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001576
Jeff Sharkey466459b2017-01-17 15:25:01 -07001577 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001578 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1579 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1580 reinterpret_cast<char*>(&dq)) != 0) {
1581 if (errno != ESRCH) {
1582 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1583 }
1584 } else {
1585#if MEASURE_DEBUG
1586 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001587#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001588 extStats.dataSize += dq.dqb_curspace;
1589 }
1590 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001591
Jeff Sharkey06a61842017-04-15 12:03:31 -06001592 if (!uuid) {
1593 ATRACE_BEGIN("dalvik");
1594 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1595 -1, -1, true);
1596 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1597 -1, -1, true);
1598 ATRACE_END();
1599 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001600
Jeff Sharkey466459b2017-01-17 15:25:01 -07001601 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001602 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001603 for (auto appId : appIds) {
1604 if (appId >= AID_APP_START) {
1605 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001606
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001607#if MEASURE_DEBUG
1608 // Sleep to make sure we don't lose logs
1609 usleep(1);
1610#endif
1611 }
1612 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001613 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001614 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001615 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001616 ATRACE_BEGIN("obb");
1617 auto obbPath = create_data_path(uuid_) + "/media/obb";
1618 calculate_tree_size(obbPath, &extStats.codeSize);
1619 ATRACE_END();
1620
Jeff Sharkey466459b2017-01-17 15:25:01 -07001621 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001622 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001623 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001624
Jeff Sharkey466459b2017-01-17 15:25:01 -07001625 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001626 auto cePath = create_data_user_ce_path(uuid_, userId);
1627 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001628 auto dePath = create_data_user_de_path(uuid_, userId);
1629 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001630 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001631
Jeff Sharkey06a61842017-04-15 12:03:31 -06001632 if (!uuid) {
1633 ATRACE_BEGIN("profile");
1634 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1635 calculate_tree_size(userProfilePath, &stats.dataSize);
1636 auto refProfilePath = create_primary_ref_profile_dir_path();
1637 calculate_tree_size(refProfilePath, &stats.codeSize);
1638 ATRACE_END();
1639 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001640
Jeff Sharkey466459b2017-01-17 15:25:01 -07001641 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001642 auto dataMediaPath = create_data_media_path(uuid_, userId);
1643 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1644#if MEASURE_DEBUG
1645 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1646 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001647#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001648 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001649
Jeff Sharkey06a61842017-04-15 12:03:31 -06001650 if (!uuid) {
1651 ATRACE_BEGIN("dalvik");
1652 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1653 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1654 ATRACE_END();
1655 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001656 }
1657
1658 std::vector<int64_t> ret;
1659 ret.push_back(stats.codeSize);
1660 ret.push_back(stats.dataSize);
1661 ret.push_back(stats.cacheSize);
1662 ret.push_back(extStats.codeSize);
1663 ret.push_back(extStats.dataSize);
1664 ret.push_back(extStats.cacheSize);
1665#if MEASURE_DEBUG
1666 LOG(DEBUG) << "Final result " << toString(ret);
1667#endif
1668 *_aidl_return = ret;
1669 return ok();
1670}
1671
1672binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001673 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1674 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001675 ENFORCE_UID(AID_SYSTEM);
1676 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001677 // NOTE: Locking is relaxed on this method, since it's limited to
1678 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001679
1680 // When modifying this logic, always verify using tests:
1681 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1682
1683#if MEASURE_DEBUG
1684 LOG(INFO) << "Measuring external " << userId;
1685#endif
1686
1687 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1688
1689 int64_t totalSize = 0;
1690 int64_t audioSize = 0;
1691 int64_t videoSize = 0;
1692 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001693 int64_t appSize = 0;
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001694 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001695
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001696 auto device = findQuotaDeviceForUuid(uuid);
1697 if (device.empty()) {
1698 flags &= ~FLAG_USE_QUOTA;
1699 }
1700
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001701 if (flags & FLAG_USE_QUOTA) {
1702 struct dqblk dq;
1703
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001704 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001705 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1706 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1707 reinterpret_cast<char*>(&dq)) != 0) {
1708 if (errno != ESRCH) {
1709 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1710 }
1711 } else {
1712#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001713 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001714#endif
1715 totalSize = dq.dqb_curspace;
1716 }
1717
1718 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1719 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1720 reinterpret_cast<char*>(&dq)) == 0) {
1721#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001722 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001723#endif
1724 audioSize = dq.dqb_curspace;
1725 }
1726 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1727 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1728 reinterpret_cast<char*>(&dq)) == 0) {
1729#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001730 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001731#endif
1732 videoSize = dq.dqb_curspace;
1733 }
1734 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1735 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1736 reinterpret_cast<char*>(&dq)) == 0) {
1737#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001738 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001739#endif
1740 imageSize = dq.dqb_curspace;
1741 }
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001742 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1743 reinterpret_cast<char*>(&dq)) == 0) {
1744#if MEASURE_DEBUG
1745 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1746#endif
1747 obbSize = dq.dqb_curspace;
1748 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001749 ATRACE_END();
1750
1751 ATRACE_BEGIN("apps");
1752 struct stats extStats;
1753 memset(&extStats, 0, sizeof(extStats));
1754 for (auto appId : appIds) {
1755 if (appId >= AID_APP_START) {
1756 collectQuotaStats(device, userId, appId, nullptr, &extStats);
1757 }
1758 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06001759 appSize = extStats.dataSize;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001760 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001761 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001762 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001763 FTS *fts;
1764 FTSENT *p;
1765 auto path = create_data_media_path(uuid_, userId);
1766 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001767 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001768 return error("Failed to fts_open " + path);
1769 }
1770 while ((p = fts_read(fts)) != NULL) {
1771 char* ext;
1772 int64_t size = (p->fts_statp->st_blocks * 512);
1773 switch (p->fts_info) {
1774 case FTS_F:
1775 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001776 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001777 ext = strrchr(p->fts_name, '.');
1778 if (ext != nullptr) {
1779 switch (MatchExtension(++ext)) {
1780 case AID_MEDIA_AUDIO: audioSize += size; break;
1781 case AID_MEDIA_VIDEO: videoSize += size; break;
1782 case AID_MEDIA_IMAGE: imageSize += size; break;
1783 }
1784 }
1785 }
1786 // Fall through to always count against total
1787 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001788 // Ignore data belonging to specific apps
1789 p->fts_number = p->fts_parent->fts_number;
1790 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1791 p->fts_number = 1;
1792 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001793 case FTS_DEFAULT:
1794 case FTS_SL:
1795 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001796 if (p->fts_parent->fts_number == 1) {
1797 appSize += size;
1798 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001799 totalSize += size;
1800 break;
1801 }
1802 }
1803 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001804 ATRACE_END();
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001805
1806 ATRACE_BEGIN("obb");
1807 auto obbPath = create_data_media_obb_path(uuid_, "");
1808 calculate_tree_size(obbPath, &obbSize);
1809 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001810 }
1811
1812 std::vector<int64_t> ret;
1813 ret.push_back(totalSize);
1814 ret.push_back(audioSize);
1815 ret.push_back(videoSize);
1816 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001817 ret.push_back(appSize);
Jeff Sharkey4d03ee62017-07-06 11:29:37 -06001818 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001819#if MEASURE_DEBUG
1820 LOG(DEBUG) << "Final result " << toString(ret);
1821#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001822 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001823 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001824}
1825
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001826binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1827 int32_t userId, int32_t appId, int64_t cacheQuota) {
1828 ENFORCE_UID(AID_SYSTEM);
1829 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001830 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001831
1832 int32_t uid = multiuser_get_uid(userId, appId);
1833 mCacheQuotas[uid] = cacheQuota;
1834
1835 return ok();
1836}
1837
David Sehr6727c2d2016-05-17 16:06:22 -07001838// Dumps the contents of a profile file, using pkgname's dex files for pretty
1839// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001840binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1841 const std::string& codePaths, bool* _aidl_return) {
1842 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001843 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001844 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001845
1846 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001847 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001848
Jeff Sharkey90aff262016-12-12 14:28:24 -07001849 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001850 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001851}
1852
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001853// Copy the contents of a system profile over the data profile.
1854binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
1855 int32_t packageUid, const std::string& packageName, bool* _aidl_return) {
1856 ENFORCE_UID(AID_SYSTEM);
1857 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1858 std::lock_guard<std::recursive_mutex> lock(mLock);
Calin Juravle824a64d2018-01-18 20:23:17 -08001859 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName,
1860 kPrimaryProfileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001861 return ok();
1862}
1863
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001864// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001865binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001866 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001867 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001868 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001869 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001870
Calin Juravle824a64d2018-01-18 20:23:17 -08001871 *_aidl_return = analyze_primary_profiles(uid, packageName, kPrimaryProfileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001872 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001873}
1874
Calin Juravlec3596c32017-12-05 12:29:15 -08001875binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravle824a64d2018-01-18 20:23:17 -08001876 const std::string& packageName, const std::string& profileName, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08001877 ENFORCE_UID(AID_SYSTEM);
1878 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1879 std::lock_guard<std::recursive_mutex> lock(mLock);
1880
Calin Juravle824a64d2018-01-18 20:23:17 -08001881 *_aidl_return = create_profile_snapshot(appId, packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08001882 return ok();
1883}
1884
1885binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravle824a64d2018-01-18 20:23:17 -08001886 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08001887 ENFORCE_UID(AID_SYSTEM);
1888 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1889 std::lock_guard<std::recursive_mutex> lock(mLock);
1890
Calin Juravle824a64d2018-01-18 20:23:17 -08001891 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08001892 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravle824a64d2018-01-18 20:23:17 -08001893 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08001894 }
1895 return ok();
1896}
1897
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001898binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1899 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1900 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1901 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravle52c45822017-07-13 22:50:21 -07001902 const std::unique_ptr<std::string>& classLoaderContext,
David Brazdil570d3982018-01-16 20:15:43 +00001903 const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001904 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001905 CHECK_ARGUMENT_UUID(uuid);
1906 if (packageName && *packageName != "*") {
1907 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1908 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001909 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001910
1911 const char* apk_path = apkPath.c_str();
1912 const char* pkgname = packageName ? packageName->c_str() : "*";
1913 const char* instruction_set = instructionSet.c_str();
1914 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1915 const char* compiler_filter = compilerFilter.c_str();
1916 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
Calin Juravle52c45822017-07-13 22:50:21 -07001917 const char* class_loader_context = classLoaderContext ? classLoaderContext->c_str() : nullptr;
Calin Juravlecb556e32017-04-04 20:22:50 -07001918 const char* se_info = seInfo ? seInfo->c_str() : nullptr;
Calin Juravle824a64d2018-01-18 20:23:17 -08001919
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001920 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle52c45822017-07-13 22:50:21 -07001921 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Calin Juravle824a64d2018-01-18 20:23:17 -08001922 downgrade, targetSdkVersion, kPrimaryProfileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001923 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001924}
1925
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001926binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1927 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001928 std::lock_guard<std::recursive_mutex> lock(mLock);
1929
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001930 const char* instruction_set = instructionSet.c_str();
1931
1932 char boot_marker_path[PKG_PATH_MAX];
1933 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001934 "%s/%s/%s/.booting",
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001935 android_data_dir.c_str(),
Andreas Gampe02d0de52015-11-11 20:43:16 -08001936 DALVIK_CACHE,
1937 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001938
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001939 ALOGV("mark_boot_complete : %s", boot_marker_path);
1940 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001941 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001942 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001943 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001944}
1945
Mike Lockwood94afecf2012-10-24 10:45:23 -07001946void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1947 struct stat* statbuf)
1948{
1949 while (path[basepos] != 0) {
1950 if (path[basepos] == '/') {
1951 path[basepos] = 0;
1952 if (lstat(path, statbuf) < 0) {
1953 ALOGV("Making directory: %s\n", path);
1954 if (mkdir(path, mode) == 0) {
1955 chown(path, uid, gid);
1956 } else {
1957 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1958 }
1959 }
1960 path[basepos] = '/';
1961 basepos++;
1962 }
1963 basepos++;
1964 }
1965}
1966
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001967binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1968 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1969 const std::string& nativeLibPath32, int32_t userId) {
1970 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001971 CHECK_ARGUMENT_UUID(uuid);
1972 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001973 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001974
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001975 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1976 const char* pkgname = packageName.c_str();
1977 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001978 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001979 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001980
Jeff Sharkey423e7462016-12-09 18:18:43 -07001981 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1982 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001983
1984 const char* pkgdir = _pkgdir.c_str();
1985 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001986
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001987 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001988 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001989 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001990
1991 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001992 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001993 }
1994
1995 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001996 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001997 goto out;
1998 }
1999
2000 if (lstat(libsymlink, &libStat) < 0) {
2001 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002002 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002003 goto out;
2004 }
2005 } else {
2006 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002007 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002008 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002009 goto out;
2010 }
2011 } else if (S_ISLNK(libStat.st_mode)) {
2012 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002013 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002014 goto out;
2015 }
2016 }
2017 }
2018
2019 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002020 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002021 goto out;
2022 }
2023
2024out:
2025 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002026 auto msg = "Failed to cleanup chmod " + _pkgdir;
2027 if (res.isOk()) {
2028 res = error(msg);
2029 } else {
2030 PLOG(ERROR) << msg;
2031 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002032 }
2033
2034 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002035 auto msg = "Failed to cleanup chown " + _pkgdir;
2036 if (res.isOk()) {
2037 res = error(msg);
2038 } else {
2039 PLOG(ERROR) << msg;
2040 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002041 }
2042
Jeff Sharkey423e7462016-12-09 18:18:43 -07002043 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002044}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002045
2046static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2047{
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002048 execl(kIdMapPath, kIdMapPath, "--fd", target_apk, overlay_apk,
2049 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
2050 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2051}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002052
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002053static void run_verify_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
2054{
2055 execl(kIdMapPath, kIdMapPath, "--verify", target_apk, overlay_apk,
2056 StringPrintf("%d", idmap_fd).c_str(), (char*)NULL);
2057 PLOG(ERROR) << "execl (" << kIdMapPath << ") failed";
2058}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002059
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002060static bool delete_stale_idmap(const char* target_apk, const char* overlay_apk,
2061 const char* idmap_path, int32_t uid) {
2062 int idmap_fd = open(idmap_path, O_RDWR);
2063 if (idmap_fd < 0) {
2064 PLOG(ERROR) << "idmap open failed: " << idmap_path;
2065 unlink(idmap_path);
2066 return true;
2067 }
2068
2069 pid_t pid;
2070 pid = fork();
2071 if (pid == 0) {
2072 /* child -- drop privileges before continuing */
2073 if (setgid(uid) != 0) {
2074 LOG(ERROR) << "setgid(" << uid << ") failed during idmap";
2075 exit(1);
2076 }
2077 if (setuid(uid) != 0) {
2078 LOG(ERROR) << "setuid(" << uid << ") failed during idmap";
2079 exit(1);
2080 }
2081 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2082 PLOG(ERROR) << "flock(" << idmap_path << ") failed during idmap";
2083 exit(1);
2084 }
2085
2086 run_verify_idmap(target_apk, overlay_apk, idmap_fd);
2087 exit(1); /* only if exec call to deleting stale idmap failed */
2088 } else {
2089 int status = wait_child(pid);
2090 close(idmap_fd);
2091
2092 if (status != 0) {
2093 // Failed on verifying if idmap is made from target_apk and overlay_apk.
2094 LOG(DEBUG) << "delete stale idmap: " << idmap_path;
2095 unlink(idmap_path);
2096 return true;
2097 }
2098 }
2099 return false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002100}
2101
2102// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
2103// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
2104static int flatten_path(const char *prefix, const char *suffix,
2105 const char *overlay_path, char *idmap_path, size_t N)
2106{
2107 if (overlay_path == NULL || idmap_path == NULL) {
2108 return -1;
2109 }
2110 const size_t len_overlay_path = strlen(overlay_path);
2111 // will access overlay_path + 1 further below; requires absolute path
2112 if (len_overlay_path < 2 || *overlay_path != '/') {
2113 return -1;
2114 }
2115 const size_t len_idmap_root = strlen(prefix);
2116 const size_t len_suffix = strlen(suffix);
2117 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
2118 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
2119 // additions below would cause overflow
2120 return -1;
2121 }
2122 if (N < len_idmap_root + len_overlay_path + len_suffix) {
2123 return -1;
2124 }
2125 memset(idmap_path, 0, N);
2126 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
2127 char *ch = idmap_path + len_idmap_root;
2128 while (*ch != '\0') {
2129 if (*ch == '/') {
2130 *ch = '@';
2131 }
2132 ++ch;
2133 }
2134 return 0;
2135}
2136
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002137binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
2138 const std::string& overlayApkPath, int32_t uid) {
2139 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002140 std::lock_guard<std::recursive_mutex> lock(mLock);
2141
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002142 const char* target_apk = targetApkPath.c_str();
2143 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002144 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2145
2146 int idmap_fd = -1;
2147 char idmap_path[PATH_MAX];
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002148 struct stat idmap_stat;
2149 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002150
2151 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2152 idmap_path, sizeof(idmap_path)) == -1) {
2153 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2154 goto fail;
2155 }
2156
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002157 if (stat(idmap_path, &idmap_stat) < 0) {
2158 outdated = true;
2159 } else {
2160 outdated = delete_stale_idmap(target_apk, overlay_apk, idmap_path, uid);
2161 }
2162
2163 if (outdated) {
2164 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2165 } else {
2166 idmap_fd = open(idmap_path, O_RDWR);
2167 }
2168
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002169 if (idmap_fd < 0) {
2170 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2171 goto fail;
2172 }
2173 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2174 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2175 goto fail;
2176 }
2177 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2178 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2179 goto fail;
2180 }
2181
Jaekyun Seok5cb903e2017-05-18 00:13:44 +09002182 if (!outdated) {
2183 close(idmap_fd);
2184 return ok();
2185 }
2186
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002187 pid_t pid;
2188 pid = fork();
2189 if (pid == 0) {
2190 /* child -- drop privileges before continuing */
2191 if (setgid(uid) != 0) {
2192 ALOGE("setgid(%d) failed during idmap\n", uid);
2193 exit(1);
2194 }
2195 if (setuid(uid) != 0) {
2196 ALOGE("setuid(%d) failed during idmap\n", uid);
2197 exit(1);
2198 }
2199 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2200 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2201 exit(1);
2202 }
2203
2204 run_idmap(target_apk, overlay_apk, idmap_fd);
2205 exit(1); /* only if exec call to idmap failed */
2206 } else {
2207 int status = wait_child(pid);
2208 if (status != 0) {
2209 ALOGE("idmap failed, status=0x%04x\n", status);
2210 goto fail;
2211 }
2212 }
2213
2214 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002215 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002216fail:
2217 if (idmap_fd >= 0) {
2218 close(idmap_fd);
2219 unlink(idmap_path);
2220 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002221 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002222}
Robert Craige9887e42014-02-20 10:25:56 -05002223
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002224binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
2225 const char* overlay_apk = overlayApkPath.c_str();
2226 char idmap_path[PATH_MAX];
2227
2228 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2229 idmap_path, sizeof(idmap_path)) == -1) {
2230 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2231 return error();
2232 }
2233 if (unlink(idmap_path) < 0) {
2234 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2235 return error();
2236 }
2237 return ok();
2238}
2239
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002240binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2241 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2242 const std::string& seInfo) {
2243 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002244 CHECK_ARGUMENT_UUID(uuid);
2245 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002246 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002247
2248 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002249
Robert Craigda30dc72014-03-27 10:21:12 -04002250 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002251 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002252 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2253 const char* pkgName = packageName.c_str();
2254 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002255
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002256 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002257 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002258 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002259 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002260 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002261 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002262 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002263 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002264 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002265 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002266 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002267 }
Robert Craige9887e42014-02-20 10:25:56 -05002268 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002269 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002270}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002271
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002272binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2273 const std::string& instructionSet) {
2274 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002275 std::lock_guard<std::recursive_mutex> lock(mLock);
2276
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002277 const char* oat_dir = oatDir.c_str();
2278 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002279 char oat_instr_dir[PKG_PATH_MAX];
2280
2281 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002282 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002283 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002284 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002285 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002286 }
2287 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002288 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002289 }
2290 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002291 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002292 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002293 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002294 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002295}
2296
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002297binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2298 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002299 std::lock_guard<std::recursive_mutex> lock(mLock);
2300
Jeff Sharkey423e7462016-12-09 18:18:43 -07002301 if (validate_apk_path(packageDir.c_str())) {
2302 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002303 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002304 if (delete_dir_contents_and_dir(packageDir) != 0) {
2305 return error("Failed to delete " + packageDir);
2306 }
2307 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002308}
2309
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002310binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2311 const std::string& fromBase, const std::string& toBase) {
2312 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002313 std::lock_guard<std::recursive_mutex> lock(mLock);
2314
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002315 const char* relative_path = relativePath.c_str();
2316 const char* from_base = fromBase.c_str();
2317 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002318 char from_path[PKG_PATH_MAX];
2319 char to_path[PKG_PATH_MAX];
2320 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2321 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2322
2323 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002324 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002325 }
2326
2327 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002328 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002329 }
2330
Jeff Sharkey423e7462016-12-09 18:18:43 -07002331 if (link(from_path, to_path) < 0) {
2332 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002333 }
2334
Jeff Sharkey423e7462016-12-09 18:18:43 -07002335 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002336}
2337
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002338binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2339 const std::string& instructionSet, const std::string& outputPath) {
2340 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002341 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002342
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002343 const char* apk_path = apkPath.c_str();
2344 const char* instruction_set = instructionSet.c_str();
2345 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002346
Jeff Sharkey90aff262016-12-12 14:28:24 -07002347 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002348 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002349}
2350
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002351binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
Andreas Gampec5234092017-05-31 16:39:58 -07002352 const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002353 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002354 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002355
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002356 const char* apk_path = apkPath.c_str();
2357 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07002358 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002359
Jeff Sharkey90aff262016-12-12 14:28:24 -07002360 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2361 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002362}
2363
Victor Hsieh99de5162017-10-06 14:44:14 -07002364binder::Status InstalldNativeService::installApkVerity(const std::string& /*filePath*/,
2365 const ::android::base::unique_fd& /*verityInput*/) {
2366 ENFORCE_UID(AID_SYSTEM);
2367 if (!android::base::GetBoolProperty(kPropApkVerityMode, false)) {
2368 return ok();
2369 }
2370 // TODO: Append verity to filePath then issue ioctl to enable
2371 // it and hide the tree. See b/30972906.
2372 return error("not implemented yet");
2373}
2374
Calin Juravlebd968362017-01-25 01:17:17 -08002375binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2376 const std::string& dexPath, const std::string& packageName, int32_t uid,
2377 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2378 int32_t storage_flag, bool* _aidl_return) {
2379 ENFORCE_UID(AID_SYSTEM);
2380 CHECK_ARGUMENT_UUID(volumeUuid);
2381 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2382
2383 std::lock_guard<std::recursive_mutex> lock(mLock);
2384 bool result = android::installd::reconcile_secondary_dex_file(
2385 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2386 return result ? ok() : error();
2387}
2388
Alan Stokesa25d90c2017-10-16 10:56:00 +01002389binder::Status InstalldNativeService::hashSecondaryDexFile(
2390 const std::string& dexPath, const std::string& packageName, int32_t uid,
2391 const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
2392 std::vector<uint8_t>* _aidl_return) {
2393 ENFORCE_UID(AID_SYSTEM);
2394 CHECK_ARGUMENT_UUID(volumeUuid);
2395 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2396
2397 // mLock is not taken here since we will never modify the file system.
2398 // If a file is modified just as we are reading it this may result in an
2399 // anomalous hash, but that's ok.
2400 bool result = android::installd::hash_secondary_dex_file(
2401 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
2402 return result ? ok() : error();
2403}
2404
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002405binder::Status InstalldNativeService::invalidateMounts() {
2406 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002407 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002408
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002409 mStorageMounts.clear();
2410 mQuotaReverseMounts.clear();
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002411
2412 std::ifstream in("/proc/mounts");
2413 if (!in.is_open()) {
2414 return error("Failed to read mounts");
2415 }
2416
2417 std::string source;
2418 std::string target;
2419 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002420 while (!in.eof()) {
2421 std::getline(in, source, ' ');
2422 std::getline(in, target, ' ');
2423 std::getline(in, ignored);
2424
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002425#if !BYPASS_SDCARDFS
2426 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2427 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2428 mStorageMounts[source] = target;
2429 }
2430#endif
2431
2432#if !BYPASS_QUOTA
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002433 if (source.compare(0, 11, "/dev/block/") == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002434 struct dqblk dq;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002435 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2436 reinterpret_cast<char*>(&dq)) == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002437 LOG(DEBUG) << "Found quota mount " << source << " at " << target;
2438 mQuotaReverseMounts[target] = source;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002439
2440 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
2441 // need to kick it again to enable DQUOT_LIMITS_ENABLED.
2442 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2443 && errno != EBUSY) {
2444 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2445 }
2446 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2447 && errno != EBUSY) {
2448 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2449 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002450 }
2451 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002452#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002453 }
2454 return ok();
2455}
2456
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002457std::string InstalldNativeService::findDataMediaPath(
2458 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2459 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2460 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2461 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2462 auto resolved = mStorageMounts[path];
2463 if (resolved.empty()) {
2464 LOG(WARNING) << "Failed to find storage mount for " << path;
2465 resolved = path;
2466 }
2467 return StringPrintf("%s/%u", resolved.c_str(), userid);
2468}
2469
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002470std::string InstalldNativeService::findQuotaDeviceForUuid(
2471 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002472 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002473 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002474 return mQuotaReverseMounts[path];
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002475}
2476
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002477binder::Status InstalldNativeService::isQuotaSupported(
2478 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2479 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2480 return ok();
2481}
2482
Andreas Gampe02d0de52015-11-11 20:43:16 -08002483} // namespace installd
2484} // namespace android