blob: d7c9b40d92c95ea666711e88b9d7ecf61470d0e1 [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
19#include <errno.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070020#include <fts.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080021#include <inttypes.h>
Victor Hsiehc7ab5642023-07-28 15:07:55 -070022#include <linux/fsverity.h>
Keun young Park144a9892021-10-13 16:43:58 -070023#include <stdio.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080024#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070025#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026#include <sys/capability.h>
27#include <sys/file.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080028#include <sys/ioctl.h>
29#include <sys/mman.h>
Ricky Waiff9d3ea2019-11-18 18:18:24 +000030#include <sys/mount.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080031#include <sys/resource.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>
Samiul Islamc40dff52022-01-14 16:24:48 +000038#include <algorithm>
39#include <filesystem>
40#include <fstream>
41#include <functional>
42#include <regex>
Samiul Islam92f5cf02022-02-03 12:45:51 +000043#include <unordered_set>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070044
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000045#include <android-base/file.h>
Andreas Gampeafa58d12016-06-03 16:09:32 -070046#include <android-base/logging.h>
Oli Lanc7789572020-03-16 18:18:41 +000047#include <android-base/parseint.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070048#include <android-base/properties.h>
Narayan Kamathe63ca7d2019-01-14 15:21:52 +000049#include <android-base/scopeguard.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080050#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070051#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010052#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080053#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080054#include <cutils/fs.h>
Victor Hsiehc7ab5642023-07-28 15:07:55 -070055#include <cutils/misc.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070056#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070057#include <cutils/sched_policy.h>
Shikha Malhotra976ae002022-02-26 15:39:53 +000058#include <linux/quota.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070059#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070060#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080061#include <private/android_filesystem_config.h>
Martijn Coenen771cc342020-02-19 23:26:56 +010062#include <private/android_projectid_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070063#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080064#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070065#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070066
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070067#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070068#include "globals.h"
69#include "installd_deps.h"
70#include "otapreopt_utils.h"
71#include "utils.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070072
Jeff Sharkey88ddd942017-01-17 18:05:54 -070073#include "CacheTracker.h"
Felka Chang2a0a2462019-11-20 14:20:40 +080074#include "CrateManager.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070075#include "MatchExtensionGen.h"
Risan5f308262018-10-26 12:06:58 -060076#include "QuotaUtils.h"
Zim23457d02022-08-17 12:57:41 +010077#include "SysTrace.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070078
Andreas Gampe02d0de52015-11-11 20:43:16 -080079#ifndef LOG_TAG
80#define LOG_TAG "installd"
81#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070082
Alex Buynytskyy779447d2021-11-22 17:06:53 -080083#define GRANULAR_LOCKS
Alex Buynytskyy4fef8862021-11-21 16:09:33 -080084
Oli Lanc7789572020-03-16 18:18:41 +000085using android::base::ParseUint;
Samiul Islam92f5cf02022-02-03 12:45:51 +000086using android::base::Split;
Jeff Sharkey41ea4242015-04-09 11:34:03 -070087using android::base::StringPrintf;
Victor Hsiehc7ab5642023-07-28 15:07:55 -070088using android::base::unique_fd;
89using android::os::ParcelFileDescriptor;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070090using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070091
Andreas Gampe02d0de52015-11-11 20:43:16 -080092namespace android {
93namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070094
Nikita Ioffe8e4d3462019-01-21 17:56:03 +000095// An uuid used in unit tests.
96static constexpr const char* kTestUuid = "TEST";
97
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000098static constexpr const mode_t kRollbackFolderMode = 0700;
99
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700100static constexpr const char* kCpPath = "/system/bin/cp";
101static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -0700102
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000103static constexpr const char* kDataMirrorCePath = "/data_mirror/data_ce";
104static constexpr const char* kDataMirrorDePath = "/data_mirror/data_de";
Sanjana Sunil691163d2022-03-28 19:15:54 +0000105static constexpr const char* kMiscMirrorCePath = "/data_mirror/misc_ce";
106static constexpr const char* kMiscMirrorDePath = "/data_mirror/misc_de";
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000107
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -0700108static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +0000109
Andreas Gampe0354bd02016-06-27 14:25:30 -0700110static constexpr const char* PKG_LIB_POSTFIX = "/lib";
111static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
112static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
113
Zim0ce832d2019-12-03 17:03:58 +0000114static constexpr const char* kFuseProp = "persist.sys.fuse";
Victor Hsieh99de5162017-10-06 14:44:14 -0700115
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000116/**
117 * Property to control if app data isolation is enabled.
118 */
119static constexpr const char* kAppDataIsolationEnabledProperty = "persist.zygote.app_data_isolation";
Zim1edb92a2020-01-09 08:48:00 +0000120static constexpr const char* kMntSdcardfs = "/mnt/runtime/default/";
121static constexpr const char* kMntFuse = "/mnt/pass_through/0/";
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000122
123static std::atomic<bool> sAppDataIsolationEnabled(false);
124
Shikha Malhotradcf469b2022-03-23 11:53:58 +0000125/**
126 * Flag to control if project ids are supported for internal storage
127 */
128static std::atomic<bool> sUsingProjectIdsFlag(false);
129static std::once_flag flag;
130
Jeff Sharkey0274c972016-12-06 09:32:04 -0700131namespace {
132
Jeff Sharkey423e7462016-12-09 18:18:43 -0700133static binder::Status ok() {
134 return binder::Status::ok();
135}
136
137static binder::Status exception(uint32_t code, const std::string& msg) {
Jeff Sharkey8e9bf352018-02-27 11:40:45 -0700138 LOG(ERROR) << msg << " (" << code << ")";
Jeff Sharkey423e7462016-12-09 18:18:43 -0700139 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
140}
141
142static binder::Status error() {
143 return binder::Status::fromServiceSpecificError(errno);
144}
145
146static binder::Status error(const std::string& msg) {
147 PLOG(ERROR) << msg;
148 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
149}
150
151static binder::Status error(uint32_t code, const std::string& msg) {
152 LOG(ERROR) << msg << " (" << code << ")";
153 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
154}
155
Jeff Sharkey0274c972016-12-06 09:32:04 -0700156binder::Status checkUid(uid_t expectedUid) {
157 uid_t uid = IPCThreadState::self()->getCallingUid();
158 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700159 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700160 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700161 return exception(binder::Status::EX_SECURITY,
162 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
163 }
164}
165
Jooyung Han149be4a2020-01-23 12:45:10 +0900166binder::Status checkArgumentUuid(const std::optional<std::string>& uuid) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700167 if (!uuid || is_valid_filename(*uuid)) {
168 return ok();
169 } else {
170 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
171 StringPrintf("UUID %s is malformed", uuid->c_str()));
172 }
173}
174
Jooyung Han149be4a2020-01-23 12:45:10 +0900175binder::Status checkArgumentUuidTestOrNull(const std::optional<std::string>& uuid) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000176 if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
177 return ok();
178 } else {
179 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
180 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
181 }
182}
183
Jeff Sharkey423e7462016-12-09 18:18:43 -0700184binder::Status checkArgumentPackageName(const std::string& packageName) {
Greg Kaiser6d758fc2019-03-26 08:55:32 -0700185 if (is_valid_package_name(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700186 return ok();
187 } else {
188 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
189 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700190 }
191}
192
Jeff Sharkey53594302018-02-24 18:59:39 -0700193binder::Status checkArgumentPath(const std::string& path) {
194 if (path.empty()) {
195 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
196 }
197 if (path[0] != '/') {
198 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
199 StringPrintf("Path %s is relative", path.c_str()));
200 }
201 if ((path + '/').find("/../") != std::string::npos) {
202 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
203 StringPrintf("Path %s is shady", path.c_str()));
204 }
205 for (const char& c : path) {
206 if (c == '\0' || c == '\n') {
207 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
208 StringPrintf("Path %s is malformed", path.c_str()));
209 }
210 }
211 return ok();
212}
213
Jooyung Han149be4a2020-01-23 12:45:10 +0900214binder::Status checkArgumentPath(const std::optional<std::string>& path) {
Jeff Sharkey53594302018-02-24 18:59:39 -0700215 if (path) {
216 return checkArgumentPath(*path);
217 } else {
218 return ok();
219 }
220}
221
Alex Buynytskyyd04631f2022-08-12 15:14:41 -0700222binder::Status checkArgumentFileName(const std::string& path) {
223 if (path.empty()) {
224 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing name");
225 }
226 for (const char& c : path) {
227 if (c == '\0' || c == '\n' || c == '/') {
228 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
229 StringPrintf("Name %s is malformed", path.c_str()));
230 }
231 }
232 return ok();
233}
234
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700235binder::Status checkUidInAppRange(int32_t appUid) {
236 if (FIRST_APPLICATION_UID <= appUid && appUid <= LAST_APPLICATION_UID) {
237 return ok();
238 }
239 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
240 StringPrintf("UID %d is outside of the range", appUid));
241}
242
Jeff Sharkey0274c972016-12-06 09:32:04 -0700243#define ENFORCE_UID(uid) { \
244 binder::Status status = checkUid((uid)); \
245 if (!status.isOk()) { \
246 return status; \
247 } \
248}
249
Steven Moreland36945362023-07-05 20:29:10 +0000250// we could have tighter checks, but this is only to avoid hard errors. Negative values are defined
251// in UserHandle.java and carry specific meanings that may not be handled by certain APIs here.
Steven Moreland3e543b92023-09-07 20:08:15 +0000252#define ENFORCE_VALID_USER(userId) \
253 { \
254 if (static_cast<uid_t>(userId) >= std::numeric_limits<uid_t>::max() / AID_USER_OFFSET) { \
255 return error("userId invalid: " + std::to_string(userId)); \
256 } \
257 }
258
259#define ENFORCE_VALID_USER_OR_NULL(userId) \
260 { \
261 if (static_cast<uid_t>(userId) != USER_NULL) { \
262 ENFORCE_VALID_USER(userId); \
263 } \
Steven Moreland36945362023-07-05 20:29:10 +0000264 }
265
Jeff Sharkey423e7462016-12-09 18:18:43 -0700266#define CHECK_ARGUMENT_UUID(uuid) { \
267 binder::Status status = checkArgumentUuid((uuid)); \
268 if (!status.isOk()) { \
269 return status; \
270 } \
271}
272
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000273#define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) { \
274 auto status = checkArgumentUuidTestOrNull(uuid); \
275 if (!status.isOk()) { \
276 return status; \
277 } \
278} \
279
Jeff Sharkey423e7462016-12-09 18:18:43 -0700280#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
281 binder::Status status = \
282 checkArgumentPackageName((packageName)); \
283 if (!status.isOk()) { \
284 return status; \
285 } \
286}
287
Jeff Sharkey53594302018-02-24 18:59:39 -0700288#define CHECK_ARGUMENT_PATH(path) { \
289 binder::Status status = checkArgumentPath((path)); \
290 if (!status.isOk()) { \
291 return status; \
292 } \
293}
294
Alex Buynytskyyd04631f2022-08-12 15:14:41 -0700295#define CHECK_ARGUMENT_FILE_NAME(path) \
296 { \
297 binder::Status status = checkArgumentFileName((path)); \
298 if (!status.isOk()) { \
299 return status; \
300 } \
301 }
302
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700303#define CHECK_ARGUMENT_UID_IN_APP_RANGE(uid) \
304 { \
305 binder::Status status = checkUidInAppRange((uid)); \
306 if (!status.isOk()) { \
307 return status; \
308 } \
309 }
310
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800311#ifdef GRANULAR_LOCKS
312
313/**
314 * This class obtains in constructor and keeps the local strong pointer to the RefLock.
315 * On destruction, it checks if there are any other strong pointers, and remove the map entry if
316 * this was the last one.
317 */
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800318template <class Key, class Mutex>
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800319struct LocalLockHolder {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800320 using WeakPointer = std::weak_ptr<Mutex>;
321 using StrongPointer = std::shared_ptr<Mutex>;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800322 using Map = std::unordered_map<Key, WeakPointer>;
323 using MapLock = std::recursive_mutex;
324
325 LocalLockHolder(Key key, Map& map, MapLock& mapLock)
326 : mKey(std::move(key)), mMap(map), mMapLock(mapLock) {
327 std::lock_guard lock(mMapLock);
328 auto& weakPtr = mMap[mKey];
329
330 // Check if the RefLock is still alive.
331 mRefLock = weakPtr.lock();
332 if (!mRefLock) {
333 // Create a new lock.
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800334 mRefLock = std::make_shared<Mutex>();
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800335 weakPtr = mRefLock;
336 }
337 }
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800338 LocalLockHolder(LocalLockHolder&& other) noexcept
339 : mKey(std::move(other.mKey)),
340 mMap(other.mMap),
341 mMapLock(other.mMapLock),
342 mRefLock(std::move(other.mRefLock)) {
343 other.mRefLock.reset();
344 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800345 ~LocalLockHolder() {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800346 if (!mRefLock) {
347 return;
348 }
349
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800350 std::lock_guard lock(mMapLock);
351 // Clear the strong pointer.
352 mRefLock.reset();
353 auto found = mMap.find(mKey);
354 if (found == mMap.end()) {
355 return;
356 }
357 const auto& weakPtr = found->second;
358 // If this was the last pointer then it's ok to remove the map entry.
359 if (weakPtr.expired()) {
360 mMap.erase(found);
361 }
362 }
363
364 void lock() { mRefLock->lock(); }
365 void unlock() { mRefLock->unlock(); }
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800366 void lock_shared() { mRefLock->lock_shared(); }
367 void unlock_shared() { mRefLock->unlock_shared(); }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800368
369private:
370 Key mKey;
371 Map& mMap;
372 MapLock& mMapLock;
373 StrongPointer mRefLock;
374};
375
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800376using UserLock = LocalLockHolder<userid_t, std::shared_mutex>;
377using UserWriteLockGuard = std::unique_lock<UserLock>;
378using UserReadLockGuard = std::shared_lock<UserLock>;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800379
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800380using PackageLock = LocalLockHolder<std::string, std::recursive_mutex>;
381using PackageLockGuard = std::lock_guard<PackageLock>;
382
383#define LOCK_USER() \
384 UserLock localUserLock(userId, mUserIdLock, mLock); \
385 UserWriteLockGuard userLock(localUserLock)
386
387#define LOCK_USER_READ() \
388 UserLock localUserLock(userId, mUserIdLock, mLock); \
389 UserReadLockGuard userLock(localUserLock)
390
391#define LOCK_PACKAGE() \
392 PackageLock localPackageLock(packageName, mPackageNameLock, mLock); \
393 PackageLockGuard packageLock(localPackageLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800394
395#define LOCK_PACKAGE_USER() \
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800396 LOCK_USER_READ(); \
397 LOCK_PACKAGE()
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800398
399#else
400
401#define LOCK_USER() std::lock_guard lock(mLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800402#define LOCK_PACKAGE() std::lock_guard lock(mLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800403#define LOCK_PACKAGE_USER() \
404 (void)userId; \
405 std::lock_guard lock(mLock)
406
407#endif // GRANULAR_LOCKS
408
Jeff Sharkey0274c972016-12-06 09:32:04 -0700409} // namespace
410
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700411binder::Status InstalldNativeService::FsveritySetupAuthToken::authenticate(
412 const ParcelFileDescriptor& authFd, int32_t appUid, int32_t userId) {
413 int open_flags = fcntl(authFd.get(), F_GETFL);
414 if (open_flags < 0) {
415 return exception(binder::Status::EX_SERVICE_SPECIFIC, "fcntl failed");
416 }
417 if ((open_flags & O_ACCMODE) != O_WRONLY && (open_flags & O_ACCMODE) != O_RDWR) {
418 return exception(binder::Status::EX_SECURITY, "Received FD with unexpected open flag");
419 }
420 if (fstat(authFd.get(), &this->mStatFromAuthFd) < 0) {
421 return exception(binder::Status::EX_SERVICE_SPECIFIC, "fstat failed");
422 }
423 if (!S_ISREG(this->mStatFromAuthFd.st_mode)) {
424 return exception(binder::Status::EX_SECURITY, "Not a regular file");
425 }
426 // Don't accept a file owned by a different app.
427 uid_t uid = multiuser_get_uid(userId, appUid);
428 if (this->mStatFromAuthFd.st_uid != uid) {
429 return exception(binder::Status::EX_SERVICE_SPECIFIC, "File not owned by appUid");
430 }
431 return ok();
432}
433
434bool InstalldNativeService::FsveritySetupAuthToken::isSameStat(const struct stat& st) const {
435 return memcmp(&st, &mStatFromAuthFd, sizeof(st)) == 0;
436}
437
Jeff Sharkey0274c972016-12-06 09:32:04 -0700438status_t InstalldNativeService::start() {
439 IPCThreadState::self()->disableBackgroundScheduling(true);
440 status_t ret = BinderService<InstalldNativeService>::publish();
441 if (ret != android::OK) {
442 return ret;
443 }
444 sp<ProcessState> ps(ProcessState::self());
445 ps->startThreadPool();
446 ps->giveThreadPoolName();
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000447 sAppDataIsolationEnabled = android::base::GetBoolProperty(
Ricky Wai30f947d2019-12-19 17:24:48 +0000448 kAppDataIsolationEnabledProperty, true);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700449 return android::OK;
450}
451
Alex Buynytskyy17b12dc2022-09-12 20:57:24 -0700452status_t InstalldNativeService::dump(int fd, const Vector<String16>& /* args */) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700453 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600454 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Keun young Park144a9892021-10-13 16:43:58 -0700455 dprintf(fd, "Storage mounts:\n");
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600456 for (const auto& n : mStorageMounts) {
Keun young Park144a9892021-10-13 16:43:58 -0700457 dprintf(fd, " %s = %s\n", n.first.c_str(), n.second.c_str());
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600458 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700459 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700460
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700461 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600462 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Keun young Park144a9892021-10-13 16:43:58 -0700463 dprintf(fd, "Per-UID cache quotas:\n");
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700464 for (const auto& n : mCacheQuotas) {
Keun young Park144a9892021-10-13 16:43:58 -0700465 dprintf(fd, " %d = %" PRId64 "\n", n.first, n.second);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700466 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700467 }
468
Keun young Park144a9892021-10-13 16:43:58 -0700469 dprintf(fd, "is_dexopt_blocked:%d\n", android::installd::is_dexopt_blocked());
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700470
Jeff Sharkey0274c972016-12-06 09:32:04 -0700471 return NO_ERROR;
472}
473
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600474/**
475 * Perform restorecon of the given path, but only perform recursive restorecon
476 * if the label of that top-level file actually changed. This can save us
477 * significant time by avoiding no-op traversals of large filesystem trees.
478 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700479static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
480 bool existing) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700481 ScopedTrace tracer("restorecon-lazy");
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600482 int res = 0;
483 char* before = nullptr;
484 char* after = nullptr;
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000485 if (!existing) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700486 ScopedTrace tracer("new-path");
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000487 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
488 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
489 PLOG(ERROR) << "Failed recursive restorecon for " << path;
490 goto fail;
491 }
492 return res;
493 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600494
495 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
496 // libselinux. Not needed here.
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600497 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600498 PLOG(ERROR) << "Failed before getfilecon for " << path;
499 goto fail;
500 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700501 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600502 PLOG(ERROR) << "Failed top-level restorecon for " << path;
503 goto fail;
504 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600505 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600506 PLOG(ERROR) << "Failed after getfilecon for " << path;
507 goto fail;
508 }
509
510 // If the initial top-level restorecon above changed the label, then go
511 // back and restorecon everything recursively
Jeff Vander Stoep4689cdc2021-06-28 18:59:47 +0200512 if (strcmp(before, after)) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700513 ScopedTrace tracer("label-change");
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700514 if (existing) {
515 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
516 << path << "; running recursive restorecon";
517 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700518 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600519 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
520 PLOG(ERROR) << "Failed recursive restorecon for " << path;
521 goto fail;
522 }
523 }
524
525 goto done;
526fail:
527 res = -1;
528done:
529 free(before);
530 free(after);
531 return res;
532}
Shikha Malhotra976ae002022-02-26 15:39:53 +0000533static bool internal_storage_has_project_id() {
534 // The following path is populated in setFirstBoot, so if this file is present
Shikha Malhotradcf469b2022-03-23 11:53:58 +0000535 // then project ids can be used. Using call once to cache the result of this check
536 // to avoid having to check the file presence again and again.
537 std::call_once(flag, []() {
538 auto using_project_ids =
539 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
540 sUsingProjectIdsFlag = access(using_project_ids.c_str(), F_OK) == 0;
541 });
Shikha Malhotra8f55b3d2022-04-04 14:11:43 +0000542 // return sUsingProjectIdsFlag;
543 return false;
Shikha Malhotra976ae002022-02-26 15:39:53 +0000544}
545
546static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid, gid_t gid,
547 long project_id) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700548 {
549 ScopedTrace tracer("prepare-dir");
550 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
551 PLOG(ERROR) << "Failed to prepare " << path;
552 return -1;
553 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600554 }
Shikha Malhotra976ae002022-02-26 15:39:53 +0000555 if (internal_storage_has_project_id()) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700556 ScopedTrace tracer("set-quota");
Shikha Malhotra976ae002022-02-26 15:39:53 +0000557 return set_quota_project_id(path, project_id, true);
558 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600559 return 0;
560}
561
Shikha Malhotra976ae002022-02-26 15:39:53 +0000562static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
563 uid_t uid, gid_t gid, long project_id) {
564 auto path = StringPrintf("%s/%s", parent.c_str(), name);
Alex Buynytskyya203d712023-06-08 12:56:15 -0700565 int ret;
566 {
567 ScopedTrace tracer("prepare-cache-dir");
568 ret = prepare_app_cache_dir(parent, name, target_mode, uid, gid);
569 }
Shikha Malhotra976ae002022-02-26 15:39:53 +0000570 if (ret == 0 && internal_storage_has_project_id()) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700571 ScopedTrace tracer("set-quota-cache-dir");
Shikha Malhotra976ae002022-02-26 15:39:53 +0000572 return set_quota_project_id(path, project_id, true);
573 }
574 return ret;
575}
576
Calin Juravled2affb82017-11-28 17:41:43 -0800577static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700578 ScopedTrace tracer("prepare-app-profile");
Calin Juravled2affb82017-11-28 17:41:43 -0800579 int32_t uid = multiuser_get_uid(userId, appId);
580 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
581 if (shared_app_gid == -1) {
582 // TODO(calin): this should no longer be possible but do not continue if we don't get
583 // a valid shared gid.
584 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
585 return true;
586 }
587
588 const std::string profile_dir =
589 create_primary_current_profile_package_dir_path(userId, packageName);
590 // read-write-execute only for the app user.
591 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
592 PLOG(ERROR) << "Failed to prepare " << profile_dir;
593 return false;
594 }
Alan Stokes928d2c12020-12-09 10:11:24 +0000595 if (selinux_android_restorecon(profile_dir.c_str(), 0)) {
596 PLOG(ERROR) << "Failed to restorecon " << profile_dir;
597 return false;
598 }
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800599
Calin Juravled2affb82017-11-28 17:41:43 -0800600 const std::string ref_profile_path =
601 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800602
603 // Prepare the reference profile directory. Note that we use the non strict version of
604 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
605 // This is particularly important given that in O there were some fixes for how the
606 // shared_app_gid is computed.
607 //
608 // Note that by the time we get here we know that we are using a correct uid (otherwise
609 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
610 // are sure that the gid being used belongs to the owning app and not someone else.
611 //
612 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
613 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800614 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
615 return false;
616 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800617
Calin Juravled2affb82017-11-28 17:41:43 -0800618 return true;
619}
620
John Wu84e8f242021-10-21 11:50:41 -0700621static bool chown_app_dir(const std::string& path, uid_t uid, uid_t previousUid, gid_t cacheGid) {
622 FTS* fts;
623 char *argv[] = { (char*) path.c_str(), nullptr };
624 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
625 return false;
626 }
627 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
628 if (p->fts_info == FTS_D && p->fts_level == 1
629 && (strcmp(p->fts_name, "cache") == 0
630 || strcmp(p->fts_name, "code_cache") == 0)) {
631 // Mark cache dirs
632 p->fts_number = 1;
633 } else {
634 // Inherit parent's number
635 p->fts_number = p->fts_parent->fts_number;
636 }
637
638 switch (p->fts_info) {
639 case FTS_D:
640 case FTS_F:
641 case FTS_SL:
642 case FTS_SLNONE:
643 if (p->fts_statp->st_uid == previousUid) {
644 if (lchown(p->fts_path, uid, p->fts_number ? cacheGid : uid) != 0) {
645 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
646 }
647 } else {
648 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected UID "
649 << p->fts_statp->st_uid << " instead of " << previousUid;
650 }
651 break;
652 }
653 }
654 fts_close(fts);
655 return true;
656}
657
658static void chown_app_profile_dir(const std::string &packageName, int32_t appId, int32_t userId) {
659 uid_t uid = multiuser_get_uid(userId, appId);
660 gid_t sharedGid = multiuser_get_shared_gid(userId, appId);
661
662 const std::string profile_dir =
663 create_primary_current_profile_package_dir_path(userId, packageName);
664 char *argv[] = { (char*) profile_dir.c_str(), nullptr };
665 if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
666 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
667 switch (p->fts_info) {
668 case FTS_D:
669 case FTS_F:
670 case FTS_SL:
671 case FTS_SLNONE:
672 if (lchown(p->fts_path, uid, uid) != 0) {
673 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
674 }
675 break;
676 }
677 }
678 fts_close(fts);
679 }
680
681 const std::string ref_profile_path =
682 create_primary_reference_profile_package_dir_path(packageName);
683 argv[0] = (char *) ref_profile_path.c_str();
684 if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
685 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
686 if (p->fts_info == FTS_D && p->fts_level == 0) {
687 if (chown(p->fts_path, AID_SYSTEM, sharedGid) != 0) {
688 PLOG(WARNING) << "Failed to chown " << p->fts_path;
689 }
690 continue;
691 }
692 switch (p->fts_info) {
693 case FTS_D:
694 case FTS_F:
695 case FTS_SL:
696 case FTS_SLNONE:
697 if (lchown(p->fts_path, sharedGid, sharedGid) != 0) {
698 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
699 }
700 break;
701 }
702 }
703 fts_close(fts);
704 }
705}
706
Mohammad Samiul Islama73327a2022-03-09 09:59:32 +0000707static binder::Status createAppDataDirs(const std::string& path, int32_t uid, int32_t gid,
John Wu841a8022022-04-05 21:17:54 +0000708 int32_t previousUid, int32_t cacheGid,
Samiul Islam8621e552022-03-30 16:26:45 +0100709 const std::string& seInfo, mode_t targetMode,
710 long projectIdApp, long projectIdCache) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700711 ScopedTrace tracer("create-dirs");
John Wu84e8f242021-10-21 11:50:41 -0700712 struct stat st{};
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000713 bool parent_dir_exists = (stat(path.c_str(), &st) == 0);
714
715 auto cache_path = StringPrintf("%s/%s", path.c_str(), "cache");
716 auto code_cache_path = StringPrintf("%s/%s", path.c_str(), "code_cache");
717 bool cache_exists = (access(cache_path.c_str(), F_OK) == 0);
718 bool code_cache_exists = (access(code_cache_path.c_str(), F_OK) == 0);
719
720 if (parent_dir_exists) {
John Wu841a8022022-04-05 21:17:54 +0000721 if (previousUid > 0 && previousUid != uid) {
722 if (!chown_app_dir(path, uid, previousUid, cacheGid)) {
John Wu84e8f242021-10-21 11:50:41 -0700723 return error("Failed to chown " + path);
724 }
725 }
726 }
727
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000728 // Prepare only the parent app directory
Samiul Islam8621e552022-03-30 16:26:45 +0100729 if (prepare_app_dir(path, targetMode, uid, gid, projectIdApp) ||
730 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid, projectIdCache) ||
731 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid, projectIdCache)) {
John Wu84e8f242021-10-21 11:50:41 -0700732 return error("Failed to prepare " + path);
733 }
734
735 // Consider restorecon over contents if label changed
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000736 if (restorecon_app_data_lazy(path, seInfo, uid, parent_dir_exists)) {
John Wu84e8f242021-10-21 11:50:41 -0700737 return error("Failed to restorecon " + path);
738 }
739
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000740 // If the parent dir exists, the restorecon would already have been done
741 // as a part of the recursive restorecon above
742 if (parent_dir_exists && !cache_exists
743 && restorecon_app_data_lazy(cache_path, seInfo, uid, false)) {
744 return error("Failed to restorecon " + cache_path);
745 }
746
747 // If the parent dir exists, the restorecon would already have been done
748 // as a part of the recursive restorecon above
749 if (parent_dir_exists && !code_cache_exists
750 && restorecon_app_data_lazy(code_cache_path, seInfo, uid, false)) {
751 return error("Failed to restorecon " + code_cache_path);
752 }
John Wu84e8f242021-10-21 11:50:41 -0700753 return ok();
754}
755
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800756binder::Status InstalldNativeService::createAppDataLocked(
757 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
758 int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000759 int32_t targetSdkVersion, int64_t* ceDataInode, int64_t* deDataInode) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700760 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000761 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700762 CHECK_ARGUMENT_UUID(uuid);
763 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700764
765 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
766 const char* pkgname = packageName.c_str();
767
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700768 // Assume invalid inode unless filled in below
Songchun Fancb567f92023-09-11 17:04:47 +0000769 if (ceDataInode != nullptr) *ceDataInode = -1;
770 if (deDataInode != nullptr) *deDataInode = -1;
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700771
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700772 int32_t uid = multiuser_get_uid(userId, appId);
John Wu84e8f242021-10-21 11:50:41 -0700773
John Wu841a8022022-04-05 21:17:54 +0000774 // If previousAppId > 0, an app is changing its app ID
775 int32_t previousUid =
776 previousAppId > 0 ? (int32_t)multiuser_get_uid(userId, previousAppId) : -1;
John Wu84e8f242021-10-21 11:50:41 -0700777
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700778 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700779 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
780
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700781 // If UID doesn't have a specific cache GID, use UID value
782 if (cacheGid == -1) {
783 cacheGid = uid;
784 }
785
Samiul Islam8621e552022-03-30 16:26:45 +0100786 long projectIdApp = get_project_id(uid, PROJECT_ID_APP_START);
787 long projectIdCache = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
788
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700789 if (flags & FLAG_STORAGE_CE) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700790 ScopedTrace tracer("ce");
Jeff Sharkey0274c972016-12-06 09:32:04 -0700791 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700792
John Wu841a8022022-04-05 21:17:54 +0000793 auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
Samiul Islam8621e552022-03-30 16:26:45 +0100794 projectIdApp, projectIdCache);
John Wu84e8f242021-10-21 11:50:41 -0700795 if (!status.isOk()) {
796 return status;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600797 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600798
799 // Remember inode numbers of cache directories so that we can clear
800 // contents while CE storage is locked
801 if (write_path_inode(path, "cache", kXattrInodeCache) ||
802 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700803 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700804 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700805
806 // And return the CE inode of the top-level data directory so we can
807 // clear contents while CE storage is locked
Songchun Fancb567f92023-09-11 17:04:47 +0000808 if (ceDataInode != nullptr) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000809 ino_t result;
810 if (get_path_inode(path, &result) != 0) {
811 return error("Failed to get_path_inode for " + path);
812 }
Songchun Fancb567f92023-09-11 17:04:47 +0000813 *ceDataInode = static_cast<uint64_t>(result);
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700814 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700815 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700816 if (flags & FLAG_STORAGE_DE) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700817 ScopedTrace tracer("de");
Jeff Sharkey0274c972016-12-06 09:32:04 -0700818 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700819
John Wu841a8022022-04-05 21:17:54 +0000820 auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
Samiul Islam8621e552022-03-30 16:26:45 +0100821 projectIdApp, projectIdCache);
John Wu84e8f242021-10-21 11:50:41 -0700822 if (!status.isOk()) {
823 return status;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600824 }
John Wu841a8022022-04-05 21:17:54 +0000825 if (previousUid > 0 && previousUid != uid) {
John Wu3b383372022-02-09 02:21:39 -0800826 chown_app_profile_dir(packageName, appId, userId);
827 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600828
Calin Juravled2affb82017-11-28 17:41:43 -0800829 if (!prepare_app_profile_dir(packageName, appId, userId)) {
830 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000831 }
Songchun Fancb567f92023-09-11 17:04:47 +0000832
833 if (deDataInode != nullptr) {
834 ino_t result;
835 if (get_path_inode(path, &result) != 0) {
836 return error("Failed to get_path_inode for " + path);
837 }
838 *deDataInode = static_cast<uint64_t>(result);
839 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700840 }
Samiul Islamc40dff52022-01-14 16:24:48 +0000841
Samiul Islam7d5b1da2022-02-21 15:23:36 +0000842 if (flags & FLAG_STORAGE_SDK) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700843 ScopedTrace tracer("sdk");
Samiul Islam92f5cf02022-02-03 12:45:51 +0000844 // Safe to ignore status since we can retry creating this by calling reconcileSdkData
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000845 auto ignore = createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000846 if (!ignore.isOk()) {
847 PLOG(WARNING) << "Failed to create sdk data package directory for " << packageName;
Samiul Islamc40dff52022-01-14 16:24:48 +0000848 }
Samiul Islam92f5cf02022-02-03 12:45:51 +0000849 } else {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700850 ScopedTrace tracer("destroy-sdk");
Samiul Islam92f5cf02022-02-03 12:45:51 +0000851 // Package does not need sdk storage. Remove it.
Rishabh Singhe84b0b12022-02-02 20:56:13 +0000852 destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
Samiul Islamc40dff52022-01-14 16:24:48 +0000853 }
854
855 return ok();
856}
857
858/**
Samiul Islam92f5cf02022-02-03 12:45:51 +0000859 * Responsible for creating /data/misc_{ce|de}/user/0/sdksandbox/<package-name> directory and other
Samiul Islamc40dff52022-01-14 16:24:48 +0000860 * app level sub directories, such as ./shared
861 */
Samiul Islam92f5cf02022-02-03 12:45:51 +0000862binder::Status InstalldNativeService::createSdkSandboxDataPackageDirectory(
Samiul Islamc40dff52022-01-14 16:24:48 +0000863 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000864 int32_t appId, int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +0000865 ENFORCE_VALID_USER(userId);
866
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000867 int32_t sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
868 if (sdkSandboxUid == -1) {
869 // There no valid sdk sandbox process for this app. Skip creation of data directory
Samiul Islamc40dff52022-01-14 16:24:48 +0000870 return ok();
871 }
872
Samiul Islamc40dff52022-01-14 16:24:48 +0000873 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
874
875 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +0000876 for (int currentFlag : storageFlags) {
Samiul Islamc40dff52022-01-14 16:24:48 +0000877 if ((flags & currentFlag) == 0) {
878 continue;
879 }
880 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
881
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000882 // /data/misc_{ce,de}/<user-id>/sdksandbox directory gets created by vold
Samiul Islamc40dff52022-01-14 16:24:48 +0000883 // during user creation
884
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000885 // Prepare the package directory
Samiul Islam92f5cf02022-02-03 12:45:51 +0000886 auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
887 packageName.c_str());
888#if SDK_DEBUG
889 LOG(DEBUG) << "Creating app-level sdk data directory: " << packagePath;
890#endif
891
Shikha Malhotra976ae002022-02-26 15:39:53 +0000892 if (prepare_app_dir(packagePath, 0751, AID_SYSTEM, AID_SYSTEM, 0)) {
Samiul Islam92f5cf02022-02-03 12:45:51 +0000893 return error("Failed to prepare " + packagePath);
Samiul Islamc40dff52022-01-14 16:24:48 +0000894 }
Samiul Islamc40dff52022-01-14 16:24:48 +0000895 }
896
Jeff Sharkey423e7462016-12-09 18:18:43 -0700897 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700898}
899
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600900binder::Status InstalldNativeService::createAppData(
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800901 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
902 int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000903 int32_t targetSdkVersion, int64_t* ceDataInode, int64_t* deDataInode) {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800904 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000905 ENFORCE_VALID_USER(userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800906 CHECK_ARGUMENT_UUID(uuid);
907 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
908 LOCK_PACKAGE_USER();
909 return createAppDataLocked(uuid, packageName, userId, flags, appId, previousAppId, seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000910 targetSdkVersion, ceDataInode, deDataInode);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800911}
912
913binder::Status InstalldNativeService::createAppData(
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600914 const android::os::CreateAppDataArgs& args,
915 android::os::CreateAppDataResult* _aidl_return) {
916 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000917 ENFORCE_VALID_USER(args.userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800918 // Locking is performed depeer in the callstack.
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600919
920 int64_t ceDataInode = -1;
Songchun Fancb567f92023-09-11 17:04:47 +0000921 int64_t deDataInode = -1;
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600922 auto status = createAppData(args.uuid, args.packageName, args.userId, args.flags, args.appId,
Songchun Fancb567f92023-09-11 17:04:47 +0000923 args.previousAppId, args.seInfo, args.targetSdkVersion,
924 &ceDataInode, &deDataInode);
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600925 _aidl_return->ceDataInode = ceDataInode;
Songchun Fancb567f92023-09-11 17:04:47 +0000926 _aidl_return->deDataInode = deDataInode;
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600927 _aidl_return->exceptionCode = status.exceptionCode();
928 _aidl_return->exceptionMessage = status.exceptionMessage();
929 return ok();
930}
931
932binder::Status InstalldNativeService::createAppDataBatched(
933 const std::vector<android::os::CreateAppDataArgs>& args,
934 std::vector<android::os::CreateAppDataResult>* _aidl_return) {
935 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000936 for (const auto& arg : args) {
937 ENFORCE_VALID_USER(arg.userId);
938 }
939
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800940 // Locking is performed depeer in the callstack.
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600941
942 std::vector<android::os::CreateAppDataResult> results;
John Wu84e8f242021-10-21 11:50:41 -0700943 for (const auto &arg : args) {
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600944 android::os::CreateAppDataResult result;
945 createAppData(arg, &result);
946 results.push_back(result);
947 }
948 *_aidl_return = results;
949 return ok();
950}
951
Samiul Islam92f5cf02022-02-03 12:45:51 +0000952binder::Status InstalldNativeService::reconcileSdkData(
953 const android::os::ReconcileSdkDataArgs& args) {
Steven Moreland36945362023-07-05 20:29:10 +0000954 ENFORCE_VALID_USER(args.userId);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000955 // Locking is performed depeer in the callstack.
956
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000957 return reconcileSdkData(args.uuid, args.packageName, args.subDirNames, args.userId, args.appId,
958 args.previousAppId, args.seInfo, args.flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000959}
960
961/**
962 * Reconciles per-sdk directory under app-level sdk data directory.
963
964 * E.g. `/data/misc_ce/0/sdksandbox/<package-name>/<sdkPackageName>-<randomSuffix>
965 *
966 * - If the sdk data package directory is missing, we create it first.
967 * - If sdkPackageNames is empty, we delete sdk package directory since it's not needed anymore.
968 * - If a sdk level directory we need to prepare already exist, we skip creating it again. This
969 * is to avoid having same per-sdk directory with different suffix.
970 * - If a sdk level directory exist which is absent from sdkPackageNames, we remove it.
971 */
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000972binder::Status InstalldNativeService::reconcileSdkData(const std::optional<std::string>& uuid,
973 const std::string& packageName,
974 const std::vector<std::string>& subDirNames,
975 int userId, int appId, int previousAppId,
976 const std::string& seInfo, int flags) {
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +0000977 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000978 ENFORCE_VALID_USER(userId);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000979 CHECK_ARGUMENT_UUID(uuid);
980 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000981 LOCK_PACKAGE_USER();
982
983#if SDK_DEBUG
984 LOG(DEBUG) << "Creating per sdk data directory for: " << packageName;
985#endif
986
987 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
988
Samiul Islam92f5cf02022-02-03 12:45:51 +0000989 // Prepare the sdk package directory in case it's missing
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000990 const auto status =
991 createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000992 if (!status.isOk()) {
993 return status;
994 }
995
996 auto res = ok();
997 // We have to create sdk data for CE and DE storage
998 const int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
999 for (int currentFlag : storageFlags) {
1000 if ((flags & currentFlag) == 0) {
1001 continue;
1002 }
1003 const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1004
Samiul Islam92f5cf02022-02-03 12:45:51 +00001005 const auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
1006 packageName.c_str());
Samiul Islam92f5cf02022-02-03 12:45:51 +00001007
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001008 // Remove existing sub-directories not referred in subDirNames
1009 const std::unordered_set<std::string> expectedSubDirNames(subDirNames.begin(),
1010 subDirNames.end());
1011 const auto subDirHandler = [&packagePath, &expectedSubDirNames,
1012 &res](const std::string& subDirName) {
Samiul Islam92f5cf02022-02-03 12:45:51 +00001013 // Remove the per-sdk directory if it is not referred in
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001014 // expectedSubDirNames
1015 if (expectedSubDirNames.find(subDirName) == expectedSubDirNames.end()) {
1016 auto path = packagePath + "/" + subDirName;
1017 if (delete_dir_contents_and_dir(path) != 0) {
1018 res = error("Failed to delete " + path);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001019 return;
1020 }
Samiul Islam92f5cf02022-02-03 12:45:51 +00001021 }
1022 };
1023 const int ec = foreach_subdir(packagePath, subDirHandler);
1024 if (ec != 0) {
1025 res = error("Failed to process subdirs for " + packagePath);
1026 continue;
1027 }
1028
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001029 // Now create the subDirNames
1030 for (const auto& subDirName : subDirNames) {
1031 const std::string path =
1032 create_data_misc_sdk_sandbox_sdk_path(uuid_, isCeData, userId,
1033 packageName.c_str(), subDirName.c_str());
Samiul Islam92f5cf02022-02-03 12:45:51 +00001034
1035 // Create the directory along with cache and code_cache
1036 const int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
1037 if (cacheGid == -1) {
1038 return exception(binder::Status::EX_ILLEGAL_STATE,
1039 StringPrintf("cacheGid cannot be -1 for sdk data"));
1040 }
1041 const int32_t sandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
1042 int32_t previousSandboxUid = multiuser_get_sdk_sandbox_uid(userId, previousAppId);
Samiul Islam8621e552022-03-30 16:26:45 +01001043 int32_t appUid = multiuser_get_uid(userId, appId);
1044 long projectIdApp = get_project_id(appUid, PROJECT_ID_APP_START);
1045 long projectIdCache = get_project_id(appUid, PROJECT_ID_APP_CACHE_START);
1046 auto status =
John Wu841a8022022-04-05 21:17:54 +00001047 createAppDataDirs(path, sandboxUid, AID_NOBODY, previousSandboxUid, cacheGid,
Samiul Islam8621e552022-03-30 16:26:45 +01001048 seInfo, 0700 | S_ISGID, projectIdApp, projectIdCache);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001049 if (!status.isOk()) {
1050 res = status;
1051 continue;
1052 }
1053 }
1054 }
1055
1056 return res;
1057}
1058
Jooyung Han149be4a2020-01-23 12:45:10 +09001059binder::Status InstalldNativeService::migrateAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001060 const std::string& packageName, int32_t userId, int32_t flags) {
1061 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001062 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001063 CHECK_ARGUMENT_UUID(uuid);
1064 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001065 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001066
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001067 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1068 const char* pkgname = packageName.c_str();
1069
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001070 // This method only exists to upgrade system apps that have requested
1071 // forceDeviceEncrypted, so their default storage always lives in a
1072 // consistent location. This only works on non-FBE devices, since we
1073 // never want to risk exposing data on a device with real CE/DE storage.
1074
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001075 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
1076 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001077
1078 // If neither directory is marked as default, assume CE is default
1079 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
1080 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
1081 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001082 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001083 }
1084 }
1085
1086 // Migrate default data location if needed
1087 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
1088 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
1089
1090 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
1091 LOG(WARNING) << "Requested default storage " << target
1092 << " is not active; migrating from " << source;
1093 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001094 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001095 }
1096 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001097 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001098 }
1099 }
1100
Jeff Sharkey423e7462016-12-09 18:18:43 -07001101 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001102}
1103
Calin Juravle6a1648e2016-02-01 12:12:16 +00001104
Calin Juravle562de812018-01-20 23:34:18 -08001105binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
1106 const std::string& profileName) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001107 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001108 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyydf2fb612022-08-12 15:42:01 -07001109 CHECK_ARGUMENT_FILE_NAME(profileName);
1110 if (!base::EndsWith(profileName, ".prof")) {
1111 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
1112 StringPrintf("Profile name %s does not end with .prof",
1113 profileName.c_str()));
1114 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001115 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001116
Jeff Sharkey423e7462016-12-09 18:18:43 -07001117 binder::Status res = ok();
Calin Juravle562de812018-01-20 23:34:18 -08001118 if (!clear_primary_reference_profile(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001119 res = error("Failed to clear reference profile for " + packageName);
1120 }
Calin Juravle562de812018-01-20 23:34:18 -08001121 if (!clear_primary_current_profiles(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001122 res = error("Failed to clear current profiles for " + packageName);
1123 }
1124 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001125}
1126
Jooyung Han149be4a2020-01-23 12:45:10 +09001127binder::Status InstalldNativeService::clearAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001128 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1129 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001130 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001131 CHECK_ARGUMENT_UUID(uuid);
1132 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001133 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001134
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001135 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1136 const char* pkgname = packageName.c_str();
1137
Jeff Sharkey423e7462016-12-09 18:18:43 -07001138 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001139 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001140 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001141 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1142 path = read_path_inode(path, "cache", kXattrInodeCache);
1143 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1144 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
1145 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001146 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001147 if (delete_dir_contents(path) != 0) {
1148 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +09001149 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
1150 remove_path_xattr(path, kXattrInodeCache);
1151 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001152 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001153 }
1154 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001155 if (flags & FLAG_STORAGE_DE) {
John Wu84e8f242021-10-21 11:50:41 -07001156 std::string suffix;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001157 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1158 suffix = CACHE_DIR_POSTFIX;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001159 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1160 suffix = CODE_CACHE_DIR_POSTFIX;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001161 }
1162
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001163 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001164 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001165 if (delete_dir_contents(path) != 0) {
1166 res = error("Failed to delete contents of " + path);
1167 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001168 }
1169 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001170 if (flags & FLAG_STORAGE_EXTERNAL) {
1171 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1172 for (const auto& n : mStorageMounts) {
1173 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +00001174
1175 if (android::base::GetBoolProperty(kFuseProp, false)) {
1176 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1177 if (std::regex_match(extPath, re)) {
1178 extPath += "/" + std::to_string(userId);
1179 }
1180 } else {
1181 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1182 extPath += StringPrintf("/%d", userId);
1183 } else if (userId != 0) {
1184 // TODO: support devices mounted under secondary users
1185 continue;
1186 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001187 }
Zim0ce832d2019-12-03 17:03:58 +00001188
Jeff Sharkey6e175692019-05-14 14:55:33 -06001189 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1190 // Clear only cached data from shared storage
1191 auto path = StringPrintf("%s/Android/data/%s/cache", extPath.c_str(), pkgname);
1192 if (delete_dir_contents(path, true) != 0) {
1193 res = error("Failed to delete contents of " + path);
1194 }
1195 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1196 // No code cache on shared storage
1197 } else {
1198 // Clear everything on shared storage
1199 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
1200 if (delete_dir_contents(path, true) != 0) {
1201 res = error("Failed to delete contents of " + path);
1202 }
1203 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
1204 if (delete_dir_contents(path, true) != 0) {
1205 res = error("Failed to delete contents of " + path);
1206 }
Martijn Coenen24a93072020-01-08 10:10:43 +01001207 // Note that we explicitly don't delete OBBs - those are only removed on
1208 // app uninstall.
Jeff Sharkey6e175692019-05-14 14:55:33 -06001209 }
1210 }
1211 }
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001212 auto status = clearSdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1213 if (!status.isOk()) {
1214 res = status;
1215 }
1216 return res;
1217}
1218
1219binder::Status InstalldNativeService::clearSdkSandboxDataPackageDirectory(
1220 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1221 int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00001222 ENFORCE_VALID_USER(userId);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001223 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1224 const char* pkgname = packageName.c_str();
1225
1226 binder::Status res = ok();
1227 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1228 for (int i = 0; i < 2; i++) {
1229 int currentFlag = storageFlags[i];
1230 if ((flags & currentFlag) == 0) {
1231 continue;
1232 }
1233 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1234 std::string suffix;
1235 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1236 suffix = CACHE_DIR_POSTFIX;
1237 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1238 suffix = CODE_CACHE_DIR_POSTFIX;
1239 }
1240
1241 auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1242 if (access(appPath.c_str(), F_OK) != 0) continue;
1243 const auto subDirHandler = [&appPath, &res, &suffix](const std::string& filename) {
1244 auto filepath = appPath + "/" + filename + suffix;
1245 if (delete_dir_contents(filepath, true) != 0) {
1246 res = error("Failed to clear contents of " + filepath);
1247 }
1248 };
1249 const int ec = foreach_subdir(appPath, subDirHandler);
1250 if (ec != 0) {
1251 res = error("Failed to process subdirs for " + appPath);
1252 }
1253 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001254 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001255}
1256
Calin Juravle76268c52017-03-09 13:19:42 -08001257static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +01001258 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -08001259 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +01001260 /*ignore_if_missing*/ true);
1261}
1262
Calin Juravle76268c52017-03-09 13:19:42 -08001263static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +01001264 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -08001265 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +01001266 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +00001267}
1268
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001269binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
1270 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001271 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001272 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001273
Jeff Sharkey423e7462016-12-09 18:18:43 -07001274 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +00001275 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1276 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -08001277 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001278 res = error("Failed to destroy current profiles for " + packageName);
1279 }
Calin Juravleedae6692016-03-23 13:55:31 +00001280 }
Calin Juravle76268c52017-03-09 13:19:42 -08001281 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001282 res = error("Failed to destroy reference profile for " + packageName);
1283 }
1284 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +00001285}
1286
Jiakai Zhangee00e3b2022-03-24 15:03:04 +00001287binder::Status InstalldNativeService::deleteReferenceProfile(const std::string& packageName,
1288 const std::string& profileName) {
1289 ENFORCE_UID(AID_SYSTEM);
1290 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1291 LOCK_PACKAGE();
1292
1293 // This function only supports primary dex'es.
1294 std::string path =
1295 create_reference_profile_path(packageName, profileName, /*is_secondary_dex=*/false);
1296 if (unlink(path.c_str()) != 0) {
1297 if (errno == ENOENT) {
1298 return ok();
1299 } else {
1300 return error("Failed to delete profile " + profileName + " for " + packageName);
1301 }
1302 }
1303 return ok();
1304}
1305
Jooyung Han149be4a2020-01-23 12:45:10 +09001306binder::Status InstalldNativeService::destroyAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001307 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1308 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001309 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001310 CHECK_ARGUMENT_UUID(uuid);
1311 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001312 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001313
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001314 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1315 const char* pkgname = packageName.c_str();
1316
Jeff Sharkey423e7462016-12-09 18:18:43 -07001317 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001318 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001319 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08001320 if (rename_delete_dir_contents_and_dir(path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001321 res = error("Failed to delete " + path);
1322 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001323 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001324 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001325 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08001326 if (rename_delete_dir_contents_and_dir(path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001327 res = error("Failed to delete " + path);
1328 }
Alan Stokesd983cc72020-02-14 14:36:58 +00001329 if ((flags & FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES) == 0) {
1330 destroy_app_current_profiles(packageName, userId);
1331 // TODO(calin): If the package is still installed by other users it's probably
1332 // beneficial to keep the reference profile around.
1333 // Verify if it's ok to do that.
1334 destroy_app_reference_profile(packageName);
1335 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001336 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001337 if (flags & FLAG_STORAGE_EXTERNAL) {
1338 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1339 for (const auto& n : mStorageMounts) {
1340 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +00001341
1342 if (android::base::GetBoolProperty(kFuseProp, false)) {
1343 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1344 if (std::regex_match(extPath, re)) {
1345 extPath += "/" + std::to_string(userId);
1346 }
1347 } else {
1348 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1349 extPath += StringPrintf("/%d", userId);
1350 } else if (userId != 0) {
1351 // TODO: support devices mounted under secondary users
1352 continue;
1353 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001354 }
Zim0ce832d2019-12-03 17:03:58 +00001355
Jeff Sharkey6e175692019-05-14 14:55:33 -06001356 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001357 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001358 res = error("Failed to delete contents of " + path);
1359 }
1360 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001361 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001362 res = error("Failed to delete contents of " + path);
1363 }
1364 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001365 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001366 res = error("Failed to delete contents of " + path);
1367 }
1368 }
1369 }
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001370 auto status = destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1371 if (!status.isOk()) {
1372 res = status;
1373 }
1374 return res;
1375}
1376
1377binder::Status InstalldNativeService::destroySdkSandboxDataPackageDirectory(
1378 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1379 int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00001380 ENFORCE_VALID_USER(userId);
1381
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001382 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1383 const char* pkgname = packageName.c_str();
1384
1385 binder::Status res = ok();
1386 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1387 for (int i = 0; i < 2; i++) {
1388 int currentFlag = storageFlags[i];
1389 if ((flags & currentFlag) == 0) {
1390 continue;
1391 }
1392 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1393 auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1394 if (rename_delete_dir_contents_and_dir(appPath) != 0) {
1395 res = error("Failed to delete " + appPath);
1396 }
1397 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001398 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001399}
1400
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001401static gid_t get_cache_gid(uid_t uid) {
1402 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
1403 return (gid != -1) ? gid : uid;
1404}
1405
Jooyung Han149be4a2020-01-23 12:45:10 +09001406binder::Status InstalldNativeService::fixupAppData(const std::optional<std::string>& uuid,
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001407 int32_t flags) {
1408 ENFORCE_UID(AID_SYSTEM);
1409 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001410
1411 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001412 for (auto userId : get_known_users(uuid_)) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001413 LOCK_USER();
Zim23457d02022-08-17 12:57:41 +01001414 atrace_pm_begin("fixup user");
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001415 FTS* fts;
1416 FTSENT* p;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001417 auto ce_path = create_data_user_ce_path(uuid_, userId);
1418 auto de_path = create_data_user_de_path(uuid_, userId);
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001419 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001420 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001421 return error("Failed to fts_open");
1422 }
1423 while ((p = fts_read(fts)) != nullptr) {
1424 if (p->fts_info == FTS_D && p->fts_level == 1) {
1425 // Track down inodes of cache directories
1426 uint64_t raw = 0;
1427 ino_t inode_cache = 0;
1428 ino_t inode_code_cache = 0;
1429 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1430 inode_cache = raw;
1431 }
1432 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1433 inode_code_cache = raw;
1434 }
1435
1436 // Figure out expected GID of each child
1437 FTSENT* child = fts_children(fts, 0);
1438 while (child != nullptr) {
1439 if ((child->fts_statp->st_ino == inode_cache)
1440 || (child->fts_statp->st_ino == inode_code_cache)
1441 || !strcmp(child->fts_name, "cache")
1442 || !strcmp(child->fts_name, "code_cache")) {
1443 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
1444 } else {
1445 child->fts_number = p->fts_statp->st_uid;
1446 }
1447 child = child->fts_link;
1448 }
1449 } else if (p->fts_level >= 2) {
1450 if (p->fts_level > 2) {
1451 // Inherit GID from parent once we're deeper into tree
1452 p->fts_number = p->fts_parent->fts_number;
1453 }
1454
1455 uid_t uid = p->fts_parent->fts_statp->st_uid;
1456 gid_t cache_gid = get_cache_gid(uid);
1457 gid_t expected = p->fts_number;
1458 gid_t actual = p->fts_statp->st_gid;
1459 if (actual == expected) {
1460#if FIXUP_DEBUG
1461 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
1462#endif
1463 if (!(flags & FLAG_FORCE)) {
1464 fts_set(fts, p, FTS_SKIP);
1465 }
1466 } else if ((actual == uid) || (actual == cache_gid)) {
1467 // Only consider fixing up when current GID belongs to app
1468 if (p->fts_info != FTS_D) {
1469 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
1470 << " instead of " << expected;
1471 }
1472 switch (p->fts_info) {
1473 case FTS_DP:
1474 // If we're moving towards cache GID, we need to set S_ISGID
1475 if (expected == cache_gid) {
1476 if (chmod(p->fts_path, 02771) != 0) {
1477 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1478 }
1479 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001480 [[fallthrough]]; // also set GID
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001481 case FTS_F:
1482 if (chown(p->fts_path, -1, expected) != 0) {
1483 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1484 }
1485 break;
1486 case FTS_SL:
1487 case FTS_SLNONE:
1488 if (lchown(p->fts_path, -1, expected) != 0) {
1489 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1490 }
1491 break;
1492 }
1493 } else {
1494 // Ignore all other GID transitions, since they're kinda shady
1495 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
1496 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -06001497 if (!(flags & FLAG_FORCE)) {
1498 fts_set(fts, p, FTS_SKIP);
1499 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001500 }
1501 }
1502 }
1503 fts_close(fts);
Zim23457d02022-08-17 12:57:41 +01001504 atrace_pm_end();
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001505 }
1506 return ok();
1507}
1508
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001509static int32_t copy_directory_recursive(const char* from, const char* to) {
Dario Freni918beeb2021-12-22 01:00:01 +00001510 char* argv[] =
1511 {(char*)kCpPath,
1512 (char*)"-F", /* delete any existing destination file first (--remove-destination) */
1513 (char*)"--preserve=mode,ownership,timestamps,xattr", /* preserve properties */
1514 (char*)"-R", /* recurse into subdirectories (DEST must be a directory) */
1515 (char*)"-P", /* Do not follow symlinks [default] */
1516 (char*)"-d", /* don't dereference symlinks */
1517 (char*)from,
1518 (char*)to};
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001519
1520 LOG(DEBUG) << "Copying " << from << " to " << to;
Tom Cherrye79cde52019-09-25 16:51:56 -07001521 return logwrap_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, LOG_ALOG, false, nullptr);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001522}
1523
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001524binder::Status InstalldNativeService::snapshotAppData(const std::optional<std::string>& volumeUuid,
1525 const std::string& packageName,
1526 int32_t userId, int32_t snapshotId,
1527 int32_t storageFlags, int64_t* _aidl_return) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001528 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001529 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001530 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001531 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001532 LOCK_PACKAGE_USER();
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001533
1534 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1535 const char* package_name = packageName.c_str();
1536
1537 binder::Status res = ok();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001538 // Default result to 0, it will be populated with inode of ce data snapshot
1539 // if FLAG_STORAGE_CE has been passed.
1540 if (_aidl_return != nullptr) *_aidl_return = 0;
1541
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001542 bool clear_ce_on_exit = false;
1543 bool clear_de_on_exit = false;
1544
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001545 auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &userId, &package_name,
1546 &snapshotId] {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001547 if (clear_de_on_exit) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001548 auto to = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1549 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001550 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1551 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1552 }
1553 }
1554
1555 if (clear_ce_on_exit) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001556 auto to = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1557 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001558 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1559 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1560 }
1561 }
1562 };
1563
1564 auto scope_guard = android::base::make_scope_guard(deleter);
1565
JW Wang1d643c72020-10-06 13:42:41 +08001566 if (storageFlags & FLAG_STORAGE_DE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001567 auto from = create_data_user_de_package_path(volume_uuid, userId, package_name);
1568 auto to = create_data_misc_de_rollback_path(volume_uuid, userId, snapshotId);
1569 auto rollback_package_path =
1570 create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1571 package_name);
JW Wang1d643c72020-10-06 13:42:41 +08001572
1573 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1574 if (rc != 0) {
1575 return error(rc, "Failed to create folder " + to);
1576 }
1577
1578 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1579 if (rc != 0) {
1580 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1581 }
1582
1583 // Check if we have data to copy.
1584 if (access(from.c_str(), F_OK) == 0) {
1585 rc = copy_directory_recursive(from.c_str(), to.c_str());
1586 }
1587 if (rc != 0) {
1588 res = error(rc, "Failed copying " + from + " to " + to);
1589 clear_de_on_exit = true;
1590 return res;
1591 }
1592 }
1593
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001594 // The app may not have any data at all, in which case it's OK to skip here.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001595 auto from_ce = create_data_user_ce_package_path(volume_uuid, userId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001596 if (access(from_ce.c_str(), F_OK) != 0) {
1597 LOG(INFO) << "Missing source " << from_ce;
1598 return ok();
1599 }
1600
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001601 // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001602 binder::Status clear_cache_result =
1603 clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001604 if (!clear_cache_result.isOk()) {
1605 // It should be fine to continue snapshot if we for some reason failed
1606 // to clear cache.
1607 LOG(WARNING) << "Failed to clear cache of app " << packageName;
1608 }
1609
1610 // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001611 binder::Status clear_code_cache_result =
1612 clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY,
1613 0);
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001614 if (!clear_code_cache_result.isOk()) {
1615 // It should be fine to continue snapshot if we for some reason failed
1616 // to clear code_cache.
1617 LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
1618 }
1619
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001620 if (storageFlags & FLAG_STORAGE_CE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001621 auto from = create_data_user_ce_package_path(volume_uuid, userId, package_name);
1622 auto to = create_data_misc_ce_rollback_path(volume_uuid, userId, snapshotId);
1623 auto rollback_package_path =
1624 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1625 package_name);
Nikita Ioffe835ae772019-01-23 16:32:13 +00001626
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001627 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1628 if (rc != 0) {
1629 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +00001630 }
1631
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001632 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1633 if (rc != 0) {
1634 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1635 }
1636
1637 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001638 if (rc != 0) {
1639 res = error(rc, "Failed copying " + from + " to " + to);
1640 clear_ce_on_exit = true;
1641 return res;
1642 }
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001643 if (_aidl_return != nullptr) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001644 auto ce_snapshot_path =
1645 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1646 package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001647 rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
1648 if (rc != 0) {
1649 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
1650 clear_ce_on_exit = true;
1651 return res;
1652 }
1653 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001654 }
1655
1656 return res;
1657}
1658
1659binder::Status InstalldNativeService::restoreAppDataSnapshot(
Jooyung Han149be4a2020-01-23 12:45:10 +09001660 const std::optional<std::string>& volumeUuid, const std::string& packageName,
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001661 const int32_t appId, const std::string& seInfo, const int32_t userId,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001662 const int32_t snapshotId, int32_t storageFlags) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001663 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001664 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001665 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001666 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001667 LOCK_PACKAGE_USER();
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001668
1669 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1670 const char* package_name = packageName.c_str();
1671
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001672 auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1673 package_name);
1674 auto from_de = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1675 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001676
1677 const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
1678 (access(from_ce.c_str(), F_OK) == 0);
1679 const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
1680 (access(from_de.c_str(), F_OK) == 0);
1681
1682 if (!needs_ce_rollback && !needs_de_rollback) {
1683 return ok();
1684 }
1685
1686 // We know we're going to rollback one of the CE or DE data, so we clear
1687 // application data first. Note that it's possible that we're asked to
1688 // restore both CE & DE data but that one of the restores fail. Leaving the
1689 // app with no data in those cases is arguably better than leaving the app
1690 // with mismatched / stale data.
1691 LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001692 // It's fine to pass 0 as ceDataInode here, because restoreAppDataSnapshot
1693 // can only be called when user unlocks the phone, meaning that CE user data
1694 // is decrypted.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001695 binder::Status res =
1696 clearAppData(volumeUuid, packageName, userId, storageFlags, 0 /* ceDataInode */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001697 if (!res.isOk()) {
1698 return res;
1699 }
1700
1701 if (needs_ce_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001702 auto to_ce = create_data_user_ce_path(volume_uuid, userId);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001703 int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
1704 if (rc != 0) {
1705 res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
1706 return res;
1707 }
JW Wangfda19ec2020-05-18 16:54:08 +08001708 delete_dir_contents_and_dir(from_ce, true /* ignore_if_missing */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001709 }
1710
1711 if (needs_de_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001712 auto to_de = create_data_user_de_path(volume_uuid, userId);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001713 int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
1714 if (rc != 0) {
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001715 if (needs_ce_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001716 auto ce_data = create_data_user_ce_package_path(volume_uuid, userId, package_name);
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001717 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
1718 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
1719 LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
1720 }
1721 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001722 res = error(rc, "Failed copying " + from_de + " to " + to_de);
1723 return res;
1724 }
JW Wangfda19ec2020-05-18 16:54:08 +08001725 delete_dir_contents_and_dir(from_de, true /* ignore_if_missing */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001726 }
1727
1728 // Finally, restore the SELinux label on the app data.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001729 return restoreconAppData(volumeUuid, packageName, userId, storageFlags, appId, seInfo);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001730}
1731
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001732binder::Status InstalldNativeService::destroyAppDataSnapshot(
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001733 const std::optional<std::string>& volumeUuid, const std::string& packageName,
1734 const int32_t userId, const int64_t ceSnapshotInode, const int32_t snapshotId,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001735 int32_t storageFlags) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001736 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001737 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001738 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1739 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001740 LOCK_PACKAGE_USER();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001741
1742 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1743 const char* package_name = packageName.c_str();
1744
1745 if (storageFlags & FLAG_STORAGE_DE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001746 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid, userId,
1747 snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001748
1749 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
1750 if (res != 0) {
1751 return error(res, "Failed clearing snapshot " + de_snapshot_path);
1752 }
1753 }
1754
1755 if (storageFlags & FLAG_STORAGE_CE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001756 auto ce_snapshot_path =
1757 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1758 package_name, ceSnapshotInode);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001759 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
1760 if (res != 0) {
1761 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
1762 }
1763 }
1764 return ok();
1765}
1766
Oli Lanc7789572020-03-16 18:18:41 +00001767binder::Status InstalldNativeService::destroyCeSnapshotsNotSpecified(
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001768 const std::optional<std::string>& volumeUuid, const int32_t userId,
Oli Lanc7789572020-03-16 18:18:41 +00001769 const std::vector<int32_t>& retainSnapshotIds) {
1770 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001771 ENFORCE_VALID_USER(userId);
Oli Lanc7789572020-03-16 18:18:41 +00001772 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001773 LOCK_USER();
Oli Lanc7789572020-03-16 18:18:41 +00001774
1775 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1776
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001777 auto base_path = create_data_misc_ce_rollback_base_path(volume_uuid, userId);
Oli Lanc7789572020-03-16 18:18:41 +00001778
1779 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(base_path.c_str()), closedir);
1780 if (!dir) {
1781 return error(-1, "Failed to open rollback base dir " + base_path);
1782 }
1783
1784 struct dirent* ent;
1785 while ((ent = readdir(dir.get()))) {
1786 if (ent->d_type != DT_DIR) {
1787 continue;
1788 }
1789
1790 uint snapshot_id;
1791 bool parse_ok = ParseUint(ent->d_name, &snapshot_id);
1792 if (parse_ok &&
1793 std::find(retainSnapshotIds.begin(), retainSnapshotIds.end(),
1794 snapshot_id) == retainSnapshotIds.end()) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001795 auto rollback_path =
1796 create_data_misc_ce_rollback_path(volume_uuid, userId, snapshot_id);
Oli Lanc7789572020-03-16 18:18:41 +00001797 int res = delete_dir_contents_and_dir(rollback_path, true /* ignore_if_missing */);
1798 if (res != 0) {
1799 return error(res, "Failed clearing snapshot " + rollback_path);
1800 }
1801 }
1802 }
1803 return ok();
1804}
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001805
Jooyung Han149be4a2020-01-23 12:45:10 +09001806binder::Status InstalldNativeService::moveCompleteApp(const std::optional<std::string>& fromUuid,
1807 const std::optional<std::string>& toUuid, const std::string& packageName,
Songchun Fandc2083f2020-02-18 17:45:46 -08001808 int32_t appId, const std::string& seInfo,
Songchun Fanaed33372020-02-05 12:02:22 -08001809 int32_t targetSdkVersion, const std::string& fromCodePath) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001810 ENFORCE_UID(AID_SYSTEM);
1811 CHECK_ARGUMENT_UUID(fromUuid);
1812 CHECK_ARGUMENT_UUID(toUuid);
1813 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001814 LOCK_PACKAGE();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001815
1816 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1817 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1818 const char* package_name = packageName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001819
Jeff Sharkey423e7462016-12-09 18:18:43 -07001820 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001821 std::vector<userid_t> users = get_known_users(from_uuid);
1822
Songchun Fandc2083f2020-02-18 17:45:46 -08001823 auto to_app_package_path_parent = create_data_app_path(to_uuid);
1824 auto to_app_package_path = StringPrintf("%s/%s", to_app_package_path_parent.c_str(),
1825 android::base::Basename(fromCodePath).c_str());
1826
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001827 // Copy app
1828 {
Songchun Fandc2083f2020-02-18 17:45:46 -08001829 int rc = copy_directory_recursive(fromCodePath.c_str(), to_app_package_path_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001830 if (rc != 0) {
Songchun Fandc2083f2020-02-18 17:45:46 -08001831 res = error(rc, "Failed copying " + fromCodePath + " to " + to_app_package_path);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001832 goto fail;
1833 }
1834
Songchun Fandc2083f2020-02-18 17:45:46 -08001835 if (selinux_android_restorecon(to_app_package_path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
1836 res = error("Failed to restorecon " + to_app_package_path);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001837 goto fail;
1838 }
1839 }
1840
1841 // Copy private data for all known users
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001842 for (auto userId : users) {
1843 LOCK_USER();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001844
1845 // Data source may not exist for all users; that's okay
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001846 auto from_ce = create_data_user_ce_package_path(from_uuid, userId, package_name);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001847 if (access(from_ce.c_str(), F_OK) != 0) {
1848 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001849 continue;
1850 }
1851
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001852 if (!createAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
Songchun Fancb567f92023-09-11 17:04:47 +00001853 appId, /* previousAppId */ -1, seInfo, targetSdkVersion, nullptr,
1854 nullptr)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001855 .isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001856 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001857 goto fail;
1858 }
Jeff Sharkey51c94492016-05-10 17:46:39 -06001859 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001860 auto from = create_data_user_de_package_path(from_uuid, userId, package_name);
1861 auto to = create_data_user_de_path(to_uuid, userId);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001862
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001863 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001864 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001865 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001866 goto fail;
1867 }
1868 }
1869 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001870 auto from = create_data_user_ce_package_path(from_uuid, userId, package_name);
1871 auto to = create_data_user_ce_path(to_uuid, userId);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001872
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001873 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001874 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001875 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001876 goto fail;
1877 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001878 }
1879
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001880 if (!restoreconAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1881 appId, seInfo)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001882 .isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001883 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001884 goto fail;
1885 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001886 }
1887
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001888 // Copy sdk data for all known users
1889 for (auto userId : users) {
1890 LOCK_USER();
1891
1892 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1893 for (int currentFlag : storageFlags) {
1894 const bool isCeData = currentFlag == FLAG_STORAGE_CE;
1895
1896 const auto from = create_data_misc_sdk_sandbox_package_path(from_uuid, isCeData, userId,
1897 package_name);
1898 if (access(from.c_str(), F_OK) != 0) {
1899 LOG(INFO) << "Missing source " << from;
1900 continue;
1901 }
1902 const auto to = create_data_misc_sdk_sandbox_path(to_uuid, isCeData, userId);
1903
1904 const int rc = copy_directory_recursive(from.c_str(), to.c_str());
1905 if (rc != 0) {
1906 res = error(rc, "Failed copying " + from + " to " + to);
1907 goto fail;
1908 }
1909 }
1910
1911 if (!restoreconSdkDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1912 appId, seInfo)
1913 .isOk()) {
1914 res = error("Failed to restorecon");
1915 goto fail;
1916 }
1917 }
Jeff Sharkey31f08982015-07-07 13:31:37 -07001918 // We let the framework scan the new location and persist that before
1919 // deleting the data in the old location; this ordering ensures that
1920 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001921 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001922
1923fail:
1924 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001925 {
Songchun Fandc2083f2020-02-18 17:45:46 -08001926 if (delete_dir_contents(to_app_package_path.c_str(), 1, nullptr) != 0) {
1927 LOG(WARNING) << "Failed to rollback " << to_app_package_path;
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001928 }
1929 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001930 for (auto userId : users) {
1931 LOCK_USER();
Jeff Sharkey51c94492016-05-10 17:46:39 -06001932 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001933 auto to = create_data_user_de_package_path(to_uuid, userId, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001934 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001935 LOG(WARNING) << "Failed to rollback " << to;
1936 }
1937 }
1938 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001939 auto to = create_data_user_ce_package_path(to_uuid, userId, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001940 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001941 LOG(WARNING) << "Failed to rollback " << to;
1942 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001943 }
1944 }
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001945 for (auto userId : users) {
1946 LOCK_USER();
1947 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1948 for (int currentFlag : storageFlags) {
1949 const bool isCeData = currentFlag == FLAG_STORAGE_CE;
1950 const auto to = create_data_misc_sdk_sandbox_package_path(to_uuid, isCeData, userId,
1951 package_name);
1952 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1953 LOG(WARNING) << "Failed to rollback " << to;
1954 }
1955 }
1956 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001957 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001958}
1959
Jooyung Han149be4a2020-01-23 12:45:10 +09001960binder::Status InstalldNativeService::createUserData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001961 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
1962 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001963 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001964 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001965 LOCK_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001966
Alex Buynytskyya203d712023-06-08 12:56:15 -07001967 ScopedTrace tracer("create-user-data");
1968
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001969 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001970 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001971 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001972 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001973 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07001974 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001975 }
1976 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001977
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001978 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001979}
1980
Jooyung Han149be4a2020-01-23 12:45:10 +09001981binder::Status InstalldNativeService::destroyUserData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001982 int32_t userId, int32_t flags) {
1983 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001984 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001985 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001986 LOCK_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001987
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001988 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001989 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001990 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001991 auto path = create_data_user_de_path(uuid_, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00001992 // Contents only, as vold is responsible for the user_de dir itself.
1993 if (delete_dir_contents(path, true) != 0) {
1994 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001995 }
Rishabh Singh8d784372022-03-09 15:54:46 +00001996 auto sdk_sandbox_de_path =
1997 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
1998 if (delete_dir_contents_and_dir(sdk_sandbox_de_path, true) != 0) {
1999 res = error("Failed to delete " + sdk_sandbox_de_path);
2000 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002001 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002002 path = create_data_misc_legacy_path(userId);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08002003 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002004 res = error("Failed to delete " + path);
2005 }
Calin Juravle114f0812017-03-08 19:05:07 -08002006 path = create_primary_cur_profile_dir_path(userId);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08002007 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002008 res = error("Failed to delete " + path);
2009 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002010 }
Robin Lee095c7632014-04-25 15:05:19 +01002011 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06002012 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002013 auto path = create_data_user_ce_path(uuid_, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00002014 // Contents only, as vold is responsible for the user_ce dir itself.
2015 if (delete_dir_contents(path, true) != 0) {
2016 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002017 }
Rishabh Singh8d784372022-03-09 15:54:46 +00002018 auto sdk_sandbox_ce_path =
2019 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2020 if (delete_dir_contents_and_dir(sdk_sandbox_ce_path, true) != 0) {
2021 res = error("Failed to delete " + sdk_sandbox_ce_path);
2022 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002023 path = findDataMediaPath(uuid, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00002024 // Contents only, as vold is responsible for the media dir itself.
2025 if (delete_dir_contents(path, true) != 0) {
2026 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002027 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06002028 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002029 return res;
Robin Lee095c7632014-04-25 15:05:19 +01002030}
2031
Jooyung Han149be4a2020-01-23 12:45:10 +09002032binder::Status InstalldNativeService::freeCache(const std::optional<std::string>& uuid,
Neharika Jali0e542312021-10-25 06:41:24 +00002033 int64_t targetFreeBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002034 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002035 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002036#ifndef GRANULAR_LOCKS
2037 std::lock_guard lock(mLock);
2038#endif // !GRANULAR_LOCKS
Jeff Sharkey423e7462016-12-09 18:18:43 -07002039
Jooyung Han149be4a2020-01-23 12:45:10 +09002040 auto uuidString = uuid.value_or("");
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002041 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002042 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002043 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Neharika Jali1d667a22021-10-25 19:36:18 +00002044 auto defy_target = (flags & FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002045
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002046 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002047 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002048 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002049 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002050
Jeff Sharkey60f8a532017-05-30 14:38:42 -06002051 int64_t needed = targetFreeBytes - free;
Neharika Jali1d667a22021-10-25 19:36:18 +00002052 if (!defy_target) {
2053 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
2054 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002055
Neharika Jali1d667a22021-10-25 19:36:18 +00002056 if (free >= targetFreeBytes) {
2057 return ok();
2058 }
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002059 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002060
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002061 if (flags & FLAG_FREE_CACHE_V2) {
2062 // This new cache strategy fairly removes files from UIDs by deleting
2063 // files from the UIDs which are most over their allocated quota
2064
2065 // 1. Create trackers for every known UID
Zim23457d02022-08-17 12:57:41 +01002066 atrace_pm_begin("create");
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002067 const auto users = get_known_users(uuid_);
2068#ifdef GRANULAR_LOCKS
2069 std::vector<UserLock> userLocks;
2070 userLocks.reserve(users.size());
2071 std::vector<UserWriteLockGuard> lockGuards;
2072 lockGuards.reserve(users.size());
2073#endif // GRANULAR_LOCKS
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002074 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002075 for (auto userId : users) {
2076#ifdef GRANULAR_LOCKS
2077 userLocks.emplace_back(userId, mUserIdLock, mLock);
2078 lockGuards.emplace_back(userLocks.back());
2079#endif // GRANULAR_LOCKS
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002080 FTS *fts;
2081 FTSENT *p;
Samiul Islama2198092022-05-07 23:22:45 +01002082
2083 // Create a list of data paths whose children have cache directories
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002084 auto ce_path = create_data_user_ce_path(uuid_, userId);
2085 auto de_path = create_data_user_de_path(uuid_, userId);
2086 auto media_path = findDataMediaPath(uuid, userId) + "/Android/data/";
Samiul Islama2198092022-05-07 23:22:45 +01002087 auto ce_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2088 auto de_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
2089
2090 std::vector<std::string> dataPaths = {ce_path, de_path, media_path};
2091 foreach_subdir(ce_sdk_path, [&ce_sdk_path, &dataPaths](const std::string subDir) {
2092 const auto fullpath = ce_sdk_path + "/" + subDir;
2093 dataPaths.push_back(fullpath);
2094 });
2095 foreach_subdir(de_sdk_path, [&de_sdk_path, &dataPaths](const std::string subDir) {
2096 const auto fullpath = de_sdk_path + "/" + subDir;
2097 dataPaths.push_back((char*)fullpath.c_str());
2098 });
2099
2100 char* argv[dataPaths.size() + 1];
2101 for (unsigned int i = 0; i < dataPaths.size(); i++) {
2102 argv[i] = (char*)dataPaths[i].c_str();
2103 }
2104 argv[dataPaths.size()] = nullptr;
2105
Yi Konge7bf3772018-07-17 16:16:24 -07002106 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002107 return error("Failed to fts_open");
2108 }
Yi Konge7bf3772018-07-17 16:16:24 -07002109 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002110 if (p->fts_info == FTS_D && p->fts_level == 1) {
2111 uid_t uid = p->fts_statp->st_uid;
Samiul Islama2198092022-05-07 23:22:45 +01002112
2113 // If uid belongs to sdk sandbox, then the cache should be attributed to the
2114 // original client app.
2115 const auto client_uid = multiuser_convert_sdk_sandbox_to_app_uid(uid);
2116 const bool isSandboxUid = (client_uid != (uid_t)-1);
2117 if (isSandboxUid) uid = client_uid;
2118
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002119 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
2120 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
2121 + AID_APP_START;
2122 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002123 auto search = trackers.find(uid);
2124 if (search != trackers.end()) {
2125 search->second->addDataPath(p->fts_path);
2126 } else {
2127 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06002128 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002129 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002130 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002131 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002132 tracker->cacheQuota = mCacheQuotas[uid];
2133 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002134 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002135#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002136 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002137#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002138 tracker->cacheQuota = 67108864;
2139 }
2140 trackers[uid] = tracker;
2141 }
2142 fts_set(fts, p, FTS_SKIP);
2143 }
2144 }
2145 fts_close(fts);
2146 }
Zim23457d02022-08-17 12:57:41 +01002147 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002148
2149 // 2. Populate tracker stats and insert into priority queue
Zim23457d02022-08-17 12:57:41 +01002150 atrace_pm_begin("populate");
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002151 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
2152 return (left->getCacheRatio() < right->getCacheRatio());
2153 };
2154 std::priority_queue<std::shared_ptr<CacheTracker>,
2155 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
2156 for (const auto& it : trackers) {
2157 it.second->loadStats();
2158 queue.push(it.second);
2159 }
Zim23457d02022-08-17 12:57:41 +01002160 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002161
2162 // 3. Bounce across the queue, freeing items from whichever tracker is
2163 // the most over their assigned quota
Zim23457d02022-08-17 12:57:41 +01002164 atrace_pm_begin("bounce");
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002165 std::shared_ptr<CacheTracker> active;
2166 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07002167 // Only look at apps under quota when explicitly requested
2168 if (active && (active->getCacheRatio() < 10000)
2169 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
2170 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
2171 << " isn't over quota, and defy not requested";
2172 break;
2173 }
2174
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002175 // Find the best tracker to work with; this might involve swapping
2176 // if the active tracker is no longer the most over quota
2177 bool nextBetter = active && !queue.empty()
2178 && active->getCacheRatio() < queue.top()->getCacheRatio();
2179 if (!active || nextBetter) {
2180 if (active) {
2181 // Current tracker still has items, so we'll consider it
2182 // again later once it bubbles up to surface
2183 queue.push(active);
2184 }
2185 active = queue.top(); queue.pop();
2186 active->ensureItems();
2187 continue;
2188 }
2189
2190 // If no items remain, go find another tracker
2191 if (active->items.empty()) {
2192 active = nullptr;
2193 continue;
2194 } else {
2195 auto item = active->items.back();
2196 active->items.pop_back();
2197
2198 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
2199 if (!noop) {
2200 item->purge();
2201 }
2202 active->cacheUsed -= item->size;
2203 needed -= item->size;
2204 }
2205
Neharika Jali1d667a22021-10-25 19:36:18 +00002206 if (!defy_target) {
2207 // Verify that we're actually done before bailing, since sneaky
2208 // apps might be using hardlinks
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002209 if (needed <= 0) {
Neharika Jali1d667a22021-10-25 19:36:18 +00002210 free = data_disk_free(data_path);
2211 needed = targetFreeBytes - free;
2212 if (needed <= 0) {
2213 break;
2214 } else {
2215 LOG(WARNING) << "Expected to be done but still need " << needed;
2216 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002217 }
2218 }
2219 }
Zim23457d02022-08-17 12:57:41 +01002220 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002221
2222 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06002223 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07002224 }
2225
Neharika Jali1d667a22021-10-25 19:36:18 +00002226 if (!defy_target) {
2227 free = data_disk_free(data_path);
2228 if (free >= targetFreeBytes) {
2229 return ok();
2230 } else {
2231 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
2232 targetFreeBytes, data_path.c_str(), free));
2233 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002234 } else {
Neharika Jali1d667a22021-10-25 19:36:18 +00002235 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002236 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002237}
2238
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002239binder::Status InstalldNativeService::rmdex(const std::string& codePath,
2240 const std::string& instructionSet) {
2241 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002242 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002243
Mike Lockwood94afecf2012-10-24 10:45:23 -07002244 char dex_path[PKG_PATH_MAX];
2245
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002246 const char* path = codePath.c_str();
2247 const char* instruction_set = instructionSet.c_str();
2248
Jeff Sharkey770180a2014-09-08 17:14:26 -07002249 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002250 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07002251 }
2252
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002253 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002254 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002255 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002256
2257 ALOGV("unlink %s\n", dex_path);
2258 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07002259 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
2260 // but could not be unlinked.
2261 if (errno != ENOENT) {
2262 return error(StringPrintf("Failed to unlink %s", dex_path));
2263 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002264 }
Calin Juravle249f2d32017-05-03 17:22:27 -07002265 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002266}
2267
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002268struct stats {
2269 int64_t codeSize;
2270 int64_t dataSize;
2271 int64_t cacheSize;
2272};
2273
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002274#if MEASURE_DEBUG
2275static std::string toString(std::vector<int64_t> values) {
2276 std::stringstream res;
2277 res << "[";
2278 for (size_t i = 0; i < values.size(); i++) {
2279 res << values[i];
2280 if (i < values.size() - 1) {
2281 res << ",";
2282 }
2283 }
2284 res << "]";
2285 return res.str();
2286}
2287#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002288
Shikha Malhotra976ae002022-02-26 15:39:53 +00002289// On devices without sdcardfs, if internal and external are on
2290// the same volume, a uid such as u0_a123 is used for both
2291// internal and external storage; therefore, subtract that
2292// amount from internal to make sure we don't count it double.
2293// This needs to happen for data, cache and OBB
2294static void deductDoubleSpaceIfNeeded(stats* stats, int64_t doubleSpaceToBeDeleted, uid_t uid,
2295 const std::string& uuid) {
2296 if (!supports_sdcardfs()) {
2297 stats->dataSize -= doubleSpaceToBeDeleted;
2298 long obbProjectId = get_project_id(uid, PROJECT_ID_EXT_OBB_START);
2299 int64_t appObbSize = GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2300 stats->dataSize -= appObbSize;
2301 }
2302}
2303
Risan5f308262018-10-26 12:06:58 -06002304static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002305 int32_t appId, struct stats* stats, struct stats* extStats) {
Shikha Malhotra976ae002022-02-26 15:39:53 +00002306 int64_t space, doubleSpaceToBeDeleted = 0;
Martijn Coenen771cc342020-02-19 23:26:56 +01002307 uid_t uid = multiuser_get_uid(userId, appId);
Shikha Malhotra976ae002022-02-26 15:39:53 +00002308 static const bool supportsProjectId = internal_storage_has_project_id();
2309
2310 if (extStats != nullptr) {
2311 space = get_occupied_app_space_external(uuid, userId, appId);
2312
2313 if (space != -1) {
2314 extStats->dataSize += space;
2315 doubleSpaceToBeDeleted += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002316 }
2317
Shikha Malhotra976ae002022-02-26 15:39:53 +00002318 space = get_occupied_app_cache_space_external(uuid, userId, appId);
2319 if (space != -1) {
2320 extStats->dataSize += space; // cache counts for "data"
2321 extStats->cacheSize += space;
2322 doubleSpaceToBeDeleted += space;
2323 }
2324 }
2325
2326 if (stats != nullptr) {
2327 if (!supportsProjectId) {
2328 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002329 stats->dataSize += space;
2330 }
Shikha Malhotra976ae002022-02-26 15:39:53 +00002331 deductDoubleSpaceIfNeeded(stats, doubleSpaceToBeDeleted, uid, uuid);
2332 int sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
2333 if (sdkSandboxUid != -1) {
2334 if ((space = GetOccupiedSpaceForUid(uuid, sdkSandboxUid)) != -1) {
2335 stats->dataSize += space;
2336 }
2337 }
2338 int cacheGid = multiuser_get_cache_gid(userId, appId);
2339 if (cacheGid != -1) {
2340 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
2341 stats->cacheSize += space;
2342 }
2343 }
2344 } else {
2345 long projectId = get_project_id(uid, PROJECT_ID_APP_START);
2346 if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
2347 stats->dataSize += space;
2348 }
2349 projectId = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
2350 if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
Risan5f308262018-10-26 12:06:58 -06002351 stats->cacheSize += space;
Shikha Malhotra976ae002022-02-26 15:39:53 +00002352 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002353 }
2354 }
2355
2356 int sharedGid = multiuser_get_shared_gid(0, appId);
2357 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06002358 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
2359 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002360 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002361 }
2362 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002363}
2364
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002365static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07002366 DIR *d;
2367 int dfd;
2368 struct dirent *de;
2369 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002370
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002371 d = opendir(path.c_str());
2372 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002373 if (errno != ENOENT) {
2374 PLOG(WARNING) << "Failed to open " << path;
2375 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002376 return;
2377 }
2378 dfd = dirfd(d);
2379 while ((de = readdir(d))) {
2380 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002381
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002382 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002383 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002384 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002385 }
2386
2387 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002388 if (!strcmp(name, ".")) {
2389 // Don't recurse, but still count node size
2390 } else if (!strcmp(name, "..")) {
2391 // Don't recurse or count node size
2392 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002393 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002394 // Measure all children nodes
2395 size = 0;
2396 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002397 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002398
2399 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
2400 stats->cacheSize += size;
2401 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002402 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002403
2404 // Legacy symlink isn't owned by app
2405 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
2406 continue;
2407 }
2408
2409 // Everything found inside is considered data
2410 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002411 }
2412 closedir(d);
2413}
2414
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002415void collectManualStatsForSubDirectories(const std::string& path, struct stats* stats) {
2416 const auto subDirHandler = [&path, &stats](const std::string& subDir) {
2417 auto fullpath = path + "/" + subDir;
2418 collectManualStats(fullpath, stats);
2419 };
2420 foreach_subdir(path, subDirHandler);
2421}
2422
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002423static void collectManualStatsForUser(const std::string& path, struct stats* stats,
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002424 bool exclude_apps = false,
2425 bool is_sdk_sandbox_storage = false) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002426 DIR *d;
2427 int dfd;
2428 struct dirent *de;
2429 struct stat s;
2430
2431 d = opendir(path.c_str());
2432 if (d == nullptr) {
2433 if (errno != ENOENT) {
2434 PLOG(WARNING) << "Failed to open " << path;
2435 }
2436 return;
2437 }
2438 dfd = dirfd(d);
2439 while ((de = readdir(d))) {
2440 if (de->d_type == DT_DIR) {
2441 const char *name = de->d_name;
2442 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
2443 continue;
2444 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002445 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002446 if (!strcmp(name, ".") || !strcmp(name, "..")) {
2447 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002448 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002449 continue;
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002450 } else if (is_sdk_sandbox_storage) {
2451 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2452 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2453 collectManualStatsForSubDirectories(StringPrintf("%s/%s", path.c_str(), name),
2454 stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002455 } else {
2456 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
2457 }
2458 }
2459 }
2460 closedir(d);
2461}
2462
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002463static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
2464 FTS *fts;
2465 FTSENT *p;
2466 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07002467 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002468 PLOG(ERROR) << "Failed to fts_open " << path;
2469 return;
2470 }
Yi Konge7bf3772018-07-17 16:16:24 -07002471 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002472 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002473 switch (p->fts_info) {
2474 case FTS_D:
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002475 if (p->fts_level == 3
2476 && !strcmp(p->fts_parent->fts_name, "obb")
2477 && !strcmp(p->fts_parent->fts_parent->fts_name, "Android")) {
2478 p->fts_number = 1;
2479 } else if (p->fts_level == 4
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002480 && !strcmp(p->fts_name, "cache")
2481 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
2482 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002483 p->fts_number = 2;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002484 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002485 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002486 case FTS_DEFAULT:
2487 case FTS_F:
2488 case FTS_SL:
2489 case FTS_SLNONE:
2490 int64_t size = (p->fts_statp->st_blocks * 512);
2491 if (p->fts_number == 1) {
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002492 stats->codeSize += size;
2493 } else {
2494 if (p->fts_number == 2) {
2495 stats->cacheSize += size;
2496 }
2497 stats->dataSize += size;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002498 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002499 break;
2500 }
2501 }
2502 fts_close(fts);
2503}
Shikha Malhotraaae96442021-11-25 10:52:50 +00002504static bool ownsExternalStorage(int32_t appId) {
Shikha Malhotra976ae002022-02-26 15:39:53 +00002505 // if project id calculation is supported then, there is no need to
2506 // calculate in a different way and project_id based calculation can work
2507 if (internal_storage_has_project_id()) {
2508 return false;
2509 }
2510
Shikha Malhotraaae96442021-11-25 10:52:50 +00002511 // Fetch external storage owner appid and check if it is the same as the
2512 // current appId whose size is calculated
2513 struct stat s;
2514 auto _picDir = StringPrintf("%s/Pictures", create_data_media_path(nullptr, 0).c_str());
2515 // check if the stat are present
2516 if (stat(_picDir.c_str(), &s) == 0) {
2517 // fetch the appId from the uid of the media app
2518 return ((int32_t)multiuser_get_app_id(s.st_uid) == appId);
2519 }
2520 return false;
2521}
Jooyung Han149be4a2020-01-23 12:45:10 +09002522binder::Status InstalldNativeService::getAppSize(const std::optional<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002523 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
2524 int32_t appId, const std::vector<int64_t>& ceDataInodes,
2525 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002526 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002527 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyya6823ef2022-02-28 14:18:19 -08002528 if (packageNames.size() != ceDataInodes.size()) {
2529 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
2530 "packageNames/ceDataInodes size mismatch.");
2531 }
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002532 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002533 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2534 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002535 for (const auto& codePath : codePaths) {
2536 CHECK_ARGUMENT_PATH(codePath);
2537 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002538 // NOTE: Locking is relaxed on this method, since it's limited to
2539 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07002540
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002541 // When modifying this logic, always verify using tests:
2542 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
2543
2544#if MEASURE_DEBUG
2545 LOG(INFO) << "Measuring user " << userId << " app " << appId;
2546#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002547
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002548 // Here's a summary of the common storage locations across the platform,
2549 // and how they're each tagged:
2550 //
2551 // /data/app/com.example UID system
2552 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002553 // /data/user/0/com.example UID u0_a10 GID u0_a10
2554 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
2555 // /data/media/0/foo.txt UID u0_media_rw
2556 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
2557 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
2558 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
2559 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002560
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002561 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002562 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002563 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002564 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002565
Jooyung Han149be4a2020-01-23 12:45:10 +09002566 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002567 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002568
Risan5f308262018-10-26 12:06:58 -06002569 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002570 flags &= ~FLAG_USE_QUOTA;
2571 }
2572
Zim23457d02022-08-17 12:57:41 +01002573 atrace_pm_begin("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002574 for (const auto& packageName : packageNames) {
Jeff Sharkey6d775c52019-03-22 13:46:20 -06002575 auto obbCodePath = create_data_media_package_path(uuid_, userId,
2576 "obb", packageName.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002577 calculate_tree_size(obbCodePath, &extStats.codeSize);
2578 }
Zim23457d02022-08-17 12:57:41 +01002579 atrace_pm_end();
Shikha Malhotraaae96442021-11-25 10:52:50 +00002580 // Calculating the app size of the external storage owning app in a manual way, since
2581 // calculating it through quota apis also includes external media storage in the app storage
2582 // numbers
2583 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START && !ownsExternalStorage(appId)) {
Zim23457d02022-08-17 12:57:41 +01002584 atrace_pm_begin("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002585 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002586 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002587 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002588 }
Zim23457d02022-08-17 12:57:41 +01002589 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002590
Zim23457d02022-08-17 12:57:41 +01002591 atrace_pm_begin("quota");
Risan5f308262018-10-26 12:06:58 -06002592 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Zim23457d02022-08-17 12:57:41 +01002593 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002594 } else {
Zim23457d02022-08-17 12:57:41 +01002595 atrace_pm_begin("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002596 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002597 calculate_tree_size(codePath, &stats.codeSize);
2598 }
Zim23457d02022-08-17 12:57:41 +01002599 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002600
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002601 for (size_t i = 0; i < packageNames.size(); i++) {
2602 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002603
Zim23457d02022-08-17 12:57:41 +01002604 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002605 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
2606 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002607 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
2608 collectManualStats(dePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002609 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002610
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002611 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2612 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2613 if (appId >= AID_APP_START && appId <= AID_APP_END) {
Zim23457d02022-08-17 12:57:41 +01002614 atrace_pm_begin("sdksandbox");
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002615 auto sdkSandboxCePath =
2616 create_data_misc_sdk_sandbox_package_path(uuid_, true, userId, pkgname);
2617 collectManualStatsForSubDirectories(sdkSandboxCePath, &stats);
2618 auto sdkSandboxDePath =
2619 create_data_misc_sdk_sandbox_package_path(uuid_, false, userId, pkgname);
2620 collectManualStatsForSubDirectories(sdkSandboxDePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002621 atrace_pm_end();
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002622 }
2623
Jeff Sharkey06a61842017-04-15 12:03:31 -06002624 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002625 atrace_pm_begin("profiles");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002626 calculate_tree_size(
2627 create_primary_current_profile_package_dir_path(userId, pkgname),
2628 &stats.dataSize);
2629 calculate_tree_size(
2630 create_primary_reference_profile_package_dir_path(pkgname),
2631 &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002632 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002633 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002634
Zim23457d02022-08-17 12:57:41 +01002635 atrace_pm_begin("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002636 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002637 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002638 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002639 calculate_tree_size(mediaPath, &extStats.dataSize);
Zim23457d02022-08-17 12:57:41 +01002640 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002641 }
2642
Jeff Sharkey06a61842017-04-15 12:03:31 -06002643 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002644 atrace_pm_begin("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002645 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06002646 if (sharedGid != -1) {
2647 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2648 sharedGid, -1);
2649 }
Zim23457d02022-08-17 12:57:41 +01002650 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002651 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002652 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002653
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002654 std::vector<int64_t> ret;
2655 ret.push_back(stats.codeSize);
2656 ret.push_back(stats.dataSize);
2657 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002658 ret.push_back(extStats.codeSize);
2659 ret.push_back(extStats.dataSize);
2660 ret.push_back(extStats.cacheSize);
2661#if MEASURE_DEBUG
2662 LOG(DEBUG) << "Final result " << toString(ret);
2663#endif
2664 *_aidl_return = ret;
2665 return ok();
2666}
2667
Martijn Coenen771cc342020-02-19 23:26:56 +01002668struct external_sizes {
2669 int64_t audioSize;
2670 int64_t videoSize;
2671 int64_t imageSize;
2672 int64_t totalSize; // excludes OBBs (Android/obb), but includes app data + cache
2673 int64_t obbSize;
2674};
2675
2676#define PER_USER_RANGE 100000
2677
2678static long getProjectIdForUser(int userId, long projectId) {
2679 return userId * PER_USER_RANGE + projectId;
2680}
2681
2682static external_sizes getExternalSizesForUserWithQuota(const std::string& uuid, int32_t userId, const std::vector<int32_t>& appIds) {
2683 struct external_sizes sizes = {};
2684 int64_t space;
2685
2686 if (supports_sdcardfs()) {
2687 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
2688 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
2689 sizes.totalSize = space;
2690 }
2691
2692 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
2693 if ((space = GetOccupiedSpaceForGid(uuid, audioGid)) != -1) {
2694 sizes.audioSize = space;
2695 }
2696
2697 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
2698 if ((space = GetOccupiedSpaceForGid(uuid, videoGid)) != -1) {
2699 sizes.videoSize = space;
2700 }
2701
2702 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
2703 if ((space = GetOccupiedSpaceForGid(uuid, imageGid)) != -1) {
2704 sizes.imageSize = space;
2705 }
2706
2707 if ((space = GetOccupiedSpaceForGid(uuid, AID_MEDIA_OBB)) != -1) {
2708 sizes.obbSize = space;
2709 }
2710 } else {
2711 int64_t totalSize = 0;
2712 long defaultProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_DEFAULT);
2713 if ((space = GetOccupiedSpaceForProjectId(uuid, defaultProjectId)) != -1) {
2714 // This is all files that are not audio/video/images, excluding
2715 // OBBs and app-private data
2716 totalSize += space;
2717 }
2718
2719 long audioProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_AUDIO);
2720 if ((space = GetOccupiedSpaceForProjectId(uuid, audioProjectId)) != -1) {
2721 sizes.audioSize = space;
2722 totalSize += space;
2723 }
2724
2725 long videoProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_VIDEO);
2726 if ((space = GetOccupiedSpaceForProjectId(uuid, videoProjectId)) != -1) {
2727 sizes.videoSize = space;
2728 totalSize += space;
2729 }
2730
2731 long imageProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_IMAGE);
2732 if ((space = GetOccupiedSpaceForProjectId(uuid, imageProjectId)) != -1) {
2733 sizes.imageSize = space;
2734 totalSize += space;
2735 }
2736
2737 int64_t totalAppDataSize = 0;
2738 int64_t totalAppCacheSize = 0;
2739 int64_t totalAppObbSize = 0;
2740 for (auto appId : appIds) {
2741 if (appId >= AID_APP_START) {
2742 // App data
2743 uid_t uid = multiuser_get_uid(userId, appId);
2744 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
2745 totalAppDataSize += GetOccupiedSpaceForProjectId(uuid, projectId);
2746
2747 // App cache
2748 long cacheProjectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
2749 totalAppCacheSize += GetOccupiedSpaceForProjectId(uuid, cacheProjectId);
2750
2751 // App OBBs
2752 long obbProjectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
2753 totalAppObbSize += GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2754 }
2755 }
2756 // Total size should include app data + cache
2757 totalSize += totalAppDataSize;
2758 totalSize += totalAppCacheSize;
2759 sizes.totalSize = totalSize;
2760
2761 // Only OBB is separate
2762 sizes.obbSize = totalAppObbSize;
2763 }
2764
2765 return sizes;
2766}
2767
Jooyung Han149be4a2020-01-23 12:45:10 +09002768binder::Status InstalldNativeService::getUserSize(const std::optional<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002769 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2770 std::vector<int64_t>* _aidl_return) {
2771 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002772 ENFORCE_VALID_USER(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002773 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002774 // NOTE: Locking is relaxed on this method, since it's limited to
2775 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002776
2777 // When modifying this logic, always verify using tests:
2778 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
2779
2780#if MEASURE_DEBUG
2781 LOG(INFO) << "Measuring user " << userId;
2782#endif
2783
2784 struct stats stats;
2785 struct stats extStats;
2786 memset(&stats, 0, sizeof(stats));
2787 memset(&extStats, 0, sizeof(extStats));
2788
Jooyung Han149be4a2020-01-23 12:45:10 +09002789 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002790 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2791
Risan5f308262018-10-26 12:06:58 -06002792 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002793 flags &= ~FLAG_USE_QUOTA;
2794 }
2795
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002796 if (flags & FLAG_USE_QUOTA) {
Zim23457d02022-08-17 12:57:41 +01002797 atrace_pm_begin("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002798 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002799 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002800
Zim23457d02022-08-17 12:57:41 +01002801 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002802 auto cePath = create_data_user_ce_path(uuid_, userId);
2803 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002804 auto dePath = create_data_user_de_path(uuid_, userId);
2805 collectManualStatsForUser(dePath, &stats, true);
Zim23457d02022-08-17 12:57:41 +01002806 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002807
Jeff Sharkey06a61842017-04-15 12:03:31 -06002808 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002809 atrace_pm_begin("profile");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002810 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2811 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
2812 auto refProfilePath = create_primary_ref_profile_dir_path();
2813 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002814 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002815 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002816
Zim23457d02022-08-17 12:57:41 +01002817 atrace_pm_begin("external");
Martijn Coenen771cc342020-02-19 23:26:56 +01002818 auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2819 extStats.dataSize += sizes.totalSize;
2820 extStats.codeSize += sizes.obbSize;
Zim23457d02022-08-17 12:57:41 +01002821 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002822
Jeff Sharkey06a61842017-04-15 12:03:31 -06002823 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002824 atrace_pm_begin("dalvik");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002825 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2826 -1, -1, true);
2827 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
2828 -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002829 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002830 }
Zim23457d02022-08-17 12:57:41 +01002831 atrace_pm_begin("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002832 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002833 for (auto appId : appIds) {
2834 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06002835 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002836#if MEASURE_DEBUG
2837 // Sleep to make sure we don't lose logs
2838 usleep(1);
2839#endif
2840 }
2841 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002842 extStats.dataSize = dataSize;
Zim23457d02022-08-17 12:57:41 +01002843 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002844 } else {
Zim23457d02022-08-17 12:57:41 +01002845 atrace_pm_begin("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002846 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002847 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002848
Zim23457d02022-08-17 12:57:41 +01002849 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002850 auto cePath = create_data_user_ce_path(uuid_, userId);
2851 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002852 auto dePath = create_data_user_de_path(uuid_, userId);
2853 collectManualStatsForUser(dePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002854 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002855
Zim23457d02022-08-17 12:57:41 +01002856 atrace_pm_begin("sdksandbox");
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002857 auto sdkSandboxCePath = create_data_misc_sdk_sandbox_path(uuid_, true, userId);
2858 collectManualStatsForUser(sdkSandboxCePath, &stats, false, true);
2859 auto sdkSandboxDePath = create_data_misc_sdk_sandbox_path(uuid_, false, userId);
2860 collectManualStatsForUser(sdkSandboxDePath, &stats, false, true);
Zim23457d02022-08-17 12:57:41 +01002861 atrace_pm_end();
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002862
Jeff Sharkey06a61842017-04-15 12:03:31 -06002863 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002864 atrace_pm_begin("profile");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002865 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2866 calculate_tree_size(userProfilePath, &stats.dataSize);
2867 auto refProfilePath = create_primary_ref_profile_dir_path();
2868 calculate_tree_size(refProfilePath, &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002869 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002870 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002871
Zim23457d02022-08-17 12:57:41 +01002872 atrace_pm_begin("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002873 auto dataMediaPath = create_data_media_path(uuid_, userId);
2874 collectManualExternalStatsForUser(dataMediaPath, &extStats);
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002875
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002876#if MEASURE_DEBUG
2877 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002878 << extStats.cacheSize << " code " << extStats.codeSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002879#endif
Zim23457d02022-08-17 12:57:41 +01002880 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002881
Jeff Sharkey06a61842017-04-15 12:03:31 -06002882 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002883 atrace_pm_begin("dalvik");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002884 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
2885 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
Zim23457d02022-08-17 12:57:41 +01002886 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002887 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002888 }
2889
2890 std::vector<int64_t> ret;
2891 ret.push_back(stats.codeSize);
2892 ret.push_back(stats.dataSize);
2893 ret.push_back(stats.cacheSize);
2894 ret.push_back(extStats.codeSize);
2895 ret.push_back(extStats.dataSize);
2896 ret.push_back(extStats.cacheSize);
2897#if MEASURE_DEBUG
2898 LOG(DEBUG) << "Final result " << toString(ret);
2899#endif
2900 *_aidl_return = ret;
2901 return ok();
2902}
2903
Jooyung Han149be4a2020-01-23 12:45:10 +09002904binder::Status InstalldNativeService::getExternalSize(const std::optional<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002905 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2906 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002907 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002908 ENFORCE_VALID_USER(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002909 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002910 // NOTE: Locking is relaxed on this method, since it's limited to
2911 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002912
2913 // When modifying this logic, always verify using tests:
2914 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
2915
2916#if MEASURE_DEBUG
2917 LOG(INFO) << "Measuring external " << userId;
2918#endif
2919
Jooyung Han149be4a2020-01-23 12:45:10 +09002920 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002921 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2922
2923 int64_t totalSize = 0;
2924 int64_t audioSize = 0;
2925 int64_t videoSize = 0;
2926 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002927 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06002928 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002929
Risan5f308262018-10-26 12:06:58 -06002930 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002931 flags &= ~FLAG_USE_QUOTA;
2932 }
2933
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002934 if (flags & FLAG_USE_QUOTA) {
Zim23457d02022-08-17 12:57:41 +01002935 atrace_pm_begin("quota");
Martijn Coenen771cc342020-02-19 23:26:56 +01002936 auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2937 totalSize = sizes.totalSize;
2938 audioSize = sizes.audioSize;
2939 videoSize = sizes.videoSize;
2940 imageSize = sizes.imageSize;
2941 obbSize = sizes.obbSize;
Zim23457d02022-08-17 12:57:41 +01002942 atrace_pm_end();
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002943
Zim23457d02022-08-17 12:57:41 +01002944 atrace_pm_begin("apps");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002945 struct stats extStats;
2946 memset(&extStats, 0, sizeof(extStats));
2947 for (auto appId : appIds) {
2948 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06002949 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002950 }
2951 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06002952 appSize = extStats.dataSize;
Zim23457d02022-08-17 12:57:41 +01002953 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002954 } else {
Zim23457d02022-08-17 12:57:41 +01002955 atrace_pm_begin("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002956 FTS *fts;
2957 FTSENT *p;
2958 auto path = create_data_media_path(uuid_, userId);
2959 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07002960 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002961 return error("Failed to fts_open " + path);
2962 }
Yi Konge7bf3772018-07-17 16:16:24 -07002963 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002964 char* ext;
2965 int64_t size = (p->fts_statp->st_blocks * 512);
2966 switch (p->fts_info) {
2967 case FTS_F:
2968 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06002969 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002970 ext = strrchr(p->fts_name, '.');
2971 if (ext != nullptr) {
2972 switch (MatchExtension(++ext)) {
2973 case AID_MEDIA_AUDIO: audioSize += size; break;
2974 case AID_MEDIA_VIDEO: videoSize += size; break;
2975 case AID_MEDIA_IMAGE: imageSize += size; break;
2976 }
2977 }
2978 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002979 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002980 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06002981 // Ignore data belonging to specific apps
2982 p->fts_number = p->fts_parent->fts_number;
2983 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
2984 p->fts_number = 1;
2985 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002986 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002987 case FTS_DEFAULT:
2988 case FTS_SL:
2989 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002990 if (p->fts_parent->fts_number == 1) {
2991 appSize += size;
2992 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002993 totalSize += size;
2994 break;
2995 }
2996 }
2997 fts_close(fts);
Zim23457d02022-08-17 12:57:41 +01002998 atrace_pm_end();
Jeff Sharkeya0136982017-07-06 11:29:37 -06002999
Zim23457d02022-08-17 12:57:41 +01003000 atrace_pm_begin("obb");
Jeff Sharkey6d775c52019-03-22 13:46:20 -06003001 auto obbPath = StringPrintf("%s/Android/obb",
3002 create_data_media_path(uuid_, userId).c_str());
Jeff Sharkeya0136982017-07-06 11:29:37 -06003003 calculate_tree_size(obbPath, &obbSize);
Chuwei Xu5d64ddf2019-12-04 15:32:18 +08003004 if (!(flags & FLAG_USE_QUOTA)) {
3005 totalSize -= obbSize;
3006 }
Zim23457d02022-08-17 12:57:41 +01003007 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003008 }
3009
3010 std::vector<int64_t> ret;
3011 ret.push_back(totalSize);
3012 ret.push_back(audioSize);
3013 ret.push_back(videoSize);
3014 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06003015 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06003016 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003017#if MEASURE_DEBUG
3018 LOG(DEBUG) << "Final result " << toString(ret);
3019#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07003020 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07003021 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003022}
3023
Felka Chang2a0a2462019-11-20 14:20:40 +08003024binder::Status InstalldNativeService::getAppCrates(
Jooyung Han149be4a2020-01-23 12:45:10 +09003025 const std::optional<std::string>& uuid,
Felka Chang2a0a2462019-11-20 14:20:40 +08003026 const std::vector<std::string>& packageNames, int32_t userId,
Jooyung Han149be4a2020-01-23 12:45:10 +09003027 std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
Felka Chang2a0a2462019-11-20 14:20:40 +08003028 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003029 ENFORCE_VALID_USER(userId);
Felka Chang2a0a2462019-11-20 14:20:40 +08003030 CHECK_ARGUMENT_UUID(uuid);
3031 for (const auto& packageName : packageNames) {
3032 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3033 }
Felka Chang4df87f62020-02-11 19:08:43 +08003034#ifdef ENABLE_STORAGE_CRATES
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003035 LOCK_PACKAGE_USER();
Felka Chang2a0a2462019-11-20 14:20:40 +08003036
Jooyung Han149be4a2020-01-23 12:45:10 +09003037 auto retVector = std::vector<std::optional<CrateMetadata>>();
Felka Chang2a0a2462019-11-20 14:20:40 +08003038 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3039
Jooyung Han149be4a2020-01-23 12:45:10 +09003040 std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3041 [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
Felka Chang2a0a2462019-11-20 14:20:40 +08003042 if (cratedFolder == nullptr) {
3043 return;
3044 }
Jooyung Han149be4a2020-01-23 12:45:10 +09003045 retVector.push_back(std::move(crateMetadata));
Felka Chang2a0a2462019-11-20 14:20:40 +08003046 };
3047
3048 for (const auto& packageName : packageNames) {
3049#if CRATE_DEBUG
3050 LOG(DEBUG) << "packageName = " << packageName;
3051#endif
3052 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageName);
3053 crateManager->traverseAllCrates(onCreateCrate);
3054 }
3055
3056#if CRATE_DEBUG
Jooyung Han149be4a2020-01-23 12:45:10 +09003057 LOG(WARNING) << "retVector.size() =" << retVector.size();
3058 for (auto& item : retVector) {
Jooyung Hand520e802020-03-03 02:56:34 +09003059 CrateManager::dump(*item);
Felka Chang2a0a2462019-11-20 14:20:40 +08003060 }
3061#endif
3062
3063 *_aidl_return = std::move(retVector);
Felka Chang4df87f62020-02-11 19:08:43 +08003064#else // ENABLE_STORAGE_CRATES
Jooyung Han149be4a2020-01-23 12:45:10 +09003065 _aidl_return->reset();
Felka Chang4df87f62020-02-11 19:08:43 +08003066
3067 /* prevent compile warning fail */
3068 if (userId < 0) {
3069 return error();
3070 }
3071#endif // ENABLE_STORAGE_CRATES
Felka Chang2a0a2462019-11-20 14:20:40 +08003072 return ok();
3073}
3074
3075binder::Status InstalldNativeService::getUserCrates(
Jooyung Han149be4a2020-01-23 12:45:10 +09003076 const std::optional<std::string>& uuid, int32_t userId,
3077 std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
Felka Chang2a0a2462019-11-20 14:20:40 +08003078 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003079 ENFORCE_VALID_USER(userId);
Felka Chang2a0a2462019-11-20 14:20:40 +08003080 CHECK_ARGUMENT_UUID(uuid);
Felka Chang4df87f62020-02-11 19:08:43 +08003081#ifdef ENABLE_STORAGE_CRATES
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003082 LOCK_USER();
Felka Chang2a0a2462019-11-20 14:20:40 +08003083
3084 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jooyung Han149be4a2020-01-23 12:45:10 +09003085 auto retVector = std::vector<std::optional<CrateMetadata>>();
Felka Chang2a0a2462019-11-20 14:20:40 +08003086
Jooyung Han149be4a2020-01-23 12:45:10 +09003087 std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3088 [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
Felka Chang2a0a2462019-11-20 14:20:40 +08003089 if (cratedFolder == nullptr) {
3090 return;
3091 }
Jooyung Hand520e802020-03-03 02:56:34 +09003092 retVector.push_back(std::move(crateMetadata));
Felka Chang2a0a2462019-11-20 14:20:40 +08003093 };
3094
3095 std::function<void(FTSENT*)> onHandingPackage = [&](FTSENT* packageDir) -> void {
3096 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageDir->fts_name);
3097 crateManager->traverseAllCrates(onCreateCrate);
3098 };
3099 CrateManager::traverseAllPackagesForUser(uuid, userId, onHandingPackage);
3100
3101#if CRATE_DEBUG
Jooyung Han149be4a2020-01-23 12:45:10 +09003102 LOG(DEBUG) << "retVector.size() =" << retVector.size();
3103 for (auto& item : retVector) {
Jooyung Hand520e802020-03-03 02:56:34 +09003104 CrateManager::dump(*item);
Felka Chang2a0a2462019-11-20 14:20:40 +08003105 }
3106#endif
3107
3108 *_aidl_return = std::move(retVector);
Felka Chang4df87f62020-02-11 19:08:43 +08003109#else // ENABLE_STORAGE_CRATES
Jooyung Han149be4a2020-01-23 12:45:10 +09003110 _aidl_return->reset();
Felka Chang4df87f62020-02-11 19:08:43 +08003111
3112 /* prevent compile warning fail */
3113 if (userId < 0) {
3114 return error();
3115 }
3116#endif // ENABLE_STORAGE_CRATES
Felka Chang2a0a2462019-11-20 14:20:40 +08003117 return ok();
3118}
3119
Jooyung Han149be4a2020-01-23 12:45:10 +09003120binder::Status InstalldNativeService::setAppQuota(const std::optional<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003121 int32_t userId, int32_t appId, int64_t cacheQuota) {
3122 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003123 ENFORCE_VALID_USER(userId);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003124 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003125 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003126
3127 int32_t uid = multiuser_get_uid(userId, appId);
3128 mCacheQuotas[uid] = cacheQuota;
3129
3130 return ok();
3131}
3132
David Sehr6727c2d2016-05-17 16:06:22 -07003133// Dumps the contents of a profile file, using pkgname's dex files for pretty
3134// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003135binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Martin Stjernholmfd000402022-04-11 18:04:59 +01003136 const std::string& profileName,
3137 const std::string& codePath,
3138 bool dumpClassesAndMethods, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003139 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003140 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003141 CHECK_ARGUMENT_PATH(codePath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003142 LOCK_PACKAGE();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003143
Martin Stjernholmfd000402022-04-11 18:04:59 +01003144 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath, dumpClassesAndMethods);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003145 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07003146}
3147
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003148// Copy the contents of a system profile over the data profile.
3149binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08003150 int32_t packageUid, const std::string& packageName, const std::string& profileName,
3151 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003152 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyyd04631f2022-08-12 15:14:41 -07003153 CHECK_ARGUMENT_PATH(systemProfile);
3154 if (!base::EndsWith(systemProfile, ".prof")) {
3155 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3156 StringPrintf("System profile path %s does not end with .prof",
3157 systemProfile.c_str()));
3158 }
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003159 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyyd04631f2022-08-12 15:14:41 -07003160 CHECK_ARGUMENT_FILE_NAME(profileName);
3161 if (!base::EndsWith(profileName, ".prof")) {
3162 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3163 StringPrintf("Profile name %s does not end with .prof",
3164 profileName.c_str()));
3165 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003166 LOCK_PACKAGE();
Calin Juravle562de812018-01-20 23:34:18 -08003167 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003168 return ok();
3169}
3170
Andreas Gampe4d0f8252016-03-20 11:30:28 -07003171// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003172binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle3b758282021-06-08 08:04:52 -07003173 const std::string& profileName, int* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003174 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003175 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003176 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07003177
Calin Juravle562de812018-01-20 23:34:18 -08003178 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003179 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07003180}
3181
Calin Juravlec41dac22017-12-05 12:29:15 -08003182binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08003183 const std::string& packageName, const std::string& profileName,
3184 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08003185 ENFORCE_UID(AID_SYSTEM);
3186 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003187 LOCK_PACKAGE();
Calin Juravle29591732017-11-20 17:46:19 -08003188
Calin Juravlee61189e2018-01-23 19:54:11 -08003189 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08003190 return ok();
3191}
3192
3193binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003194 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08003195 ENFORCE_UID(AID_SYSTEM);
3196 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003197 LOCK_PACKAGE();
Calin Juravle29591732017-11-20 17:46:19 -08003198
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003199 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08003200 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003201 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08003202 }
3203 return ok();
3204}
3205
Jooyung Han149be4a2020-01-23 12:45:10 +09003206static const char* getCStr(const std::optional<std::string>& data,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003207 const char* default_value = nullptr) {
Jooyung Han149be4a2020-01-23 12:45:10 +09003208 return data ? data->c_str() : default_value;
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003209}
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003210binder::Status InstalldNativeService::dexopt(
3211 const std::string& apkPath, int32_t uid, const std::string& packageName,
3212 const std::string& instructionSet, int32_t dexoptNeeded,
3213 const std::optional<std::string>& outputPath, int32_t dexFlags,
Jooyung Han149be4a2020-01-23 12:45:10 +09003214 const std::string& compilerFilter, const std::optional<std::string>& uuid,
3215 const std::optional<std::string>& classLoaderContext,
3216 const std::optional<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
3217 const std::optional<std::string>& profileName,
3218 const std::optional<std::string>& dexMetadataPath,
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003219 const std::optional<std::string>& compilationReason, bool* aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003220 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003221 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07003222 CHECK_ARGUMENT_PATH(apkPath);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003223 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003224 CHECK_ARGUMENT_PATH(outputPath);
3225 CHECK_ARGUMENT_PATH(dexMetadataPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003226 const auto userId = multiuser_get_user_id(uid);
3227 LOCK_PACKAGE_USER();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003228
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07003229 const char* oat_dir = getCStr(outputPath);
3230 const char* instruction_set = instructionSet.c_str();
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003231 if (oat_dir != nullptr && !createOatDir(packageName, oat_dir, instruction_set).isOk()) {
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07003232 // Can't create oat dir - let dexopt use cache dir.
3233 oat_dir = nullptr;
3234 }
3235
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003236 const char* apk_path = apkPath.c_str();
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003237 const char* pkgname = packageName.c_str();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003238 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003239 const char* volume_uuid = getCStr(uuid);
3240 const char* class_loader_context = getCStr(classLoaderContext);
3241 const char* se_info = getCStr(seInfo);
3242 const char* profile_name = getCStr(profileName);
3243 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08003244 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08003245 std::string error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07003246 bool completed = false; // not necessary but for compiler
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003247 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07003248 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Keun young Park65578d62021-06-28 17:52:05 -07003249 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg,
3250 &completed);
3251 *aidl_return = completed;
Andreas Gampe023b2242018-02-28 16:03:25 -08003252 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003253}
3254
Keun young Park65578d62021-06-28 17:52:05 -07003255binder::Status InstalldNativeService::controlDexOptBlocking(bool block) {
3256 android::installd::control_dexopt_blocking(block);
3257 return ok();
3258}
3259
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003260binder::Status InstalldNativeService::linkNativeLibraryDirectory(
Jooyung Han149be4a2020-01-23 12:45:10 +09003261 const std::optional<std::string>& uuid, const std::string& packageName,
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003262 const std::string& nativeLibPath32, int32_t userId) {
3263 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003264 CHECK_ARGUMENT_UUID(uuid);
3265 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003266 CHECK_ARGUMENT_PATH(nativeLibPath32);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003267 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07003268
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003269 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3270 const char* pkgname = packageName.c_str();
3271 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003272 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07003273 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003274
Jeff Sharkey423e7462016-12-09 18:18:43 -07003275 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
3276 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07003277
3278 const char* pkgdir = _pkgdir.c_str();
3279 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003280
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003281 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003282 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003283 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003284
Nick Kralevich85958b62019-01-30 12:32:21 -08003285 char *con = nullptr;
3286 if (lgetfilecon(pkgdir, &con) < 0) {
3287 return error("Failed to lgetfilecon " + _pkgdir);
3288 }
3289
Mike Lockwood94afecf2012-10-24 10:45:23 -07003290 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08003291 res = error("Failed to chown " + _pkgdir);
3292 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07003293 }
3294
3295 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003296 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003297 goto out;
3298 }
3299
3300 if (lstat(libsymlink, &libStat) < 0) {
3301 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003302 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003303 goto out;
3304 }
3305 } else {
3306 if (S_ISDIR(libStat.st_mode)) {
Yi Konge7bf3772018-07-17 16:16:24 -07003307 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003308 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003309 goto out;
3310 }
3311 } else if (S_ISLNK(libStat.st_mode)) {
3312 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003313 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003314 goto out;
3315 }
3316 }
3317 }
3318
3319 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003320 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003321 goto out;
3322 }
3323
Nick Kralevich85958b62019-01-30 12:32:21 -08003324 if (lsetfilecon(libsymlink, con) < 0) {
3325 res = error("Failed to lsetfilecon " + _libsymlink);
3326 goto out;
3327 }
3328
Mike Lockwood94afecf2012-10-24 10:45:23 -07003329out:
Nick Kralevich85958b62019-01-30 12:32:21 -08003330 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003331 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003332 auto msg = "Failed to cleanup chmod " + _pkgdir;
3333 if (res.isOk()) {
3334 res = error(msg);
3335 } else {
3336 PLOG(ERROR) << msg;
3337 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003338 }
3339
3340 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003341 auto msg = "Failed to cleanup chown " + _pkgdir;
3342 if (res.isOk()) {
3343 res = error(msg);
3344 } else {
3345 PLOG(ERROR) << msg;
3346 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003347 }
3348
Jeff Sharkey423e7462016-12-09 18:18:43 -07003349 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07003350}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01003351
Jooyung Han149be4a2020-01-23 12:45:10 +09003352binder::Status InstalldNativeService::restoreconAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003353 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
3354 const std::string& seInfo) {
3355 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003356 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003357 CHECK_ARGUMENT_UUID(uuid);
3358 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003359 LOCK_PACKAGE_USER();
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08003360 return restoreconAppDataLocked(uuid, packageName, userId, flags, appId, seInfo);
3361}
3362
3363binder::Status InstalldNativeService::restoreconAppDataLocked(
3364 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3365 int32_t flags, int32_t appId, const std::string& seInfo) {
3366 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003367 ENFORCE_VALID_USER(userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08003368 CHECK_ARGUMENT_UUID(uuid);
3369 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003370
3371 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05003372
Robert Craigda30dc72014-03-27 10:21:12 -04003373 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003374 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003375 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3376 const char* pkgName = packageName.c_str();
3377 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04003378
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003379 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07003380 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003381 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003382 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003383 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07003384 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003385 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07003386 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003387 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003388 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003389 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07003390 }
Robert Craige9887e42014-02-20 10:25:56 -05003391 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07003392 return res;
Robert Craige9887e42014-02-20 10:25:56 -05003393}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01003394
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00003395binder::Status InstalldNativeService::restoreconSdkDataLocked(
3396 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3397 int32_t flags, int32_t appId, const std::string& seInfo) {
3398 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003399 ENFORCE_VALID_USER(userId);
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00003400 CHECK_ARGUMENT_UUID(uuid);
3401 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3402
3403 binder::Status res = ok();
3404
3405 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
3406 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
3407 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3408 const char* pkgName = packageName.c_str();
3409 const char* seinfo = seInfo.c_str();
3410
3411 uid_t uid = multiuser_get_sdk_sandbox_uid(userId, appId);
3412 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
3413 for (int currentFlag : storageFlags) {
3414 if ((flags & currentFlag) == 0) {
3415 continue;
3416 }
3417 const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
3418 const auto packagePath =
3419 create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgName);
3420 if (access(packagePath.c_str(), F_OK) != 0) {
3421 LOG(INFO) << "Missing source " << packagePath;
3422 continue;
3423 }
3424 const auto subDirHandler = [&packagePath, &seinfo, &uid, &seflags,
3425 &res](const std::string& subDir) {
3426 const auto& fullpath = packagePath + "/" + subDir;
3427 if (selinux_android_restorecon_pkgdir(fullpath.c_str(), seinfo, uid, seflags) < 0) {
3428 res = error("restorecon failed for " + fullpath);
3429 }
3430 };
3431 const auto ec = foreach_subdir(packagePath, subDirHandler);
3432 if (ec != 0) {
3433 res = error("Failed to restorecon for subdirs of " + packagePath);
3434 }
3435 }
3436 return res;
3437}
3438
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003439binder::Status InstalldNativeService::createOatDir(const std::string& packageName,
3440 const std::string& oatDir,
3441 const std::string& instructionSet) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003442 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003443 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003444 CHECK_ARGUMENT_PATH(oatDir);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003445 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003446
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003447 const char* oat_dir = oatDir.c_str();
3448 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003449 char oat_instr_dir[PKG_PATH_MAX];
3450
3451 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003452 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003453 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07003454 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003455 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003456 }
3457 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003458 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003459 }
3460 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07003461 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003462 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003463 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07003464 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003465}
3466
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003467binder::Status InstalldNativeService::rmPackageDir(const std::string& packageName,
3468 const std::string& packageDir) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003469 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07003470 CHECK_ARGUMENT_PATH(packageDir);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003471 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003472
Jeff Sharkey423e7462016-12-09 18:18:43 -07003473 if (validate_apk_path(packageDir.c_str())) {
3474 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003475 }
Oleksandr Peletskyid2be6322019-01-24 17:59:45 +01003476 if (rm_package_dir(packageDir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003477 return error("Failed to delete " + packageDir);
3478 }
3479 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003480}
3481
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003482binder::Status InstalldNativeService::linkFile(const std::string& packageName,
3483 const std::string& relativePath,
3484 const std::string& fromBase,
3485 const std::string& toBase) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003486 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003487 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003488 CHECK_ARGUMENT_PATH(fromBase);
3489 CHECK_ARGUMENT_PATH(toBase);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003490 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003491
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003492 const char* relative_path = relativePath.c_str();
3493 const char* from_base = fromBase.c_str();
3494 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01003495 char from_path[PKG_PATH_MAX];
3496 char to_path[PKG_PATH_MAX];
3497 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
3498 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
3499
3500 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003501 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003502 }
3503
3504 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003505 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003506 }
3507
Jeff Sharkey423e7462016-12-09 18:18:43 -07003508 if (link(from_path, to_path) < 0) {
3509 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003510 }
3511
Jeff Sharkey423e7462016-12-09 18:18:43 -07003512 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01003513}
3514
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003515binder::Status InstalldNativeService::moveAb(const std::string& packageName,
3516 const std::string& apkPath,
3517 const std::string& instructionSet,
3518 const std::string& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003519 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003520 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003521 CHECK_ARGUMENT_PATH(apkPath);
3522 CHECK_ARGUMENT_PATH(outputPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003523 LOCK_PACKAGE();
Jeff Sharkey90aff262016-12-12 14:28:24 -07003524
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003525 const char* apk_path = apkPath.c_str();
3526 const char* instruction_set = instructionSet.c_str();
3527 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07003528
Jeff Sharkey90aff262016-12-12 14:28:24 -07003529 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003530 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08003531}
3532
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003533binder::Status InstalldNativeService::deleteOdex(const std::string& packageName,
3534 const std::string& apkPath,
3535 const std::string& instructionSet,
3536 const std::optional<std::string>& outputPath,
3537 int64_t* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003538 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003539 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003540 CHECK_ARGUMENT_PATH(apkPath);
3541 CHECK_ARGUMENT_PATH(outputPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003542 LOCK_PACKAGE();
Jeff Sharkey90aff262016-12-12 14:28:24 -07003543
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003544 const char* apk_path = apkPath.c_str();
3545 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07003546 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003547
Calin Juravleea214ad2021-06-11 09:17:20 -07003548 *_aidl_return = delete_odex(apk_path, instruction_set, oat_dir);
3549 return *_aidl_return == -1 ? error() : ok();
Andreas Gampe3964da02016-09-09 17:07:04 -07003550}
3551
Calin Juravlebd968362017-01-25 01:17:17 -08003552binder::Status InstalldNativeService::reconcileSecondaryDexFile(
3553 const std::string& dexPath, const std::string& packageName, int32_t uid,
Jooyung Han149be4a2020-01-23 12:45:10 +09003554 const std::vector<std::string>& isas, const std::optional<std::string>& volumeUuid,
Calin Juravlebd968362017-01-25 01:17:17 -08003555 int32_t storage_flag, bool* _aidl_return) {
3556 ENFORCE_UID(AID_SYSTEM);
3557 CHECK_ARGUMENT_UUID(volumeUuid);
3558 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003559 CHECK_ARGUMENT_PATH(dexPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003560 const auto userId = multiuser_get_user_id(uid);
3561 LOCK_PACKAGE_USER();
Jeff Sharkey53594302018-02-24 18:59:39 -07003562
Calin Juravlebd968362017-01-25 01:17:17 -08003563 bool result = android::installd::reconcile_secondary_dex_file(
3564 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
3565 return result ? ok() : error();
3566}
3567
Alan Stokes753dc712017-10-16 10:56:00 +01003568binder::Status InstalldNativeService::hashSecondaryDexFile(
3569 const std::string& dexPath, const std::string& packageName, int32_t uid,
Jooyung Han149be4a2020-01-23 12:45:10 +09003570 const std::optional<std::string>& volumeUuid, int32_t storageFlag,
Alan Stokes753dc712017-10-16 10:56:00 +01003571 std::vector<uint8_t>* _aidl_return) {
3572 ENFORCE_UID(AID_SYSTEM);
3573 CHECK_ARGUMENT_UUID(volumeUuid);
3574 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003575 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01003576
3577 // mLock is not taken here since we will never modify the file system.
3578 // If a file is modified just as we are reading it this may result in an
3579 // anomalous hash, but that's ok.
3580 bool result = android::installd::hash_secondary_dex_file(
3581 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
3582 return result ? ok() : error();
3583}
Shikha Malhotra976ae002022-02-26 15:39:53 +00003584/**
3585 * Returns true if ioctl feature (F2FS_IOC_FS{GET,SET}XATTR) is supported as
3586 * these were introduced in Linux 4.14, so kernel versions before that will fail
3587 * while setting project id attributes. Only when these features are enabled,
3588 * storage calculation using project_id is enabled
3589 */
3590bool check_if_ioctl_feature_is_supported() {
3591 bool result = false;
3592 auto temp_path = StringPrintf("%smisc/installd/ioctl_check", android_data_dir.c_str());
3593 if (access(temp_path.c_str(), F_OK) != 0) {
3594 int fd = open(temp_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644);
Shikha Malhotrac18afa82022-04-01 22:13:39 +00003595 result = set_quota_project_id(temp_path, 0, false) == 0;
Shikha Malhotra976ae002022-02-26 15:39:53 +00003596 close(fd);
3597 // delete the temp file
3598 remove(temp_path.c_str());
3599 }
3600 return result;
3601}
3602
3603binder::Status InstalldNativeService::setFirstBoot() {
3604 ENFORCE_UID(AID_SYSTEM);
3605 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3606 std::string uuid;
3607 if (GetOccupiedSpaceForProjectId(uuid, 0) != -1 && check_if_ioctl_feature_is_supported()) {
3608 auto first_boot_path =
3609 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
3610 if (access(first_boot_path.c_str(), F_OK) != 0) {
3611 close(open(first_boot_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644));
3612 }
3613 }
3614 return ok();
3615}
Alan Stokes753dc712017-10-16 10:56:00 +01003616
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003617binder::Status InstalldNativeService::invalidateMounts() {
3618 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003619 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003620
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003621 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06003622
3623#if !BYPASS_QUOTA
3624 if (!InvalidateQuotaMounts()) {
3625 return error("Failed to read mounts");
3626 }
3627#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003628
3629 std::ifstream in("/proc/mounts");
3630 if (!in.is_open()) {
3631 return error("Failed to read mounts");
3632 }
3633
3634 std::string source;
3635 std::string target;
3636 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003637 while (!in.eof()) {
3638 std::getline(in, source, ' ');
3639 std::getline(in, target, ' ');
3640 std::getline(in, ignored);
3641
Zim0ce832d2019-12-03 17:03:58 +00003642 if (android::base::GetBoolProperty(kFuseProp, false)) {
Zim1edb92a2020-01-09 08:48:00 +00003643 if (target.find(kMntFuse) == 0) {
Zim0ce832d2019-12-03 17:03:58 +00003644 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3645 mStorageMounts[source] = target;
3646 }
3647 } else {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003648#if !BYPASS_SDCARDFS
Zim1edb92a2020-01-09 08:48:00 +00003649 if (target.find(kMntSdcardfs) == 0) {
Zim0ce832d2019-12-03 17:03:58 +00003650 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3651 mStorageMounts[source] = target;
3652 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003653#endif
Zim0ce832d2019-12-03 17:03:58 +00003654 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003655 }
3656 return ok();
3657}
3658
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003659// Mount volume's CE and DE storage to mirror
Ricky Wai2a4983f2020-02-07 14:25:45 +00003660binder::Status InstalldNativeService::tryMountDataMirror(
Jooyung Han149be4a2020-01-23 12:45:10 +09003661 const std::optional<std::string>& uuid) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003662 ENFORCE_UID(AID_SYSTEM);
3663 CHECK_ARGUMENT_UUID(uuid);
3664 if (!sAppDataIsolationEnabled) {
3665 return ok();
3666 }
3667 if (!uuid) {
3668 return error("Should not happen, mounting uuid == null");
3669 }
3670
3671 const char* uuid_ = uuid->c_str();
Ricky Wai2a4983f2020-02-07 14:25:45 +00003672
Alex Buynytskyy40c45ba2021-11-18 15:16:27 -08003673 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3674
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003675 std::string mirrorVolCePath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003676 if (fs_prepare_dir(mirrorVolCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003677 return error("Failed to create CE data mirror");
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003678 }
Ricky Wai2a4983f2020-02-07 14:25:45 +00003679
3680 std::string mirrorVolDePath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003681 if (fs_prepare_dir(mirrorVolDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003682 return error("Failed to create DE data mirror");
3683 }
3684
3685 std::string mirrorVolMiscCePath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003686 if (fs_prepare_dir(mirrorVolMiscCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003687 return error("Failed to create CE misc mirror");
3688 }
3689
3690 std::string mirrorVolMiscDePath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003691 if (fs_prepare_dir(mirrorVolMiscDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003692 return error("Failed to create DE misc mirror");
Ricky Wai2a4983f2020-02-07 14:25:45 +00003693 }
3694
3695 auto cePath = StringPrintf("%s/user", create_data_path(uuid_).c_str());
3696 auto dePath = StringPrintf("%s/user_de", create_data_path(uuid_).c_str());
Sanjana Sunil691163d2022-03-28 19:15:54 +00003697 auto miscCePath = StringPrintf("%s/misc_ce", create_data_path(uuid_).c_str());
3698 auto miscDePath = StringPrintf("%s/misc_de", create_data_path(uuid_).c_str());
Ricky Wai2a4983f2020-02-07 14:25:45 +00003699
3700 if (access(cePath.c_str(), F_OK) != 0) {
3701 return error("Cannot access CE path: " + cePath);
3702 }
3703 if (access(dePath.c_str(), F_OK) != 0) {
3704 return error("Cannot access DE path: " + dePath);
3705 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003706 if (access(miscCePath.c_str(), F_OK) != 0) {
3707 return error("Cannot access misc CE path: " + cePath);
3708 }
3709 if (access(miscDePath.c_str(), F_OK) != 0) {
3710 return error("Cannot access misc DE path: " + dePath);
3711 }
Ricky Wai2a4983f2020-02-07 14:25:45 +00003712
3713 struct stat ceStat, mirrorCeStat;
3714 if (stat(cePath.c_str(), &ceStat) != 0) {
3715 return error("Failed to stat " + cePath);
3716 }
3717 if (stat(mirrorVolCePath.c_str(), &mirrorCeStat) != 0) {
3718 return error("Failed to stat " + mirrorVolCePath);
3719 }
3720
Eric Biggersab9ea462022-05-26 00:28:09 +00003721 if (mirrorCeStat.st_ino == ceStat.st_ino && mirrorCeStat.st_dev == ceStat.st_dev) {
Ricky Wai2a4983f2020-02-07 14:25:45 +00003722 // As it's being called by prepareUserStorage, it can be called multiple times.
3723 // Hence, we if we mount it already, we should skip it.
Eric Biggersab9ea462022-05-26 00:28:09 +00003724 LOG(INFO) << "CE dir is mounted already: " + cePath;
Ricky Wai2a4983f2020-02-07 14:25:45 +00003725 return ok();
3726 }
3727
3728 // Mount CE mirror
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003729 if (TEMP_FAILURE_RETRY(mount(cePath.c_str(), mirrorVolCePath.c_str(), NULL,
3730 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3731 return error("Failed to mount " + mirrorVolCePath);
3732 }
3733
3734 // Mount DE mirror
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003735 if (TEMP_FAILURE_RETRY(mount(dePath.c_str(), mirrorVolDePath.c_str(), NULL,
3736 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3737 return error("Failed to mount " + mirrorVolDePath);
3738 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003739
3740 // Mount misc CE mirror
3741 if (TEMP_FAILURE_RETRY(mount(miscCePath.c_str(), mirrorVolMiscCePath.c_str(), NULL,
3742 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3743 nullptr)) == -1) {
3744 return error("Failed to mount " + mirrorVolMiscCePath);
3745 }
3746
3747 // Mount misc DE mirror
3748 if (TEMP_FAILURE_RETRY(mount(miscDePath.c_str(), mirrorVolMiscDePath.c_str(), NULL,
3749 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3750 nullptr)) == -1) {
3751 return error("Failed to mount " + mirrorVolMiscDePath);
3752 }
3753
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003754 return ok();
3755}
3756
3757// Unmount volume's CE and DE storage from mirror
3758binder::Status InstalldNativeService::onPrivateVolumeRemoved(
Jooyung Han149be4a2020-01-23 12:45:10 +09003759 const std::optional<std::string>& uuid) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003760 ENFORCE_UID(AID_SYSTEM);
3761 CHECK_ARGUMENT_UUID(uuid);
3762 if (!sAppDataIsolationEnabled) {
3763 return ok();
3764 }
3765 if (!uuid) {
3766 // It happens when private volume failed to mount.
3767 LOG(INFO) << "Ignore unmount uuid=null";
3768 return ok();
3769 }
3770 const char* uuid_ = uuid->c_str();
3771
3772 binder::Status res = ok();
3773
3774 std::string mirrorCeVolPath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
3775 std::string mirrorDeVolPath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
Sanjana Sunil691163d2022-03-28 19:15:54 +00003776 std::string mirrorMiscCeVolPath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
3777 std::string mirrorMiscDeVolPath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003778
Alex Buynytskyy40c45ba2021-11-18 15:16:27 -08003779 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3780
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003781 // Unmount CE storage
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003782 if (TEMP_FAILURE_RETRY(umount(mirrorCeVolPath.c_str())) != 0) {
3783 if (errno != ENOENT) {
3784 res = error(StringPrintf("Failed to umount %s %s", mirrorCeVolPath.c_str(),
3785 strerror(errno)));
3786 }
3787 }
3788 if (delete_dir_contents_and_dir(mirrorCeVolPath, true) != 0) {
3789 res = error("Failed to delete " + mirrorCeVolPath);
3790 }
3791
3792 // Unmount DE storage
3793 if (TEMP_FAILURE_RETRY(umount(mirrorDeVolPath.c_str())) != 0) {
3794 if (errno != ENOENT) {
3795 res = error(StringPrintf("Failed to umount %s %s", mirrorDeVolPath.c_str(),
3796 strerror(errno)));
3797 }
3798 }
3799 if (delete_dir_contents_and_dir(mirrorDeVolPath, true) != 0) {
3800 res = error("Failed to delete " + mirrorDeVolPath);
3801 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003802
3803 // Unmount misc CE storage
3804 if (TEMP_FAILURE_RETRY(umount(mirrorMiscCeVolPath.c_str())) != 0) {
3805 if (errno != ENOENT) {
3806 res = error(StringPrintf("Failed to umount %s %s", mirrorMiscCeVolPath.c_str(),
3807 strerror(errno)));
3808 }
3809 }
3810 if (delete_dir_contents_and_dir(mirrorMiscCeVolPath, true) != 0) {
3811 res = error("Failed to delete " + mirrorMiscCeVolPath);
3812 }
3813
3814 // Unmount misc DE storage
3815 if (TEMP_FAILURE_RETRY(umount(mirrorMiscDeVolPath.c_str())) != 0) {
3816 if (errno != ENOENT) {
3817 res = error(StringPrintf("Failed to umount %s %s", mirrorMiscDeVolPath.c_str(),
3818 strerror(errno)));
3819 }
3820 }
3821 if (delete_dir_contents_and_dir(mirrorMiscDeVolPath, true) != 0) {
3822 res = error("Failed to delete " + mirrorMiscDeVolPath);
3823 }
3824
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003825 return res;
3826}
3827
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003828std::string InstalldNativeService::findDataMediaPath(
Jooyung Han149be4a2020-01-23 12:45:10 +09003829 const std::optional<std::string>& uuid, userid_t userid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003830 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3831 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3832 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
3833 auto resolved = mStorageMounts[path];
3834 if (resolved.empty()) {
3835 LOG(WARNING) << "Failed to find storage mount for " << path;
3836 resolved = path;
3837 }
3838 return StringPrintf("%s/%u", resolved.c_str(), userid);
3839}
3840
Jeff Sharkey325b8c92017-02-21 10:00:53 -07003841binder::Status InstalldNativeService::isQuotaSupported(
Jooyung Han149be4a2020-01-23 12:45:10 +09003842 const std::optional<std::string>& uuid, bool* _aidl_return) {
3843 *_aidl_return = IsQuotaSupported(uuid.value_or(""));
Jeff Sharkey325b8c92017-02-21 10:00:53 -07003844 return ok();
3845}
3846
Calin Juravlebc5ab872018-01-18 22:32:58 -08003847binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
3848 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
Jooyung Han149be4a2020-01-23 12:45:10 +09003849 const std::optional<std::string>& dexMetadata, bool* _aidl_return) {
Calin Juravlebc5ab872018-01-18 22:32:58 -08003850 ENFORCE_UID(AID_SYSTEM);
Steven Moreland3e543b92023-09-07 20:08:15 +00003851 ENFORCE_VALID_USER_OR_NULL(userId);
Calin Juravlebc5ab872018-01-18 22:32:58 -08003852 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003853 CHECK_ARGUMENT_PATH(codePath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003854 LOCK_PACKAGE_USER();
Calin Juravlebc5ab872018-01-18 22:32:58 -08003855
3856 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
3857 dexMetadata);
3858 return ok();
3859}
3860
Narayan Kamath28ab93b2019-05-15 18:29:44 +01003861binder::Status InstalldNativeService::migrateLegacyObbData() {
3862 ENFORCE_UID(AID_SYSTEM);
3863 // NOTE: The lint warning doesn't apply to the use of system(3) with
3864 // absolute parse and no command line arguments.
Cole Faustf6cd58a2022-09-01 17:34:36 -07003865 if (system("/system/bin/migrate_legacy_obb_data") != 0) { // NOLINT(cert-env33-c)
Narayan Kamath28ab93b2019-05-15 18:29:44 +01003866 LOG(ERROR) << "Unable to migrate legacy obb data";
3867 }
3868
3869 return ok();
3870}
3871
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003872binder::Status InstalldNativeService::cleanupInvalidPackageDirs(
3873 const std::optional<std::string>& uuid, int32_t userId, int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00003874 ENFORCE_VALID_USER(userId);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003875 const char* uuid_cstr = uuid ? uuid->c_str() : nullptr;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003876
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003877 if (flags & FLAG_STORAGE_CE) {
3878 auto ce_path = create_data_user_ce_path(uuid_cstr, userId);
3879 cleanup_invalid_package_dirs_under_path(ce_path);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00003880 auto sdksandbox_ce_path =
3881 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/true, userId);
3882 cleanup_invalid_package_dirs_under_path(sdksandbox_ce_path);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003883 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003884
3885 if (flags & FLAG_STORAGE_DE) {
3886 auto de_path = create_data_user_de_path(uuid_cstr, userId);
3887 cleanup_invalid_package_dirs_under_path(de_path);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00003888 auto sdksandbox_de_path =
3889 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/false, userId);
3890 cleanup_invalid_package_dirs_under_path(sdksandbox_de_path);
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003891 }
3892
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003893 return ok();
3894}
3895
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00003896binder::Status InstalldNativeService::getOdexVisibility(
3897 const std::string& packageName, const std::string& apkPath,
3898 const std::string& instructionSet, const std::optional<std::string>& outputPath,
3899 int32_t* _aidl_return) {
3900 ENFORCE_UID(AID_SYSTEM);
3901 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3902 CHECK_ARGUMENT_PATH(apkPath);
3903 CHECK_ARGUMENT_PATH(outputPath);
3904 LOCK_PACKAGE();
3905
3906 const char* apk_path = apkPath.c_str();
3907 const char* instruction_set = instructionSet.c_str();
3908 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
3909
3910 *_aidl_return = get_odex_visibility(apk_path, instruction_set, oat_dir);
3911 return *_aidl_return == -1 ? error() : ok();
3912}
3913
Victor Hsiehc7ab5642023-07-28 15:07:55 -07003914// Creates an auth token to be used in enableFsverity. This token is really to store a proof that
3915// the caller can write to a file, represented by the authFd. Effectively, system_server as the
3916// attacker-in-the-middle cannot enable fs-verity on arbitrary app files. If the FD is not writable,
3917// return null.
3918//
3919// appUid and userId are passed for additional ownership check, such that one app can not be
3920// authenticated for another app's file. These parameters are assumed trusted for this purpose of
3921// consistency check.
3922//
3923// Notably, creating the token allows us to manage the writable FD easily during enableFsverity.
3924// Since enabling fs-verity to a file requires no outstanding writable FD, passing the authFd to the
3925// server allows the server to hold the only reference (as long as the client app doesn't).
3926binder::Status InstalldNativeService::createFsveritySetupAuthToken(
3927 const ParcelFileDescriptor& authFd, int32_t appUid, int32_t userId,
3928 sp<IFsveritySetupAuthToken>* _aidl_return) {
3929 CHECK_ARGUMENT_UID_IN_APP_RANGE(appUid);
3930 ENFORCE_VALID_USER(userId);
3931
3932 auto token = sp<FsveritySetupAuthToken>::make();
3933 binder::Status status = token->authenticate(authFd, appUid, userId);
3934 if (!status.isOk()) {
3935 return status;
3936 }
3937 *_aidl_return = token;
3938 return ok();
3939}
3940
3941// Enables fs-verity for filePath, which must be an absolute path and the same inode as in the auth
3942// token previously returned from createFsveritySetupAuthToken, and owned by the app uid. As
3943// installd is more privileged than its client / system server, we attempt to limit what a
3944// (compromised) client can do.
3945//
3946// The reason for this app request to go through installd is to avoid exposing a risky area (PKCS#7
3947// signature verification) in the kernel to the app as an attack surface (it can't be system server
3948// because it can't override DAC and manipulate app files). Note that we should be able to drop
3949// these hops and simply the app calls the ioctl, once all upgrading devices run with a kernel
3950// without fs-verity built-in signature (https://r.android.com/2650402).
3951binder::Status InstalldNativeService::enableFsverity(const sp<IFsveritySetupAuthToken>& authToken,
3952 const std::string& filePath,
3953 const std::string& packageName,
3954 int32_t* _aidl_return) {
3955 ENFORCE_UID(AID_SYSTEM);
3956 CHECK_ARGUMENT_PATH(filePath);
3957 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3958 LOCK_PACKAGE();
3959 if (authToken == nullptr) {
3960 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Received a null auth token");
3961 }
3962
3963 // Authenticate to check the targeting file is the same inode as the authFd.
3964 sp<IBinder> authTokenBinder = IInterface::asBinder(authToken)->localBinder();
3965 if (authTokenBinder == nullptr) {
3966 return exception(binder::Status::EX_SECURITY, "Received a non-local auth token");
3967 }
3968 auto authTokenInstance = sp<FsveritySetupAuthToken>::cast(authTokenBinder);
3969 unique_fd rfd(open(filePath.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
3970 struct stat stFromPath;
3971 if (fstat(rfd.get(), &stFromPath) < 0) {
3972 *_aidl_return = errno;
3973 return ok();
3974 }
3975 if (!authTokenInstance->isSameStat(stFromPath)) {
3976 LOG(DEBUG) << "FD authentication failed";
3977 *_aidl_return = EPERM;
3978 return ok();
3979 }
3980
3981 fsverity_enable_arg arg = {};
3982 arg.version = 1;
3983 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
3984 arg.block_size = 4096;
3985 if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, &arg) < 0) {
3986 *_aidl_return = errno;
3987 } else {
3988 *_aidl_return = 0;
3989 }
3990 return ok();
3991}
3992
Andreas Gampe02d0de52015-11-11 20:43:16 -08003993} // namespace installd
3994} // namespace android