blob: 4946b4d51bb163b54800ed532edc6c371506f604 [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 {
208 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
209 out << endl << "Devices with quota support:" << endl;
210 for (const auto& n : mQuotaDevices) {
211 out << " " << n.first << " = " << n.second << endl;
212 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700213 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700214
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700215 {
216 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
217 out << endl << "Per-UID cache quotas:" << endl;
218 for (const auto& n : mCacheQuotas) {
219 out << " " << n.first << " = " << n.second << endl;
220 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700221 }
222
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700223 out << endl;
224 out.flush();
225
Jeff Sharkey0274c972016-12-06 09:32:04 -0700226 return NO_ERROR;
227}
228
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600229/**
230 * Perform restorecon of the given path, but only perform recursive restorecon
231 * if the label of that top-level file actually changed. This can save us
232 * significant time by avoiding no-op traversals of large filesystem trees.
233 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700234static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
235 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600236 int res = 0;
237 char* before = nullptr;
238 char* after = nullptr;
239
240 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
241 // libselinux. Not needed here.
242
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600243 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600244 PLOG(ERROR) << "Failed before getfilecon for " << path;
245 goto fail;
246 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700247 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600248 PLOG(ERROR) << "Failed top-level restorecon for " << path;
249 goto fail;
250 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600251 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600252 PLOG(ERROR) << "Failed after getfilecon for " << path;
253 goto fail;
254 }
255
256 // If the initial top-level restorecon above changed the label, then go
257 // back and restorecon everything recursively
258 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700259 if (existing) {
260 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
261 << path << "; running recursive restorecon";
262 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700263 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600264 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
265 PLOG(ERROR) << "Failed recursive restorecon for " << path;
266 goto fail;
267 }
268 }
269
270 goto done;
271fail:
272 res = -1;
273done:
274 free(before);
275 free(after);
276 return res;
277}
278
Jeff Sharkey0274c972016-12-06 09:32:04 -0700279static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700280 const std::string& seInfo, uid_t uid, bool existing) {
281 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
282 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600283}
284
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600285static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600286 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
287 PLOG(ERROR) << "Failed to prepare " << path;
288 return -1;
289 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600290 return 0;
291}
292
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600293/**
294 * Ensure that we have a hard-limit quota to protect against abusive apps;
295 * they should never use more than 90% of blocks or 50% of inodes.
296 */
297static int prepare_app_quota(const std::unique_ptr<std::string>& uuid, const std::string& device,
298 uid_t uid) {
299 if (device.empty()) return 0;
300
301 struct dqblk dq;
302 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
303 reinterpret_cast<char*>(&dq)) != 0) {
304 PLOG(WARNING) << "Failed to find quota for " << uid;
305 return -1;
306 }
307
308 if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
309 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
310 struct statvfs stat;
311 if (statvfs(path.c_str(), &stat) != 0) {
312 PLOG(WARNING) << "Failed to statvfs " << path;
313 return -1;
314 }
315
316 dq.dqb_valid = QIF_LIMITS;
317 dq.dqb_bhardlimit = (((stat.f_blocks * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
318 dq.dqb_ihardlimit = (stat.f_files / 2);
319 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
320 reinterpret_cast<char*>(&dq)) != 0) {
321 PLOG(WARNING) << "Failed to set hard quota for " << uid;
322 return -1;
323 } else {
324 LOG(DEBUG) << "Applied hard quotas for " << uid;
325 return 0;
326 }
327 } else {
328 // Hard quota already set; assume it's reasonable
329 return 0;
330 }
331}
332
Jeff Sharkey0274c972016-12-06 09:32:04 -0700333binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
334 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700335 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700336 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700337 CHECK_ARGUMENT_UUID(uuid);
338 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700339 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700340
341 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
342 const char* pkgname = packageName.c_str();
343
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700344 // Assume invalid inode unless filled in below
345 if (_aidl_return != nullptr) *_aidl_return = -1;
346
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700347 int32_t uid = multiuser_get_uid(userId, appId);
348 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700349 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
350
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700351 // If UID doesn't have a specific cache GID, use UID value
352 if (cacheGid == -1) {
353 cacheGid = uid;
354 }
355
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700356 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700357 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700358 bool existing = (access(path.c_str(), F_OK) == 0);
359
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700360 if (prepare_app_dir(path, targetMode, uid) ||
361 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
362 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700363 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600364 }
365
366 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700367 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
368 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
369 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700370 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700371 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600372
373 // Remember inode numbers of cache directories so that we can clear
374 // contents while CE storage is locked
375 if (write_path_inode(path, "cache", kXattrInodeCache) ||
376 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700377 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700378 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700379
380 // And return the CE inode of the top-level data directory so we can
381 // clear contents while CE storage is locked
382 if ((_aidl_return != nullptr)
383 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
384 return error("Failed to get_path_inode for " + path);
385 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700386 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700387 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700388 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700389 bool existing = (access(path.c_str(), F_OK) == 0);
390
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700391 if (prepare_app_dir(path, targetMode, uid) ||
392 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
393 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700394 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700395 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000396
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600397 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700398 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700399 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600400 }
401
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600402 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
403 return error("Failed to set hard quota " + path);
404 }
405
Jeff Sharkey90aff262016-12-12 14:28:24 -0700406 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Calin Juravle114f0812017-03-08 19:05:07 -0800407 const std::string profile_dir =
408 create_primary_current_profile_package_dir_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000409 // read-write-execute only for the app user.
Calin Juravle114f0812017-03-08 19:05:07 -0800410 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
411 return error("Failed to prepare " + profile_dir);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000412 }
Calin Juravle114f0812017-03-08 19:05:07 -0800413 const std::string profile_file = create_current_profile_path(userId, pkgname,
414 /*is_secondary_dex*/false);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100415 // read-write only for the app user.
416 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Calin Juravle114f0812017-03-08 19:05:07 -0800417 return error("Failed to prepare " + profile_file);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100418 }
Calin Juravle114f0812017-03-08 19:05:07 -0800419 const std::string ref_profile_path =
420 create_primary_reference_profile_package_dir_path(pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000421 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
422 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700423 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700424 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000425 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700426 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000427 }
428 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700429 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700430 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700431}
432
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700433binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
434 const std::string& packageName, int32_t userId, int32_t flags) {
435 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700436 CHECK_ARGUMENT_UUID(uuid);
437 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700438 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700439
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700440 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
441 const char* pkgname = packageName.c_str();
442
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700443 // This method only exists to upgrade system apps that have requested
444 // forceDeviceEncrypted, so their default storage always lives in a
445 // consistent location. This only works on non-FBE devices, since we
446 // never want to risk exposing data on a device with real CE/DE storage.
447
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700448 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
449 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700450
451 // If neither directory is marked as default, assume CE is default
452 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
453 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
454 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700455 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700456 }
457 }
458
459 // Migrate default data location if needed
460 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
461 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
462
463 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
464 LOG(WARNING) << "Requested default storage " << target
465 << " is not active; migrating from " << source;
466 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700467 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700468 }
469 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700470 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700471 }
472 }
473
Jeff Sharkey423e7462016-12-09 18:18:43 -0700474 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700475}
476
Calin Juravle6a1648e2016-02-01 12:12:16 +0000477
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700478binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
479 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700480 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700481 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700482
Jeff Sharkey423e7462016-12-09 18:18:43 -0700483 binder::Status res = ok();
Calin Juravle114f0812017-03-08 19:05:07 -0800484 if (!clear_primary_reference_profile(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700485 res = error("Failed to clear reference profile for " + packageName);
486 }
Calin Juravle114f0812017-03-08 19:05:07 -0800487 if (!clear_primary_current_profiles(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700488 res = error("Failed to clear current profiles for " + packageName);
489 }
490 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000491}
492
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700493binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
494 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
495 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700496 CHECK_ARGUMENT_UUID(uuid);
497 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700498 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700499
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700500 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
501 const char* pkgname = packageName.c_str();
502
Jeff Sharkey423e7462016-12-09 18:18:43 -0700503 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700504 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700505 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600506 if (flags & FLAG_CLEAR_CACHE_ONLY) {
507 path = read_path_inode(path, "cache", kXattrInodeCache);
508 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
509 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
510 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700511 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700512 if (delete_dir_contents(path) != 0) {
513 res = error("Failed to delete contents of " + path);
514 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700515 }
516 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700517 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600518 std::string suffix = "";
519 bool only_cache = false;
520 if (flags & FLAG_CLEAR_CACHE_ONLY) {
521 suffix = CACHE_DIR_POSTFIX;
522 only_cache = true;
523 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
524 suffix = CODE_CACHE_DIR_POSTFIX;
525 only_cache = true;
526 }
527
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700528 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700529 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700530 if (delete_dir_contents(path) != 0) {
531 res = error("Failed to delete contents of " + path);
532 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700533 }
Calin Juravleedae6692016-03-23 13:55:31 +0000534 if (!only_cache) {
Calin Juravle114f0812017-03-08 19:05:07 -0800535 if (!clear_primary_current_profile(packageName, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700536 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000537 }
538 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700539 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700540 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700541}
542
Calin Juravle76268c52017-03-09 13:19:42 -0800543static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +0100544 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800545 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +0100546 /*ignore_if_missing*/ true);
547}
548
Calin Juravle76268c52017-03-09 13:19:42 -0800549static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100550 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -0800551 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +0100552 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000553}
554
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700555binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
556 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700557 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700558 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700559
Jeff Sharkey423e7462016-12-09 18:18:43 -0700560 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000561 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
562 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -0800563 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700564 res = error("Failed to destroy current profiles for " + packageName);
565 }
Calin Juravleedae6692016-03-23 13:55:31 +0000566 }
Calin Juravle76268c52017-03-09 13:19:42 -0800567 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700568 res = error("Failed to destroy reference profile for " + packageName);
569 }
570 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000571}
572
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700573binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
574 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
575 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700576 CHECK_ARGUMENT_UUID(uuid);
577 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700578 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700579
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700580 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
581 const char* pkgname = packageName.c_str();
582
Jeff Sharkey423e7462016-12-09 18:18:43 -0700583 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700584 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700585 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
586 if (delete_dir_contents_and_dir(path) != 0) {
587 res = error("Failed to delete " + path);
588 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700589 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700590 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700591 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
592 if (delete_dir_contents_and_dir(path) != 0) {
593 res = error("Failed to delete " + path);
594 }
Calin Juravle76268c52017-03-09 13:19:42 -0800595 destroy_app_current_profiles(packageName, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100596 // TODO(calin): If the package is still installed by other users it's probably
597 // beneficial to keep the reference profile around.
598 // Verify if it's ok to do that.
Calin Juravle76268c52017-03-09 13:19:42 -0800599 destroy_app_reference_profile(packageName);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700600 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700601 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700602}
603
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600604static gid_t get_cache_gid(uid_t uid) {
605 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
606 return (gid != -1) ? gid : uid;
607}
608
609binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
610 int32_t flags) {
611 ENFORCE_UID(AID_SYSTEM);
612 CHECK_ARGUMENT_UUID(uuid);
613 std::lock_guard<std::recursive_mutex> lock(mLock);
614
615 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
616 for (auto user : get_known_users(uuid_)) {
617 ATRACE_BEGIN("fixup user");
618 FTS* fts;
619 FTSENT* p;
620 char *argv[] = {
621 (char*) create_data_user_ce_path(uuid_, user).c_str(),
622 (char*) create_data_user_de_path(uuid_, user).c_str(),
623 nullptr
624 };
625 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
626 return error("Failed to fts_open");
627 }
628 while ((p = fts_read(fts)) != nullptr) {
629 if (p->fts_info == FTS_D && p->fts_level == 1) {
630 // Track down inodes of cache directories
631 uint64_t raw = 0;
632 ino_t inode_cache = 0;
633 ino_t inode_code_cache = 0;
634 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
635 inode_cache = raw;
636 }
637 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
638 inode_code_cache = raw;
639 }
640
641 // Figure out expected GID of each child
642 FTSENT* child = fts_children(fts, 0);
643 while (child != nullptr) {
644 if ((child->fts_statp->st_ino == inode_cache)
645 || (child->fts_statp->st_ino == inode_code_cache)
646 || !strcmp(child->fts_name, "cache")
647 || !strcmp(child->fts_name, "code_cache")) {
648 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
649 } else {
650 child->fts_number = p->fts_statp->st_uid;
651 }
652 child = child->fts_link;
653 }
654 } else if (p->fts_level >= 2) {
655 if (p->fts_level > 2) {
656 // Inherit GID from parent once we're deeper into tree
657 p->fts_number = p->fts_parent->fts_number;
658 }
659
660 uid_t uid = p->fts_parent->fts_statp->st_uid;
661 gid_t cache_gid = get_cache_gid(uid);
662 gid_t expected = p->fts_number;
663 gid_t actual = p->fts_statp->st_gid;
664 if (actual == expected) {
665#if FIXUP_DEBUG
666 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
667#endif
668 if (!(flags & FLAG_FORCE)) {
669 fts_set(fts, p, FTS_SKIP);
670 }
671 } else if ((actual == uid) || (actual == cache_gid)) {
672 // Only consider fixing up when current GID belongs to app
673 if (p->fts_info != FTS_D) {
674 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
675 << " instead of " << expected;
676 }
677 switch (p->fts_info) {
678 case FTS_DP:
679 // If we're moving towards cache GID, we need to set S_ISGID
680 if (expected == cache_gid) {
681 if (chmod(p->fts_path, 02771) != 0) {
682 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
683 }
684 }
685 // Intentional fall through to also set GID
686 case FTS_F:
687 if (chown(p->fts_path, -1, expected) != 0) {
688 PLOG(WARNING) << "Failed to chown " << p->fts_path;
689 }
690 break;
691 case FTS_SL:
692 case FTS_SLNONE:
693 if (lchown(p->fts_path, -1, expected) != 0) {
694 PLOG(WARNING) << "Failed to chown " << p->fts_path;
695 }
696 break;
697 }
698 } else {
699 // Ignore all other GID transitions, since they're kinda shady
700 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
701 << " instead of " << expected;
702 }
703 }
704 }
705 fts_close(fts);
706 ATRACE_END();
707 }
708 return ok();
709}
710
Jeff Sharkey0274c972016-12-06 09:32:04 -0700711binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
712 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
713 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
714 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700715 ENFORCE_UID(AID_SYSTEM);
716 CHECK_ARGUMENT_UUID(fromUuid);
717 CHECK_ARGUMENT_UUID(toUuid);
718 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700719 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700720
721 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
722 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
723 const char* package_name = packageName.c_str();
724 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700725
Jeff Sharkey423e7462016-12-09 18:18:43 -0700726 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700727 std::vector<userid_t> users = get_known_users(from_uuid);
728
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700729 // Copy app
730 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600731 auto from = create_data_app_package_path(from_uuid, data_app_name);
732 auto to = create_data_app_package_path(to_uuid, data_app_name);
733 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700734
735 char *argv[] = {
736 (char*) kCpPath,
737 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
738 (char*) "-p", /* preserve timestamps, ownership, and permissions */
739 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
740 (char*) "-P", /* Do not follow symlinks [default] */
741 (char*) "-d", /* don't dereference symlinks */
742 (char*) from.c_str(),
743 (char*) to_parent.c_str()
744 };
745
746 LOG(DEBUG) << "Copying " << from << " to " << to;
747 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700748 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700749 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700750 goto fail;
751 }
752
753 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700754 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700755 goto fail;
756 }
757 }
758
759 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700760 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700761
762 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600763 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
764 if (access(from_ce.c_str(), F_OK) != 0) {
765 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700766 continue;
767 }
768
Jeff Sharkey0274c972016-12-06 09:32:04 -0700769 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700770 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700771 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700772 goto fail;
773 }
774
775 char *argv[] = {
776 (char*) kCpPath,
777 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
778 (char*) "-p", /* preserve timestamps, ownership, and permissions */
779 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
780 (char*) "-P", /* Do not follow symlinks [default] */
781 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600782 nullptr,
783 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700784 };
785
Jeff Sharkey51c94492016-05-10 17:46:39 -0600786 {
787 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
788 auto to = create_data_user_de_path(to_uuid, user);
789 argv[6] = (char*) from.c_str();
790 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700791
Jeff Sharkey51c94492016-05-10 17:46:39 -0600792 LOG(DEBUG) << "Copying " << from << " to " << to;
793 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
794 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700795 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600796 goto fail;
797 }
798 }
799 {
800 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
801 auto to = create_data_user_ce_path(to_uuid, user);
802 argv[6] = (char*) from.c_str();
803 argv[7] = (char*) to.c_str();
804
805 LOG(DEBUG) << "Copying " << from << " to " << to;
806 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
807 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700808 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600809 goto fail;
810 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700811 }
812
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700813 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
814 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700815 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700816 goto fail;
817 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700818 }
819
Jeff Sharkey31f08982015-07-07 13:31:37 -0700820 // We let the framework scan the new location and persist that before
821 // deleting the data in the old location; this ordering ensures that
822 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700823 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700824
825fail:
826 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700827 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600828 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700829 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
830 LOG(WARNING) << "Failed to rollback " << to;
831 }
832 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700833 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600834 {
835 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
836 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
837 LOG(WARNING) << "Failed to rollback " << to;
838 }
839 }
840 {
841 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
842 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
843 LOG(WARNING) << "Failed to rollback " << to;
844 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700845 }
846 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700847 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700848}
849
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700850binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
851 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
852 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700853 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700854 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700855
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700856 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600857 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700858 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700859 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700860 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700861 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700862 }
863 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600864
865 // Data under /data/media doesn't have an app, but we still want
866 // to limit it to prevent abuse.
867 if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
868 multiuser_get_uid(userId, AID_MEDIA_RW))) {
869 return error("Failed to set hard quota for media_rw");
870 }
871
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700872 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700873}
874
875binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
876 int32_t userId, int32_t flags) {
877 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700878 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700879 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700880
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700881 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700882 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700883 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700884 auto path = create_data_user_de_path(uuid_, userId);
885 if (delete_dir_contents_and_dir(path, true) != 0) {
886 res = error("Failed to delete " + path);
887 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700888 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700889 path = create_data_misc_legacy_path(userId);
890 if (delete_dir_contents_and_dir(path, true) != 0) {
891 res = error("Failed to delete " + path);
892 }
Calin Juravle114f0812017-03-08 19:05:07 -0800893 path = create_primary_cur_profile_dir_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700894 if (delete_dir_contents_and_dir(path, true) != 0) {
895 res = error("Failed to delete " + path);
896 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700897 }
Robin Lee095c7632014-04-25 15:05:19 +0100898 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600899 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700900 auto path = create_data_user_ce_path(uuid_, userId);
901 if (delete_dir_contents_and_dir(path, true) != 0) {
902 res = error("Failed to delete " + path);
903 }
904 path = create_data_media_path(uuid_, userId);
905 if (delete_dir_contents_and_dir(path, true) != 0) {
906 res = error("Failed to delete " + path);
907 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600908 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700909 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100910}
911
Mike Lockwood94afecf2012-10-24 10:45:23 -0700912/* Try to ensure free_size bytes of storage are available.
913 * Returns 0 on success.
914 * This is rather simple-minded because doing a full LRU would
915 * be potentially memory-intensive, and without atime it would
916 * also require that apps constantly modify file metadata even
917 * when just reading from the cache, which is pretty awful.
918 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700919binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700920 int64_t freeStorageSize, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700921 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700922 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700923 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700924
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700925 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700926 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700927 auto device = findQuotaDeviceForUuid(uuid);
928 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700929
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700930 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700931 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700932 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700933 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700934
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600935 int64_t needed = freeStorageSize - free;
936 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
937 << freeStorageSize << "; needed " << needed;
938
939 if (free >= freeStorageSize) {
940 return ok();
941 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700942
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700943 if (flags & FLAG_FREE_CACHE_V2) {
944 // This new cache strategy fairly removes files from UIDs by deleting
945 // files from the UIDs which are most over their allocated quota
946
947 // 1. Create trackers for every known UID
948 ATRACE_BEGIN("create");
949 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
950 for (auto user : get_known_users(uuid_)) {
951 FTS *fts;
952 FTSENT *p;
953 char *argv[] = {
954 (char*) create_data_user_ce_path(uuid_, user).c_str(),
955 (char*) create_data_user_de_path(uuid_, user).c_str(),
956 nullptr
957 };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700958 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700959 return error("Failed to fts_open");
960 }
961 while ((p = fts_read(fts)) != NULL) {
962 if (p->fts_info == FTS_D && p->fts_level == 1) {
963 uid_t uid = p->fts_statp->st_uid;
964 auto search = trackers.find(uid);
965 if (search != trackers.end()) {
966 search->second->addDataPath(p->fts_path);
967 } else {
968 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
969 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
970 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700971 {
972 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
973 tracker->cacheQuota = mCacheQuotas[uid];
974 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700975 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600976#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700977 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600978#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700979 tracker->cacheQuota = 67108864;
980 }
981 trackers[uid] = tracker;
982 }
983 fts_set(fts, p, FTS_SKIP);
984 }
985 }
986 fts_close(fts);
987 }
988 ATRACE_END();
989
990 // 2. Populate tracker stats and insert into priority queue
991 ATRACE_BEGIN("populate");
992 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
993 return (left->getCacheRatio() < right->getCacheRatio());
994 };
995 std::priority_queue<std::shared_ptr<CacheTracker>,
996 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
997 for (const auto& it : trackers) {
998 it.second->loadStats();
999 queue.push(it.second);
1000 }
1001 ATRACE_END();
1002
1003 // 3. Bounce across the queue, freeing items from whichever tracker is
1004 // the most over their assigned quota
1005 ATRACE_BEGIN("bounce");
1006 std::shared_ptr<CacheTracker> active;
1007 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07001008 // Only look at apps under quota when explicitly requested
1009 if (active && (active->getCacheRatio() < 10000)
1010 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
1011 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
1012 << " isn't over quota, and defy not requested";
1013 break;
1014 }
1015
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001016 // Find the best tracker to work with; this might involve swapping
1017 // if the active tracker is no longer the most over quota
1018 bool nextBetter = active && !queue.empty()
1019 && active->getCacheRatio() < queue.top()->getCacheRatio();
1020 if (!active || nextBetter) {
1021 if (active) {
1022 // Current tracker still has items, so we'll consider it
1023 // again later once it bubbles up to surface
1024 queue.push(active);
1025 }
1026 active = queue.top(); queue.pop();
1027 active->ensureItems();
1028 continue;
1029 }
1030
1031 // If no items remain, go find another tracker
1032 if (active->items.empty()) {
1033 active = nullptr;
1034 continue;
1035 } else {
1036 auto item = active->items.back();
1037 active->items.pop_back();
1038
1039 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
1040 if (!noop) {
1041 item->purge();
1042 }
1043 active->cacheUsed -= item->size;
1044 needed -= item->size;
1045 }
1046
1047 // Verify that we're actually done before bailing, since sneaky
1048 // apps might be using hardlinks
1049 if (needed <= 0) {
1050 free = data_disk_free(data_path);
1051 needed = freeStorageSize - free;
1052 if (needed <= 0) {
1053 break;
1054 } else {
1055 LOG(WARNING) << "Expected to be done but still need " << needed;
1056 }
1057 }
1058 }
1059 ATRACE_END();
1060
1061 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06001062 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07001063 }
1064
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001065 free = data_disk_free(data_path);
1066 if (free >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001067 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001068 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001069 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001070 freeStorageSize, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001071 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001072}
1073
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001074binder::Status InstalldNativeService::rmdex(const std::string& codePath,
1075 const std::string& instructionSet) {
1076 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001077 std::lock_guard<std::recursive_mutex> lock(mLock);
1078
Mike Lockwood94afecf2012-10-24 10:45:23 -07001079 char dex_path[PKG_PATH_MAX];
1080
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001081 const char* path = codePath.c_str();
1082 const char* instruction_set = instructionSet.c_str();
1083
Jeff Sharkey770180a2014-09-08 17:14:26 -07001084 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001085 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07001086 }
1087
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001088 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001089 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001090 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001091
1092 ALOGV("unlink %s\n", dex_path);
1093 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001094 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001095 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001096 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001097 }
1098}
1099
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001100struct stats {
1101 int64_t codeSize;
1102 int64_t dataSize;
1103 int64_t cacheSize;
1104};
1105
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001106#if MEASURE_DEBUG
1107static std::string toString(std::vector<int64_t> values) {
1108 std::stringstream res;
1109 res << "[";
1110 for (size_t i = 0; i < values.size(); i++) {
1111 res << values[i];
1112 if (i < values.size() - 1) {
1113 res << ",";
1114 }
1115 }
1116 res << "]";
1117 return res.str();
1118}
1119#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001120
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001121static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001122 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001123 if (device.empty()) return;
1124
1125 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001126
1127 uid_t uid = multiuser_get_uid(userId, appId);
1128 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1129 reinterpret_cast<char*>(&dq)) != 0) {
1130 if (errno != ESRCH) {
1131 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1132 }
1133 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001134#if MEASURE_DEBUG
1135 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1136#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001137 stats->dataSize += dq.dqb_curspace;
1138 }
1139
1140 int cacheGid = multiuser_get_cache_gid(userId, appId);
1141 if (cacheGid != -1) {
1142 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1143 reinterpret_cast<char*>(&dq)) != 0) {
1144 if (errno != ESRCH) {
1145 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1146 }
1147 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001148#if MEASURE_DEBUG
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001149 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001150#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001151 stats->cacheSize += dq.dqb_curspace;
1152 }
1153 }
1154
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001155#if HACK_FOR_37193650
1156 extStats->dataSize = extStats->dataSize;
1157#else
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001158 int extGid = multiuser_get_ext_gid(userId, appId);
1159 if (extGid != -1) {
1160 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1161 reinterpret_cast<char*>(&dq)) != 0) {
1162 if (errno != ESRCH) {
1163 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1164 }
1165 } else {
1166#if MEASURE_DEBUG
1167 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
1168#endif
1169 extStats->dataSize += dq.dqb_curspace;
1170 }
1171 }
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001172#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001173
1174 int sharedGid = multiuser_get_shared_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001175 if (sharedGid != -1) {
1176 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1177 reinterpret_cast<char*>(&dq)) != 0) {
1178 if (errno != ESRCH) {
1179 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1180 }
1181 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001182#if MEASURE_DEBUG
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001183 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001184#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001185 stats->codeSize += dq.dqb_curspace;
1186 }
1187 }
1188}
1189
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001190static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001191 DIR *d;
1192 int dfd;
1193 struct dirent *de;
1194 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001195
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001196 d = opendir(path.c_str());
1197 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001198 if (errno != ENOENT) {
1199 PLOG(WARNING) << "Failed to open " << path;
1200 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001201 return;
1202 }
1203 dfd = dirfd(d);
1204 while ((de = readdir(d))) {
1205 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001206
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001207 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001208 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001209 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001210 }
1211
1212 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001213 if (!strcmp(name, ".")) {
1214 // Don't recurse, but still count node size
1215 } else if (!strcmp(name, "..")) {
1216 // Don't recurse or count node size
1217 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001218 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001219 // Measure all children nodes
1220 size = 0;
1221 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001222 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001223
1224 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1225 stats->cacheSize += size;
1226 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001227 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001228
1229 // Legacy symlink isn't owned by app
1230 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1231 continue;
1232 }
1233
1234 // Everything found inside is considered data
1235 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001236 }
1237 closedir(d);
1238}
1239
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001240static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1241 bool exclude_apps = false) {
1242 DIR *d;
1243 int dfd;
1244 struct dirent *de;
1245 struct stat s;
1246
1247 d = opendir(path.c_str());
1248 if (d == nullptr) {
1249 if (errno != ENOENT) {
1250 PLOG(WARNING) << "Failed to open " << path;
1251 }
1252 return;
1253 }
1254 dfd = dirfd(d);
1255 while ((de = readdir(d))) {
1256 if (de->d_type == DT_DIR) {
1257 const char *name = de->d_name;
1258 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1259 continue;
1260 }
1261 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1262 continue;
1263 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1264 continue;
1265 } else {
1266 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1267 }
1268 }
1269 }
1270 closedir(d);
1271}
1272
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001273static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1274 FTS *fts;
1275 FTSENT *p;
1276 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001277 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001278 PLOG(ERROR) << "Failed to fts_open " << path;
1279 return;
1280 }
1281 while ((p = fts_read(fts)) != NULL) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001282 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001283 switch (p->fts_info) {
1284 case FTS_D:
1285 if (p->fts_level == 4
1286 && !strcmp(p->fts_name, "cache")
1287 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1288 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1289 p->fts_number = 1;
1290 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001291 // Fall through to count the directory
1292 case FTS_DEFAULT:
1293 case FTS_F:
1294 case FTS_SL:
1295 case FTS_SLNONE:
1296 int64_t size = (p->fts_statp->st_blocks * 512);
1297 if (p->fts_number == 1) {
1298 stats->cacheSize += size;
1299 }
1300 stats->dataSize += size;
1301 break;
1302 }
1303 }
1304 fts_close(fts);
1305}
1306
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001307binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001308 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1309 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1310 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001311 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001312 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001313 for (auto packageName : packageNames) {
1314 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1315 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001316 // NOTE: Locking is relaxed on this method, since it's limited to
1317 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001318
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001319 // When modifying this logic, always verify using tests:
1320 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1321
1322#if MEASURE_DEBUG
1323 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1324#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001325
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001326 // Here's a summary of the common storage locations across the platform,
1327 // and how they're each tagged:
1328 //
1329 // /data/app/com.example UID system
1330 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001331 // /data/user/0/com.example UID u0_a10 GID u0_a10
1332 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1333 // /data/media/0/foo.txt UID u0_media_rw
1334 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1335 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1336 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1337 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001338
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001339 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001340 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001341 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001342 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001343
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001344 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001345
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001346 auto device = findQuotaDeviceForUuid(uuid);
1347 if (device.empty()) {
1348 flags &= ~FLAG_USE_QUOTA;
1349 }
1350
Jeff Sharkey466459b2017-01-17 15:25:01 -07001351 ATRACE_BEGIN("obb");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001352 for (auto packageName : packageNames) {
1353 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1354 calculate_tree_size(obbCodePath, &extStats.codeSize);
1355 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001356 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001357
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001358 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001359 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001360 for (auto codePath : codePaths) {
1361 calculate_tree_size(codePath, &stats.codeSize, -1,
1362 multiuser_get_shared_gid(userId, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001363 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001364 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001365
Jeff Sharkey466459b2017-01-17 15:25:01 -07001366 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001367 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001368 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001369
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001370#if HACK_FOR_37193650
1371 ATRACE_BEGIN("external");
1372 for (size_t i = 0; i < packageNames.size(); i++) {
1373 const char* pkgname = packageNames[i].c_str();
1374 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
1375 calculate_tree_size(extPath, &extStats.dataSize);
1376 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
1377 calculate_tree_size(mediaPath, &extStats.dataSize);
1378 }
1379 ATRACE_END();
1380#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001381 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001382 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001383 for (auto codePath : codePaths) {
1384 calculate_tree_size(codePath, &stats.codeSize);
1385 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001386 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001387
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001388 for (size_t i = 0; i < packageNames.size(); i++) {
1389 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001390
Jeff Sharkey466459b2017-01-17 15:25:01 -07001391 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001392 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1393 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001394 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1395 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001396 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001397
Jeff Sharkey06a61842017-04-15 12:03:31 -06001398 if (!uuid) {
1399 ATRACE_BEGIN("profiles");
1400 calculate_tree_size(
1401 create_primary_current_profile_package_dir_path(userId, pkgname),
1402 &stats.dataSize);
1403 calculate_tree_size(
1404 create_primary_reference_profile_package_dir_path(pkgname),
1405 &stats.codeSize);
1406 ATRACE_END();
1407 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001408
Jeff Sharkey466459b2017-01-17 15:25:01 -07001409 ATRACE_BEGIN("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001410 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001411 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07001412 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001413 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001414 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001415 }
1416
Jeff Sharkey06a61842017-04-15 12:03:31 -06001417 if (!uuid) {
1418 ATRACE_BEGIN("dalvik");
1419 int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1420 if (sharedGid != -1) {
1421 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1422 sharedGid, -1);
1423 }
1424 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001425 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001426 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001427
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001428 std::vector<int64_t> ret;
1429 ret.push_back(stats.codeSize);
1430 ret.push_back(stats.dataSize);
1431 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001432 ret.push_back(extStats.codeSize);
1433 ret.push_back(extStats.dataSize);
1434 ret.push_back(extStats.cacheSize);
1435#if MEASURE_DEBUG
1436 LOG(DEBUG) << "Final result " << toString(ret);
1437#endif
1438 *_aidl_return = ret;
1439 return ok();
1440}
1441
1442binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1443 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1444 std::vector<int64_t>* _aidl_return) {
1445 ENFORCE_UID(AID_SYSTEM);
1446 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001447 // NOTE: Locking is relaxed on this method, since it's limited to
1448 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001449
1450 // When modifying this logic, always verify using tests:
1451 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1452
1453#if MEASURE_DEBUG
1454 LOG(INFO) << "Measuring user " << userId;
1455#endif
1456
1457 struct stats stats;
1458 struct stats extStats;
1459 memset(&stats, 0, sizeof(stats));
1460 memset(&extStats, 0, sizeof(extStats));
1461
1462 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1463
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001464 auto device = findQuotaDeviceForUuid(uuid);
1465 if (device.empty()) {
1466 flags &= ~FLAG_USE_QUOTA;
1467 }
1468
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001469#if HACK_FOR_37193650
1470 if (userId != 0) {
1471 flags &= ~FLAG_USE_QUOTA;
1472 }
1473#endif
1474
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001475 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001476 struct dqblk dq;
1477
1478 ATRACE_BEGIN("obb");
1479 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1480 reinterpret_cast<char*>(&dq)) != 0) {
1481 if (errno != ESRCH) {
1482 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1483 }
1484 } else {
1485#if MEASURE_DEBUG
1486 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1487#endif
1488 extStats.codeSize += dq.dqb_curspace;
1489 }
1490 ATRACE_END();
1491
Jeff Sharkey466459b2017-01-17 15:25:01 -07001492 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001493 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001494 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001495
Jeff Sharkey466459b2017-01-17 15:25:01 -07001496 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001497 auto cePath = create_data_user_ce_path(uuid_, userId);
1498 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001499 auto dePath = create_data_user_de_path(uuid_, userId);
1500 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001501 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001502
Jeff Sharkey06a61842017-04-15 12:03:31 -06001503 if (!uuid) {
1504 ATRACE_BEGIN("profile");
1505 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1506 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1507 auto refProfilePath = create_primary_ref_profile_dir_path();
1508 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1509 ATRACE_END();
1510 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001511
Jeff Sharkey466459b2017-01-17 15:25:01 -07001512 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001513 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1514 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1515 reinterpret_cast<char*>(&dq)) != 0) {
1516 if (errno != ESRCH) {
1517 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1518 }
1519 } else {
1520#if MEASURE_DEBUG
1521 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001522#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001523 extStats.dataSize += dq.dqb_curspace;
1524 }
1525 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001526
Jeff Sharkey06a61842017-04-15 12:03:31 -06001527 if (!uuid) {
1528 ATRACE_BEGIN("dalvik");
1529 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1530 -1, -1, true);
1531 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1532 -1, -1, true);
1533 ATRACE_END();
1534 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001535
Jeff Sharkey466459b2017-01-17 15:25:01 -07001536 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001537 for (auto appId : appIds) {
1538 if (appId >= AID_APP_START) {
1539 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkeyec1be622017-04-10 00:19:46 -06001540
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001541#if MEASURE_DEBUG
1542 // Sleep to make sure we don't lose logs
1543 usleep(1);
1544#endif
1545 }
1546 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001547 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001548 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001549 ATRACE_BEGIN("obb");
1550 auto obbPath = create_data_path(uuid_) + "/media/obb";
1551 calculate_tree_size(obbPath, &extStats.codeSize);
1552 ATRACE_END();
1553
Jeff Sharkey466459b2017-01-17 15:25:01 -07001554 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001555 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001556 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001557
Jeff Sharkey466459b2017-01-17 15:25:01 -07001558 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001559 auto cePath = create_data_user_ce_path(uuid_, userId);
1560 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001561 auto dePath = create_data_user_de_path(uuid_, userId);
1562 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001563 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001564
Jeff Sharkey06a61842017-04-15 12:03:31 -06001565 if (!uuid) {
1566 ATRACE_BEGIN("profile");
1567 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1568 calculate_tree_size(userProfilePath, &stats.dataSize);
1569 auto refProfilePath = create_primary_ref_profile_dir_path();
1570 calculate_tree_size(refProfilePath, &stats.codeSize);
1571 ATRACE_END();
1572 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001573
Jeff Sharkey466459b2017-01-17 15:25:01 -07001574 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001575 auto dataMediaPath = create_data_media_path(uuid_, userId);
1576 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1577#if MEASURE_DEBUG
1578 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1579 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001580#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001581 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001582
Jeff Sharkey06a61842017-04-15 12:03:31 -06001583 if (!uuid) {
1584 ATRACE_BEGIN("dalvik");
1585 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1586 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1587 ATRACE_END();
1588 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001589 }
1590
1591 std::vector<int64_t> ret;
1592 ret.push_back(stats.codeSize);
1593 ret.push_back(stats.dataSize);
1594 ret.push_back(stats.cacheSize);
1595 ret.push_back(extStats.codeSize);
1596 ret.push_back(extStats.dataSize);
1597 ret.push_back(extStats.cacheSize);
1598#if MEASURE_DEBUG
1599 LOG(DEBUG) << "Final result " << toString(ret);
1600#endif
1601 *_aidl_return = ret;
1602 return ok();
1603}
1604
1605binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1606 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1607 ENFORCE_UID(AID_SYSTEM);
1608 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001609 // NOTE: Locking is relaxed on this method, since it's limited to
1610 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001611
1612 // When modifying this logic, always verify using tests:
1613 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1614
1615#if MEASURE_DEBUG
1616 LOG(INFO) << "Measuring external " << userId;
1617#endif
1618
1619 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1620
1621 int64_t totalSize = 0;
1622 int64_t audioSize = 0;
1623 int64_t videoSize = 0;
1624 int64_t imageSize = 0;
1625
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001626 auto device = findQuotaDeviceForUuid(uuid);
1627 if (device.empty()) {
1628 flags &= ~FLAG_USE_QUOTA;
1629 }
1630
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001631 if (flags & FLAG_USE_QUOTA) {
1632 struct dqblk dq;
1633
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001634 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1635 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1636 reinterpret_cast<char*>(&dq)) != 0) {
1637 if (errno != ESRCH) {
1638 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1639 }
1640 } else {
1641#if MEASURE_DEBUG
1642 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1643#endif
1644 totalSize = dq.dqb_curspace;
1645 }
1646
1647 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1648 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1649 reinterpret_cast<char*>(&dq)) == 0) {
1650#if MEASURE_DEBUG
1651 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1652#endif
1653 audioSize = dq.dqb_curspace;
1654 }
1655 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1656 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1657 reinterpret_cast<char*>(&dq)) == 0) {
1658#if MEASURE_DEBUG
1659 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1660#endif
1661 videoSize = dq.dqb_curspace;
1662 }
1663 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1664 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1665 reinterpret_cast<char*>(&dq)) == 0) {
1666#if MEASURE_DEBUG
1667 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1668#endif
1669 imageSize = dq.dqb_curspace;
1670 }
1671 } else {
1672 FTS *fts;
1673 FTSENT *p;
1674 auto path = create_data_media_path(uuid_, userId);
1675 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001676 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001677 return error("Failed to fts_open " + path);
1678 }
1679 while ((p = fts_read(fts)) != NULL) {
1680 char* ext;
1681 int64_t size = (p->fts_statp->st_blocks * 512);
1682 switch (p->fts_info) {
1683 case FTS_F:
1684 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001685 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001686 ext = strrchr(p->fts_name, '.');
1687 if (ext != nullptr) {
1688 switch (MatchExtension(++ext)) {
1689 case AID_MEDIA_AUDIO: audioSize += size; break;
1690 case AID_MEDIA_VIDEO: videoSize += size; break;
1691 case AID_MEDIA_IMAGE: imageSize += size; break;
1692 }
1693 }
1694 }
1695 // Fall through to always count against total
1696 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06001697 // Ignore data belonging to specific apps
1698 p->fts_number = p->fts_parent->fts_number;
1699 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1700 p->fts_number = 1;
1701 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001702 case FTS_DEFAULT:
1703 case FTS_SL:
1704 case FTS_SLNONE:
1705 totalSize += size;
1706 break;
1707 }
1708 }
1709 fts_close(fts);
1710 }
1711
1712 std::vector<int64_t> ret;
1713 ret.push_back(totalSize);
1714 ret.push_back(audioSize);
1715 ret.push_back(videoSize);
1716 ret.push_back(imageSize);
1717#if MEASURE_DEBUG
1718 LOG(DEBUG) << "Final result " << toString(ret);
1719#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001720 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001721 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001722}
1723
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001724binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1725 int32_t userId, int32_t appId, int64_t cacheQuota) {
1726 ENFORCE_UID(AID_SYSTEM);
1727 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07001728 std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001729
1730 int32_t uid = multiuser_get_uid(userId, appId);
1731 mCacheQuotas[uid] = cacheQuota;
1732
1733 return ok();
1734}
1735
David Sehr6727c2d2016-05-17 16:06:22 -07001736// Dumps the contents of a profile file, using pkgname's dex files for pretty
1737// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001738binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1739 const std::string& codePaths, bool* _aidl_return) {
1740 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001741 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001742 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001743
1744 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001745 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001746
Jeff Sharkey90aff262016-12-12 14:28:24 -07001747 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001748 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001749}
1750
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001751// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001752binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001753 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001754 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001755 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001756 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001757
Calin Juravle114f0812017-03-08 19:05:07 -08001758 *_aidl_return = analyze_primary_profiles(uid, packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001759 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001760}
1761
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001762binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1763 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1764 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1765 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
Calin Juravlecb556e32017-04-04 20:22:50 -07001766 const std::unique_ptr<std::string>& sharedLibraries,
1767 const std::unique_ptr<std::string>& seInfo) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001768 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001769 CHECK_ARGUMENT_UUID(uuid);
1770 if (packageName && *packageName != "*") {
1771 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1772 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001773 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001774
1775 const char* apk_path = apkPath.c_str();
1776 const char* pkgname = packageName ? packageName->c_str() : "*";
1777 const char* instruction_set = instructionSet.c_str();
1778 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1779 const char* compiler_filter = compilerFilter.c_str();
1780 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1781 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
Calin Juravlecb556e32017-04-04 20:22:50 -07001782 const char* se_info = seInfo ? seInfo->c_str() : nullptr;
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001783 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravlecb556e32017-04-04 20:22:50 -07001784 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries, se_info);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001785 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001786}
1787
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001788binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1789 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001790 std::lock_guard<std::recursive_mutex> lock(mLock);
1791
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001792 const char* instruction_set = instructionSet.c_str();
1793
1794 char boot_marker_path[PKG_PATH_MAX];
1795 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001796 "%s/%s/%s/.booting",
1797 android_data_dir.path,
1798 DALVIK_CACHE,
1799 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001800
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001801 ALOGV("mark_boot_complete : %s", boot_marker_path);
1802 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001803 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001804 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001805 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001806}
1807
Mike Lockwood94afecf2012-10-24 10:45:23 -07001808void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1809 struct stat* statbuf)
1810{
1811 while (path[basepos] != 0) {
1812 if (path[basepos] == '/') {
1813 path[basepos] = 0;
1814 if (lstat(path, statbuf) < 0) {
1815 ALOGV("Making directory: %s\n", path);
1816 if (mkdir(path, mode) == 0) {
1817 chown(path, uid, gid);
1818 } else {
1819 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1820 }
1821 }
1822 path[basepos] = '/';
1823 basepos++;
1824 }
1825 basepos++;
1826 }
1827}
1828
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001829binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1830 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1831 const std::string& nativeLibPath32, int32_t userId) {
1832 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001833 CHECK_ARGUMENT_UUID(uuid);
1834 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001835 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001836
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001837 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1838 const char* pkgname = packageName.c_str();
1839 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001840 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001841 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001842
Jeff Sharkey423e7462016-12-09 18:18:43 -07001843 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1844 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001845
1846 const char* pkgdir = _pkgdir.c_str();
1847 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001848
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001849 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001850 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001851 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001852
1853 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001854 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001855 }
1856
1857 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001858 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001859 goto out;
1860 }
1861
1862 if (lstat(libsymlink, &libStat) < 0) {
1863 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001864 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001865 goto out;
1866 }
1867 } else {
1868 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001869 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001870 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001871 goto out;
1872 }
1873 } else if (S_ISLNK(libStat.st_mode)) {
1874 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001875 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001876 goto out;
1877 }
1878 }
1879 }
1880
1881 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001882 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001883 goto out;
1884 }
1885
1886out:
1887 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001888 auto msg = "Failed to cleanup chmod " + _pkgdir;
1889 if (res.isOk()) {
1890 res = error(msg);
1891 } else {
1892 PLOG(ERROR) << msg;
1893 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001894 }
1895
1896 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001897 auto msg = "Failed to cleanup chown " + _pkgdir;
1898 if (res.isOk()) {
1899 res = error(msg);
1900 } else {
1901 PLOG(ERROR) << msg;
1902 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001903 }
1904
Jeff Sharkey423e7462016-12-09 18:18:43 -07001905 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001906}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001907
1908static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1909{
1910 static const char *IDMAP_BIN = "/system/bin/idmap";
1911 static const size_t MAX_INT_LEN = 32;
1912 char idmap_str[MAX_INT_LEN];
1913
1914 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1915
1916 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1917 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1918}
1919
1920// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1921// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1922static int flatten_path(const char *prefix, const char *suffix,
1923 const char *overlay_path, char *idmap_path, size_t N)
1924{
1925 if (overlay_path == NULL || idmap_path == NULL) {
1926 return -1;
1927 }
1928 const size_t len_overlay_path = strlen(overlay_path);
1929 // will access overlay_path + 1 further below; requires absolute path
1930 if (len_overlay_path < 2 || *overlay_path != '/') {
1931 return -1;
1932 }
1933 const size_t len_idmap_root = strlen(prefix);
1934 const size_t len_suffix = strlen(suffix);
1935 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1936 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1937 // additions below would cause overflow
1938 return -1;
1939 }
1940 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1941 return -1;
1942 }
1943 memset(idmap_path, 0, N);
1944 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1945 char *ch = idmap_path + len_idmap_root;
1946 while (*ch != '\0') {
1947 if (*ch == '/') {
1948 *ch = '@';
1949 }
1950 ++ch;
1951 }
1952 return 0;
1953}
1954
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001955binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1956 const std::string& overlayApkPath, int32_t uid) {
1957 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001958 std::lock_guard<std::recursive_mutex> lock(mLock);
1959
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001960 const char* target_apk = targetApkPath.c_str();
1961 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001962 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1963
1964 int idmap_fd = -1;
1965 char idmap_path[PATH_MAX];
1966
1967 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1968 idmap_path, sizeof(idmap_path)) == -1) {
1969 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1970 goto fail;
1971 }
1972
1973 unlink(idmap_path);
1974 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1975 if (idmap_fd < 0) {
1976 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1977 goto fail;
1978 }
1979 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1980 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1981 goto fail;
1982 }
1983 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1984 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1985 goto fail;
1986 }
1987
1988 pid_t pid;
1989 pid = fork();
1990 if (pid == 0) {
1991 /* child -- drop privileges before continuing */
1992 if (setgid(uid) != 0) {
1993 ALOGE("setgid(%d) failed during idmap\n", uid);
1994 exit(1);
1995 }
1996 if (setuid(uid) != 0) {
1997 ALOGE("setuid(%d) failed during idmap\n", uid);
1998 exit(1);
1999 }
2000 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
2001 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
2002 exit(1);
2003 }
2004
2005 run_idmap(target_apk, overlay_apk, idmap_fd);
2006 exit(1); /* only if exec call to idmap failed */
2007 } else {
2008 int status = wait_child(pid);
2009 if (status != 0) {
2010 ALOGE("idmap failed, status=0x%04x\n", status);
2011 goto fail;
2012 }
2013 }
2014
2015 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002016 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002017fail:
2018 if (idmap_fd >= 0) {
2019 close(idmap_fd);
2020 unlink(idmap_path);
2021 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002022 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01002023}
Robert Craige9887e42014-02-20 10:25:56 -05002024
MÃ¥rten Kongstad5c6944c2015-12-15 14:02:30 +01002025binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
2026 const char* overlay_apk = overlayApkPath.c_str();
2027 char idmap_path[PATH_MAX];
2028
2029 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
2030 idmap_path, sizeof(idmap_path)) == -1) {
2031 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
2032 return error();
2033 }
2034 if (unlink(idmap_path) < 0) {
2035 ALOGE("couldn't unlink idmap file %s\n", idmap_path);
2036 return error();
2037 }
2038 return ok();
2039}
2040
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002041binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
2042 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
2043 const std::string& seInfo) {
2044 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002045 CHECK_ARGUMENT_UUID(uuid);
2046 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002047 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002048
2049 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05002050
Robert Craigda30dc72014-03-27 10:21:12 -04002051 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002052 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002053 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2054 const char* pkgName = packageName.c_str();
2055 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04002056
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002057 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002058 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002059 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002060 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002061 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07002062 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002063 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07002064 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002065 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07002066 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002067 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002068 }
Robert Craige9887e42014-02-20 10:25:56 -05002069 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002070 return res;
Robert Craige9887e42014-02-20 10:25:56 -05002071}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01002072
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002073binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
2074 const std::string& instructionSet) {
2075 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002076 std::lock_guard<std::recursive_mutex> lock(mLock);
2077
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002078 const char* oat_dir = oatDir.c_str();
2079 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002080 char oat_instr_dir[PKG_PATH_MAX];
2081
2082 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002083 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002084 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002085 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002086 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002087 }
2088 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002089 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002090 }
2091 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07002092 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002093 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002094 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002095 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002096}
2097
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002098binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
2099 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002100 std::lock_guard<std::recursive_mutex> lock(mLock);
2101
Jeff Sharkey423e7462016-12-09 18:18:43 -07002102 if (validate_apk_path(packageDir.c_str())) {
2103 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002104 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002105 if (delete_dir_contents_and_dir(packageDir) != 0) {
2106 return error("Failed to delete " + packageDir);
2107 }
2108 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08002109}
2110
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002111binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
2112 const std::string& fromBase, const std::string& toBase) {
2113 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002114 std::lock_guard<std::recursive_mutex> lock(mLock);
2115
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002116 const char* relative_path = relativePath.c_str();
2117 const char* from_base = fromBase.c_str();
2118 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01002119 char from_path[PKG_PATH_MAX];
2120 char to_path[PKG_PATH_MAX];
2121 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
2122 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
2123
2124 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002125 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002126 }
2127
2128 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002129 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002130 }
2131
Jeff Sharkey423e7462016-12-09 18:18:43 -07002132 if (link(from_path, to_path) < 0) {
2133 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01002134 }
2135
Jeff Sharkey423e7462016-12-09 18:18:43 -07002136 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01002137}
2138
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002139binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
2140 const std::string& instructionSet, const std::string& outputPath) {
2141 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002142 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002143
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002144 const char* apk_path = apkPath.c_str();
2145 const char* instruction_set = instructionSet.c_str();
2146 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07002147
Jeff Sharkey90aff262016-12-12 14:28:24 -07002148 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002149 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002150}
2151
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002152binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2153 const std::string& instructionSet, const std::string& outputPath) {
2154 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002155 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002156
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002157 const char* apk_path = apkPath.c_str();
2158 const char* instruction_set = instructionSet.c_str();
2159 const char* oat_dir = outputPath.c_str();
2160
Jeff Sharkey90aff262016-12-12 14:28:24 -07002161 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2162 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002163}
2164
Calin Juravlebd968362017-01-25 01:17:17 -08002165binder::Status InstalldNativeService::reconcileSecondaryDexFile(
2166 const std::string& dexPath, const std::string& packageName, int32_t uid,
2167 const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
2168 int32_t storage_flag, bool* _aidl_return) {
2169 ENFORCE_UID(AID_SYSTEM);
2170 CHECK_ARGUMENT_UUID(volumeUuid);
2171 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2172
2173 std::lock_guard<std::recursive_mutex> lock(mLock);
2174 bool result = android::installd::reconcile_secondary_dex_file(
2175 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2176 return result ? ok() : error();
2177}
2178
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002179binder::Status InstalldNativeService::invalidateMounts() {
2180 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002181 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002182
2183 mQuotaDevices.clear();
2184
2185 std::ifstream in("/proc/mounts");
2186 if (!in.is_open()) {
2187 return error("Failed to read mounts");
2188 }
2189
2190 std::string source;
2191 std::string target;
2192 std::string ignored;
2193 struct dqblk dq;
2194 while (!in.eof()) {
2195 std::getline(in, source, ' ');
2196 std::getline(in, target, ' ');
2197 std::getline(in, ignored);
2198
2199 if (source.compare(0, 11, "/dev/block/") == 0) {
2200 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2201 reinterpret_cast<char*>(&dq)) == 0) {
2202 LOG(DEBUG) << "Found " << source << " with quota";
2203 mQuotaDevices[target] = source;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002204
2205 // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
2206 // need to kick it again to enable DQUOT_LIMITS_ENABLED.
2207 if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2208 && errno != EBUSY) {
2209 PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
2210 }
2211 if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1, nullptr) != 0
2212 && errno != EBUSY) {
2213 PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
2214 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002215 }
2216 }
2217 }
2218 return ok();
2219}
2220
2221std::string InstalldNativeService::findQuotaDeviceForUuid(
2222 const std::unique_ptr<std::string>& uuid) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002223 std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002224 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
2225 return mQuotaDevices[path];
2226}
2227
Jeff Sharkey325b8c92017-02-21 10:00:53 -07002228binder::Status InstalldNativeService::isQuotaSupported(
2229 const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2230 *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2231 return ok();
2232}
2233
Andreas Gampe02d0de52015-11-11 20:43:16 -08002234} // namespace installd
2235} // namespace android