blob: eac2564209a627f6a115791e460ab9cdc04299d2 [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;
Jeff Sharkeye12d5962017-04-03 16:41:02 -060091static constexpr int FLAG_FORCE = 1 << 16;
Calin Juravle6a1648e2016-02-01 12:12:16 +000092
Jeff Sharkey0274c972016-12-06 09:32:04 -070093namespace {
94
95constexpr const char* kDump = "android.permission.DUMP";
96
Jeff Sharkey423e7462016-12-09 18:18:43 -070097static binder::Status ok() {
98 return binder::Status::ok();
99}
100
101static binder::Status exception(uint32_t code, const std::string& msg) {
102 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
103}
104
105static binder::Status error() {
106 return binder::Status::fromServiceSpecificError(errno);
107}
108
109static binder::Status error(const std::string& msg) {
110 PLOG(ERROR) << msg;
111 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
112}
113
114static binder::Status error(uint32_t code, const std::string& msg) {
115 LOG(ERROR) << msg << " (" << code << ")";
116 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
117}
118
Jeff Sharkey0274c972016-12-06 09:32:04 -0700119binder::Status checkPermission(const char* permission) {
120 pid_t pid;
121 uid_t uid;
122
123 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
124 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700125 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700126 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700127 return exception(binder::Status::EX_SECURITY,
128 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700129 }
130}
131
132binder::Status checkUid(uid_t expectedUid) {
133 uid_t uid = IPCThreadState::self()->getCallingUid();
134 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700135 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700136 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700137 return exception(binder::Status::EX_SECURITY,
138 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
139 }
140}
141
142binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
143 if (!uuid || is_valid_filename(*uuid)) {
144 return ok();
145 } else {
146 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
147 StringPrintf("UUID %s is malformed", uuid->c_str()));
148 }
149}
150
151binder::Status checkArgumentPackageName(const std::string& packageName) {
152 if (is_valid_package_name(packageName.c_str())) {
153 return ok();
154 } else {
155 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
156 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700157 }
158}
159
160#define ENFORCE_UID(uid) { \
161 binder::Status status = checkUid((uid)); \
162 if (!status.isOk()) { \
163 return status; \
164 } \
165}
166
Jeff Sharkey423e7462016-12-09 18:18:43 -0700167#define CHECK_ARGUMENT_UUID(uuid) { \
168 binder::Status status = checkArgumentUuid((uuid)); \
169 if (!status.isOk()) { \
170 return status; \
171 } \
172}
173
174#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
175 binder::Status status = \
176 checkArgumentPackageName((packageName)); \
177 if (!status.isOk()) { \
178 return status; \
179 } \
180}
181
Jeff Sharkey0274c972016-12-06 09:32:04 -0700182} // namespace
183
184status_t InstalldNativeService::start() {
185 IPCThreadState::self()->disableBackgroundScheduling(true);
186 status_t ret = BinderService<InstalldNativeService>::publish();
187 if (ret != android::OK) {
188 return ret;
189 }
190 sp<ProcessState> ps(ProcessState::self());
191 ps->startThreadPool();
192 ps->giveThreadPoolName();
193 return android::OK;
194}
195
196status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700197 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700198 const binder::Status dump_permission = checkPermission(kDump);
199 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700200 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700201 return PERMISSION_DENIED;
202 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700203 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700204
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700205 out << "installd is happy!" << endl;
206
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700207 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600208 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
209 out << endl << "Storage mounts:" << endl;
210 for (const auto& n : mStorageMounts) {
211 out << " " << n.first << " = " << n.second << endl;
212 }
213
214 out << endl << "Quota reverse mounts:" << endl;
215 for (const auto& n : mQuotaReverseMounts) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700216 out << " " << n.first << " = " << n.second << endl;
217 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700218 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700219
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700220 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600221 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700222 out << endl << "Per-UID cache quotas:" << endl;
223 for (const auto& n : mCacheQuotas) {
224 out << " " << n.first << " = " << n.second << endl;
225 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700226 }
227
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700228 out << endl;
229 out.flush();
230
Jeff Sharkey0274c972016-12-06 09:32:04 -0700231 return NO_ERROR;
232}
233
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600234/**
235 * Perform restorecon of the given path, but only perform recursive restorecon
236 * if the label of that top-level file actually changed. This can save us
237 * significant time by avoiding no-op traversals of large filesystem trees.
238 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700239static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
240 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600241 int res = 0;
242 char* before = nullptr;
243 char* after = nullptr;
244
245 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
246 // libselinux. Not needed here.
247
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600248 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600249 PLOG(ERROR) << "Failed before getfilecon for " << path;
250 goto fail;
251 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700252 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600253 PLOG(ERROR) << "Failed top-level restorecon for " << path;
254 goto fail;
255 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600256 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600257 PLOG(ERROR) << "Failed after getfilecon for " << path;
258 goto fail;
259 }
260
261 // If the initial top-level restorecon above changed the label, then go
262 // back and restorecon everything recursively
263 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700264 if (existing) {
265 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
266 << path << "; running recursive restorecon";
267 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700268 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600269 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
270 PLOG(ERROR) << "Failed recursive restorecon for " << path;
271 goto fail;
272 }
273 }
274
275 goto done;
276fail:
277 res = -1;
278done:
279 free(before);
280 free(after);
281 return res;
282}
283
Jeff Sharkey0274c972016-12-06 09:32:04 -0700284static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700285 const std::string& seInfo, uid_t uid, bool existing) {
286 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
287 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600288}
289
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600290static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600291 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
292 PLOG(ERROR) << "Failed to prepare " << path;
293 return -1;
294 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600295 return 0;
296}
297
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600298/**
299 * Ensure that we have a hard-limit quota to protect against abusive apps;
300 * they should never use more than 90% of blocks or 50% of inodes.
301 */
302static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
303 uid_t uid) {
304 if (device.empty()) return 0;
305
306 struct dqblk dq;
307 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
308 reinterpret_cast<char*>(&dq)) != 0) {
309 PLOG(WARNING) << "Failed to find quota for " << uid;
310 return -1;
311 }
312
313 if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
314 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
315 struct statvfs stat;
316 if (statvfs(path.c_str(), &stat) != 0) {
317 PLOG(WARNING) << "Failed to statvfs " << path;
318 return -1;
319 }
320
321 dq.dqb_valid = QIF_LIMITS;
322 dq.dqb_bhardlimit = (((stat.f_blocks * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
323 dq.dqb_ihardlimit = (stat.f_files / 2);
324 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
325 reinterpret_cast<char*>(&dq)) != 0) {
326 PLOG(WARNING) << "Failed to set hard quota for " << uid;
327 return -1;
328 } else {
329 LOG(DEBUG) << "Applied hard quotas for " << uid;
330 return 0;
331 }
332 } else {
333 // Hard quota already set; assume it's reasonable
334 return 0;
335 }
336}
337
Jeff Sharkey0274c972016-12-06 09:32:04 -0700338binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
339 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700340 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700341 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700342 CHECK_ARGUMENT_UUID(uuid);
343 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700344 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700345
346 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
347 const char* pkgname = packageName.c_str();
348
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700349 // Assume invalid inode unless filled in below
350 if (_aidl_return != nullptr) *_aidl_return = -1;
351
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700352 int32_t uid = multiuser_get_uid(userId, appId);
353 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700354 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
355
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700356 // If UID doesn't have a specific cache GID, use UID value
357 if (cacheGid == -1) {
358 cacheGid = uid;
359 }
360
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700361 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700362 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700363 bool existing = (access(path.c_str(), F_OK) == 0);
364
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700365 if (prepare_app_dir(path, targetMode, uid) ||
366 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
367 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700368 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600369 }
370
371 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700372 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
373 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
374 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700375 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700376 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600377
378 // Remember inode numbers of cache directories so that we can clear
379 // contents while CE storage is locked
380 if (write_path_inode(path, "cache", kXattrInodeCache) ||
381 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700382 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700383 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700384
385 // And return the CE inode of the top-level data directory so we can
386 // clear contents while CE storage is locked
387 if ((_aidl_return != nullptr)
388 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
389 return error("Failed to get_path_inode for " + path);
390 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700391 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700392 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700393 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700394 bool existing = (access(path.c_str(), F_OK) == 0);
395
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700396 if (prepare_app_dir(path, targetMode, uid) ||
397 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
398 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700399 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700400 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000401
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600402 // Consider restorecon over contents if label changed
Jeff Sharkey7b6c8402017-04-15 12:09:22 -0600403 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
404 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
405 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700406 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600407 }
408
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600409 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
410 return error("Failed to set hard quota " + path);
411 }
412
Jeff Sharkey90aff262016-12-12 14:28:24 -0700413 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800414 const std::string profile_dir =
415 create_primary_current_profile_package_dir_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000416 // read-write-execute only for the app user.
Calin Juravle114f0812017-03-08 19:05:07 -0800417 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
418 return error("Failed to prepare " + profile_dir);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000419 }
Calin Juravle114f0812017-03-08 19:05:07 -0800420 const std::string profile_file = create_current_profile_path(userId, pkgname,
421 /*is_secondary_dex*/false);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100422 // read-write only for the app user.
423 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800424 return error("Failed to prepare " + profile_file);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100425 }
Calin Juravle114f0812017-03-08 19:05:07 -0800426 const std::string ref_profile_path =
427 create_primary_reference_profile_package_dir_path(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000428 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
429 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700430 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700431 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000432 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700433 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000434 }
435 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700436 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700437 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700438}
439
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700440binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
441 const std::string& packageName, int32_t userId, int32_t flags) {
442 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700443 CHECK_ARGUMENT_UUID(uuid);
444 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700445 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700446
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700447 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
448 const char* pkgname = packageName.c_str();
449
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700450 // This method only exists to upgrade system apps that have requested
451 // forceDeviceEncrypted, so their default storage always lives in a
452 // consistent location. This only works on non-FBE devices, since we
453 // never want to risk exposing data on a device with real CE/DE storage.
454
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700455 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
456 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700457
458 // If neither directory is marked as default, assume CE is default
459 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
460 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
461 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700462 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700463 }
464 }
465
466 // Migrate default data location if needed
467 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
468 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
469
470 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
471 LOG(WARNING) << "Requested default storage " << target
472 << " is not active; migrating from " << source;
473 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700474 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700475 }
476 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700477 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700478 }
479 }
480
Jeff Sharkey423e7462016-12-09 18:18:43 -0700481 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700482}
483
Calin Juravle6a1648e2016-02-01 12:12:16 +0000484
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700485binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
486 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700487 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700488 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700489
Jeff Sharkey423e7462016-12-09 18:18:43 -0700490 binder::Status res = ok();
Calin Juravle114f0812017-03-08 19:05:07 -0800491 if (!clear_primary_reference_profile(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700492 res = error("Failed to clear reference profile for " + packageName);
493 }
Calin Juravle114f0812017-03-08 19:05:07 -0800494 if (!clear_primary_current_profiles(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700495 res = error("Failed to clear current profiles for " + packageName);
496 }
497 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000498}
499
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700500binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
501 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
502 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700503 CHECK_ARGUMENT_UUID(uuid);
504 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700505 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700506
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700507 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
508 const char* pkgname = packageName.c_str();
509
Jeff Sharkey423e7462016-12-09 18:18:43 -0700510 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700511 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700512 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600513 if (flags & FLAG_CLEAR_CACHE_ONLY) {
514 path = read_path_inode(path, "cache", kXattrInodeCache);
515 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
516 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
517 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700518 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700519 if (delete_dir_contents(path) != 0) {
520 res = error("Failed to delete contents of " + path);
521 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700522 }
523 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700524 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600525 std::string suffix = "";
526 bool only_cache = false;
527 if (flags & FLAG_CLEAR_CACHE_ONLY) {
528 suffix = CACHE_DIR_POSTFIX;
529 only_cache = true;
530 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
531 suffix = CODE_CACHE_DIR_POSTFIX;
532 only_cache = true;
533 }
534
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700535 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700536 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700537 if (delete_dir_contents(path) != 0) {
538 res = error("Failed to delete contents of " + path);
539 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700540 }
Calin Juravleedae6692016-03-23 13:55:31 +0000541 if (!only_cache) {
Calin Juravle114f0812017-03-08 19:05:07 -0800542 if (!clear_primary_current_profile(packageName, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700543 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000544 }
545 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700546 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700548}
549
Calin Juravle76268c52017-03-09 13:19:42 -0800550static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100551 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800552 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100553 /*ignore_if_missing*/ true);
554}
555
Calin Juravle76268c52017-03-09 13:19:42 -0800556static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100557 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800558 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100559 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000560}
561
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700562binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
563 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700564 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700565 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700566
Jeff Sharkey423e7462016-12-09 18:18:43 -0700567 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000568 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
569 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800570 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700571 res = error("Failed to destroy current profiles for " + packageName);
572 }
Calin Juravleedae6692016-03-23 13:55:31 +0000573 }
Calin Juravle76268c52017-03-09 13:19:42 -0800574 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700575 res = error("Failed to destroy reference profile for " + packageName);
576 }
577 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000578}
579
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700580binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
581 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
582 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700583 CHECK_ARGUMENT_UUID(uuid);
584 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700585 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700586
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700587 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
588 const char* pkgname = packageName.c_str();
589
Jeff Sharkey423e7462016-12-09 18:18:43 -0700590 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700591 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700592 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
593 if (delete_dir_contents_and_dir(path) != 0) {
594 res = error("Failed to delete " + path);
595 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700596 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700597 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700598 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
599 if (delete_dir_contents_and_dir(path) != 0) {
600 res = error("Failed to delete " + path);
601 }
Calin Juravle76268c52017-03-09 13:19:42 -0800602 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100603 // TODO(calin): If the package is still installed by other users it's probably
604 // beneficial to keep the reference profile around.
605 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800606 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700607 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700608 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700609}
610
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600611static gid_t get_cache_gid(uid_t uid) {
612 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
613 return (gid != -1) ? gid : uid;
614}
615
616binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
617 int32_t flags) {
618 ENFORCE_UID(AID_SYSTEM);
619 CHECK_ARGUMENT_UUID(uuid);
620 std::lock_guard<std::recursive_mutex> lock(mLock);
621
622 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
623 for (auto user : get_known_users(uuid_)) {
624 ATRACE_BEGIN("fixup user");
625 FTS* fts;
626 FTSENT* p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600627 auto ce_path = create_data_user_ce_path(uuid_, user);
628 auto de_path = create_data_user_de_path(uuid_, user);
629 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600630 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
631 return error("Failed to fts_open");
632 }
633 while ((p = fts_read(fts)) != nullptr) {
634 if (p->fts_info == FTS_D && p->fts_level == 1) {
635 // Track down inodes of cache directories
636 uint64_t raw = 0;
637 ino_t inode_cache = 0;
638 ino_t inode_code_cache = 0;
639 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
640 inode_cache = raw;
641 }
642 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
643 inode_code_cache = raw;
644 }
645
646 // Figure out expected GID of each child
647 FTSENT* child = fts_children(fts, 0);
648 while (child != nullptr) {
649 if ((child->fts_statp->st_ino == inode_cache)
650 || (child->fts_statp->st_ino == inode_code_cache)
651 || !strcmp(child->fts_name, "cache")
652 || !strcmp(child->fts_name, "code_cache")) {
653 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
654 } else {
655 child->fts_number = p->fts_statp->st_uid;
656 }
657 child = child->fts_link;
658 }
659 } else if (p->fts_level >= 2) {
660 if (p->fts_level > 2) {
661 // Inherit GID from parent once we're deeper into tree
662 p->fts_number = p->fts_parent->fts_number;
663 }
664
665 uid_t uid = p->fts_parent->fts_statp->st_uid;
666 gid_t cache_gid = get_cache_gid(uid);
667 gid_t expected = p->fts_number;
668 gid_t actual = p->fts_statp->st_gid;
669 if (actual == expected) {
670#if FIXUP_DEBUG
671 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
672#endif
673 if (!(flags & FLAG_FORCE)) {
674 fts_set(fts, p, FTS_SKIP);
675 }
676 } else if ((actual == uid) || (actual == cache_gid)) {
677 // Only consider fixing up when current GID belongs to app
678 if (p->fts_info != FTS_D) {
679 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
680 << " instead of " << expected;
681 }
682 switch (p->fts_info) {
683 case FTS_DP:
684 // If we're moving towards cache GID, we need to set S_ISGID
685 if (expected == cache_gid) {
686 if (chmod(p->fts_path, 02771) != 0) {
687 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
688 }
689 }
690 // Intentional fall through to also set GID
691 case FTS_F:
692 if (chown(p->fts_path, -1, expected) != 0) {
693 PLOG(WARNING) << "Failed to chown " << p->fts_path;
694 }
695 break;
696 case FTS_SL:
697 case FTS_SLNONE:
698 if (lchown(p->fts_path, -1, expected) != 0) {
699 PLOG(WARNING) << "Failed to chown " << p->fts_path;
700 }
701 break;
702 }
703 } else {
704 // Ignore all other GID transitions, since they're kinda shady
705 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
706 << " instead of " << expected;
707 }
708 }
709 }
710 fts_close(fts);
711 ATRACE_END();
712 }
713 return ok();
714}
715
Jeff Sharkey0274c972016-12-06 09:32:04 -0700716binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
717 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
718 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
719 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700720 ENFORCE_UID(AID_SYSTEM);
721 CHECK_ARGUMENT_UUID(fromUuid);
722 CHECK_ARGUMENT_UUID(toUuid);
723 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700724 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700725
726 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
727 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
728 const char* package_name = packageName.c_str();
729 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700730
Jeff Sharkey423e7462016-12-09 18:18:43 -0700731 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700732 std::vector<userid_t> users = get_known_users(from_uuid);
733
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700734 // Copy app
735 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600736 auto from = create_data_app_package_path(from_uuid, data_app_name);
737 auto to = create_data_app_package_path(to_uuid, data_app_name);
738 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700739
740 char *argv[] = {
741 (char*) kCpPath,
742 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
743 (char*) "-p", /* preserve timestamps, ownership, and permissions */
744 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
745 (char*) "-P", /* Do not follow symlinks [default] */
746 (char*) "-d", /* don't dereference symlinks */
747 (char*) from.c_str(),
748 (char*) to_parent.c_str()
749 };
750
751 LOG(DEBUG) << "Copying " << from << " to " << to;
752 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700753 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700754 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700755 goto fail;
756 }
757
758 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700759 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700760 goto fail;
761 }
762 }
763
764 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700765 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700766
767 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600768 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
769 if (access(from_ce.c_str(), F_OK) != 0) {
770 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700771 continue;
772 }
773
Jeff Sharkey0274c972016-12-06 09:32:04 -0700774 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700775 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700776 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700777 goto fail;
778 }
779
780 char *argv[] = {
781 (char*) kCpPath,
782 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
783 (char*) "-p", /* preserve timestamps, ownership, and permissions */
784 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
785 (char*) "-P", /* Do not follow symlinks [default] */
786 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600787 nullptr,
788 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700789 };
790
Jeff Sharkey51c94492016-05-10 17:46:39 -0600791 {
792 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
793 auto to = create_data_user_de_path(to_uuid, user);
794 argv[6] = (char*) from.c_str();
795 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700796
Jeff Sharkey51c94492016-05-10 17:46:39 -0600797 LOG(DEBUG) << "Copying " << from << " to " << to;
798 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
799 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700800 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600801 goto fail;
802 }
803 }
804 {
805 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
806 auto to = create_data_user_ce_path(to_uuid, user);
807 argv[6] = (char*) from.c_str();
808 argv[7] = (char*) to.c_str();
809
810 LOG(DEBUG) << "Copying " << from << " to " << to;
811 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
812 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700813 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600814 goto fail;
815 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700816 }
817
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700818 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
819 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700820 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700821 goto fail;
822 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700823 }
824
Jeff Sharkey31f08982015-07-07 13:31:37 -0700825 // We let the framework scan the new location and persist that before
826 // deleting the data in the old location; this ordering ensures that
827 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700828 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700829
830fail:
831 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700832 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600833 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700834 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
835 LOG(WARNING) << "Failed to rollback " << to;
836 }
837 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700838 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600839 {
840 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
841 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
842 LOG(WARNING) << "Failed to rollback " << to;
843 }
844 }
845 {
846 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
847 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
848 LOG(WARNING) << "Failed to rollback " << to;
849 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700850 }
851 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700852 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700853}
854
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700855binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
856 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
857 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700858 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700859 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700860
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700861 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600862 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700863 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700864 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700865 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700866 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700867 }
868 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600869
870 // Data under /data/media doesn't have an app, but we still want
871 // to limit it to prevent abuse.
872 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
873 multiuser_get_uid(userId, AID_MEDIA_RW))) {
874 return error("Failed to set hard quota for media_rw");
875 }
876
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700877 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700878}
879
880binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
881 int32_t userId, int32_t flags) {
882 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700883 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700884 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700885
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700886 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700887 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700888 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700889 auto path = create_data_user_de_path(uuid_, userId);
890 if (delete_dir_contents_and_dir(path, true) != 0) {
891 res = error("Failed to delete " + path);
892 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700893 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700894 path = create_data_misc_legacy_path(userId);
895 if (delete_dir_contents_and_dir(path, true) != 0) {
896 res = error("Failed to delete " + path);
897 }
Calin Juravle114f0812017-03-08 19:05:07 -0800898 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700899 if (delete_dir_contents_and_dir(path, true) != 0) {
900 res = error("Failed to delete " + path);
901 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700902 }
Robin Lee095c7632014-04-25 15:05:19 +0100903 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600904 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700905 auto path = create_data_user_ce_path(uuid_, userId);
906 if (delete_dir_contents_and_dir(path, true) != 0) {
907 res = error("Failed to delete " + path);
908 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600909 path = findDataMediaPath(uuid, userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700910 if (delete_dir_contents_and_dir(path, true) != 0) {
911 res = error("Failed to delete " + path);
912 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600913 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700914 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100915}
916
Mike Lockwood94afecf2012-10-24 10:45:23 -0700917/* Try to ensure free_size bytes of storage are available.
918 * Returns 0 on success.
919 * This is rather simple-minded because doing a full LRU would
920 * be potentially memory-intensive, and without atime it would
921 * also require that apps constantly modify file metadata even
922 * when just reading from the cache, which is pretty awful.
923 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700924binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700925 int64_t freeStorageSize, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700926 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700927 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700928 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700929
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700930 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700931 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700932 auto device = findQuotaDeviceForUuid(uuid);
933 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700934
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700935 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700936 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700937 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700938 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700939
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600940 int64_t needed = freeStorageSize - free;
941 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
942 << freeStorageSize << "; needed " << needed;
943
944 if (free >= freeStorageSize) {
945 return ok();
946 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700947
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700948 if (flags & FLAG_FREE_CACHE_V2) {
949 // This new cache strategy fairly removes files from UIDs by deleting
950 // files from the UIDs which are most over their allocated quota
951
952 // 1. Create trackers for every known UID
953 ATRACE_BEGIN("create");
954 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
955 for (auto user : get_known_users(uuid_)) {
956 FTS *fts;
957 FTSENT *p;
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -0600958 auto ce_path = create_data_user_ce_path(uuid_, user);
959 auto de_path = create_data_user_de_path(uuid_, user);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600960 auto media_path = findDataMediaPath(uuid, user) + "/Android/data/";
961 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(),
962 (char*) media_path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700963 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700964 return error("Failed to fts_open");
965 }
966 while ((p = fts_read(fts)) != NULL) {
967 if (p->fts_info == FTS_D && p->fts_level == 1) {
968 uid_t uid = p->fts_statp->st_uid;
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600969 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
970 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
971 + AID_APP_START;
972 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700973 auto search = trackers.find(uid);
974 if (search != trackers.end()) {
975 search->second->addDataPath(p->fts_path);
976 } else {
977 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
978 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
979 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700980 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600981 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700982 tracker->cacheQuota = mCacheQuotas[uid];
983 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700984 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600985#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700986 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600987#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700988 tracker->cacheQuota = 67108864;
989 }
990 trackers[uid] = tracker;
991 }
992 fts_set(fts, p, FTS_SKIP);
993 }
994 }
995 fts_close(fts);
996 }
997 ATRACE_END();
998
999 // 2. Populate tracker stats and insert into priority queue
1000 ATRACE_BEGIN("populate");
1001 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
1002 return (left->getCacheRatio() < right->getCacheRatio());
1003 };
1004 std::priority_queue<std::shared_ptr<CacheTracker>,
1005 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
1006 for (const auto& it : trackers) {
1007 it.second->loadStats();
1008 queue.push(it.second);
1009 }
1010 ATRACE_END();
1011
1012 // 3. Bounce across the queue, freeing items from whichever tracker is
1013 // the most over their assigned quota
1014 ATRACE_BEGIN("bounce");
1015 std::shared_ptr<CacheTracker> active;
1016 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001017 // Only look at apps under quota when explicitly requested
1018 if (active && (active->getCacheRatio() < 10000)
1019 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1020 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1021 << " isn't over quota, and defy not requested";
1022 break;
1023 }
1024
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001025 // Find the best tracker to work with; this might involve swapping
1026 // if the active tracker is no longer the most over quota
1027 bool nextBetter = active && !queue.empty()
1028 && active->getCacheRatio() < queue.top()->getCacheRatio();
1029 if (!active || nextBetter) {
1030 if (active) {
1031 // Current tracker still has items, so we'll consider it
1032 // again later once it bubbles up to surface
1033 queue.push(active);
1034 }
1035 active = queue.top(); queue.pop();
1036 active->ensureItems();
1037 continue;
1038 }
1039
1040 // If no items remain, go find another tracker
1041 if (active->items.empty()) {
1042 active = nullptr;
1043 continue;
1044 } else {
1045 auto item = active->items.back();
1046 active->items.pop_back();
1047
1048 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1049 if (!noop) {
1050 item->purge();
1051 }
1052 active->cacheUsed -= item->size;
1053 needed -= item->size;
1054 }
1055
1056 // Verify that we're actually done before bailing, since sneaky
1057 // apps might be using hardlinks
1058 if (needed <= 0) {
1059 free = data_disk_free(data_path);
1060 needed = freeStorageSize - free;
1061 if (needed <= 0) {
1062 break;
1063 } else {
1064 LOG(WARNING) << "Expected to be done but still need " << needed;
1065 }
1066 }
1067 }
1068 ATRACE_END();
1069
1070 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001071 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001072 }
1073
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001074 free = data_disk_free(data_path);
1075 if (free >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001076 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001077 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001078 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001079 freeStorageSize, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001080 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001081}
1082
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001083binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1084 const std::string& instructionSet) {
1085 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001086 std::lock_guard<std::recursive_mutex> lock(mLock);
1087
Mike Lockwood94afecf2012-10-24 10:45:23 -07001088 char dex_path[PKG_PATH_MAX];
1089
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001090 const char* path = codePath.c_str();
1091 const char* instruction_set = instructionSet.c_str();
1092
Jeff Sharkey770180a2014-09-08 17:14:26 -07001093 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001094 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001095 }
1096
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001097 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001098 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001099 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001100
1101 ALOGV("unlink %s\n", dex_path);
1102 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001103 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001104 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001105 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001106 }
1107}
1108
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001109struct stats {
1110 int64_t codeSize;
1111 int64_t dataSize;
1112 int64_t cacheSize;
1113};
1114
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001115#if MEASURE_DEBUG
1116static std::string toString(std::vector<int64_t> values) {
1117 std::stringstream res;
1118 res << "[";
1119 for (size_t i = 0; i < values.size(); i++) {
1120 res << values[i];
1121 if (i < values.size() - 1) {
1122 res << ",";
1123 }
1124 }
1125 res << "]";
1126 return res.str();
1127}
1128#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001129
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001130static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001131 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001132 if (device.empty()) return;
1133
1134 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001135
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001136 if (stats != nullptr) {
1137 uid_t uid = multiuser_get_uid(userId, appId);
1138 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001139 reinterpret_cast<char*>(&dq)) != 0) {
1140 if (errno != ESRCH) {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001141 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001142 }
1143 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001144#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001145 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001146#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001147 stats->dataSize += dq.dqb_curspace;
1148 }
1149
1150 int cacheGid = multiuser_get_cache_gid(userId, appId);
1151 if (cacheGid != -1) {
1152 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1153 reinterpret_cast<char*>(&dq)) != 0) {
1154 if (errno != ESRCH) {
1155 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1156 }
1157 } else {
1158#if MEASURE_DEBUG
1159 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1160#endif
1161 stats->cacheSize += dq.dqb_curspace;
1162 }
1163 }
1164
1165 int sharedGid = multiuser_get_shared_gid(0, appId);
1166 if (sharedGid != -1) {
1167 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1168 reinterpret_cast<char*>(&dq)) != 0) {
1169 if (errno != ESRCH) {
1170 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1171 }
1172 } else {
1173#if MEASURE_DEBUG
1174 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1175#endif
1176 stats->codeSize += dq.dqb_curspace;
1177 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001178 }
1179 }
1180
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001181 if (extStats != nullptr) {
1182 int extGid = multiuser_get_ext_gid(userId, appId);
1183 if (extGid != -1) {
1184 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1185 reinterpret_cast<char*>(&dq)) != 0) {
1186 if (errno != ESRCH) {
1187 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1188 }
1189 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001190#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001191 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001192#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001193 extStats->dataSize += dq.dqb_curspace;
1194 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001195 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001196
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001197 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1198 if (extCacheGid != -1) {
1199 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extCacheGid,
1200 reinterpret_cast<char*>(&dq)) != 0) {
1201 if (errno != ESRCH) {
1202 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extCacheGid;
1203 }
1204 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001205#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001206 LOG(DEBUG) << "quotactl() for GID " << extCacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001207#endif
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001208 extStats->dataSize += dq.dqb_curspace;
1209 extStats->cacheSize += dq.dqb_curspace;
1210 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001211 }
1212 }
1213}
1214
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001215static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001216 DIR *d;
1217 int dfd;
1218 struct dirent *de;
1219 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001220
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001221 d = opendir(path.c_str());
1222 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001223 if (errno != ENOENT) {
1224 PLOG(WARNING) << "Failed to open " << path;
1225 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001226 return;
1227 }
1228 dfd = dirfd(d);
1229 while ((de = readdir(d))) {
1230 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001231
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001232 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001233 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001234 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001235 }
1236
1237 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001238 if (!strcmp(name, ".")) {
1239 // Don't recurse, but still count node size
1240 } else if (!strcmp(name, "..")) {
1241 // Don't recurse or count node size
1242 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001243 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001244 // Measure all children nodes
1245 size = 0;
1246 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001247 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001248
1249 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1250 stats->cacheSize += size;
1251 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001252 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001253
1254 // Legacy symlink isn't owned by app
1255 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1256 continue;
1257 }
1258
1259 // Everything found inside is considered data
1260 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001261 }
1262 closedir(d);
1263}
1264
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001265static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1266 bool exclude_apps = false) {
1267 DIR *d;
1268 int dfd;
1269 struct dirent *de;
1270 struct stat s;
1271
1272 d = opendir(path.c_str());
1273 if (d == nullptr) {
1274 if (errno != ENOENT) {
1275 PLOG(WARNING) << "Failed to open " << path;
1276 }
1277 return;
1278 }
1279 dfd = dirfd(d);
1280 while ((de = readdir(d))) {
1281 if (de->d_type == DT_DIR) {
1282 const char *name = de->d_name;
1283 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1284 continue;
1285 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001286 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001287 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1288 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001289 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001290 continue;
1291 } else {
1292 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1293 }
1294 }
1295 }
1296 closedir(d);
1297}
1298
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001299static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1300 FTS *fts;
1301 FTSENT *p;
1302 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001303 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001304 PLOG(ERROR) << "Failed to fts_open " << path;
1305 return;
1306 }
1307 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001308 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001309 switch (p->fts_info) {
1310 case FTS_D:
1311 if (p->fts_level == 4
1312 && !strcmp(p->fts_name, "cache")
1313 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1314 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1315 p->fts_number = 1;
1316 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001317 // Fall through to count the directory
1318 case FTS_DEFAULT:
1319 case FTS_F:
1320 case FTS_SL:
1321 case FTS_SLNONE:
1322 int64_t size = (p->fts_statp->st_blocks * 512);
1323 if (p->fts_number == 1) {
1324 stats->cacheSize += size;
1325 }
1326 stats->dataSize += size;
1327 break;
1328 }
1329 }
1330 fts_close(fts);
1331}
1332
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001333binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001334 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1335 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1336 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001337 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001338 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001339 for (auto packageName : packageNames) {
1340 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1341 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001342 // NOTE: Locking is relaxed on this method, since it's limited to
1343 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001344
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001345 // When modifying this logic, always verify using tests:
1346 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1347
1348#if MEASURE_DEBUG
1349 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1350#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001351
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001352 // Here's a summary of the common storage locations across the platform,
1353 // and how they're each tagged:
1354 //
1355 // /data/app/com.example UID system
1356 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001357 // /data/user/0/com.example UID u0_a10 GID u0_a10
1358 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1359 // /data/media/0/foo.txt UID u0_media_rw
1360 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1361 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1362 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1363 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001364
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001365 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001366 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001367 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001368 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001369
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001370 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001371
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001372 auto device = findQuotaDeviceForUuid(uuid);
1373 if (device.empty()) {
1374 flags &= ~FLAG_USE_QUOTA;
1375 }
1376
Jeff Sharkey466459b2017-01-17 15:25:01 -07001377 ATRACE_BEGIN("obb");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001378 for (auto packageName : packageNames) {
1379 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1380 calculate_tree_size(obbCodePath, &extStats.codeSize);
1381 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001382 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001383
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001384 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001385 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001386 for (auto codePath : codePaths) {
1387 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001388 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001389 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001390 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001391
Jeff Sharkey466459b2017-01-17 15:25:01 -07001392 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001393 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001394 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001395 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001396 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001397 for (auto codePath : codePaths) {
1398 calculate_tree_size(codePath, &stats.codeSize);
1399 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001400 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001401
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001402 for (size_t i = 0; i < packageNames.size(); i++) {
1403 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001404
Jeff Sharkey466459b2017-01-17 15:25:01 -07001405 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001406 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1407 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001408 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1409 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001410 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001411
Jeff Sharkey06a61842017-04-15 12:03:31 -06001412 if (!uuid) {
1413 ATRACE_BEGIN("profiles");
1414 calculate_tree_size(
1415 create_primary_current_profile_package_dir_path(userId, pkgname),
1416 &stats.dataSize);
1417 calculate_tree_size(
1418 create_primary_reference_profile_package_dir_path(pkgname),
1419 &stats.codeSize);
1420 ATRACE_END();
1421 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001422
Jeff Sharkey466459b2017-01-17 15:25:01 -07001423 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001424 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001425 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001426 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001427 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001428 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001429 }
1430
Jeff Sharkey06a61842017-04-15 12:03:31 -06001431 if (!uuid) {
1432 ATRACE_BEGIN("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001433 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06001434 if (sharedGid != -1) {
1435 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1436 sharedGid, -1);
1437 }
1438 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001439 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001440 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001441
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001442 std::vector<int64_t> ret;
1443 ret.push_back(stats.codeSize);
1444 ret.push_back(stats.dataSize);
1445 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001446 ret.push_back(extStats.codeSize);
1447 ret.push_back(extStats.dataSize);
1448 ret.push_back(extStats.cacheSize);
1449#if MEASURE_DEBUG
1450 LOG(DEBUG) << "Final result " << toString(ret);
1451#endif
1452 *_aidl_return = ret;
1453 return ok();
1454}
1455
1456binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1457 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1458 std::vector<int64_t>* _aidl_return) {
1459 ENFORCE_UID(AID_SYSTEM);
1460 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001461 // NOTE: Locking is relaxed on this method, since it's limited to
1462 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001463
1464 // When modifying this logic, always verify using tests:
1465 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1466
1467#if MEASURE_DEBUG
1468 LOG(INFO) << "Measuring user " << userId;
1469#endif
1470
1471 struct stats stats;
1472 struct stats extStats;
1473 memset(&stats, 0, sizeof(stats));
1474 memset(&extStats, 0, sizeof(extStats));
1475
1476 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1477
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001478 auto device = findQuotaDeviceForUuid(uuid);
1479 if (device.empty()) {
1480 flags &= ~FLAG_USE_QUOTA;
1481 }
1482
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001483 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001484 struct dqblk dq;
1485
1486 ATRACE_BEGIN("obb");
1487 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1488 reinterpret_cast<char*>(&dq)) != 0) {
1489 if (errno != ESRCH) {
1490 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1491 }
1492 } else {
1493#if MEASURE_DEBUG
1494 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1495#endif
1496 extStats.codeSize += dq.dqb_curspace;
1497 }
1498 ATRACE_END();
1499
Jeff Sharkey466459b2017-01-17 15:25:01 -07001500 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001501 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001502 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001503
Jeff Sharkey466459b2017-01-17 15:25:01 -07001504 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001505 auto cePath = create_data_user_ce_path(uuid_, userId);
1506 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001507 auto dePath = create_data_user_de_path(uuid_, userId);
1508 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001509 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001510
Jeff Sharkey06a61842017-04-15 12:03:31 -06001511 if (!uuid) {
1512 ATRACE_BEGIN("profile");
1513 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1514 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1515 auto refProfilePath = create_primary_ref_profile_dir_path();
1516 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1517 ATRACE_END();
1518 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001519
Jeff Sharkey466459b2017-01-17 15:25:01 -07001520 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001521 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1522 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1523 reinterpret_cast<char*>(&dq)) != 0) {
1524 if (errno != ESRCH) {
1525 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1526 }
1527 } else {
1528#if MEASURE_DEBUG
1529 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001530#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001531 extStats.dataSize += dq.dqb_curspace;
1532 }
1533 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001534
Jeff Sharkey06a61842017-04-15 12:03:31 -06001535 if (!uuid) {
1536 ATRACE_BEGIN("dalvik");
1537 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1538 -1, -1, true);
1539 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1540 -1, -1, true);
1541 ATRACE_END();
1542 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001543
Jeff Sharkey466459b2017-01-17 15:25:01 -07001544 ATRACE_BEGIN("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001545 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001546 for (auto appId : appIds) {
1547 if (appId >= AID_APP_START) {
1548 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001549
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001550#if MEASURE_DEBUG
1551 // Sleep to make sure we don't lose logs
1552 usleep(1);
1553#endif
1554 }
1555 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001556 extStats.dataSize = dataSize;
Jeff Sharkey466459b2017-01-17 15:25:01 -07001557 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001558 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001559 ATRACE_BEGIN("obb");
1560 auto obbPath = create_data_path(uuid_) + "/media/obb";
1561 calculate_tree_size(obbPath, &extStats.codeSize);
1562 ATRACE_END();
1563
Jeff Sharkey466459b2017-01-17 15:25:01 -07001564 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001565 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001566 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001567
Jeff Sharkey466459b2017-01-17 15:25:01 -07001568 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001569 auto cePath = create_data_user_ce_path(uuid_, userId);
1570 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001571 auto dePath = create_data_user_de_path(uuid_, userId);
1572 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001573 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001574
Jeff Sharkey06a61842017-04-15 12:03:31 -06001575 if (!uuid) {
1576 ATRACE_BEGIN("profile");
1577 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1578 calculate_tree_size(userProfilePath, &stats.dataSize);
1579 auto refProfilePath = create_primary_ref_profile_dir_path();
1580 calculate_tree_size(refProfilePath, &stats.codeSize);
1581 ATRACE_END();
1582 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001583
Jeff Sharkey466459b2017-01-17 15:25:01 -07001584 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001585 auto dataMediaPath = create_data_media_path(uuid_, userId);
1586 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1587#if MEASURE_DEBUG
1588 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1589 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001590#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001591 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001592
Jeff Sharkey06a61842017-04-15 12:03:31 -06001593 if (!uuid) {
1594 ATRACE_BEGIN("dalvik");
1595 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1596 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1597 ATRACE_END();
1598 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001599 }
1600
1601 std::vector<int64_t> ret;
1602 ret.push_back(stats.codeSize);
1603 ret.push_back(stats.dataSize);
1604 ret.push_back(stats.cacheSize);
1605 ret.push_back(extStats.codeSize);
1606 ret.push_back(extStats.dataSize);
1607 ret.push_back(extStats.cacheSize);
1608#if MEASURE_DEBUG
1609 LOG(DEBUG) << "Final result " << toString(ret);
1610#endif
1611 *_aidl_return = ret;
1612 return ok();
1613}
1614
1615binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001616 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1617 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001618 ENFORCE_UID(AID_SYSTEM);
1619 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001620 // NOTE: Locking is relaxed on this method, since it's limited to
1621 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001622
1623 // When modifying this logic, always verify using tests:
1624 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1625
1626#if MEASURE_DEBUG
1627 LOG(INFO) << "Measuring external " << userId;
1628#endif
1629
1630 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1631
1632 int64_t totalSize = 0;
1633 int64_t audioSize = 0;
1634 int64_t videoSize = 0;
1635 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001636 int64_t appSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001637
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001638 auto device = findQuotaDeviceForUuid(uuid);
1639 if (device.empty()) {
1640 flags &= ~FLAG_USE_QUOTA;
1641 }
1642
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001643 if (flags & FLAG_USE_QUOTA) {
1644 struct dqblk dq;
1645
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001646 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001647 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1648 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1649 reinterpret_cast<char*>(&dq)) != 0) {
1650 if (errno != ESRCH) {
1651 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1652 }
1653 } else {
1654#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001655 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001656#endif
1657 totalSize = dq.dqb_curspace;
1658 }
1659
1660 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1661 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1662 reinterpret_cast<char*>(&dq)) == 0) {
1663#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001664 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001665#endif
1666 audioSize = dq.dqb_curspace;
1667 }
1668 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1669 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1670 reinterpret_cast<char*>(&dq)) == 0) {
1671#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001672 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001673#endif
1674 videoSize = dq.dqb_curspace;
1675 }
1676 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1677 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1678 reinterpret_cast<char*>(&dq)) == 0) {
1679#if MEASURE_DEBUG
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001680 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001681#endif
1682 imageSize = dq.dqb_curspace;
1683 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001684 ATRACE_END();
1685
1686 ATRACE_BEGIN("apps");
1687 struct stats extStats;
1688 memset(&extStats, 0, sizeof(extStats));
1689 for (auto appId : appIds) {
1690 if (appId >= AID_APP_START) {
1691 collectQuotaStats(device, userId, appId, nullptr, &extStats);
1692 }
1693 }
1694 appSize = extStats.dataSize + extStats.cacheSize;
1695 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001696 } else {
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001697 ATRACE_BEGIN("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001698 FTS *fts;
1699 FTSENT *p;
1700 auto path = create_data_media_path(uuid_, userId);
1701 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001702 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001703 return error("Failed to fts_open " + path);
1704 }
1705 while ((p = fts_read(fts)) != NULL) {
1706 char* ext;
1707 int64_t size = (p->fts_statp->st_blocks * 512);
1708 switch (p->fts_info) {
1709 case FTS_F:
1710 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001711 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001712 ext = strrchr(p->fts_name, '.');
1713 if (ext != nullptr) {
1714 switch (MatchExtension(++ext)) {
1715 case AID_MEDIA_AUDIO: audioSize += size; break;
1716 case AID_MEDIA_VIDEO: videoSize += size; break;
1717 case AID_MEDIA_IMAGE: imageSize += size; break;
1718 }
1719 }
1720 }
1721 // Fall through to always count against total
1722 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001723 // Ignore data belonging to specific apps
1724 p->fts_number = p->fts_parent->fts_number;
1725 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1726 p->fts_number = 1;
1727 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001728 case FTS_DEFAULT:
1729 case FTS_SL:
1730 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001731 if (p->fts_parent->fts_number == 1) {
1732 appSize += size;
1733 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001734 totalSize += size;
1735 break;
1736 }
1737 }
1738 fts_close(fts);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001739 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001740 }
1741
1742 std::vector<int64_t> ret;
1743 ret.push_back(totalSize);
1744 ret.push_back(audioSize);
1745 ret.push_back(videoSize);
1746 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06001747 ret.push_back(appSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001748#if MEASURE_DEBUG
1749 LOG(DEBUG) << "Final result " << toString(ret);
1750#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001751 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001752 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001753}
1754
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001755binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1756 int32_t userId, int32_t appId, int64_t cacheQuota) {
1757 ENFORCE_UID(AID_SYSTEM);
1758 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001759 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001760
1761 int32_t uid = multiuser_get_uid(userId, appId);
1762 mCacheQuotas[uid] = cacheQuota;
1763
1764 return ok();
1765}
1766
David Sehr6727c2d2016-05-17 16:06:22 -07001767// Dumps the contents of a profile file, using pkgname's dex files for pretty
1768// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001769binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1770 const std::string& codePaths, bool* _aidl_return) {
1771 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001772 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001773 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001774
1775 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001776 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001777
Jeff Sharkey90aff262016-12-12 14:28:24 -07001778 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001779 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001780}
1781
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07001782// Copy the contents of a system profile over the data profile.
1783binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
1784 int32_t packageUid, const std::string& packageName, bool* _aidl_return) {
1785 ENFORCE_UID(AID_SYSTEM);
1786 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1787 std::lock_guard<std::recursive_mutex> lock(mLock);
1788 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName);
1789 return ok();
1790}
1791
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001792// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001793binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001794 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001795 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001796 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001797 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001798
Calin Juravle114f0812017-03-08 19:05:07 -08001799 *_aidl_return = analyze_primary_profiles(uid, packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001800 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001801}
1802
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001803binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1804 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1805 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1806 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravlecb556e32017-04-04 20:22:50 -07001807 const std::unique_ptr<std::string>& sharedLibraries,
1808 const std::unique_ptr<std::string>& seInfo) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001809 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001810 CHECK_ARGUMENT_UUID(uuid);
1811 if (packageName && *packageName != "*") {
1812 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1813 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001814 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001815
1816 const char* apk_path = apkPath.c_str();
1817 const char* pkgname = packageName ? packageName->c_str() : "*";
1818 const char* instruction_set = instructionSet.c_str();
1819 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1820 const char* compiler_filter = compilerFilter.c_str();
1821 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1822 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
Calin Juravlecb556e32017-04-04 20:22:50 -07001823 const char* se_info = seInfo ? seInfo->c_str() : nullptr;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001824 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravlecb556e32017-04-04 20:22:50 -07001825 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries, se_info);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001826 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001827}
1828
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001829binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1830 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001831 std::lock_guard<std::recursive_mutex> lock(mLock);
1832
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001833 const char* instruction_set = instructionSet.c_str();
1834
1835 char boot_marker_path[PKG_PATH_MAX];
1836 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001837 "%s/%s/%s/.booting",
1838 android_data_dir.path,
1839 DALVIK_CACHE,
1840 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001841
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001842 ALOGV("mark_boot_complete : %s", boot_marker_path);
1843 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001844 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001845 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001846 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001847}
1848
Mike Lockwood94afecf2012-10-24 10:45:23 -07001849void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1850 struct stat* statbuf)
1851{
1852 while (path[basepos] != 0) {
1853 if (path[basepos] == '/') {
1854 path[basepos] = 0;
1855 if (lstat(path, statbuf) < 0) {
1856 ALOGV("Making directory: %s\n", path);
1857 if (mkdir(path, mode) == 0) {
1858 chown(path, uid, gid);
1859 } else {
1860 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1861 }
1862 }
1863 path[basepos] = '/';
1864 basepos++;
1865 }
1866 basepos++;
1867 }
1868}
1869
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001870binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1871 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1872 const std::string& nativeLibPath32, int32_t userId) {
1873 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001874 CHECK_ARGUMENT_UUID(uuid);
1875 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001876 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001877
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001878 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1879 const char* pkgname = packageName.c_str();
1880 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001881 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001882 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001883
Jeff Sharkey423e7462016-12-09 18:18:43 -07001884 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1885 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001886
1887 const char* pkgdir = _pkgdir.c_str();
1888 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001889
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001890 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001891 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001892 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001893
1894 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001895 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001896 }
1897
1898 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001899 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001900 goto out;
1901 }
1902
1903 if (lstat(libsymlink, &libStat) < 0) {
1904 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001905 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001906 goto out;
1907 }
1908 } else {
1909 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001910 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001911 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001912 goto out;
1913 }
1914 } else if (S_ISLNK(libStat.st_mode)) {
1915 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001916 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001917 goto out;
1918 }
1919 }
1920 }
1921
1922 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001923 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001924 goto out;
1925 }
1926
1927out:
1928 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001929 auto msg = "Failed to cleanup chmod " + _pkgdir;
1930 if (res.isOk()) {
1931 res = error(msg);
1932 } else {
1933 PLOG(ERROR) << msg;
1934 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001935 }
1936
1937 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001938 auto msg = "Failed to cleanup chown " + _pkgdir;
1939 if (res.isOk()) {
1940 res = error(msg);
1941 } else {
1942 PLOG(ERROR) << msg;
1943 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001944 }
1945
Jeff Sharkey423e7462016-12-09 18:18:43 -07001946 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001947}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001948
1949static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1950{
1951 static const char *IDMAP_BIN = "/system/bin/idmap";
1952 static const size_t MAX_INT_LEN = 32;
1953 char idmap_str[MAX_INT_LEN];
1954
1955 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1956
1957 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1958 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1959}
1960
1961// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1962// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1963static int flatten_path(const char *prefix, const char *suffix,
1964 const char *overlay_path, char *idmap_path, size_t N)
1965{
1966 if (overlay_path == NULL || idmap_path == NULL) {
1967 return -1;
1968 }
1969 const size_t len_overlay_path = strlen(overlay_path);
1970 // will access overlay_path + 1 further below; requires absolute path
1971 if (len_overlay_path < 2 || *overlay_path != '/') {
1972 return -1;
1973 }
1974 const size_t len_idmap_root = strlen(prefix);
1975 const size_t len_suffix = strlen(suffix);
1976 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1977 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1978 // additions below would cause overflow
1979 return -1;
1980 }
1981 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1982 return -1;
1983 }
1984 memset(idmap_path, 0, N);
1985 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1986 char *ch = idmap_path + len_idmap_root;
1987 while (*ch != '\0') {
1988 if (*ch == '/') {
1989 *ch = '@';
1990 }
1991 ++ch;
1992 }
1993 return 0;
1994}
1995
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001996binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1997 const std::string& overlayApkPath, int32_t uid) {
1998 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001999 std::lock_guard<std::recursive_mutex> lock(mLock);
2000
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002001 const char* target_apk = targetApkPath.c_str();
2002 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002003 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
2004
2005 int idmap_fd = -1;
2006 char idmap_path[PATH_MAX];
Jaekyun Seok1d091462017-04-19 11:01:38 +09002007 struct stat target_apk_stat, overlay_apk_stat, idmap_stat;
2008 bool outdated = false;
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002009
2010 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2011 idmap_path, sizeof(idmap_path)) == -1) {
2012 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2013 goto fail;
2014 }
2015
Jaekyun Seok1d091462017-04-19 11:01:38 +09002016 if (stat(idmap_path, &idmap_stat) < 0 ||
2017 stat(target_apk, &target_apk_stat) < 0 ||
2018 stat(overlay_apk, &overlay_apk_stat) < 0) {
2019 outdated = true;
2020 } else if (idmap_stat.st_mtime < target_apk_stat.st_mtime ||
2021 idmap_stat.st_mtime < overlay_apk_stat.st_mtime) {
2022 outdated = true;
2023 }
2024
2025 if (outdated) {
2026 unlink(idmap_path);
2027 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
2028 } else {
2029 idmap_fd = open(idmap_path, O_RDWR);
2030 }
2031
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002032 if (idmap_fd < 0) {
2033 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
2034 goto fail;
2035 }
2036 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
2037 ALOGE("idmap cannot chown '%s'\n", idmap_path);
2038 goto fail;
2039 }
2040 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
2041 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
2042 goto fail;
2043 }
2044
Jaekyun Seok1d091462017-04-19 11:01:38 +09002045 if (!outdated) {
2046 close(idmap_fd);
2047 return ok();
2048 }
2049
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002050 pid_t pid;
2051 pid = fork();
2052 if (pid == 0) {
2053 /* child -- drop privileges before continuing */
2054 if (setgid(uid) != 0) {
2055 ALOGE("setgid(%d) failed during idmap\n", uid);
2056 exit(1);
2057 }
2058 if (setuid(uid) != 0) {
2059 ALOGE("setuid(%d) failed during idmap\n", uid);
2060 exit(1);
2061 }
2062 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2063 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2064 exit(1);
2065 }
2066
2067 run_idmap(target_apk, overlay_apk, idmap_fd);
2068 exit(1); /* only if exec call to idmap failed */
2069 } else {
2070 int status = wait_child(pid);
2071 if (status != 0) {
2072 ALOGE("idmap failed, status=0x%04x\n", status);
2073 goto fail;
2074 }
2075 }
2076
2077 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002078 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002079fail:
2080 if (idmap_fd >= 0) {
2081 close(idmap_fd);
2082 unlink(idmap_path);
2083 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002084 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002085}
Robert Craige9887e42014-02-20 10:25:56 -05002086
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002087binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
2088 const char* overlay_apk = overlayApkPath.c_str();
2089 char idmap_path[PATH_MAX];
2090
2091 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2092 idmap_path, sizeof(idmap_path)) == -1) {
2093 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2094 return error();
2095 }
2096 if (unlink(idmap_path) < 0) {
2097 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2098 return error();
2099 }
2100 return ok();
2101}
2102
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002103binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2104 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2105 const std::string& seInfo) {
2106 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002107 CHECK_ARGUMENT_UUID(uuid);
2108 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002109 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002110
2111 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002112
Robert Craigda30dc72014-03-27 10:21:12 -04002113 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002114 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002115 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2116 const char* pkgName = packageName.c_str();
2117 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002118
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002119 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002120 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002121 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002122 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002123 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002124 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002125 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002126 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002127 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002128 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002129 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002130 }
Robert Craige9887e42014-02-20 10:25:56 -05002131 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002132 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002133}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002134
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002135binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2136 const std::string& instructionSet) {
2137 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002138 std::lock_guard<std::recursive_mutex> lock(mLock);
2139
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002140 const char* oat_dir = oatDir.c_str();
2141 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002142 char oat_instr_dir[PKG_PATH_MAX];
2143
2144 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002145 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002146 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002147 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002148 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002149 }
2150 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002151 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002152 }
2153 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002154 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002155 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002156 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002157 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002158}
2159
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002160binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2161 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002162 std::lock_guard<std::recursive_mutex> lock(mLock);
2163
Jeff Sharkey423e7462016-12-09 18:18:43 -07002164 if (validate_apk_path(packageDir.c_str())) {
2165 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002166 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002167 if (delete_dir_contents_and_dir(packageDir) != 0) {
2168 return error("Failed to delete " + packageDir);
2169 }
2170 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002171}
2172
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002173binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2174 const std::string& fromBase, const std::string& toBase) {
2175 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002176 std::lock_guard<std::recursive_mutex> lock(mLock);
2177
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002178 const char* relative_path = relativePath.c_str();
2179 const char* from_base = fromBase.c_str();
2180 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002181 char from_path[PKG_PATH_MAX];
2182 char to_path[PKG_PATH_MAX];
2183 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2184 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2185
2186 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002187 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002188 }
2189
2190 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002191 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002192 }
2193
Jeff Sharkey423e7462016-12-09 18:18:43 -07002194 if (link(from_path, to_path) < 0) {
2195 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002196 }
2197
Jeff Sharkey423e7462016-12-09 18:18:43 -07002198 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002199}
2200
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002201binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2202 const std::string& instructionSet, const std::string& outputPath) {
2203 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002204 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002205
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002206 const char* apk_path = apkPath.c_str();
2207 const char* instruction_set = instructionSet.c_str();
2208 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002209
Jeff Sharkey90aff262016-12-12 14:28:24 -07002210 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002211 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002212}
2213
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002214binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2215 const std::string& instructionSet, const std::string& outputPath) {
2216 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002217 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002218
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002219 const char* apk_path = apkPath.c_str();
2220 const char* instruction_set = instructionSet.c_str();
2221 const char* oat_dir = outputPath.c_str();
2222
Jeff Sharkey90aff262016-12-12 14:28:24 -07002223 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2224 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002225}
2226
Calin Juravlebd968362017-01-25 01:17:17 -08002227binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2228 const std::string& dexPath, const std::string& packageName, int32_t uid,
2229 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2230 int32_t storage_flag, bool* _aidl_return) {
2231 ENFORCE_UID(AID_SYSTEM);
2232 CHECK_ARGUMENT_UUID(volumeUuid);
2233 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2234
2235 std::lock_guard<std::recursive_mutex> lock(mLock);
2236 bool result = android::installd::reconcile_secondary_dex_file(
2237 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2238 return result ? ok() : error();
2239}
2240
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002241binder::Status InstalldNativeService::invalidateMounts() {
2242 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002243 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002244
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002245 mStorageMounts.clear();
2246 mQuotaReverseMounts.clear();
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002247
2248 std::ifstream in("/proc/mounts");
2249 if (!in.is_open()) {
2250 return error("Failed to read mounts");
2251 }
2252
2253 std::string source;
2254 std::string target;
2255 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002256 while (!in.eof()) {
2257 std::getline(in, source, ' ');
2258 std::getline(in, target, ' ');
2259 std::getline(in, ignored);
2260
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002261#if !BYPASS_SDCARDFS
2262 if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
2263 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
2264 mStorageMounts[source] = target;
2265 }
2266#endif
2267
2268#if !BYPASS_QUOTA
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002269 if (source.compare(0, 11, "/dev/block/") == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002270 struct dqblk dq;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002271 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2272 reinterpret_cast<char*>(&dq)) == 0) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002273 LOG(DEBUG) << "Found quota mount " << source << " at " << target;
2274 mQuotaReverseMounts[target] = source;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002275
2276 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
2277 // need to kick it again to enable DQUOT_LIMITS_ENABLED.
2278 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2279 && errno != EBUSY) {
2280 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2281 }
2282 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2283 && errno != EBUSY) {
2284 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2285 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002286 }
2287 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002288#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002289 }
2290 return ok();
2291}
2292
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002293std::string InstalldNativeService::findDataMediaPath(
2294 const std::unique_ptr<std::string>& uuid, userid_t userid) {
2295 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
2296 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2297 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
2298 auto resolved = mStorageMounts[path];
2299 if (resolved.empty()) {
2300 LOG(WARNING) << "Failed to find storage mount for " << path;
2301 resolved = path;
2302 }
2303 return StringPrintf("%s/%u", resolved.c_str(), userid);
2304}
2305
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002306std::string InstalldNativeService::findQuotaDeviceForUuid(
2307 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002308 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002309 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002310 return mQuotaReverseMounts[path];
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002311}
2312
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002313binder::Status InstalldNativeService::isQuotaSupported(
2314 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2315 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2316 return ok();
2317}
2318
Andreas Gampe02d0de52015-11-11 20:43:16 -08002319} // namespace installd
2320} // namespace android