blob: ede31fcecf4a90885d5573cca9e9ca625943529d [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
84// NOTE: keep in sync with StorageManager
85static constexpr int FLAG_STORAGE_DE = 1 << 0;
86static constexpr int FLAG_STORAGE_CE = 1 << 1;
87
88// NOTE: keep in sync with Installer
89static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
90static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070091static constexpr int FLAG_USE_QUOTA = 1 << 12;
Jeff Sharkey88ddd942017-01-17 18:05:54 -070092static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
93static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 14;
Calin Juravle6a1648e2016-02-01 12:12:16 +000094
Jeff Sharkey0274c972016-12-06 09:32:04 -070095namespace {
96
97constexpr const char* kDump = "android.permission.DUMP";
98
Jeff Sharkey423e7462016-12-09 18:18:43 -070099static binder::Status ok() {
100 return binder::Status::ok();
101}
102
103static binder::Status exception(uint32_t code, const std::string& msg) {
104 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
105}
106
107static binder::Status error() {
108 return binder::Status::fromServiceSpecificError(errno);
109}
110
111static binder::Status error(const std::string& msg) {
112 PLOG(ERROR) << msg;
113 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
114}
115
116static binder::Status error(uint32_t code, const std::string& msg) {
117 LOG(ERROR) << msg << " (" << code << ")";
118 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
119}
120
Jeff Sharkey0274c972016-12-06 09:32:04 -0700121binder::Status checkPermission(const char* permission) {
122 pid_t pid;
123 uid_t uid;
124
125 if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
126 reinterpret_cast<int32_t*>(&uid))) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700127 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700128 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700129 return exception(binder::Status::EX_SECURITY,
130 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700131 }
132}
133
134binder::Status checkUid(uid_t expectedUid) {
135 uid_t uid = IPCThreadState::self()->getCallingUid();
136 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700137 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700138 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700139 return exception(binder::Status::EX_SECURITY,
140 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
141 }
142}
143
144binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
145 if (!uuid || is_valid_filename(*uuid)) {
146 return ok();
147 } else {
148 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
149 StringPrintf("UUID %s is malformed", uuid->c_str()));
150 }
151}
152
153binder::Status checkArgumentPackageName(const std::string& packageName) {
154 if (is_valid_package_name(packageName.c_str())) {
155 return ok();
156 } else {
157 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
158 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700159 }
160}
161
162#define ENFORCE_UID(uid) { \
163 binder::Status status = checkUid((uid)); \
164 if (!status.isOk()) { \
165 return status; \
166 } \
167}
168
Jeff Sharkey423e7462016-12-09 18:18:43 -0700169#define CHECK_ARGUMENT_UUID(uuid) { \
170 binder::Status status = checkArgumentUuid((uuid)); \
171 if (!status.isOk()) { \
172 return status; \
173 } \
174}
175
176#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
177 binder::Status status = \
178 checkArgumentPackageName((packageName)); \
179 if (!status.isOk()) { \
180 return status; \
181 } \
182}
183
Jeff Sharkey0274c972016-12-06 09:32:04 -0700184} // namespace
185
186status_t InstalldNativeService::start() {
187 IPCThreadState::self()->disableBackgroundScheduling(true);
188 status_t ret = BinderService<InstalldNativeService>::publish();
189 if (ret != android::OK) {
190 return ret;
191 }
192 sp<ProcessState> ps(ProcessState::self());
193 ps->startThreadPool();
194 ps->giveThreadPoolName();
195 return android::OK;
196}
197
198status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700199 auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700200 const binder::Status dump_permission = checkPermission(kDump);
201 if (!dump_permission.isOk()) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700202 out << dump_permission.toString8() << endl;
Jeff Sharkey0274c972016-12-06 09:32:04 -0700203 return PERMISSION_DENIED;
204 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700205 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700206
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700207 out << "installd is happy!" << endl;
208
209 out << endl << "Devices with quota support:" << endl;
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700210 for (const auto& n : mQuotaDevices) {
211 out << " " << n.first << " = " << n.second << endl;
212 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700213
214 out << endl << "Per-UID cache quotas:" << endl;
215 for (const auto& n : mCacheQuotas) {
216 out << " " << n.first << " = " << n.second << endl;
217 }
218
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700219 out << endl;
220 out.flush();
221
Jeff Sharkey0274c972016-12-06 09:32:04 -0700222 return NO_ERROR;
223}
224
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600225/**
226 * Perform restorecon of the given path, but only perform recursive restorecon
227 * if the label of that top-level file actually changed. This can save us
228 * significant time by avoiding no-op traversals of large filesystem trees.
229 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700230static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
231 bool existing) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600232 int res = 0;
233 char* before = nullptr;
234 char* after = nullptr;
235
236 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
237 // libselinux. Not needed here.
238
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600239 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600240 PLOG(ERROR) << "Failed before getfilecon for " << path;
241 goto fail;
242 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700243 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600244 PLOG(ERROR) << "Failed top-level restorecon for " << path;
245 goto fail;
246 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600247 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600248 PLOG(ERROR) << "Failed after getfilecon for " << path;
249 goto fail;
250 }
251
252 // If the initial top-level restorecon above changed the label, then go
253 // back and restorecon everything recursively
254 if (strcmp(before, after)) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700255 if (existing) {
256 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
257 << path << "; running recursive restorecon";
258 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700259 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600260 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
261 PLOG(ERROR) << "Failed recursive restorecon for " << path;
262 goto fail;
263 }
264 }
265
266 goto done;
267fail:
268 res = -1;
269done:
270 free(before);
271 free(after);
272 return res;
273}
274
Jeff Sharkey0274c972016-12-06 09:32:04 -0700275static int restorecon_app_data_lazy(const std::string& parent, const char* name,
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700276 const std::string& seInfo, uid_t uid, bool existing) {
277 return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
278 existing);
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600279}
280
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600281static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600282 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
283 PLOG(ERROR) << "Failed to prepare " << path;
284 return -1;
285 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600286 return 0;
287}
288
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700289/**
290 * Prepare an app cache directory, which offers to fix-up the GID and
291 * directory mode flags during a platform upgrade.
292 */
293static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
294 uid_t uid, gid_t gid) {
295 auto path = StringPrintf("%s/%s", parent.c_str(), name);
296 struct stat st;
297 if (stat(path.c_str(), &st) != 0) {
298 if (errno == ENOENT) {
299 // This is fine, just create it
300 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
301 PLOG(ERROR) << "Failed to prepare " << path;
302 return -1;
303 } else {
304 return 0;
305 }
306 } else {
307 PLOG(ERROR) << "Failed to stat " << path;
308 return -1;
309 }
310 }
311
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700312 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700313 if (st.st_uid != uid) {
314 // Mismatched UID is real trouble; we can't recover
315 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
316 << " but expected " << uid;
317 return -1;
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700318 } else if (st.st_gid == gid && actual_mode == target_mode) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700319 // Everything looks good!
320 return 0;
321 }
322
323 // Directory is owned correctly, but GID or mode mismatch means it's
324 // probably a platform upgrade so we need to fix them
325 FTS *fts;
326 FTSENT *p;
327 char *argv[] = { (char*) path.c_str(), nullptr };
328 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
329 PLOG(ERROR) << "Failed to fts_open " << path;
330 return -1;
331 }
332 while ((p = fts_read(fts)) != NULL) {
333 switch (p->fts_info) {
334 case FTS_DP:
335 if (chmod(p->fts_accpath, target_mode) != 0) {
336 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
337 }
338 // Intentional fall through to also set GID
339 case FTS_F:
340 if (chown(p->fts_accpath, -1, gid) != 0) {
341 PLOG(WARNING) << "Failed to chown " << p->fts_path;
342 }
343 break;
344 case FTS_SL:
345 case FTS_SLNONE:
346 if (lchown(p->fts_accpath, -1, gid) != 0) {
347 PLOG(WARNING) << "Failed to chown " << p->fts_path;
348 }
349 break;
350 }
351 }
352 fts_close(fts);
353 return 0;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600354}
355
Jeff Sharkey0274c972016-12-06 09:32:04 -0700356binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
357 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700358 const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700359 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700360 CHECK_ARGUMENT_UUID(uuid);
361 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700362 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700363
364 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
365 const char* pkgname = packageName.c_str();
366
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700367 // Assume invalid inode unless filled in below
368 if (_aidl_return != nullptr) *_aidl_return = -1;
369
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700370 int32_t uid = multiuser_get_uid(userId, appId);
371 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700372 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
373
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700374 // If UID doesn't have a specific cache GID, use UID value
375 if (cacheGid == -1) {
376 cacheGid = uid;
377 }
378
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700379 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700380 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700381 bool existing = (access(path.c_str(), F_OK) == 0);
382
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700383 if (prepare_app_dir(path, targetMode, uid) ||
384 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
385 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700386 return error("Failed to prepare " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600387 }
388
389 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700390 if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
391 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
392 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700393 return error("Failed to restorecon " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700394 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600395
396 // Remember inode numbers of cache directories so that we can clear
397 // contents while CE storage is locked
398 if (write_path_inode(path, "cache", kXattrInodeCache) ||
399 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700400 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700401 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700402
403 // And return the CE inode of the top-level data directory so we can
404 // clear contents while CE storage is locked
405 if ((_aidl_return != nullptr)
406 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
407 return error("Failed to get_path_inode for " + path);
408 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700409 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700410 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700411 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700412 bool existing = (access(path.c_str(), F_OK) == 0);
413
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700414 if (prepare_app_dir(path, targetMode, uid) ||
415 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
416 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700417 return error("Failed to prepare " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700418 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000419
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600420 // Consider restorecon over contents if label changed
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700421 if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700422 return error("Failed to restorecon " + path);
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600423 }
424
Jeff Sharkey90aff262016-12-12 14:28:24 -0700425 if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700426 const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000427 // read-write-execute only for the app user.
428 if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700429 return error("Failed to prepare " + profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000430 }
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100431 std::string profile_file = create_primary_profile(profile_path);
432 // read-write only for the app user.
433 if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700434 return error("Failed to prepare " + profile_path);
Calin Juravlebc56e7d2016-05-24 15:33:12 +0100435 }
Calin Juravle6a1648e2016-02-01 12:12:16 +0000436 const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
437 // dex2oat/profman runs under the shared app gid and it needs to read/write reference
438 // profiles.
Jeff Sharkeyadddd982017-01-03 14:33:50 -0700439 int shared_app_gid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey2e6dc9b2016-12-15 14:50:11 -0700440 if ((shared_app_gid != -1) && fs_prepare_dir_strict(
Calin Juravle6a1648e2016-02-01 12:12:16 +0000441 ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700442 return error("Failed to prepare " + ref_profile_path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000443 }
444 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700445 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700446 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700447}
448
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700449binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
450 const std::string& packageName, int32_t userId, int32_t flags) {
451 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700452 CHECK_ARGUMENT_UUID(uuid);
453 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700454 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700455
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700456 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
457 const char* pkgname = packageName.c_str();
458
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700459 // This method only exists to upgrade system apps that have requested
460 // forceDeviceEncrypted, so their default storage always lives in a
461 // consistent location. This only works on non-FBE devices, since we
462 // never want to risk exposing data on a device with real CE/DE storage.
463
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700464 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
465 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700466
467 // If neither directory is marked as default, assume CE is default
468 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
469 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
470 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700471 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700472 }
473 }
474
475 // Migrate default data location if needed
476 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
477 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
478
479 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
480 LOG(WARNING) << "Requested default storage " << target
481 << " is not active; migrating from " << source;
482 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700483 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700484 }
485 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700486 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700487 }
488 }
489
Jeff Sharkey423e7462016-12-09 18:18:43 -0700490 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700491}
492
Calin Juravle6a1648e2016-02-01 12:12:16 +0000493
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700494binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
495 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700496 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700497 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700498
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700499 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700500 binder::Status res = ok();
501 if (!clear_reference_profile(pkgname)) {
502 res = error("Failed to clear reference profile for " + packageName);
503 }
504 if (!clear_current_profiles(pkgname)) {
505 res = error("Failed to clear current profiles for " + packageName);
506 }
507 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +0000508}
509
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700510binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
511 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
512 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700513 CHECK_ARGUMENT_UUID(uuid);
514 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700515 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700516
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700517 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
518 const char* pkgname = packageName.c_str();
519
Jeff Sharkey423e7462016-12-09 18:18:43 -0700520 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700521 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700522 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600523 if (flags & FLAG_CLEAR_CACHE_ONLY) {
524 path = read_path_inode(path, "cache", kXattrInodeCache);
525 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
526 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
527 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700528 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700529 if (delete_dir_contents(path) != 0) {
530 res = error("Failed to delete contents of " + path);
531 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700532 }
533 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700534 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600535 std::string suffix = "";
536 bool only_cache = false;
537 if (flags & FLAG_CLEAR_CACHE_ONLY) {
538 suffix = CACHE_DIR_POSTFIX;
539 only_cache = true;
540 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
541 suffix = CODE_CACHE_DIR_POSTFIX;
542 only_cache = true;
543 }
544
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700545 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700546 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700547 if (delete_dir_contents(path) != 0) {
548 res = error("Failed to delete contents of " + path);
549 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700550 }
Calin Juravleedae6692016-03-23 13:55:31 +0000551 if (!only_cache) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700552 if (!clear_current_profile(pkgname, userId)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700553 res = error("Failed to clear current profile for " + packageName);
Calin Juravleedae6692016-03-23 13:55:31 +0000554 }
555 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700556 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700557 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700558}
559
Calin Juravle7535e8e2016-03-29 16:05:40 +0100560static int destroy_app_reference_profile(const char *pkgname) {
561 return delete_dir_contents_and_dir(
562 create_data_ref_profile_package_path(pkgname),
563 /*ignore_if_missing*/ true);
564}
565
Calin Juravleedae6692016-03-23 13:55:31 +0000566static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100567 return delete_dir_contents_and_dir(
568 create_data_user_profile_package_path(userid, pkgname),
569 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +0000570}
571
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700572binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
573 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700574 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700575 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700576
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700577 const char* pkgname = packageName.c_str();
Jeff Sharkey423e7462016-12-09 18:18:43 -0700578 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +0000579 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
580 for (auto user : users) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700581 if (destroy_app_current_profiles(pkgname, user) != 0) {
582 res = error("Failed to destroy current profiles for " + packageName);
583 }
Calin Juravleedae6692016-03-23 13:55:31 +0000584 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700585 if (destroy_app_reference_profile(pkgname) != 0) {
586 res = error("Failed to destroy reference profile for " + packageName);
587 }
588 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +0000589}
590
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700591binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
592 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
593 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700594 CHECK_ARGUMENT_UUID(uuid);
595 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700596 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700597
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700598 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
599 const char* pkgname = packageName.c_str();
600
Jeff Sharkey423e7462016-12-09 18:18:43 -0700601 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700602 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700603 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
604 if (delete_dir_contents_and_dir(path) != 0) {
605 res = error("Failed to delete " + path);
606 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700607 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700608 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700609 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
610 if (delete_dir_contents_and_dir(path) != 0) {
611 res = error("Failed to delete " + path);
612 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700613 destroy_app_current_profiles(pkgname, userId);
Calin Juravle7535e8e2016-03-29 16:05:40 +0100614 // TODO(calin): If the package is still installed by other users it's probably
615 // beneficial to keep the reference profile around.
616 // Verify if it's ok to do that.
617 destroy_app_reference_profile(pkgname);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700618 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700619 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700620}
621
Jeff Sharkey0274c972016-12-06 09:32:04 -0700622binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
623 const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
624 const std::string& dataAppName, int32_t appId, const std::string& seInfo,
625 int32_t targetSdkVersion) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700626 ENFORCE_UID(AID_SYSTEM);
627 CHECK_ARGUMENT_UUID(fromUuid);
628 CHECK_ARGUMENT_UUID(toUuid);
629 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700630 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700631
632 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
633 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
634 const char* package_name = packageName.c_str();
635 const char* data_app_name = dataAppName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700636
Jeff Sharkey423e7462016-12-09 18:18:43 -0700637 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700638 std::vector<userid_t> users = get_known_users(from_uuid);
639
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700640 // Copy app
641 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600642 auto from = create_data_app_package_path(from_uuid, data_app_name);
643 auto to = create_data_app_package_path(to_uuid, data_app_name);
644 auto to_parent = create_data_app_path(to_uuid);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700645
646 char *argv[] = {
647 (char*) kCpPath,
648 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
649 (char*) "-p", /* preserve timestamps, ownership, and permissions */
650 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
651 (char*) "-P", /* Do not follow symlinks [default] */
652 (char*) "-d", /* don't dereference symlinks */
653 (char*) from.c_str(),
654 (char*) to_parent.c_str()
655 };
656
657 LOG(DEBUG) << "Copying " << from << " to " << to;
658 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700659 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700660 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700661 goto fail;
662 }
663
664 if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700665 res = error("Failed to restorecon " + to);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700666 goto fail;
667 }
668 }
669
670 // Copy private data for all known users
Jeff Sharkeye3637242015-04-08 20:56:42 -0700671 for (auto user : users) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700672
673 // Data source may not exist for all users; that's okay
Jeff Sharkey51c94492016-05-10 17:46:39 -0600674 auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
675 if (access(from_ce.c_str(), F_OK) != 0) {
676 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700677 continue;
678 }
679
Jeff Sharkey0274c972016-12-06 09:32:04 -0700680 if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700681 seInfo, targetSdkVersion, nullptr).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700682 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -0700683 goto fail;
684 }
685
686 char *argv[] = {
687 (char*) kCpPath,
688 (char*) "-F", /* delete any existing destination file first (--remove-destination) */
689 (char*) "-p", /* preserve timestamps, ownership, and permissions */
690 (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
691 (char*) "-P", /* Do not follow symlinks [default] */
692 (char*) "-d", /* don't dereference symlinks */
Jeff Sharkey51c94492016-05-10 17:46:39 -0600693 nullptr,
694 nullptr
Jeff Sharkeye3637242015-04-08 20:56:42 -0700695 };
696
Jeff Sharkey51c94492016-05-10 17:46:39 -0600697 {
698 auto from = create_data_user_de_package_path(from_uuid, user, package_name);
699 auto to = create_data_user_de_path(to_uuid, user);
700 argv[6] = (char*) from.c_str();
701 argv[7] = (char*) to.c_str();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700702
Jeff Sharkey51c94492016-05-10 17:46:39 -0600703 LOG(DEBUG) << "Copying " << from << " to " << to;
704 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
705 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700706 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600707 goto fail;
708 }
709 }
710 {
711 auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
712 auto to = create_data_user_ce_path(to_uuid, user);
713 argv[6] = (char*) from.c_str();
714 argv[7] = (char*) to.c_str();
715
716 LOG(DEBUG) << "Copying " << from << " to " << to;
717 int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
718 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700719 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -0600720 goto fail;
721 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700722 }
723
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700724 if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
725 appId, seInfo).isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700726 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700727 goto fail;
728 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700729 }
730
Jeff Sharkey31f08982015-07-07 13:31:37 -0700731 // We let the framework scan the new location and persist that before
732 // deleting the data in the old location; this ordering ensures that
733 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -0700734 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -0700735
736fail:
737 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700738 {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600739 auto to = create_data_app_package_path(to_uuid, data_app_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700740 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
741 LOG(WARNING) << "Failed to rollback " << to;
742 }
743 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700744 for (auto user : users) {
Jeff Sharkey51c94492016-05-10 17:46:39 -0600745 {
746 auto to = create_data_user_de_package_path(to_uuid, user, package_name);
747 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
748 LOG(WARNING) << "Failed to rollback " << to;
749 }
750 }
751 {
752 auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
753 if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
754 LOG(WARNING) << "Failed to rollback " << to;
755 }
Jeff Sharkeye3637242015-04-08 20:56:42 -0700756 }
757 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700758 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -0700759}
760
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700761binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
762 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
763 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700764 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700765 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700766
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700767 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600768 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700769 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700770 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700771 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -0700772 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700773 }
774 }
Jeff Sharkey7be5ead2016-12-12 13:18:46 -0700775 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700776}
777
778binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
779 int32_t userId, int32_t flags) {
780 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700781 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700782 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700783
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700784 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700785 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700786 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700787 auto path = create_data_user_de_path(uuid_, userId);
788 if (delete_dir_contents_and_dir(path, true) != 0) {
789 res = error("Failed to delete " + path);
790 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700791 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700792 path = create_data_misc_legacy_path(userId);
793 if (delete_dir_contents_and_dir(path, true) != 0) {
794 res = error("Failed to delete " + path);
795 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700796 path = create_data_user_profile_path(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700797 if (delete_dir_contents_and_dir(path, true) != 0) {
798 res = error("Failed to delete " + path);
799 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700800 }
Robin Lee095c7632014-04-25 15:05:19 +0100801 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600802 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700803 auto path = create_data_user_ce_path(uuid_, userId);
804 if (delete_dir_contents_and_dir(path, true) != 0) {
805 res = error("Failed to delete " + path);
806 }
807 path = create_data_media_path(uuid_, userId);
808 if (delete_dir_contents_and_dir(path, true) != 0) {
809 res = error("Failed to delete " + path);
810 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600811 }
Jeff Sharkey423e7462016-12-09 18:18:43 -0700812 return res;
Robin Lee095c7632014-04-25 15:05:19 +0100813}
814
Mike Lockwood94afecf2012-10-24 10:45:23 -0700815/* Try to ensure free_size bytes of storage are available.
816 * Returns 0 on success.
817 * This is rather simple-minded because doing a full LRU would
818 * be potentially memory-intensive, and without atime it would
819 * also require that apps constantly modify file metadata even
820 * when just reading from the cache, which is pretty awful.
821 */
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700822binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700823 int64_t freeStorageSize, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700824 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700825 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700826 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700827
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700828 // TODO: remove this once framework is more robust
829 invalidateMounts();
830
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700831 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700832 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700833 auto device = findQuotaDeviceForUuid(uuid);
834 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700835
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700836 int64_t free = data_disk_free(data_path);
837 int64_t needed = freeStorageSize - free;
838 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700839 return error("Failed to determine free space for " + data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700840 } else if (free >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700841 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700842 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700843
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700844 LOG(DEBUG) << "Found " << data_path << " with " << free << " free; caller requested "
845 << freeStorageSize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700846
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700847 if (flags & FLAG_FREE_CACHE_V2) {
848 // This new cache strategy fairly removes files from UIDs by deleting
849 // files from the UIDs which are most over their allocated quota
850
851 // 1. Create trackers for every known UID
852 ATRACE_BEGIN("create");
853 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
854 for (auto user : get_known_users(uuid_)) {
855 FTS *fts;
856 FTSENT *p;
857 char *argv[] = {
858 (char*) create_data_user_ce_path(uuid_, user).c_str(),
859 (char*) create_data_user_de_path(uuid_, user).c_str(),
860 nullptr
861 };
862 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
863 return error("Failed to fts_open");
864 }
865 while ((p = fts_read(fts)) != NULL) {
866 if (p->fts_info == FTS_D && p->fts_level == 1) {
867 uid_t uid = p->fts_statp->st_uid;
868 auto search = trackers.find(uid);
869 if (search != trackers.end()) {
870 search->second->addDataPath(p->fts_path);
871 } else {
872 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
873 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
874 tracker->addDataPath(p->fts_path);
875 tracker->cacheQuota = mCacheQuotas[uid];
876 if (tracker->cacheQuota == 0) {
877 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
878 tracker->cacheQuota = 67108864;
879 }
880 trackers[uid] = tracker;
881 }
882 fts_set(fts, p, FTS_SKIP);
883 }
884 }
885 fts_close(fts);
886 }
887 ATRACE_END();
888
889 // 2. Populate tracker stats and insert into priority queue
890 ATRACE_BEGIN("populate");
891 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
892 return (left->getCacheRatio() < right->getCacheRatio());
893 };
894 std::priority_queue<std::shared_ptr<CacheTracker>,
895 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
896 for (const auto& it : trackers) {
897 it.second->loadStats();
898 queue.push(it.second);
899 }
900 ATRACE_END();
901
902 // 3. Bounce across the queue, freeing items from whichever tracker is
903 // the most over their assigned quota
904 ATRACE_BEGIN("bounce");
905 std::shared_ptr<CacheTracker> active;
906 while (active || !queue.empty()) {
907 // Find the best tracker to work with; this might involve swapping
908 // if the active tracker is no longer the most over quota
909 bool nextBetter = active && !queue.empty()
910 && active->getCacheRatio() < queue.top()->getCacheRatio();
911 if (!active || nextBetter) {
912 if (active) {
913 // Current tracker still has items, so we'll consider it
914 // again later once it bubbles up to surface
915 queue.push(active);
916 }
917 active = queue.top(); queue.pop();
918 active->ensureItems();
919 continue;
920 }
921
922 // If no items remain, go find another tracker
923 if (active->items.empty()) {
924 active = nullptr;
925 continue;
926 } else {
927 auto item = active->items.back();
928 active->items.pop_back();
929
930 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
931 if (!noop) {
932 item->purge();
933 }
934 active->cacheUsed -= item->size;
935 needed -= item->size;
936 }
937
938 // Verify that we're actually done before bailing, since sneaky
939 // apps might be using hardlinks
940 if (needed <= 0) {
941 free = data_disk_free(data_path);
942 needed = freeStorageSize - free;
943 if (needed <= 0) {
944 break;
945 } else {
946 LOG(WARNING) << "Expected to be done but still need " << needed;
947 }
948 }
949 }
950 ATRACE_END();
951
952 } else {
953 ATRACE_BEGIN("start");
954 cache_t* cache = start_cache_collection();
955 ATRACE_END();
956
957 ATRACE_BEGIN("add");
958 for (auto user : get_known_users(uuid_)) {
959 add_cache_files(cache, create_data_user_ce_path(uuid_, user));
960 add_cache_files(cache, create_data_user_de_path(uuid_, user));
961 add_cache_files(cache,
962 StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
963 }
964 ATRACE_END();
965
966 ATRACE_BEGIN("clear");
967 clear_cache_files(data_path, cache, freeStorageSize);
968 ATRACE_END();
969
970 ATRACE_BEGIN("finish");
971 finish_cache_collection(cache);
972 ATRACE_END();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700973 }
974
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700975 free = data_disk_free(data_path);
976 if (free >= freeStorageSize) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700977 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700978 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700979 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700980 freeStorageSize, data_path.c_str(), free));
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700981 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700982}
983
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700984binder::Status InstalldNativeService::rmdex(const std::string& codePath,
985 const std::string& instructionSet) {
986 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -0700987 std::lock_guard<std::recursive_mutex> lock(mLock);
988
Mike Lockwood94afecf2012-10-24 10:45:23 -0700989 char dex_path[PKG_PATH_MAX];
990
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700991 const char* path = codePath.c_str();
992 const char* instruction_set = instructionSet.c_str();
993
Jeff Sharkey770180a2014-09-08 17:14:26 -0700994 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700995 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -0700996 }
997
Jeff Sharkey475c6f92016-12-07 10:37:27 -0700998 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700999 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001000 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001001
1002 ALOGV("unlink %s\n", dex_path);
1003 if (unlink(dex_path) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001004 return error(StringPrintf("Failed to unlink %s", dex_path));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001005 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001006 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001007 }
1008}
1009
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001010struct stats {
1011 int64_t codeSize;
1012 int64_t dataSize;
1013 int64_t cacheSize;
1014};
1015
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001016#if MEASURE_DEBUG
1017static std::string toString(std::vector<int64_t> values) {
1018 std::stringstream res;
1019 res << "[";
1020 for (size_t i = 0; i < values.size(); i++) {
1021 res << values[i];
1022 if (i < values.size() - 1) {
1023 res << ",";
1024 }
1025 }
1026 res << "]";
1027 return res.str();
1028}
1029#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001030
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001031static void collectQuotaStats(const std::string& device, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001032 int32_t appId, struct stats* stats, struct stats* extStats) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001033 if (device.empty()) return;
1034
1035 struct dqblk dq;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001036
1037 uid_t uid = multiuser_get_uid(userId, appId);
1038 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1039 reinterpret_cast<char*>(&dq)) != 0) {
1040 if (errno != ESRCH) {
1041 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1042 }
1043 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001044#if MEASURE_DEBUG
1045 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1046#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001047 stats->dataSize += dq.dqb_curspace;
1048 }
1049
1050 int cacheGid = multiuser_get_cache_gid(userId, appId);
1051 if (cacheGid != -1) {
1052 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1053 reinterpret_cast<char*>(&dq)) != 0) {
1054 if (errno != ESRCH) {
1055 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1056 }
1057 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001058#if MEASURE_DEBUG
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001059 LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001060#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001061 stats->cacheSize += dq.dqb_curspace;
1062 }
1063 }
1064
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001065 int extGid = multiuser_get_ext_gid(userId, appId);
1066 if (extGid != -1) {
1067 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1068 reinterpret_cast<char*>(&dq)) != 0) {
1069 if (errno != ESRCH) {
1070 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1071 }
1072 } else {
1073#if MEASURE_DEBUG
1074 LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
1075#endif
1076 extStats->dataSize += dq.dqb_curspace;
1077 }
1078 }
1079
1080 int sharedGid = multiuser_get_shared_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001081 if (sharedGid != -1) {
1082 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1083 reinterpret_cast<char*>(&dq)) != 0) {
1084 if (errno != ESRCH) {
1085 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1086 }
1087 } else {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001088#if MEASURE_DEBUG
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001089 LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001090#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001091 stats->codeSize += dq.dqb_curspace;
1092 }
1093 }
1094}
1095
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001096static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001097 DIR *d;
1098 int dfd;
1099 struct dirent *de;
1100 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001101
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001102 d = opendir(path.c_str());
1103 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001104 if (errno != ENOENT) {
1105 PLOG(WARNING) << "Failed to open " << path;
1106 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001107 return;
1108 }
1109 dfd = dirfd(d);
1110 while ((de = readdir(d))) {
1111 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001112
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001113 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001114 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001115 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001116 }
1117
1118 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001119 if (!strcmp(name, ".")) {
1120 // Don't recurse, but still count node size
1121 } else if (!strcmp(name, "..")) {
1122 // Don't recurse or count node size
1123 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001124 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001125 // Measure all children nodes
1126 size = 0;
1127 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001128 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001129
1130 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1131 stats->cacheSize += size;
1132 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001133 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001134
1135 // Legacy symlink isn't owned by app
1136 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1137 continue;
1138 }
1139
1140 // Everything found inside is considered data
1141 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001142 }
1143 closedir(d);
1144}
1145
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001146static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1147 bool exclude_apps = false) {
1148 DIR *d;
1149 int dfd;
1150 struct dirent *de;
1151 struct stat s;
1152
1153 d = opendir(path.c_str());
1154 if (d == nullptr) {
1155 if (errno != ENOENT) {
1156 PLOG(WARNING) << "Failed to open " << path;
1157 }
1158 return;
1159 }
1160 dfd = dirfd(d);
1161 while ((de = readdir(d))) {
1162 if (de->d_type == DT_DIR) {
1163 const char *name = de->d_name;
1164 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1165 continue;
1166 }
1167 if (!strcmp(name, ".") || !strcmp(name, "..")) {
1168 continue;
1169 } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1170 continue;
1171 } else {
1172 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1173 }
1174 }
1175 }
1176 closedir(d);
1177}
1178
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001179static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1180 FTS *fts;
1181 FTSENT *p;
1182 char *argv[] = { (char*) path.c_str(), nullptr };
1183 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1184 PLOG(ERROR) << "Failed to fts_open " << path;
1185 return;
1186 }
1187 while ((p = fts_read(fts)) != NULL) {
1188 switch (p->fts_info) {
1189 case FTS_D:
1190 if (p->fts_level == 4
1191 && !strcmp(p->fts_name, "cache")
1192 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1193 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1194 p->fts_number = 1;
1195 }
1196 p->fts_number = p->fts_parent->fts_number;
1197 // Fall through to count the directory
1198 case FTS_DEFAULT:
1199 case FTS_F:
1200 case FTS_SL:
1201 case FTS_SLNONE:
1202 int64_t size = (p->fts_statp->st_blocks * 512);
1203 if (p->fts_number == 1) {
1204 stats->cacheSize += size;
1205 }
1206 stats->dataSize += size;
1207 break;
1208 }
1209 }
1210 fts_close(fts);
1211}
1212
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001213binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001214 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1215 int32_t appId, const std::vector<int64_t>& ceDataInodes,
1216 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001217 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001218 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001219 for (auto packageName : packageNames) {
1220 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1221 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001222 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001223
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001224 // When modifying this logic, always verify using tests:
1225 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1226
1227#if MEASURE_DEBUG
1228 LOG(INFO) << "Measuring user " << userId << " app " << appId;
1229#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001230
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001231 // Here's a summary of the common storage locations across the platform,
1232 // and how they're each tagged:
1233 //
1234 // /data/app/com.example UID system
1235 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001236 // /data/user/0/com.example UID u0_a10 GID u0_a10
1237 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
1238 // /data/media/0/foo.txt UID u0_media_rw
1239 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
1240 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
1241 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
1242 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001243
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001244 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001245 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001246 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001247 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001248
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001249 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001250
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001251 auto device = findQuotaDeviceForUuid(uuid);
1252 if (device.empty()) {
1253 flags &= ~FLAG_USE_QUOTA;
1254 }
1255
Jeff Sharkey466459b2017-01-17 15:25:01 -07001256 ATRACE_BEGIN("obb");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001257 for (auto packageName : packageNames) {
1258 auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1259 calculate_tree_size(obbCodePath, &extStats.codeSize);
1260 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001261 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001262
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001263 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001264 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001265 for (auto codePath : codePaths) {
1266 calculate_tree_size(codePath, &stats.codeSize, -1,
1267 multiuser_get_shared_gid(userId, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001268 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001269 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001270
Jeff Sharkey466459b2017-01-17 15:25:01 -07001271 ATRACE_BEGIN("quota");
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001272 collectQuotaStats(device, userId, appId, &stats, &extStats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001273 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001274
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001275 } else {
Jeff Sharkey466459b2017-01-17 15:25:01 -07001276 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001277 for (auto codePath : codePaths) {
1278 calculate_tree_size(codePath, &stats.codeSize);
1279 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001280 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001281
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001282 for (size_t i = 0; i < packageNames.size(); i++) {
1283 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001284
Jeff Sharkey466459b2017-01-17 15:25:01 -07001285 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001286 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1287 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001288 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1289 collectManualStats(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001290 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001291
Jeff Sharkey466459b2017-01-17 15:25:01 -07001292 ATRACE_BEGIN("profiles");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001293 auto userProfilePath = create_data_user_profile_package_path(userId, pkgname);
1294 calculate_tree_size(userProfilePath, &stats.dataSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001295 auto refProfilePath = create_data_ref_profile_package_path(pkgname);
1296 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001297 ATRACE_END();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001298
Jeff Sharkey466459b2017-01-17 15:25:01 -07001299 ATRACE_BEGIN("external");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001300 auto extPath = create_data_media_package_path(uuid_, userId, pkgname, "data");
1301 collectManualStats(extPath, &extStats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001302 auto mediaPath = create_data_media_package_path(uuid_, userId, pkgname, "media");
1303 calculate_tree_size(mediaPath, &extStats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001304 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001305 }
1306
Jeff Sharkey466459b2017-01-17 15:25:01 -07001307 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001308 int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1309 if (sharedGid != -1) {
1310 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1311 sharedGid, -1);
1312 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001313 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1314 multiuser_get_uid(userId, appId), -1);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001315 ATRACE_END();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001316 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06001317
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001318 std::vector<int64_t> ret;
1319 ret.push_back(stats.codeSize);
1320 ret.push_back(stats.dataSize);
1321 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001322 ret.push_back(extStats.codeSize);
1323 ret.push_back(extStats.dataSize);
1324 ret.push_back(extStats.cacheSize);
1325#if MEASURE_DEBUG
1326 LOG(DEBUG) << "Final result " << toString(ret);
1327#endif
1328 *_aidl_return = ret;
1329 return ok();
1330}
1331
1332binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1333 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1334 std::vector<int64_t>* _aidl_return) {
1335 ENFORCE_UID(AID_SYSTEM);
1336 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001337 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001338
1339 // When modifying this logic, always verify using tests:
1340 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1341
1342#if MEASURE_DEBUG
1343 LOG(INFO) << "Measuring user " << userId;
1344#endif
1345
1346 struct stats stats;
1347 struct stats extStats;
1348 memset(&stats, 0, sizeof(stats));
1349 memset(&extStats, 0, sizeof(extStats));
1350
1351 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1352
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001353 auto device = findQuotaDeviceForUuid(uuid);
1354 if (device.empty()) {
1355 flags &= ~FLAG_USE_QUOTA;
1356 }
1357
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001358 if (flags & FLAG_USE_QUOTA) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001359 struct dqblk dq;
1360
1361 ATRACE_BEGIN("obb");
1362 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1363 reinterpret_cast<char*>(&dq)) != 0) {
1364 if (errno != ESRCH) {
1365 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1366 }
1367 } else {
1368#if MEASURE_DEBUG
1369 LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1370#endif
1371 extStats.codeSize += dq.dqb_curspace;
1372 }
1373 ATRACE_END();
1374
Jeff Sharkey466459b2017-01-17 15:25:01 -07001375 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001376 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001377 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001378
Jeff Sharkey466459b2017-01-17 15:25:01 -07001379 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001380 auto cePath = create_data_user_ce_path(uuid_, userId);
1381 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001382 auto dePath = create_data_user_de_path(uuid_, userId);
1383 collectManualStatsForUser(dePath, &stats, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001384 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001385
Jeff Sharkey466459b2017-01-17 15:25:01 -07001386 ATRACE_BEGIN("profile");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001387 auto userProfilePath = create_data_user_profile_path(userId);
1388 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001389 auto refProfilePath = create_data_ref_profile_path();
1390 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001391 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001392
Jeff Sharkey466459b2017-01-17 15:25:01 -07001393 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001394 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1395 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1396 reinterpret_cast<char*>(&dq)) != 0) {
1397 if (errno != ESRCH) {
1398 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1399 }
1400 } else {
1401#if MEASURE_DEBUG
1402 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001403#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001404 extStats.dataSize += dq.dqb_curspace;
1405 }
1406 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001407
Jeff Sharkey466459b2017-01-17 15:25:01 -07001408 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001409 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1410 -1, -1, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001411 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize,
1412 -1, -1, true);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001413 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001414
Jeff Sharkey466459b2017-01-17 15:25:01 -07001415 ATRACE_BEGIN("quota");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001416 for (auto appId : appIds) {
1417 if (appId >= AID_APP_START) {
1418 collectQuotaStats(device, userId, appId, &stats, &extStats);
1419#if MEASURE_DEBUG
1420 // Sleep to make sure we don't lose logs
1421 usleep(1);
1422#endif
1423 }
1424 }
Jeff Sharkey466459b2017-01-17 15:25:01 -07001425 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001426 } else {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001427 ATRACE_BEGIN("obb");
1428 auto obbPath = create_data_path(uuid_) + "/media/obb";
1429 calculate_tree_size(obbPath, &extStats.codeSize);
1430 ATRACE_END();
1431
Jeff Sharkey466459b2017-01-17 15:25:01 -07001432 ATRACE_BEGIN("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001433 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001434 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001435
Jeff Sharkey466459b2017-01-17 15:25:01 -07001436 ATRACE_BEGIN("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001437 auto cePath = create_data_user_ce_path(uuid_, userId);
1438 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001439 auto dePath = create_data_user_de_path(uuid_, userId);
1440 collectManualStatsForUser(dePath, &stats);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001441 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001442
Jeff Sharkey466459b2017-01-17 15:25:01 -07001443 ATRACE_BEGIN("profile");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001444 auto userProfilePath = create_data_user_profile_path(userId);
1445 calculate_tree_size(userProfilePath, &stats.dataSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001446 auto refProfilePath = create_data_ref_profile_path();
1447 calculate_tree_size(refProfilePath, &stats.codeSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001448 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001449
Jeff Sharkey466459b2017-01-17 15:25:01 -07001450 ATRACE_BEGIN("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001451 auto dataMediaPath = create_data_media_path(uuid_, userId);
1452 collectManualExternalStatsForUser(dataMediaPath, &extStats);
1453#if MEASURE_DEBUG
1454 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1455 << extStats.cacheSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001456#endif
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07001457 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001458
Jeff Sharkey466459b2017-01-17 15:25:01 -07001459 ATRACE_BEGIN("dalvik");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001460 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001461 calculate_tree_size(create_data_misc_foreign_dex_path(userId), &stats.dataSize);
Jeff Sharkey466459b2017-01-17 15:25:01 -07001462 ATRACE_END();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001463 }
1464
1465 std::vector<int64_t> ret;
1466 ret.push_back(stats.codeSize);
1467 ret.push_back(stats.dataSize);
1468 ret.push_back(stats.cacheSize);
1469 ret.push_back(extStats.codeSize);
1470 ret.push_back(extStats.dataSize);
1471 ret.push_back(extStats.cacheSize);
1472#if MEASURE_DEBUG
1473 LOG(DEBUG) << "Final result " << toString(ret);
1474#endif
1475 *_aidl_return = ret;
1476 return ok();
1477}
1478
1479binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1480 int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1481 ENFORCE_UID(AID_SYSTEM);
1482 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001483 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001484
1485 // When modifying this logic, always verify using tests:
1486 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1487
1488#if MEASURE_DEBUG
1489 LOG(INFO) << "Measuring external " << userId;
1490#endif
1491
1492 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1493
1494 int64_t totalSize = 0;
1495 int64_t audioSize = 0;
1496 int64_t videoSize = 0;
1497 int64_t imageSize = 0;
1498
Jeff Sharkey66b1a122017-01-16 20:57:45 -07001499 auto device = findQuotaDeviceForUuid(uuid);
1500 if (device.empty()) {
1501 flags &= ~FLAG_USE_QUOTA;
1502 }
1503
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001504 if (flags & FLAG_USE_QUOTA) {
1505 struct dqblk dq;
1506
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07001507 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1508 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1509 reinterpret_cast<char*>(&dq)) != 0) {
1510 if (errno != ESRCH) {
1511 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1512 }
1513 } else {
1514#if MEASURE_DEBUG
1515 LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1516#endif
1517 totalSize = dq.dqb_curspace;
1518 }
1519
1520 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1521 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1522 reinterpret_cast<char*>(&dq)) == 0) {
1523#if MEASURE_DEBUG
1524 LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1525#endif
1526 audioSize = dq.dqb_curspace;
1527 }
1528 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1529 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1530 reinterpret_cast<char*>(&dq)) == 0) {
1531#if MEASURE_DEBUG
1532 LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1533#endif
1534 videoSize = dq.dqb_curspace;
1535 }
1536 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1537 if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1538 reinterpret_cast<char*>(&dq)) == 0) {
1539#if MEASURE_DEBUG
1540 LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1541#endif
1542 imageSize = dq.dqb_curspace;
1543 }
1544 } else {
1545 FTS *fts;
1546 FTSENT *p;
1547 auto path = create_data_media_path(uuid_, userId);
1548 char *argv[] = { (char*) path.c_str(), nullptr };
1549 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1550 return error("Failed to fts_open " + path);
1551 }
1552 while ((p = fts_read(fts)) != NULL) {
1553 char* ext;
1554 int64_t size = (p->fts_statp->st_blocks * 512);
1555 switch (p->fts_info) {
1556 case FTS_F:
1557 // Only categorize files not belonging to apps
1558 if (p->fts_statp->st_gid < AID_APP_START) {
1559 ext = strrchr(p->fts_name, '.');
1560 if (ext != nullptr) {
1561 switch (MatchExtension(++ext)) {
1562 case AID_MEDIA_AUDIO: audioSize += size; break;
1563 case AID_MEDIA_VIDEO: videoSize += size; break;
1564 case AID_MEDIA_IMAGE: imageSize += size; break;
1565 }
1566 }
1567 }
1568 // Fall through to always count against total
1569 case FTS_D:
1570 case FTS_DEFAULT:
1571 case FTS_SL:
1572 case FTS_SLNONE:
1573 totalSize += size;
1574 break;
1575 }
1576 }
1577 fts_close(fts);
1578 }
1579
1580 std::vector<int64_t> ret;
1581 ret.push_back(totalSize);
1582 ret.push_back(audioSize);
1583 ret.push_back(videoSize);
1584 ret.push_back(imageSize);
1585#if MEASURE_DEBUG
1586 LOG(DEBUG) << "Final result " << toString(ret);
1587#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07001588 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001589 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001590}
1591
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001592binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1593 int32_t userId, int32_t appId, int64_t cacheQuota) {
1594 ENFORCE_UID(AID_SYSTEM);
1595 CHECK_ARGUMENT_UUID(uuid);
1596 std::lock_guard<std::recursive_mutex> lock(mLock);
1597
1598 int32_t uid = multiuser_get_uid(userId, appId);
1599 mCacheQuotas[uid] = cacheQuota;
1600
1601 return ok();
1602}
1603
David Sehr6727c2d2016-05-17 16:06:22 -07001604// Dumps the contents of a profile file, using pkgname's dex files for pretty
1605// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001606binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1607 const std::string& codePaths, bool* _aidl_return) {
1608 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001609 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001610 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001611
1612 const char* pkgname = packageName.c_str();
Jeff Sharkey90aff262016-12-12 14:28:24 -07001613 const char* code_paths = codePaths.c_str();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001614
Jeff Sharkey90aff262016-12-12 14:28:24 -07001615 *_aidl_return = dump_profiles(uid, pkgname, code_paths);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001616 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07001617}
1618
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001619// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001620binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Jeff Sharkey423e7462016-12-09 18:18:43 -07001621 bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001622 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001623 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001624 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001625
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001626 const char* pkgname = packageName.c_str();
1627 *_aidl_return = analyse_profiles(uid, pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001628 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07001629}
1630
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001631binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1632 const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1633 int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1634 const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1635 const std::unique_ptr<std::string>& sharedLibraries) {
1636 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001637 CHECK_ARGUMENT_UUID(uuid);
1638 if (packageName && *packageName != "*") {
1639 CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1640 }
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001641 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001642
1643 const char* apk_path = apkPath.c_str();
1644 const char* pkgname = packageName ? packageName->c_str() : "*";
1645 const char* instruction_set = instructionSet.c_str();
1646 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1647 const char* compiler_filter = compilerFilter.c_str();
1648 const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1649 const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1650
1651 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1652 oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001653 return res ? error(res, "Failed to dexopt") : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07001654}
1655
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001656binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1657 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001658 std::lock_guard<std::recursive_mutex> lock(mLock);
1659
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001660 const char* instruction_set = instructionSet.c_str();
1661
1662 char boot_marker_path[PKG_PATH_MAX];
1663 sprintf(boot_marker_path,
Andreas Gampe02d0de52015-11-11 20:43:16 -08001664 "%s/%s/%s/.booting",
1665 android_data_dir.path,
1666 DALVIK_CACHE,
1667 instruction_set);
Narayan Kamath091ea772014-11-10 15:03:46 +00001668
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001669 ALOGV("mark_boot_complete : %s", boot_marker_path);
1670 if (unlink(boot_marker_path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001671 return error(StringPrintf("Failed to unlink %s", boot_marker_path));
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001672 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001673 return ok();
Narayan Kamath091ea772014-11-10 15:03:46 +00001674}
1675
Mike Lockwood94afecf2012-10-24 10:45:23 -07001676void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1677 struct stat* statbuf)
1678{
1679 while (path[basepos] != 0) {
1680 if (path[basepos] == '/') {
1681 path[basepos] = 0;
1682 if (lstat(path, statbuf) < 0) {
1683 ALOGV("Making directory: %s\n", path);
1684 if (mkdir(path, mode) == 0) {
1685 chown(path, uid, gid);
1686 } else {
1687 ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1688 }
1689 }
1690 path[basepos] = '/';
1691 basepos++;
1692 }
1693 basepos++;
1694 }
1695}
1696
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001697binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1698 const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1699 const std::string& nativeLibPath32, int32_t userId) {
1700 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001701 CHECK_ARGUMENT_UUID(uuid);
1702 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001703 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001704
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001705 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1706 const char* pkgname = packageName.c_str();
1707 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001708 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001709 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001710
Jeff Sharkey423e7462016-12-09 18:18:43 -07001711 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1712 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07001713
1714 const char* pkgdir = _pkgdir.c_str();
1715 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07001716
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001717 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001718 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001719 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001720
1721 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001722 return error("Failed to chown " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001723 }
1724
1725 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001726 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001727 goto out;
1728 }
1729
1730 if (lstat(libsymlink, &libStat) < 0) {
1731 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001732 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001733 goto out;
1734 }
1735 } else {
1736 if (S_ISDIR(libStat.st_mode)) {
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001737 if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001738 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001739 goto out;
1740 }
1741 } else if (S_ISLNK(libStat.st_mode)) {
1742 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001743 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001744 goto out;
1745 }
1746 }
1747 }
1748
1749 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001750 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001751 goto out;
1752 }
1753
1754out:
1755 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001756 auto msg = "Failed to cleanup chmod " + _pkgdir;
1757 if (res.isOk()) {
1758 res = error(msg);
1759 } else {
1760 PLOG(ERROR) << msg;
1761 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001762 }
1763
1764 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001765 auto msg = "Failed to cleanup chown " + _pkgdir;
1766 if (res.isOk()) {
1767 res = error(msg);
1768 } else {
1769 PLOG(ERROR) << msg;
1770 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001771 }
1772
Jeff Sharkey423e7462016-12-09 18:18:43 -07001773 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001774}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001775
1776static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1777{
1778 static const char *IDMAP_BIN = "/system/bin/idmap";
1779 static const size_t MAX_INT_LEN = 32;
1780 char idmap_str[MAX_INT_LEN];
1781
1782 snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1783
1784 execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1785 ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1786}
1787
1788// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1789// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1790static int flatten_path(const char *prefix, const char *suffix,
1791 const char *overlay_path, char *idmap_path, size_t N)
1792{
1793 if (overlay_path == NULL || idmap_path == NULL) {
1794 return -1;
1795 }
1796 const size_t len_overlay_path = strlen(overlay_path);
1797 // will access overlay_path + 1 further below; requires absolute path
1798 if (len_overlay_path < 2 || *overlay_path != '/') {
1799 return -1;
1800 }
1801 const size_t len_idmap_root = strlen(prefix);
1802 const size_t len_suffix = strlen(suffix);
1803 if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1804 SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1805 // additions below would cause overflow
1806 return -1;
1807 }
1808 if (N < len_idmap_root + len_overlay_path + len_suffix) {
1809 return -1;
1810 }
1811 memset(idmap_path, 0, N);
1812 snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1813 char *ch = idmap_path + len_idmap_root;
1814 while (*ch != '\0') {
1815 if (*ch == '/') {
1816 *ch = '@';
1817 }
1818 ++ch;
1819 }
1820 return 0;
1821}
1822
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001823binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1824 const std::string& overlayApkPath, int32_t uid) {
1825 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001826 std::lock_guard<std::recursive_mutex> lock(mLock);
1827
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001828 const char* target_apk = targetApkPath.c_str();
1829 const char* overlay_apk = overlayApkPath.c_str();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001830 ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1831
1832 int idmap_fd = -1;
1833 char idmap_path[PATH_MAX];
1834
1835 if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1836 idmap_path, sizeof(idmap_path)) == -1) {
1837 ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1838 goto fail;
1839 }
1840
1841 unlink(idmap_path);
1842 idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1843 if (idmap_fd < 0) {
1844 ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1845 goto fail;
1846 }
1847 if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1848 ALOGE("idmap cannot chown '%s'\n", idmap_path);
1849 goto fail;
1850 }
1851 if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1852 ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1853 goto fail;
1854 }
1855
1856 pid_t pid;
1857 pid = fork();
1858 if (pid == 0) {
1859 /* child -- drop privileges before continuing */
1860 if (setgid(uid) != 0) {
1861 ALOGE("setgid(%d) failed during idmap\n", uid);
1862 exit(1);
1863 }
1864 if (setuid(uid) != 0) {
1865 ALOGE("setuid(%d) failed during idmap\n", uid);
1866 exit(1);
1867 }
1868 if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1869 ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1870 exit(1);
1871 }
1872
1873 run_idmap(target_apk, overlay_apk, idmap_fd);
1874 exit(1); /* only if exec call to idmap failed */
1875 } else {
1876 int status = wait_child(pid);
1877 if (status != 0) {
1878 ALOGE("idmap failed, status=0x%04x\n", status);
1879 goto fail;
1880 }
1881 }
1882
1883 close(idmap_fd);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001884 return ok();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001885fail:
1886 if (idmap_fd >= 0) {
1887 close(idmap_fd);
1888 unlink(idmap_path);
1889 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001890 return error();
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01001891}
Robert Craige9887e42014-02-20 10:25:56 -05001892
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001893binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1894 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1895 const std::string& seInfo) {
1896 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001897 CHECK_ARGUMENT_UUID(uuid);
1898 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001899 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001900
1901 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05001902
Robert Craigda30dc72014-03-27 10:21:12 -04001903 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001904 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001905 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1906 const char* pkgName = packageName.c_str();
1907 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04001908
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001909 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001910 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001911 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001912 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001913 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07001914 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001915 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001916 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001917 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001918 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001919 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001920 }
Robert Craige9887e42014-02-20 10:25:56 -05001921 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001922 return res;
Robert Craige9887e42014-02-20 10:25:56 -05001923}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01001924
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001925binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1926 const std::string& instructionSet) {
1927 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001928 std::lock_guard<std::recursive_mutex> lock(mLock);
1929
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001930 const char* oat_dir = oatDir.c_str();
1931 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001932 char oat_instr_dir[PKG_PATH_MAX];
1933
1934 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001935 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001936 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001937 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001938 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001939 }
1940 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001941 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001942 }
1943 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07001944 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001945 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001946 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001947 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001948}
1949
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001950binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1951 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001952 std::lock_guard<std::recursive_mutex> lock(mLock);
1953
Jeff Sharkey423e7462016-12-09 18:18:43 -07001954 if (validate_apk_path(packageDir.c_str())) {
1955 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001956 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001957 if (delete_dir_contents_and_dir(packageDir) != 0) {
1958 return error("Failed to delete " + packageDir);
1959 }
1960 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08001961}
1962
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001963binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1964 const std::string& fromBase, const std::string& toBase) {
1965 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001966 std::lock_guard<std::recursive_mutex> lock(mLock);
1967
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001968 const char* relative_path = relativePath.c_str();
1969 const char* from_base = fromBase.c_str();
1970 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01001971 char from_path[PKG_PATH_MAX];
1972 char to_path[PKG_PATH_MAX];
1973 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1974 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1975
1976 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001977 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001978 }
1979
1980 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001981 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001982 }
1983
Jeff Sharkey423e7462016-12-09 18:18:43 -07001984 if (link(from_path, to_path) < 0) {
1985 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01001986 }
1987
Jeff Sharkey423e7462016-12-09 18:18:43 -07001988 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01001989}
1990
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001991binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1992 const std::string& instructionSet, const std::string& outputPath) {
1993 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07001994 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07001995
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001996 const char* apk_path = apkPath.c_str();
1997 const char* instruction_set = instructionSet.c_str();
1998 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07001999
Jeff Sharkey90aff262016-12-12 14:28:24 -07002000 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002001 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08002002}
2003
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002004binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
2005 const std::string& instructionSet, const std::string& outputPath) {
2006 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002007 std::lock_guard<std::recursive_mutex> lock(mLock);
Jeff Sharkey90aff262016-12-12 14:28:24 -07002008
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002009 const char* apk_path = apkPath.c_str();
2010 const char* instruction_set = instructionSet.c_str();
2011 const char* oat_dir = outputPath.c_str();
2012
Jeff Sharkey90aff262016-12-12 14:28:24 -07002013 bool res = delete_odex(apk_path, instruction_set, oat_dir);
2014 return res ? ok() : error();
Andreas Gampe3964da02016-09-09 17:07:04 -07002015}
2016
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002017binder::Status InstalldNativeService::invalidateMounts() {
2018 ENFORCE_UID(AID_SYSTEM);
2019 std::lock_guard<std::recursive_mutex> lock(mLock);
2020
2021 mQuotaDevices.clear();
2022
2023 std::ifstream in("/proc/mounts");
2024 if (!in.is_open()) {
2025 return error("Failed to read mounts");
2026 }
2027
2028 std::string source;
2029 std::string target;
2030 std::string ignored;
2031 struct dqblk dq;
2032 while (!in.eof()) {
2033 std::getline(in, source, ' ');
2034 std::getline(in, target, ' ');
2035 std::getline(in, ignored);
2036
2037 if (source.compare(0, 11, "/dev/block/") == 0) {
2038 if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2039 reinterpret_cast<char*>(&dq)) == 0) {
2040 LOG(DEBUG) << "Found " << source << " with quota";
2041 mQuotaDevices[target] = source;
2042 }
2043 }
2044 }
2045 return ok();
2046}
2047
2048std::string InstalldNativeService::findQuotaDeviceForUuid(
2049 const std::unique_ptr<std::string>& uuid) {
2050 auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
2051 return mQuotaDevices[path];
2052}
2053
Andreas Gampe02d0de52015-11-11 20:43:16 -08002054} // namespace installd
2055} // namespace android