blob: c604ca033689b51217ddbabfd1d85406662832ea [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>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080040#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070041#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010042#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080043#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070044#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070045#include <cutils/sched_policy.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070046#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070047#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080048#include <private/android_filesystem_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070049#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080050#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070051#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070052
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070053#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070054#include "globals.h"
55#include "installd_deps.h"
56#include "otapreopt_utils.h"
57#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070058
Jeff Sharkey88ddd942017-01-17 18:05:54 -070059#include "CacheTracker.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070060#include "MatchExtensionGen.h"
61
Andreas Gampe02d0de52015-11-11 20:43:16 -080062#ifndef LOG_TAG
63#define LOG_TAG "installd"
64#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070065
66using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070067using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070068
Andreas Gampe02d0de52015-11-11 20:43:16 -080069namespace android {
70namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070071
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070072static constexpr const char* kCpPath = "/system/bin/cp";
73static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070074
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -070075static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +000076
Andreas Gampe0354bd02016-06-27 14:25:30 -070077static constexpr const char* PKG_LIB_POSTFIX = "/lib";
78static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
79static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
80
81static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
82static constexpr const char* IDMAP_SUFFIX = "@idmap";
83
Andreas Gampe0354bd02016-06-27 14:25:30 -070084// NOTE: keep in sync with Installer
85static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
86static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070087static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -070088static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
Jeff Sharkey871a8f22017-02-21 18:30:28 -070089static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
90static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
Calin Juravle6a1648e2016-02-01 12:12:16 +000091
Jeff Sharkey0274c972016-12-06 09:32:04 -070092namespace {
93
94constexpr const char* kDump = "android.permission.DUMP";
95
Jeff Sharkey423e7462016-12-09 18:18:43 -070096static binder::Status ok() {
97 return binder::Status::ok();
98}
99
100static binder::Status exception(uint32_t code, const std::string& msg) {
101 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
102}
103
104static binder::Status error() {
105 return binder::Status::fromServiceSpecificError(errno);
106}
107
108static binder::Status error(const std::string& msg) {
109 PLOG(ERROR) << msg;
110 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
111}
112
113static binder::Status error(uint32_t code, const std::string& msg) {
114 LOG(ERROR) << msg << " (" << code << ")";
115 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
116}
117
Jeff Sharkey0274c972016-12-06 09:32:04 -0700118binder::Status checkPermission(const char* permission) {
119 pid_t pid;
120 uid_t uid;
121
122 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
123 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700124 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700125 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700126 return exception(binder::Status::EX_SECURITY,
127 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700128 }
129}
130
131binder::Status checkUid(uid_t expectedUid) {
132 uid_t uid = IPCThreadState::self()->getCallingUid();
133 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700134 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700135 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700136 return exception(binder::Status::EX_SECURITY,
137 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
138 }
139}
140
141binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
142 if (!uuid || is_valid_filename(*uuid)) {
143 return ok();
144 } else {
145 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
146 StringPrintf("UUID %s is malformed", uuid->c_str()));
147 }
148}
149
150binder::Status checkArgumentPackageName(const std::string& packageName) {
151 if (is_valid_package_name(packageName.c_str())) {
152 return ok();
153 } else {
154 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
155 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700156 }
157}
158
159#define ENFORCE_UID(uid) { \
160 binder::Status status = checkUid((uid)); \
161 if (!status.isOk()) { \
162 return status; \
163 } \
164}
165
Jeff Sharkey423e7462016-12-09 18:18:43 -0700166#define CHECK_ARGUMENT_UUID(uuid) { \
167 binder::Status status = checkArgumentUuid((uuid)); \
168 if (!status.isOk()) { \
169 return status; \
170 } \
171}
172
173#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
174 binder::Status status = \
175 checkArgumentPackageName((packageName)); \
176 if (!status.isOk()) { \
177 return status; \
178 } \
179}
180
Jeff Sharkey0274c972016-12-06 09:32:04 -0700181} // namespace
182
183status_t InstalldNativeService::start() {
184 IPCThreadState::self()->disableBackgroundScheduling(true);
185 status_t ret = BinderService<InstalldNativeService>::publish();
186 if (ret != android::OK) {
187 return ret;
188 }
189 sp<ProcessState> ps(ProcessState::self());
190 ps->startThreadPool();
191 ps->giveThreadPoolName();
192 return android::OK;
193}
194
195status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700196 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700197 const binder::Status dump_permission = checkPermission(kDump);
198 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700199 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700200 return PERMISSION_DENIED;
201 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700202 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700203
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700204 out << "installd is happy!" << endl;
205
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700206 {
207 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
208 out << endl << "Devices with quota support:" << endl;
209 for (const auto& n : mQuotaDevices) {
210 out << " " << n.first << " = " << n.second << endl;
211 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700212 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700213
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700214 {
215 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
216 out << endl << "Per-UID cache quotas:" << endl;
217 for (const auto& n : mCacheQuotas) {
218 out << " " << n.first << " = " << n.second << endl;
219 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700220 }
221
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700222 out << endl;
223 out.flush();
224
Jeff Sharkey0274c972016-12-06 09:32:04 -0700225 return NO_ERROR;
226}
227
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600228/**
229 * Perform restorecon of the given path, but only perform recursive restorecon
230 * if the label of that top-level file actually changed. This can save us
231 * significant time by avoiding no-op traversals of large filesystem trees.
232 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700233static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
234 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600235 int res = 0;
236 char* before = nullptr;
237 char* after = nullptr;
238
239 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
240 // libselinux. Not needed here.
241
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600242 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600243 PLOG(ERROR) << "Failed before getfilecon for " << path;
244 goto fail;
245 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700246 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600247 PLOG(ERROR) << "Failed top-level restorecon for " << path;
248 goto fail;
249 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600250 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600251 PLOG(ERROR) << "Failed after getfilecon for " << path;
252 goto fail;
253 }
254
255 // If the initial top-level restorecon above changed the label, then go
256 // back and restorecon everything recursively
257 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700258 if (existing) {
259 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
260 << path << "; running recursive restorecon";
261 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700262 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600263 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
264 PLOG(ERROR) << "Failed recursive restorecon for " << path;
265 goto fail;
266 }
267 }
268
269 goto done;
270fail:
271 res = -1;
272done:
273 free(before);
274 free(after);
275 return res;
276}
277
Jeff Sharkey0274c972016-12-06 09:32:04 -0700278static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700279 const std::string& seInfo, uid_t uid, bool existing) {
280 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
281 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600282}
283
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600284static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600285 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
286 PLOG(ERROR) << "Failed to prepare " << path;
287 return -1;
288 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600289 return 0;
290}
291
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600292/**
293 * Ensure that we have a hard-limit quota to protect against abusive apps;
294 * they should never use more than 90% of blocks or 50% of inodes.
295 */
296static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
297 uid_t uid) {
298 if (device.empty()) return 0;
299
300 struct dqblk dq;
301 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
302 reinterpret_cast<char*>(&dq)) != 0) {
303 PLOG(WARNING) << "Failed to find quota for " << uid;
304 return -1;
305 }
306
307 if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
308 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
309 struct statvfs stat;
310 if (statvfs(path.c_str(), &stat) != 0) {
311 PLOG(WARNING) << "Failed to statvfs " << path;
312 return -1;
313 }
314
315 dq.dqb_valid = QIF_LIMITS;
316 dq.dqb_bhardlimit = (((stat.f_blocks * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
317 dq.dqb_ihardlimit = (stat.f_files / 2);
318 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
319 reinterpret_cast<char*>(&dq)) != 0) {
320 PLOG(WARNING) << "Failed to set hard quota for " << uid;
321 return -1;
322 } else {
323 LOG(DEBUG) << "Applied hard quotas for " << uid;
324 return 0;
325 }
326 } else {
327 // Hard quota already set; assume it's reasonable
328 return 0;
329 }
330}
331
Jeff Sharkey0274c972016-12-06 09:32:04 -0700332binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
333 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700334 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700335 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700336 CHECK_ARGUMENT_UUID(uuid);
337 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700338 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700339
340 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
341 const char* pkgname = packageName.c_str();
342
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700343 // Assume invalid inode unless filled in below
344 if (_aidl_return != nullptr) *_aidl_return = -1;
345
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700346 int32_t uid = multiuser_get_uid(userId, appId);
347 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700348 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
349
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700350 // If UID doesn't have a specific cache GID, use UID value
351 if (cacheGid == -1) {
352 cacheGid = uid;
353 }
354
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700355 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700356 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700357 bool existing = (access(path.c_str(), F_OK) == 0);
358
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700359 if (prepare_app_dir(path, targetMode, uid) ||
360 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
361 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700362 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600363 }
364
365 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700366 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
367 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
368 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700369 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700370 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600371
372 // Remember inode numbers of cache directories so that we can clear
373 // contents while CE storage is locked
374 if (write_path_inode(path, "cache", kXattrInodeCache) ||
375 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700376 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700377 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700378
379 // And return the CE inode of the top-level data directory so we can
380 // clear contents while CE storage is locked
381 if ((_aidl_return != nullptr)
382 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
383 return error("Failed to get_path_inode for " + path);
384 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700385 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700386 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700387 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700388 bool existing = (access(path.c_str(), F_OK) == 0);
389
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700390 if (prepare_app_dir(path, targetMode, uid) ||
391 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
392 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700393 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700394 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000395
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600396 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700397 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700398 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600399 }
400
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600401 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
402 return error("Failed to set hard quota " + path);
403 }
404
Jeff Sharkey90aff262016-12-12 14:28:24 -0700405 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800406 const std::string profile_dir =
407 create_primary_current_profile_package_dir_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000408 // read-write-execute only for the app user.
Calin Juravle114f0812017-03-08 19:05:07 -0800409 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
410 return error("Failed to prepare " + profile_dir);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000411 }
Calin Juravle114f0812017-03-08 19:05:07 -0800412 const std::string profile_file = create_current_profile_path(userId, pkgname,
413 /*is_secondary_dex*/false);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100414 // read-write only for the app user.
415 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800416 return error("Failed to prepare " + profile_file);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100417 }
Calin Juravle114f0812017-03-08 19:05:07 -0800418 const std::string ref_profile_path =
419 create_primary_reference_profile_package_dir_path(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000420 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
421 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700422 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700423 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000424 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700425 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000426 }
427 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700428 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700429 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700430}
431
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700432binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
433 const std::string& packageName, int32_t userId, int32_t flags) {
434 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700435 CHECK_ARGUMENT_UUID(uuid);
436 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700437 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700438
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700439 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
440 const char* pkgname = packageName.c_str();
441
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700442 // This method only exists to upgrade system apps that have requested
443 // forceDeviceEncrypted, so their default storage always lives in a
444 // consistent location. This only works on non-FBE devices, since we
445 // never want to risk exposing data on a device with real CE/DE storage.
446
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700447 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
448 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700449
450 // If neither directory is marked as default, assume CE is default
451 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
452 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
453 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700454 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700455 }
456 }
457
458 // Migrate default data location if needed
459 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
460 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
461
462 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
463 LOG(WARNING) << "Requested default storage " << target
464 << " is not active; migrating from " << source;
465 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700466 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700467 }
468 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700469 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700470 }
471 }
472
Jeff Sharkey423e7462016-12-09 18:18:43 -0700473 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700474}
475
Calin Juravle6a1648e2016-02-01 12:12:16 +0000476
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700477binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
478 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700479 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700480 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700481
Jeff Sharkey423e7462016-12-09 18:18:43 -0700482 binder::Status res = ok();
Calin Juravle114f0812017-03-08 19:05:07 -0800483 if (!clear_primary_reference_profile(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700484 res = error("Failed to clear reference profile for " + packageName);
485 }
Calin Juravle114f0812017-03-08 19:05:07 -0800486 if (!clear_primary_current_profiles(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700487 res = error("Failed to clear current profiles for " + packageName);
488 }
489 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000490}
491
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700492binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
493 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
494 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700495 CHECK_ARGUMENT_UUID(uuid);
496 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700497 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700498
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700499 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
500 const char* pkgname = packageName.c_str();
501
Jeff Sharkey423e7462016-12-09 18:18:43 -0700502 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700503 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700504 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600505 if (flags & FLAG_CLEAR_CACHE_ONLY) {
506 path = read_path_inode(path, "cache", kXattrInodeCache);
507 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
508 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
509 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700510 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700511 if (delete_dir_contents(path) != 0) {
512 res = error("Failed to delete contents of " + path);
513 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700514 }
515 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700516 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600517 std::string suffix = "";
518 bool only_cache = false;
519 if (flags & FLAG_CLEAR_CACHE_ONLY) {
520 suffix = CACHE_DIR_POSTFIX;
521 only_cache = true;
522 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
523 suffix = CODE_CACHE_DIR_POSTFIX;
524 only_cache = true;
525 }
526
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700527 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700528 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700529 if (delete_dir_contents(path) != 0) {
530 res = error("Failed to delete contents of " + path);
531 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700532 }
Calin Juravleedae6692016-03-23 13:55:31 +0000533 if (!only_cache) {
Calin Juravle114f0812017-03-08 19:05:07 -0800534 if (!clear_primary_current_profile(packageName, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700535 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000536 }
537 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700538 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700539 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700540}
541
Calin Juravle76268c52017-03-09 13:19:42 -0800542static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100543 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800544 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100545 /*ignore_if_missing*/ true);
546}
547
Calin Juravle76268c52017-03-09 13:19:42 -0800548static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100549 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800550 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100551 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000552}
553
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700554binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
555 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700556 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700557 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700558
Jeff Sharkey423e7462016-12-09 18:18:43 -0700559 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000560 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
561 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800562 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700563 res = error("Failed to destroy current profiles for " + packageName);
564 }
Calin Juravleedae6692016-03-23 13:55:31 +0000565 }
Calin Juravle76268c52017-03-09 13:19:42 -0800566 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700567 res = error("Failed to destroy reference profile for " + packageName);
568 }
569 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000570}
571
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700572binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
573 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
574 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700575 CHECK_ARGUMENT_UUID(uuid);
576 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700577 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700578
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700579 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
580 const char* pkgname = packageName.c_str();
581
Jeff Sharkey423e7462016-12-09 18:18:43 -0700582 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700583 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700584 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
585 if (delete_dir_contents_and_dir(path) != 0) {
586 res = error("Failed to delete " + path);
587 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700588 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700589 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700590 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
591 if (delete_dir_contents_and_dir(path) != 0) {
592 res = error("Failed to delete " + path);
593 }
Calin Juravle76268c52017-03-09 13:19:42 -0800594 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100595 // TODO(calin): If the package is still installed by other users it's probably
596 // beneficial to keep the reference profile around.
597 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800598 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700599 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700600 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700601}
602
Jeff Sharkey0274c972016-12-06 09:32:04 -0700603binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
604 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
605 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
606 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700607 ENFORCE_UID(AID_SYSTEM);
608 CHECK_ARGUMENT_UUID(fromUuid);
609 CHECK_ARGUMENT_UUID(toUuid);
610 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700611 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700612
613 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
614 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
615 const char* package_name = packageName.c_str();
616 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700617
Jeff Sharkey423e7462016-12-09 18:18:43 -0700618 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700619 std::vector<userid_t> users = get_known_users(from_uuid);
620
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700621 // Copy app
622 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600623 auto from = create_data_app_package_path(from_uuid, data_app_name);
624 auto to = create_data_app_package_path(to_uuid, data_app_name);
625 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700626
627 char *argv[] = {
628 (char*) kCpPath,
629 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
630 (char*) "-p", /* preserve timestamps, ownership, and permissions */
631 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
632 (char*) "-P", /* Do not follow symlinks [default] */
633 (char*) "-d", /* don't dereference symlinks */
634 (char*) from.c_str(),
635 (char*) to_parent.c_str()
636 };
637
638 LOG(DEBUG) << "Copying " << from << " to " << to;
639 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700640 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700641 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700642 goto fail;
643 }
644
645 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700646 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700647 goto fail;
648 }
649 }
650
651 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700652 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700653
654 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600655 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
656 if (access(from_ce.c_str(), F_OK) != 0) {
657 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700658 continue;
659 }
660
Jeff Sharkey0274c972016-12-06 09:32:04 -0700661 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700662 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700663 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700664 goto fail;
665 }
666
667 char *argv[] = {
668 (char*) kCpPath,
669 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
670 (char*) "-p", /* preserve timestamps, ownership, and permissions */
671 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
672 (char*) "-P", /* Do not follow symlinks [default] */
673 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600674 nullptr,
675 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700676 };
677
Jeff Sharkey51c94492016-05-10 17:46:39 -0600678 {
679 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
680 auto to = create_data_user_de_path(to_uuid, user);
681 argv[6] = (char*) from.c_str();
682 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700683
Jeff Sharkey51c94492016-05-10 17:46:39 -0600684 LOG(DEBUG) << "Copying " << from << " to " << to;
685 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
686 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700687 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600688 goto fail;
689 }
690 }
691 {
692 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
693 auto to = create_data_user_ce_path(to_uuid, user);
694 argv[6] = (char*) from.c_str();
695 argv[7] = (char*) to.c_str();
696
697 LOG(DEBUG) << "Copying " << from << " to " << to;
698 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
699 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700700 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600701 goto fail;
702 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700703 }
704
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700705 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
706 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700707 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700708 goto fail;
709 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700710 }
711
Jeff Sharkey31f08982015-07-07 13:31:37 -0700712 // We let the framework scan the new location and persist that before
713 // deleting the data in the old location; this ordering ensures that
714 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700715 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700716
717fail:
718 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700719 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600720 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700721 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
722 LOG(WARNING) << "Failed to rollback " << to;
723 }
724 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700725 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600726 {
727 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
728 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
729 LOG(WARNING) << "Failed to rollback " << to;
730 }
731 }
732 {
733 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
734 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
735 LOG(WARNING) << "Failed to rollback " << to;
736 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700737 }
738 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700739 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700740}
741
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700742binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
743 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
744 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700745 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700746 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700747
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700748 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600749 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700750 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700751 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700752 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700753 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700754 }
755 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600756
757 // Data under /data/media doesn't have an app, but we still want
758 // to limit it to prevent abuse.
759 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
760 multiuser_get_uid(userId, AID_MEDIA_RW))) {
761 return error("Failed to set hard quota for media_rw");
762 }
763
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700764 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700765}
766
767binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
768 int32_t userId, int32_t flags) {
769 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700770 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700771 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700772
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700773 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700774 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700775 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700776 auto path = create_data_user_de_path(uuid_, userId);
777 if (delete_dir_contents_and_dir(path, true) != 0) {
778 res = error("Failed to delete " + path);
779 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700780 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700781 path = create_data_misc_legacy_path(userId);
782 if (delete_dir_contents_and_dir(path, true) != 0) {
783 res = error("Failed to delete " + path);
784 }
Calin Juravle114f0812017-03-08 19:05:07 -0800785 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700786 if (delete_dir_contents_and_dir(path, true) != 0) {
787 res = error("Failed to delete " + path);
788 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700789 }
Robin Lee095c7632014-04-25 15:05:19 +0100790 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600791 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700792 auto path = create_data_user_ce_path(uuid_, userId);
793 if (delete_dir_contents_and_dir(path, true) != 0) {
794 res = error("Failed to delete " + path);
795 }
796 path = create_data_media_path(uuid_, userId);
797 if (delete_dir_contents_and_dir(path, true) != 0) {
798 res = error("Failed to delete " + path);
799 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600800 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700801 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100802}
803
Mike Lockwood94afecf2012-10-24 10:45:23 -0700804/* Try to ensure free_size bytes of storage are available.
805 * Returns 0 on success.
806 * This is rather simple-minded because doing a full LRU would
807 * be potentially memory-intensive, and without atime it would
808 * also require that apps constantly modify file metadata even
809 * when just reading from the cache, which is pretty awful.
810 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700811binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700812 int64_t freeStorageSize, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700813 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700814 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700815 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700816
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700817 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700818 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700819 auto device = findQuotaDeviceForUuid(uuid);
820 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700821
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700822 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700823 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700824 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700825 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700826
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600827 int64_t needed = freeStorageSize - free;
828 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
829 << freeStorageSize << "; needed " << needed;
830
831 if (free >= freeStorageSize) {
832 return ok();
833 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700834
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700835 if (flags & FLAG_FREE_CACHE_V2) {
836 // This new cache strategy fairly removes files from UIDs by deleting
837 // files from the UIDs which are most over their allocated quota
838
839 // 1. Create trackers for every known UID
840 ATRACE_BEGIN("create");
841 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
842 for (auto user : get_known_users(uuid_)) {
843 FTS *fts;
844 FTSENT *p;
845 char *argv[] = {
846 (char*) create_data_user_ce_path(uuid_, user).c_str(),
847 (char*) create_data_user_de_path(uuid_, user).c_str(),
848 nullptr
849 };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700850 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700851 return error("Failed to fts_open");
852 }
853 while ((p = fts_read(fts)) != NULL) {
854 if (p->fts_info == FTS_D && p->fts_level == 1) {
855 uid_t uid = p->fts_statp->st_uid;
856 auto search = trackers.find(uid);
857 if (search != trackers.end()) {
858 search->second->addDataPath(p->fts_path);
859 } else {
860 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
861 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
862 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700863 {
864 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
865 tracker->cacheQuota = mCacheQuotas[uid];
866 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700867 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600868#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700869 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600870#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700871 tracker->cacheQuota = 67108864;
872 }
873 trackers[uid] = tracker;
874 }
875 fts_set(fts, p, FTS_SKIP);
876 }
877 }
878 fts_close(fts);
879 }
880 ATRACE_END();
881
882 // 2. Populate tracker stats and insert into priority queue
883 ATRACE_BEGIN("populate");
884 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
885 return (left->getCacheRatio() < right->getCacheRatio());
886 };
887 std::priority_queue<std::shared_ptr<CacheTracker>,
888 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
889 for (const auto& it : trackers) {
890 it.second->loadStats();
891 queue.push(it.second);
892 }
893 ATRACE_END();
894
895 // 3. Bounce across the queue, freeing items from whichever tracker is
896 // the most over their assigned quota
897 ATRACE_BEGIN("bounce");
898 std::shared_ptr<CacheTracker> active;
899 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700900 // Only look at apps under quota when explicitly requested
901 if (active && (active->getCacheRatio() < 10000)
902 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
903 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
904 << " isn't over quota, and defy not requested";
905 break;
906 }
907
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700908 // Find the best tracker to work with; this might involve swapping
909 // if the active tracker is no longer the most over quota
910 bool nextBetter = active && !queue.empty()
911 && active->getCacheRatio() < queue.top()->getCacheRatio();
912 if (!active || nextBetter) {
913 if (active) {
914 // Current tracker still has items, so we'll consider it
915 // again later once it bubbles up to surface
916 queue.push(active);
917 }
918 active = queue.top(); queue.pop();
919 active->ensureItems();
920 continue;
921 }
922
923 // If no items remain, go find another tracker
924 if (active->items.empty()) {
925 active = nullptr;
926 continue;
927 } else {
928 auto item = active->items.back();
929 active->items.pop_back();
930
931 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
932 if (!noop) {
933 item->purge();
934 }
935 active->cacheUsed -= item->size;
936 needed -= item->size;
937 }
938
939 // Verify that we're actually done before bailing, since sneaky
940 // apps might be using hardlinks
941 if (needed <= 0) {
942 free = data_disk_free(data_path);
943 needed = freeStorageSize - free;
944 if (needed <= 0) {
945 break;
946 } else {
947 LOG(WARNING) << "Expected to be done but still need " << needed;
948 }
949 }
950 }
951 ATRACE_END();
952
953 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -0600954 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -0700955 }
956
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700957 free = data_disk_free(data_path);
958 if (free >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700959 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700960 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700961 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700962 freeStorageSize, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700963 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700964}
965
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700966binder::Status InstalldNativeService::rmdex(const std::string& codePath,
967 const std::string& instructionSet) {
968 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700969 std::lock_guard<std::recursive_mutex> lock(mLock);
970
Mike Lockwood94afecf2012-10-24 10:45:23 -0700971 char dex_path[PKG_PATH_MAX];
972
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700973 const char* path = codePath.c_str();
974 const char* instruction_set = instructionSet.c_str();
975
Jeff Sharkey770180a2014-09-08 17:14:26 -0700976 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700977 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700978 }
979
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700980 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700981 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700982 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700983
984 ALOGV("unlink %s\n", dex_path);
985 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700986 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700987 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700988 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700989 }
990}
991
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700992struct stats {
993 int64_t codeSize;
994 int64_t dataSize;
995 int64_t cacheSize;
996};
997
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700998#if MEASURE_DEBUG
999static std::string toString(std::vector<int64_t> values) {
1000 std::stringstream res;
1001 res << "[";
1002 for (size_t i = 0; i < values.size(); i++) {
1003 res << values[i];
1004 if (i < values.size() - 1) {
1005 res << ",";
1006 }
1007 }
1008 res << "]";
1009 return res.str();
1010}
1011#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001012
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001013static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001014 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001015 if (device.empty()) return;
1016
1017 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001018
1019 uid_t uid = multiuser_get_uid(userId, appId);
1020 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1021 reinterpret_cast<char*>(&dq)) != 0) {
1022 if (errno != ESRCH) {
1023 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1024 }
1025 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001026#if MEASURE_DEBUG
1027 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1028#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001029 stats->dataSize += dq.dqb_curspace;
1030 }
1031
1032 int cacheGid = multiuser_get_cache_gid(userId, appId);
1033 if (cacheGid != -1) {
1034 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1035 reinterpret_cast<char*>(&dq)) != 0) {
1036 if (errno != ESRCH) {
1037 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1038 }
1039 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001040#if MEASURE_DEBUG
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001041 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001042#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001043 stats->cacheSize += dq.dqb_curspace;
1044 }
1045 }
1046
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001047 int extGid = multiuser_get_ext_gid(userId, appId);
1048 if (extGid != -1) {
1049 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1050 reinterpret_cast<char*>(&dq)) != 0) {
1051 if (errno != ESRCH) {
1052 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1053 }
1054 } else {
1055#if MEASURE_DEBUG
1056 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
1057#endif
1058 extStats->dataSize += dq.dqb_curspace;
1059 }
1060 }
1061
1062 int sharedGid = multiuser_get_shared_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001063 if (sharedGid != -1) {
1064 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1065 reinterpret_cast<char*>(&dq)) != 0) {
1066 if (errno != ESRCH) {
1067 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1068 }
1069 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001070#if MEASURE_DEBUG
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001071 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001072#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001073 stats->codeSize += dq.dqb_curspace;
1074 }
1075 }
1076}
1077
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001078static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001079 DIR *d;
1080 int dfd;
1081 struct dirent *de;
1082 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001083
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001084 d = opendir(path.c_str());
1085 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001086 if (errno != ENOENT) {
1087 PLOG(WARNING) << "Failed to open " << path;
1088 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001089 return;
1090 }
1091 dfd = dirfd(d);
1092 while ((de = readdir(d))) {
1093 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001094
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001095 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001096 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001097 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001098 }
1099
1100 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001101 if (!strcmp(name, ".")) {
1102 // Don't recurse, but still count node size
1103 } else if (!strcmp(name, "..")) {
1104 // Don't recurse or count node size
1105 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001106 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001107 // Measure all children nodes
1108 size = 0;
1109 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001110 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001111
1112 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1113 stats->cacheSize += size;
1114 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001115 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001116
1117 // Legacy symlink isn't owned by app
1118 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1119 continue;
1120 }
1121
1122 // Everything found inside is considered data
1123 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001124 }
1125 closedir(d);
1126}
1127
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001128static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1129 bool exclude_apps = false) {
1130 DIR *d;
1131 int dfd;
1132 struct dirent *de;
1133 struct stat s;
1134
1135 d = opendir(path.c_str());
1136 if (d == nullptr) {
1137 if (errno != ENOENT) {
1138 PLOG(WARNING) << "Failed to open " << path;
1139 }
1140 return;
1141 }
1142 dfd = dirfd(d);
1143 while ((de = readdir(d))) {
1144 if (de->d_type == DT_DIR) {
1145 const char *name = de->d_name;
1146 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1147 continue;
1148 }
1149 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1150 continue;
1151 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1152 continue;
1153 } else {
1154 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1155 }
1156 }
1157 }
1158 closedir(d);
1159}
1160
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001161static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1162 FTS *fts;
1163 FTSENT *p;
1164 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001165 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001166 PLOG(ERROR) << "Failed to fts_open " << path;
1167 return;
1168 }
1169 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001170 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001171 switch (p->fts_info) {
1172 case FTS_D:
1173 if (p->fts_level == 4
1174 && !strcmp(p->fts_name, "cache")
1175 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1176 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1177 p->fts_number = 1;
1178 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001179 // Fall through to count the directory
1180 case FTS_DEFAULT:
1181 case FTS_F:
1182 case FTS_SL:
1183 case FTS_SLNONE:
1184 int64_t size = (p->fts_statp->st_blocks * 512);
1185 if (p->fts_number == 1) {
1186 stats->cacheSize += size;
1187 }
1188 stats->dataSize += size;
1189 break;
1190 }
1191 }
1192 fts_close(fts);
1193}
1194
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001195binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001196 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1197 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1198 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001199 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001200 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001201 for (auto packageName : packageNames) {
1202 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1203 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001204 // NOTE: Locking is relaxed on this method, since it's limited to
1205 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001206
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001207 // When modifying this logic, always verify using tests:
1208 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1209
1210#if MEASURE_DEBUG
1211 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1212#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001213
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001214 // Here's a summary of the common storage locations across the platform,
1215 // and how they're each tagged:
1216 //
1217 // /data/app/com.example UID system
1218 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001219 // /data/user/0/com.example UID u0_a10 GID u0_a10
1220 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1221 // /data/media/0/foo.txt UID u0_media_rw
1222 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1223 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1224 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1225 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001226
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001227 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001228 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001229 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001230 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001231
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001232 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001233
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001234 auto device = findQuotaDeviceForUuid(uuid);
1235 if (device.empty()) {
1236 flags &= ~FLAG_USE_QUOTA;
1237 }
1238
Jeff Sharkey466459b2017-01-17 15:25:01 -07001239 ATRACE_BEGIN("obb");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001240 for (auto packageName : packageNames) {
1241 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1242 calculate_tree_size(obbCodePath, &extStats.codeSize);
1243 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001244 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001245
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001246 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001247 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001248 for (auto codePath : codePaths) {
1249 calculate_tree_size(codePath, &stats.codeSize, -1,
1250 multiuser_get_shared_gid(userId, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001251 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001252 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001253
Jeff Sharkey466459b2017-01-17 15:25:01 -07001254 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001255 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001256 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001257
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001258 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001259 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001260 for (auto codePath : codePaths) {
1261 calculate_tree_size(codePath, &stats.codeSize);
1262 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001263 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001264
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001265 for (size_t i = 0; i < packageNames.size(); i++) {
1266 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001267
Jeff Sharkey466459b2017-01-17 15:25:01 -07001268 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001269 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1270 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001271 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1272 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001273 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001274
Jeff Sharkey466459b2017-01-17 15:25:01 -07001275 ATRACE_BEGIN("profiles");
Calin Juravle114f0812017-03-08 19:05:07 -08001276 auto userProfilePath = create_primary_current_profile_package_dir_path(userId, pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001277 calculate_tree_size(userProfilePath, &stats.dataSize);
Calin Juravle114f0812017-03-08 19:05:07 -08001278 auto refProfilePath = create_primary_reference_profile_package_dir_path(pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001279 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001280 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001281
Jeff Sharkey466459b2017-01-17 15:25:01 -07001282 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001283 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001284 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001285 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001286 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001287 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001288 }
1289
Jeff Sharkey466459b2017-01-17 15:25:01 -07001290 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001291 int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1292 if (sharedGid != -1) {
1293 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1294 sharedGid, -1);
1295 }
Calin Juravle114f0812017-03-08 19:05:07 -08001296 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001297 multiuser_get_uid(userId, appId), -1);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001298 ATRACE_END();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001299 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001300
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001301 std::vector<int64_t> ret;
1302 ret.push_back(stats.codeSize);
1303 ret.push_back(stats.dataSize);
1304 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001305 ret.push_back(extStats.codeSize);
1306 ret.push_back(extStats.dataSize);
1307 ret.push_back(extStats.cacheSize);
1308#if MEASURE_DEBUG
1309 LOG(DEBUG) << "Final result " << toString(ret);
1310#endif
1311 *_aidl_return = ret;
1312 return ok();
1313}
1314
1315binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1316 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1317 std::vector<int64_t>* _aidl_return) {
1318 ENFORCE_UID(AID_SYSTEM);
1319 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001320 // NOTE: Locking is relaxed on this method, since it's limited to
1321 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001322
1323 // When modifying this logic, always verify using tests:
1324 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1325
1326#if MEASURE_DEBUG
1327 LOG(INFO) << "Measuring user " << userId;
1328#endif
1329
1330 struct stats stats;
1331 struct stats extStats;
1332 memset(&stats, 0, sizeof(stats));
1333 memset(&extStats, 0, sizeof(extStats));
1334
1335 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1336
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001337 auto device = findQuotaDeviceForUuid(uuid);
1338 if (device.empty()) {
1339 flags &= ~FLAG_USE_QUOTA;
1340 }
1341
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001342 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001343 struct dqblk dq;
1344
1345 ATRACE_BEGIN("obb");
1346 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1347 reinterpret_cast<char*>(&dq)) != 0) {
1348 if (errno != ESRCH) {
1349 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1350 }
1351 } else {
1352#if MEASURE_DEBUG
1353 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1354#endif
1355 extStats.codeSize += dq.dqb_curspace;
1356 }
1357 ATRACE_END();
1358
Jeff Sharkey466459b2017-01-17 15:25:01 -07001359 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001360 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001361 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001362
Jeff Sharkey466459b2017-01-17 15:25:01 -07001363 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001364 auto cePath = create_data_user_ce_path(uuid_, userId);
1365 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001366 auto dePath = create_data_user_de_path(uuid_, userId);
1367 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001368 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001369
Jeff Sharkey466459b2017-01-17 15:25:01 -07001370 ATRACE_BEGIN("profile");
Calin Juravle114f0812017-03-08 19:05:07 -08001371 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001372 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
Calin Juravle114f0812017-03-08 19:05:07 -08001373 auto refProfilePath = create_primary_ref_profile_dir_path();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001374 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001375 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001376
Jeff Sharkey466459b2017-01-17 15:25:01 -07001377 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001378 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1379 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1380 reinterpret_cast<char*>(&dq)) != 0) {
1381 if (errno != ESRCH) {
1382 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1383 }
1384 } else {
1385#if MEASURE_DEBUG
1386 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001387#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001388 extStats.dataSize += dq.dqb_curspace;
1389 }
1390 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001391
Jeff Sharkey466459b2017-01-17 15:25:01 -07001392 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001393 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1394 -1, -1, true);
Calin Juravle114f0812017-03-08 19:05:07 -08001395 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001396 -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001397 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001398
Jeff Sharkey466459b2017-01-17 15:25:01 -07001399 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001400 for (auto appId : appIds) {
1401 if (appId >= AID_APP_START) {
1402 collectQuotaStats(device, userId, appId, &stats, &extStats);
1403#if MEASURE_DEBUG
1404 // Sleep to make sure we don't lose logs
1405 usleep(1);
1406#endif
1407 }
1408 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001409 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001410 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001411 ATRACE_BEGIN("obb");
1412 auto obbPath = create_data_path(uuid_) + "/media/obb";
1413 calculate_tree_size(obbPath, &extStats.codeSize);
1414 ATRACE_END();
1415
Jeff Sharkey466459b2017-01-17 15:25:01 -07001416 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001417 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001418 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001419
Jeff Sharkey466459b2017-01-17 15:25:01 -07001420 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001421 auto cePath = create_data_user_ce_path(uuid_, userId);
1422 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001423 auto dePath = create_data_user_de_path(uuid_, userId);
1424 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001425 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001426
Jeff Sharkey466459b2017-01-17 15:25:01 -07001427 ATRACE_BEGIN("profile");
Calin Juravle114f0812017-03-08 19:05:07 -08001428 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001429 calculate_tree_size(userProfilePath, &stats.dataSize);
Calin Juravle114f0812017-03-08 19:05:07 -08001430 auto refProfilePath = create_primary_ref_profile_dir_path();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001431 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001432 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001433
Jeff Sharkey466459b2017-01-17 15:25:01 -07001434 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001435 auto dataMediaPath = create_data_media_path(uuid_, userId);
1436 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1437#if MEASURE_DEBUG
1438 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1439 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001440#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001441 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001442
Jeff Sharkey466459b2017-01-17 15:25:01 -07001443 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001444 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
Calin Juravle114f0812017-03-08 19:05:07 -08001445 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001446 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001447 }
1448
1449 std::vector<int64_t> ret;
1450 ret.push_back(stats.codeSize);
1451 ret.push_back(stats.dataSize);
1452 ret.push_back(stats.cacheSize);
1453 ret.push_back(extStats.codeSize);
1454 ret.push_back(extStats.dataSize);
1455 ret.push_back(extStats.cacheSize);
1456#if MEASURE_DEBUG
1457 LOG(DEBUG) << "Final result " << toString(ret);
1458#endif
1459 *_aidl_return = ret;
1460 return ok();
1461}
1462
1463binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1464 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1465 ENFORCE_UID(AID_SYSTEM);
1466 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001467 // NOTE: Locking is relaxed on this method, since it's limited to
1468 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001469
1470 // When modifying this logic, always verify using tests:
1471 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1472
1473#if MEASURE_DEBUG
1474 LOG(INFO) << "Measuring external " << userId;
1475#endif
1476
1477 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1478
1479 int64_t totalSize = 0;
1480 int64_t audioSize = 0;
1481 int64_t videoSize = 0;
1482 int64_t imageSize = 0;
1483
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001484 auto device = findQuotaDeviceForUuid(uuid);
1485 if (device.empty()) {
1486 flags &= ~FLAG_USE_QUOTA;
1487 }
1488
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001489 if (flags & FLAG_USE_QUOTA) {
1490 struct dqblk dq;
1491
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001492 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1493 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1494 reinterpret_cast<char*>(&dq)) != 0) {
1495 if (errno != ESRCH) {
1496 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1497 }
1498 } else {
1499#if MEASURE_DEBUG
1500 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1501#endif
1502 totalSize = dq.dqb_curspace;
1503 }
1504
1505 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1506 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1507 reinterpret_cast<char*>(&dq)) == 0) {
1508#if MEASURE_DEBUG
1509 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1510#endif
1511 audioSize = dq.dqb_curspace;
1512 }
1513 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1514 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1515 reinterpret_cast<char*>(&dq)) == 0) {
1516#if MEASURE_DEBUG
1517 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1518#endif
1519 videoSize = dq.dqb_curspace;
1520 }
1521 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1522 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1523 reinterpret_cast<char*>(&dq)) == 0) {
1524#if MEASURE_DEBUG
1525 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1526#endif
1527 imageSize = dq.dqb_curspace;
1528 }
1529 } else {
1530 FTS *fts;
1531 FTSENT *p;
1532 auto path = create_data_media_path(uuid_, userId);
1533 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001534 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001535 return error("Failed to fts_open " + path);
1536 }
1537 while ((p = fts_read(fts)) != NULL) {
1538 char* ext;
1539 int64_t size = (p->fts_statp->st_blocks * 512);
1540 switch (p->fts_info) {
1541 case FTS_F:
1542 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001543 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001544 ext = strrchr(p->fts_name, '.');
1545 if (ext != nullptr) {
1546 switch (MatchExtension(++ext)) {
1547 case AID_MEDIA_AUDIO: audioSize += size; break;
1548 case AID_MEDIA_VIDEO: videoSize += size; break;
1549 case AID_MEDIA_IMAGE: imageSize += size; break;
1550 }
1551 }
1552 }
1553 // Fall through to always count against total
1554 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001555 // Ignore data belonging to specific apps
1556 p->fts_number = p->fts_parent->fts_number;
1557 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1558 p->fts_number = 1;
1559 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001560 case FTS_DEFAULT:
1561 case FTS_SL:
1562 case FTS_SLNONE:
1563 totalSize += size;
1564 break;
1565 }
1566 }
1567 fts_close(fts);
1568 }
1569
1570 std::vector<int64_t> ret;
1571 ret.push_back(totalSize);
1572 ret.push_back(audioSize);
1573 ret.push_back(videoSize);
1574 ret.push_back(imageSize);
1575#if MEASURE_DEBUG
1576 LOG(DEBUG) << "Final result " << toString(ret);
1577#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001578 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001579 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001580}
1581
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001582binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1583 int32_t userId, int32_t appId, int64_t cacheQuota) {
1584 ENFORCE_UID(AID_SYSTEM);
1585 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001586 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001587
1588 int32_t uid = multiuser_get_uid(userId, appId);
1589 mCacheQuotas[uid] = cacheQuota;
1590
1591 return ok();
1592}
1593
David Sehr6727c2d2016-05-17 16:06:22 -07001594// Dumps the contents of a profile file, using pkgname's dex files for pretty
1595// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001596binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1597 const std::string& codePaths, bool* _aidl_return) {
1598 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001599 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001600 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001601
1602 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001603 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001604
Jeff Sharkey90aff262016-12-12 14:28:24 -07001605 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001606 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001607}
1608
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001609// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001610binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001611 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001612 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001613 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001614 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001615
Calin Juravle114f0812017-03-08 19:05:07 -08001616 *_aidl_return = analyze_primary_profiles(uid, packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001617 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001618}
1619
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001620binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1621 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1622 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1623 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1624 const std::unique_ptr<std::string>& sharedLibraries) {
1625 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001626 CHECK_ARGUMENT_UUID(uuid);
1627 if (packageName && *packageName != "*") {
1628 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1629 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001630 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001631
1632 const char* apk_path = apkPath.c_str();
1633 const char* pkgname = packageName ? packageName->c_str() : "*";
1634 const char* instruction_set = instructionSet.c_str();
1635 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1636 const char* compiler_filter = compilerFilter.c_str();
1637 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1638 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1639
1640 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1641 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001642 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001643}
1644
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001645binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1646 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001647 std::lock_guard<std::recursive_mutex> lock(mLock);
1648
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001649 const char* instruction_set = instructionSet.c_str();
1650
1651 char boot_marker_path[PKG_PATH_MAX];
1652 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001653 "%s/%s/%s/.booting",
1654 android_data_dir.path,
1655 DALVIK_CACHE,
1656 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001657
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001658 ALOGV("mark_boot_complete : %s", boot_marker_path);
1659 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001660 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001661 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001662 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001663}
1664
Mike Lockwood94afecf2012-10-24 10:45:23 -07001665void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1666 struct stat* statbuf)
1667{
1668 while (path[basepos] != 0) {
1669 if (path[basepos] == '/') {
1670 path[basepos] = 0;
1671 if (lstat(path, statbuf) < 0) {
1672 ALOGV("Making directory: %s\n", path);
1673 if (mkdir(path, mode) == 0) {
1674 chown(path, uid, gid);
1675 } else {
1676 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1677 }
1678 }
1679 path[basepos] = '/';
1680 basepos++;
1681 }
1682 basepos++;
1683 }
1684}
1685
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001686binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1687 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1688 const std::string& nativeLibPath32, int32_t userId) {
1689 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001690 CHECK_ARGUMENT_UUID(uuid);
1691 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001692 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001693
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001694 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1695 const char* pkgname = packageName.c_str();
1696 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001697 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001698 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001699
Jeff Sharkey423e7462016-12-09 18:18:43 -07001700 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1701 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001702
1703 const char* pkgdir = _pkgdir.c_str();
1704 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001705
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001706 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001707 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001708 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001709
1710 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001711 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001712 }
1713
1714 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001715 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001716 goto out;
1717 }
1718
1719 if (lstat(libsymlink, &libStat) < 0) {
1720 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001721 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001722 goto out;
1723 }
1724 } else {
1725 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001726 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001727 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001728 goto out;
1729 }
1730 } else if (S_ISLNK(libStat.st_mode)) {
1731 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001732 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001733 goto out;
1734 }
1735 }
1736 }
1737
1738 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001739 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001740 goto out;
1741 }
1742
1743out:
1744 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001745 auto msg = "Failed to cleanup chmod " + _pkgdir;
1746 if (res.isOk()) {
1747 res = error(msg);
1748 } else {
1749 PLOG(ERROR) << msg;
1750 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001751 }
1752
1753 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001754 auto msg = "Failed to cleanup chown " + _pkgdir;
1755 if (res.isOk()) {
1756 res = error(msg);
1757 } else {
1758 PLOG(ERROR) << msg;
1759 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001760 }
1761
Jeff Sharkey423e7462016-12-09 18:18:43 -07001762 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001763}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001764
1765static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1766{
1767 static const char *IDMAP_BIN = "/system/bin/idmap";
1768 static const size_t MAX_INT_LEN = 32;
1769 char idmap_str[MAX_INT_LEN];
1770
1771 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1772
1773 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1774 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1775}
1776
1777// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1778// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1779static int flatten_path(const char *prefix, const char *suffix,
1780 const char *overlay_path, char *idmap_path, size_t N)
1781{
1782 if (overlay_path == NULL || idmap_path == NULL) {
1783 return -1;
1784 }
1785 const size_t len_overlay_path = strlen(overlay_path);
1786 // will access overlay_path + 1 further below; requires absolute path
1787 if (len_overlay_path < 2 || *overlay_path != '/') {
1788 return -1;
1789 }
1790 const size_t len_idmap_root = strlen(prefix);
1791 const size_t len_suffix = strlen(suffix);
1792 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1793 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1794 // additions below would cause overflow
1795 return -1;
1796 }
1797 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1798 return -1;
1799 }
1800 memset(idmap_path, 0, N);
1801 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1802 char *ch = idmap_path + len_idmap_root;
1803 while (*ch != '\0') {
1804 if (*ch == '/') {
1805 *ch = '@';
1806 }
1807 ++ch;
1808 }
1809 return 0;
1810}
1811
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001812binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1813 const std::string& overlayApkPath, int32_t uid) {
1814 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001815 std::lock_guard<std::recursive_mutex> lock(mLock);
1816
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001817 const char* target_apk = targetApkPath.c_str();
1818 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001819 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1820
1821 int idmap_fd = -1;
1822 char idmap_path[PATH_MAX];
1823
1824 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1825 idmap_path, sizeof(idmap_path)) == -1) {
1826 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1827 goto fail;
1828 }
1829
1830 unlink(idmap_path);
1831 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1832 if (idmap_fd < 0) {
1833 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1834 goto fail;
1835 }
1836 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1837 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1838 goto fail;
1839 }
1840 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1841 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1842 goto fail;
1843 }
1844
1845 pid_t pid;
1846 pid = fork();
1847 if (pid == 0) {
1848 /* child -- drop privileges before continuing */
1849 if (setgid(uid) != 0) {
1850 ALOGE("setgid(%d) failed during idmap\n", uid);
1851 exit(1);
1852 }
1853 if (setuid(uid) != 0) {
1854 ALOGE("setuid(%d) failed during idmap\n", uid);
1855 exit(1);
1856 }
1857 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1858 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1859 exit(1);
1860 }
1861
1862 run_idmap(target_apk, overlay_apk, idmap_fd);
1863 exit(1); /* only if exec call to idmap failed */
1864 } else {
1865 int status = wait_child(pid);
1866 if (status != 0) {
1867 ALOGE("idmap failed, status=0x%04x\n", status);
1868 goto fail;
1869 }
1870 }
1871
1872 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001873 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001874fail:
1875 if (idmap_fd >= 0) {
1876 close(idmap_fd);
1877 unlink(idmap_path);
1878 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001879 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001880}
Robert Craige9887e42014-02-20 10:25:56 -05001881
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01001882binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
1883 const char* overlay_apk = overlayApkPath.c_str();
1884 char idmap_path[PATH_MAX];
1885
1886 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1887 idmap_path, sizeof(idmap_path)) == -1) {
1888 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1889 return error();
1890 }
1891 if (unlink(idmap_path) < 0) {
1892 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
1893 return error();
1894 }
1895 return ok();
1896}
1897
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001898binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1899 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1900 const std::string& seInfo) {
1901 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001902 CHECK_ARGUMENT_UUID(uuid);
1903 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001904 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001905
1906 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05001907
Robert Craigda30dc72014-03-27 10:21:12 -04001908 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001909 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001910 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1911 const char* pkgName = packageName.c_str();
1912 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04001913
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001914 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001915 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001916 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001917 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001918 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001919 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001920 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001921 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001922 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001923 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001924 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001925 }
Robert Craige9887e42014-02-20 10:25:56 -05001926 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001927 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001928}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001929
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001930binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1931 const std::string& instructionSet) {
1932 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001933 std::lock_guard<std::recursive_mutex> lock(mLock);
1934
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001935 const char* oat_dir = oatDir.c_str();
1936 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001937 char oat_instr_dir[PKG_PATH_MAX];
1938
1939 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001940 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001941 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001942 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001943 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001944 }
1945 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001946 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001947 }
1948 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001949 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001950 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001951 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001952 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001953}
1954
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001955binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1956 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001957 std::lock_guard<std::recursive_mutex> lock(mLock);
1958
Jeff Sharkey423e7462016-12-09 18:18:43 -07001959 if (validate_apk_path(packageDir.c_str())) {
1960 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001961 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001962 if (delete_dir_contents_and_dir(packageDir) != 0) {
1963 return error("Failed to delete " + packageDir);
1964 }
1965 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001966}
1967
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001968binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1969 const std::string& fromBase, const std::string& toBase) {
1970 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001971 std::lock_guard<std::recursive_mutex> lock(mLock);
1972
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001973 const char* relative_path = relativePath.c_str();
1974 const char* from_base = fromBase.c_str();
1975 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01001976 char from_path[PKG_PATH_MAX];
1977 char to_path[PKG_PATH_MAX];
1978 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1979 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1980
1981 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001982 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001983 }
1984
1985 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001986 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001987 }
1988
Jeff Sharkey423e7462016-12-09 18:18:43 -07001989 if (link(from_path, to_path) < 0) {
1990 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001991 }
1992
Jeff Sharkey423e7462016-12-09 18:18:43 -07001993 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01001994}
1995
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001996binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1997 const std::string& instructionSet, const std::string& outputPath) {
1998 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001999 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002000
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002001 const char* apk_path = apkPath.c_str();
2002 const char* instruction_set = instructionSet.c_str();
2003 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002004
Jeff Sharkey90aff262016-12-12 14:28:24 -07002005 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002006 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002007}
2008
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002009binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2010 const std::string& instructionSet, const std::string& outputPath) {
2011 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002012 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002013
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002014 const char* apk_path = apkPath.c_str();
2015 const char* instruction_set = instructionSet.c_str();
2016 const char* oat_dir = outputPath.c_str();
2017
Jeff Sharkey90aff262016-12-12 14:28:24 -07002018 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2019 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002020}
2021
Calin Juravlebd968362017-01-25 01:17:17 -08002022binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2023 const std::string& dexPath, const std::string& packageName, int32_t uid,
2024 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2025 int32_t storage_flag, bool* _aidl_return) {
2026 ENFORCE_UID(AID_SYSTEM);
2027 CHECK_ARGUMENT_UUID(volumeUuid);
2028 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2029
2030 std::lock_guard<std::recursive_mutex> lock(mLock);
2031 bool result = android::installd::reconcile_secondary_dex_file(
2032 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2033 return result ? ok() : error();
2034}
2035
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002036binder::Status InstalldNativeService::invalidateMounts() {
2037 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002038 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002039
2040 mQuotaDevices.clear();
2041
2042 std::ifstream in("/proc/mounts");
2043 if (!in.is_open()) {
2044 return error("Failed to read mounts");
2045 }
2046
2047 std::string source;
2048 std::string target;
2049 std::string ignored;
2050 struct dqblk dq;
2051 while (!in.eof()) {
2052 std::getline(in, source, ' ');
2053 std::getline(in, target, ' ');
2054 std::getline(in, ignored);
2055
2056 if (source.compare(0, 11, "/dev/block/") == 0) {
2057 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2058 reinterpret_cast<char*>(&dq)) == 0) {
2059 LOG(DEBUG) << "Found " << source << " with quota";
2060 mQuotaDevices[target] = source;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002061
2062 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
2063 // need to kick it again to enable DQUOT_LIMITS_ENABLED.
2064 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2065 && errno != EBUSY) {
2066 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2067 }
2068 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2069 && errno != EBUSY) {
2070 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2071 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002072 }
2073 }
2074 }
2075 return ok();
2076}
2077
2078std::string InstalldNativeService::findQuotaDeviceForUuid(
2079 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002080 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002081 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
2082 return mQuotaDevices[path];
2083}
2084
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002085binder::Status InstalldNativeService::isQuotaSupported(
2086 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2087 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2088 return ok();
2089}
2090
Andreas Gampe02d0de52015-11-11 20:43:16 -08002091} // namespace installd
2092} // namespace android