blob: 9399c73b2a844658109edbe69e35c04e80daf305 [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>
Alex Buynytskyy02dca6b2023-11-28 19:06:34 +000043#include <thread>
Samiul Islam92f5cf02022-02-03 12:45:51 +000044#include <unordered_set>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070045
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000046#include <android-base/file.h>
Andreas Gampeafa58d12016-06-03 16:09:32 -070047#include <android-base/logging.h>
Oli Lanc7789572020-03-16 18:18:41 +000048#include <android-base/parseint.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070049#include <android-base/properties.h>
Narayan Kamathe63ca7d2019-01-14 15:21:52 +000050#include <android-base/scopeguard.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080051#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070052#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010053#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080054#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080055#include <cutils/fs.h>
Victor Hsiehc7ab5642023-07-28 15:07:55 -070056#include <cutils/misc.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070057#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070058#include <cutils/sched_policy.h>
Shikha Malhotra976ae002022-02-26 15:39:53 +000059#include <linux/quota.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070060#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070061#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080062#include <private/android_filesystem_config.h>
Martijn Coenen771cc342020-02-19 23:26:56 +010063#include <private/android_projectid_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070064#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080065#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070066#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070067
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070068#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070069#include "globals.h"
70#include "installd_deps.h"
71#include "otapreopt_utils.h"
72#include "utils.h"
Eric Holk0ebbe0f2019-01-09 18:17:27 -080073#include "view_compiler.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070074
Jeff Sharkey88ddd942017-01-17 18:05:54 -070075#include "CacheTracker.h"
Felka Chang2a0a2462019-11-20 14:20:40 +080076#include "CrateManager.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070077#include "MatchExtensionGen.h"
Risan5f308262018-10-26 12:06:58 -060078#include "QuotaUtils.h"
Zim23457d02022-08-17 12:57:41 +010079#include "SysTrace.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070080
Andreas Gampe02d0de52015-11-11 20:43:16 -080081#ifndef LOG_TAG
82#define LOG_TAG "installd"
83#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070084
Alex Buynytskyy779447d2021-11-22 17:06:53 -080085#define GRANULAR_LOCKS
Alex Buynytskyy4fef8862021-11-21 16:09:33 -080086
Oli Lanc7789572020-03-16 18:18:41 +000087using android::base::ParseUint;
Samiul Islam92f5cf02022-02-03 12:45:51 +000088using android::base::Split;
Jeff Sharkey41ea4242015-04-09 11:34:03 -070089using android::base::StringPrintf;
Victor Hsiehc7ab5642023-07-28 15:07:55 -070090using android::base::unique_fd;
91using android::os::ParcelFileDescriptor;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070092using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070093
Andreas Gampe02d0de52015-11-11 20:43:16 -080094namespace android {
95namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070096
Nikita Ioffe8e4d3462019-01-21 17:56:03 +000097// An uuid used in unit tests.
98static constexpr const char* kTestUuid = "TEST";
99
Nikita Ioffeb68f0d12019-02-04 11:06:37 +0000100static constexpr const mode_t kRollbackFolderMode = 0700;
101
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700102static constexpr const char* kCpPath = "/system/bin/cp";
103static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -0700104
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000105static constexpr const char* kDataMirrorCePath = "/data_mirror/data_ce";
106static constexpr const char* kDataMirrorDePath = "/data_mirror/data_de";
Sanjana Sunil691163d2022-03-28 19:15:54 +0000107static constexpr const char* kMiscMirrorCePath = "/data_mirror/misc_ce";
108static constexpr const char* kMiscMirrorDePath = "/data_mirror/misc_de";
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000109
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -0700110static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +0000111
Andreas Gampe0354bd02016-06-27 14:25:30 -0700112static constexpr const char* PKG_LIB_POSTFIX = "/lib";
113static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
114static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
115
Zim0ce832d2019-12-03 17:03:58 +0000116static constexpr const char* kFuseProp = "persist.sys.fuse";
Victor Hsieh99de5162017-10-06 14:44:14 -0700117
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000118/**
119 * Property to control if app data isolation is enabled.
120 */
121static constexpr const char* kAppDataIsolationEnabledProperty = "persist.zygote.app_data_isolation";
Zim1edb92a2020-01-09 08:48:00 +0000122static constexpr const char* kMntSdcardfs = "/mnt/runtime/default/";
123static constexpr const char* kMntFuse = "/mnt/pass_through/0/";
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000124
125static std::atomic<bool> sAppDataIsolationEnabled(false);
126
Shikha Malhotradcf469b2022-03-23 11:53:58 +0000127/**
128 * Flag to control if project ids are supported for internal storage
129 */
130static std::atomic<bool> sUsingProjectIdsFlag(false);
131static std::once_flag flag;
132
Jeff Sharkey0274c972016-12-06 09:32:04 -0700133namespace {
134
Jeff Sharkey423e7462016-12-09 18:18:43 -0700135static binder::Status ok() {
136 return binder::Status::ok();
137}
138
139static binder::Status exception(uint32_t code, const std::string& msg) {
Jeff Sharkey8e9bf352018-02-27 11:40:45 -0700140 LOG(ERROR) << msg << " (" << code << ")";
Jeff Sharkey423e7462016-12-09 18:18:43 -0700141 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
142}
143
144static binder::Status error() {
145 return binder::Status::fromServiceSpecificError(errno);
146}
147
148static binder::Status error(const std::string& msg) {
149 PLOG(ERROR) << msg;
150 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
151}
152
153static binder::Status error(uint32_t code, const std::string& msg) {
154 LOG(ERROR) << msg << " (" << code << ")";
155 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
156}
157
Jeff Sharkey0274c972016-12-06 09:32:04 -0700158binder::Status checkUid(uid_t expectedUid) {
159 uid_t uid = IPCThreadState::self()->getCallingUid();
160 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700161 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700162 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700163 return exception(binder::Status::EX_SECURITY,
164 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
165 }
166}
167
Jooyung Han149be4a2020-01-23 12:45:10 +0900168binder::Status checkArgumentUuid(const std::optional<std::string>& uuid) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700169 if (!uuid || is_valid_filename(*uuid)) {
170 return ok();
171 } else {
172 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
173 StringPrintf("UUID %s is malformed", uuid->c_str()));
174 }
175}
176
Jooyung Han149be4a2020-01-23 12:45:10 +0900177binder::Status checkArgumentUuidTestOrNull(const std::optional<std::string>& uuid) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000178 if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
179 return ok();
180 } else {
181 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
182 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
183 }
184}
185
Jeff Sharkey423e7462016-12-09 18:18:43 -0700186binder::Status checkArgumentPackageName(const std::string& packageName) {
Greg Kaiser6d758fc2019-03-26 08:55:32 -0700187 if (is_valid_package_name(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700188 return ok();
189 } else {
190 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
191 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700192 }
193}
194
Jeff Sharkey53594302018-02-24 18:59:39 -0700195binder::Status checkArgumentPath(const std::string& path) {
196 if (path.empty()) {
197 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
198 }
199 if (path[0] != '/') {
200 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
201 StringPrintf("Path %s is relative", path.c_str()));
202 }
203 if ((path + '/').find("/../") != std::string::npos) {
204 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
205 StringPrintf("Path %s is shady", path.c_str()));
206 }
207 for (const char& c : path) {
208 if (c == '\0' || c == '\n') {
209 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
210 StringPrintf("Path %s is malformed", path.c_str()));
211 }
212 }
213 return ok();
214}
215
Jooyung Han149be4a2020-01-23 12:45:10 +0900216binder::Status checkArgumentPath(const std::optional<std::string>& path) {
Jeff Sharkey53594302018-02-24 18:59:39 -0700217 if (path) {
218 return checkArgumentPath(*path);
219 } else {
220 return ok();
221 }
222}
223
Alex Buynytskyyd04631f2022-08-12 15:14:41 -0700224binder::Status checkArgumentFileName(const std::string& path) {
225 if (path.empty()) {
226 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing name");
227 }
228 for (const char& c : path) {
229 if (c == '\0' || c == '\n' || c == '/') {
230 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
231 StringPrintf("Name %s is malformed", path.c_str()));
232 }
233 }
234 return ok();
235}
236
Victor Hsiehc72e4d72024-01-09 15:46:00 -0800237binder::Status checkArgumentAppId(int32_t appId) {
238 if (FIRST_APPLICATION_UID <= appId && appId <= LAST_APPLICATION_UID) {
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700239 return ok();
240 }
241 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
Victor Hsiehc72e4d72024-01-09 15:46:00 -0800242 StringPrintf("appId %d is outside of the range", appId));
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700243}
244
Jeff Sharkey0274c972016-12-06 09:32:04 -0700245#define ENFORCE_UID(uid) { \
246 binder::Status status = checkUid((uid)); \
247 if (!status.isOk()) { \
248 return status; \
249 } \
250}
251
Steven Moreland36945362023-07-05 20:29:10 +0000252// we could have tighter checks, but this is only to avoid hard errors. Negative values are defined
253// in UserHandle.java and carry specific meanings that may not be handled by certain APIs here.
Steven Moreland3e543b92023-09-07 20:08:15 +0000254#define ENFORCE_VALID_USER(userId) \
255 { \
256 if (static_cast<uid_t>(userId) >= std::numeric_limits<uid_t>::max() / AID_USER_OFFSET) { \
257 return error("userId invalid: " + std::to_string(userId)); \
258 } \
259 }
260
261#define ENFORCE_VALID_USER_OR_NULL(userId) \
262 { \
263 if (static_cast<uid_t>(userId) != USER_NULL) { \
264 ENFORCE_VALID_USER(userId); \
265 } \
Steven Moreland36945362023-07-05 20:29:10 +0000266 }
267
Jeff Sharkey423e7462016-12-09 18:18:43 -0700268#define CHECK_ARGUMENT_UUID(uuid) { \
269 binder::Status status = checkArgumentUuid((uuid)); \
270 if (!status.isOk()) { \
271 return status; \
272 } \
273}
274
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000275#define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) { \
276 auto status = checkArgumentUuidTestOrNull(uuid); \
277 if (!status.isOk()) { \
278 return status; \
279 } \
280} \
281
Jeff Sharkey423e7462016-12-09 18:18:43 -0700282#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
283 binder::Status status = \
284 checkArgumentPackageName((packageName)); \
285 if (!status.isOk()) { \
286 return status; \
287 } \
288}
289
Jeff Sharkey53594302018-02-24 18:59:39 -0700290#define CHECK_ARGUMENT_PATH(path) { \
291 binder::Status status = checkArgumentPath((path)); \
292 if (!status.isOk()) { \
293 return status; \
294 } \
295}
296
Alex Buynytskyyd04631f2022-08-12 15:14:41 -0700297#define CHECK_ARGUMENT_FILE_NAME(path) \
298 { \
299 binder::Status status = checkArgumentFileName((path)); \
300 if (!status.isOk()) { \
301 return status; \
302 } \
303 }
304
Victor Hsiehc72e4d72024-01-09 15:46:00 -0800305#define CHECK_ARGUMENT_APP_ID(appId) \
306 { \
307 binder::Status status = checkArgumentAppId((appId)); \
308 if (!status.isOk()) { \
309 return status; \
310 } \
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700311 }
312
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800313#ifdef GRANULAR_LOCKS
314
315/**
316 * This class obtains in constructor and keeps the local strong pointer to the RefLock.
317 * On destruction, it checks if there are any other strong pointers, and remove the map entry if
318 * this was the last one.
319 */
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800320template <class Key, class Mutex>
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800321struct LocalLockHolder {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800322 using WeakPointer = std::weak_ptr<Mutex>;
323 using StrongPointer = std::shared_ptr<Mutex>;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800324 using Map = std::unordered_map<Key, WeakPointer>;
325 using MapLock = std::recursive_mutex;
326
327 LocalLockHolder(Key key, Map& map, MapLock& mapLock)
328 : mKey(std::move(key)), mMap(map), mMapLock(mapLock) {
329 std::lock_guard lock(mMapLock);
330 auto& weakPtr = mMap[mKey];
331
332 // Check if the RefLock is still alive.
333 mRefLock = weakPtr.lock();
334 if (!mRefLock) {
335 // Create a new lock.
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800336 mRefLock = std::make_shared<Mutex>();
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800337 weakPtr = mRefLock;
338 }
339 }
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800340 LocalLockHolder(LocalLockHolder&& other) noexcept
341 : mKey(std::move(other.mKey)),
342 mMap(other.mMap),
343 mMapLock(other.mMapLock),
344 mRefLock(std::move(other.mRefLock)) {
345 other.mRefLock.reset();
346 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800347 ~LocalLockHolder() {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800348 if (!mRefLock) {
349 return;
350 }
351
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800352 std::lock_guard lock(mMapLock);
353 // Clear the strong pointer.
354 mRefLock.reset();
355 auto found = mMap.find(mKey);
356 if (found == mMap.end()) {
357 return;
358 }
359 const auto& weakPtr = found->second;
360 // If this was the last pointer then it's ok to remove the map entry.
361 if (weakPtr.expired()) {
362 mMap.erase(found);
363 }
364 }
365
366 void lock() { mRefLock->lock(); }
367 void unlock() { mRefLock->unlock(); }
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800368 void lock_shared() { mRefLock->lock_shared(); }
369 void unlock_shared() { mRefLock->unlock_shared(); }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800370
371private:
372 Key mKey;
373 Map& mMap;
374 MapLock& mMapLock;
375 StrongPointer mRefLock;
376};
377
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800378using UserLock = LocalLockHolder<userid_t, std::shared_mutex>;
379using UserWriteLockGuard = std::unique_lock<UserLock>;
380using UserReadLockGuard = std::shared_lock<UserLock>;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800381
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800382using PackageLock = LocalLockHolder<std::string, std::recursive_mutex>;
383using PackageLockGuard = std::lock_guard<PackageLock>;
384
385#define LOCK_USER() \
386 UserLock localUserLock(userId, mUserIdLock, mLock); \
387 UserWriteLockGuard userLock(localUserLock)
388
389#define LOCK_USER_READ() \
390 UserLock localUserLock(userId, mUserIdLock, mLock); \
391 UserReadLockGuard userLock(localUserLock)
392
393#define LOCK_PACKAGE() \
394 PackageLock localPackageLock(packageName, mPackageNameLock, mLock); \
395 PackageLockGuard packageLock(localPackageLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800396
397#define LOCK_PACKAGE_USER() \
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800398 LOCK_USER_READ(); \
399 LOCK_PACKAGE()
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800400
401#else
402
403#define LOCK_USER() std::lock_guard lock(mLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800404#define LOCK_PACKAGE() std::lock_guard lock(mLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800405#define LOCK_PACKAGE_USER() \
406 (void)userId; \
407 std::lock_guard lock(mLock)
408
409#endif // GRANULAR_LOCKS
410
Jeff Sharkey0274c972016-12-06 09:32:04 -0700411} // namespace
412
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700413binder::Status InstalldNativeService::FsveritySetupAuthToken::authenticate(
Victor Hsiehc72e4d72024-01-09 15:46:00 -0800414 const ParcelFileDescriptor& authFd, int32_t uid) {
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700415 int open_flags = fcntl(authFd.get(), F_GETFL);
416 if (open_flags < 0) {
417 return exception(binder::Status::EX_SERVICE_SPECIFIC, "fcntl failed");
418 }
419 if ((open_flags & O_ACCMODE) != O_WRONLY && (open_flags & O_ACCMODE) != O_RDWR) {
420 return exception(binder::Status::EX_SECURITY, "Received FD with unexpected open flag");
421 }
422 if (fstat(authFd.get(), &this->mStatFromAuthFd) < 0) {
423 return exception(binder::Status::EX_SERVICE_SPECIFIC, "fstat failed");
424 }
425 if (!S_ISREG(this->mStatFromAuthFd.st_mode)) {
426 return exception(binder::Status::EX_SECURITY, "Not a regular file");
427 }
428 // Don't accept a file owned by a different app.
Victor Hsiehc72e4d72024-01-09 15:46:00 -0800429 if (this->mStatFromAuthFd.st_uid != (uid_t)uid) {
430 return exception(binder::Status::EX_SERVICE_SPECIFIC, "File not owned by uid");
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700431 }
432 return ok();
433}
434
435bool InstalldNativeService::FsveritySetupAuthToken::isSameStat(const struct stat& st) const {
436 return memcmp(&st, &mStatFromAuthFd, sizeof(st)) == 0;
437}
438
Jeff Sharkey0274c972016-12-06 09:32:04 -0700439status_t InstalldNativeService::start() {
440 IPCThreadState::self()->disableBackgroundScheduling(true);
441 status_t ret = BinderService<InstalldNativeService>::publish();
442 if (ret != android::OK) {
443 return ret;
444 }
445 sp<ProcessState> ps(ProcessState::self());
446 ps->startThreadPool();
447 ps->giveThreadPoolName();
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000448 sAppDataIsolationEnabled = android::base::GetBoolProperty(
Ricky Wai30f947d2019-12-19 17:24:48 +0000449 kAppDataIsolationEnabledProperty, true);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700450 return android::OK;
451}
452
Alex Buynytskyy17b12dc2022-09-12 20:57:24 -0700453status_t InstalldNativeService::dump(int fd, const Vector<String16>& /* args */) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700454 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600455 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Keun young Park144a9892021-10-13 16:43:58 -0700456 dprintf(fd, "Storage mounts:\n");
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600457 for (const auto& n : mStorageMounts) {
Keun young Park144a9892021-10-13 16:43:58 -0700458 dprintf(fd, " %s = %s\n", n.first.c_str(), n.second.c_str());
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600459 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700460 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700461
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700462 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600463 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Keun young Park144a9892021-10-13 16:43:58 -0700464 dprintf(fd, "Per-UID cache quotas:\n");
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700465 for (const auto& n : mCacheQuotas) {
Keun young Park144a9892021-10-13 16:43:58 -0700466 dprintf(fd, " %d = %" PRId64 "\n", n.first, n.second);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700467 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700468 }
469
Keun young Park144a9892021-10-13 16:43:58 -0700470 dprintf(fd, "is_dexopt_blocked:%d\n", android::installd::is_dexopt_blocked());
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700471
Jeff Sharkey0274c972016-12-06 09:32:04 -0700472 return NO_ERROR;
473}
474
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000475constexpr const char kXattrRestoreconInProgress[] = "user.restorecon_in_progress";
476
477static std::string lgetfilecon(const std::string& path) {
478 char* context;
479 if (::lgetfilecon(path.c_str(), &context) < 0) {
480 PLOG(ERROR) << "Failed to lgetfilecon for " << path;
481 return {};
482 }
483 std::string result{context};
484 free(context);
485 return result;
486}
487
488static bool getRestoreconInProgress(const std::string& path) {
489 bool inProgress = false;
490 if (getxattr(path.c_str(), kXattrRestoreconInProgress, &inProgress, sizeof(inProgress)) !=
491 sizeof(inProgress)) {
492 if (errno != ENODATA) {
493 PLOG(ERROR) << "Failed to check in-progress restorecon for " << path;
494 }
495 return false;
496 }
497 return inProgress;
498}
499
500struct RestoreconInProgress {
501 explicit RestoreconInProgress(const std::string& path) : mPath(path) {
502 bool inProgress = true;
503 if (setxattr(mPath.c_str(), kXattrRestoreconInProgress, &inProgress, sizeof(inProgress),
504 0) != 0) {
505 PLOG(ERROR) << "Failed to set in-progress restorecon for " << path;
506 }
507 }
508 ~RestoreconInProgress() {
509 if (removexattr(mPath.c_str(), kXattrRestoreconInProgress) < 0) {
510 PLOG(ERROR) << "Failed to clear in-progress restorecon for " << mPath;
511 }
512 }
513
514private:
515 const std::string& mPath;
516};
517
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600518/**
519 * Perform restorecon of the given path, but only perform recursive restorecon
520 * if the label of that top-level file actually changed. This can save us
521 * significant time by avoiding no-op traversals of large filesystem trees.
522 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700523static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
524 bool existing) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700525 ScopedTrace tracer("restorecon-lazy");
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000526 if (!existing) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700527 ScopedTrace tracer("new-path");
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000528 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
529 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
530 PLOG(ERROR) << "Failed recursive restorecon for " << path;
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000531 return -1;
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000532 }
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000533 return 0;
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000534 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600535
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000536 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
537
538 // Check to see if there was an interrupted operation.
539 bool inProgress = getRestoreconInProgress(path);
540 std::string before, after;
541 if (!inProgress) {
542 if (before = lgetfilecon(path); before.empty()) {
543 PLOG(ERROR) << "Failed before getfilecon for " << path;
544 return -1;
545 }
546 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
547 PLOG(ERROR) << "Failed top-level restorecon for " << path;
548 return -1;
549 }
550 if (after = lgetfilecon(path); after.empty()) {
551 PLOG(ERROR) << "Failed after getfilecon for " << path;
552 return -1;
553 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600554 }
555
556 // If the initial top-level restorecon above changed the label, then go
557 // back and restorecon everything recursively
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000558 if (inProgress || before != after) {
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700559 if (existing) {
560 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
Alex Buynytskyy02dca6b2023-11-28 19:06:34 +0000561 << path << "; running recursive restorecon";
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700562 }
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000563
Alex Buynytskyy02dca6b2023-11-28 19:06:34 +0000564 auto restorecon = [path, seInfo, uid]() {
565 ScopedTrace tracer("label-change");
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000566
Alex Buynytskyy02dca6b2023-11-28 19:06:34 +0000567 // Temporary mark the folder as "in-progress" to resume in case of reboot/other failure.
568 RestoreconInProgress fence(path);
569
570 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
571 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
572 PLOG(ERROR) << "Failed recursive restorecon for " << path;
573 return -1;
574 }
575 return 0;
576 };
577 if (inProgress) {
578 // The previous restorecon was interrupted. It's either crashed (unlikely), or the phone
579 // was rebooted. Possibly because it took too much time. This time let's move it to a
580 // separate thread - so it won't block the rest of the OS.
581 std::thread(restorecon).detach();
582 } else {
583 if (int result = restorecon(); result) {
584 return result;
585 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600586 }
587 }
588
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000589 return 0;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600590}
Shikha Malhotra976ae002022-02-26 15:39:53 +0000591static bool internal_storage_has_project_id() {
592 // The following path is populated in setFirstBoot, so if this file is present
Shikha Malhotradcf469b2022-03-23 11:53:58 +0000593 // then project ids can be used. Using call once to cache the result of this check
594 // to avoid having to check the file presence again and again.
595 std::call_once(flag, []() {
596 auto using_project_ids =
597 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
598 sUsingProjectIdsFlag = access(using_project_ids.c_str(), F_OK) == 0;
599 });
Shikha Malhotra8f55b3d2022-04-04 14:11:43 +0000600 // return sUsingProjectIdsFlag;
601 return false;
Shikha Malhotra976ae002022-02-26 15:39:53 +0000602}
603
604static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid, gid_t gid,
605 long project_id) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700606 {
607 ScopedTrace tracer("prepare-dir");
608 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
609 PLOG(ERROR) << "Failed to prepare " << path;
610 return -1;
611 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600612 }
Shikha Malhotra976ae002022-02-26 15:39:53 +0000613 if (internal_storage_has_project_id()) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700614 ScopedTrace tracer("set-quota");
Shikha Malhotra976ae002022-02-26 15:39:53 +0000615 return set_quota_project_id(path, project_id, true);
616 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600617 return 0;
618}
619
Shikha Malhotra976ae002022-02-26 15:39:53 +0000620static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
621 uid_t uid, gid_t gid, long project_id) {
622 auto path = StringPrintf("%s/%s", parent.c_str(), name);
Alex Buynytskyya203d712023-06-08 12:56:15 -0700623 int ret;
624 {
625 ScopedTrace tracer("prepare-cache-dir");
626 ret = prepare_app_cache_dir(parent, name, target_mode, uid, gid);
627 }
Shikha Malhotra976ae002022-02-26 15:39:53 +0000628 if (ret == 0 && internal_storage_has_project_id()) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700629 ScopedTrace tracer("set-quota-cache-dir");
Shikha Malhotra976ae002022-02-26 15:39:53 +0000630 return set_quota_project_id(path, project_id, true);
631 }
632 return ret;
633}
634
Calin Juravled2affb82017-11-28 17:41:43 -0800635static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700636 ScopedTrace tracer("prepare-app-profile");
Calin Juravled2affb82017-11-28 17:41:43 -0800637 int32_t uid = multiuser_get_uid(userId, appId);
638 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
639 if (shared_app_gid == -1) {
640 // TODO(calin): this should no longer be possible but do not continue if we don't get
641 // a valid shared gid.
642 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
643 return true;
644 }
645
646 const std::string profile_dir =
647 create_primary_current_profile_package_dir_path(userId, packageName);
648 // read-write-execute only for the app user.
649 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
650 PLOG(ERROR) << "Failed to prepare " << profile_dir;
651 return false;
652 }
Alan Stokes928d2c12020-12-09 10:11:24 +0000653 if (selinux_android_restorecon(profile_dir.c_str(), 0)) {
654 PLOG(ERROR) << "Failed to restorecon " << profile_dir;
655 return false;
656 }
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800657
Calin Juravled2affb82017-11-28 17:41:43 -0800658 const std::string ref_profile_path =
659 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800660
661 // Prepare the reference profile directory. Note that we use the non strict version of
662 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
663 // This is particularly important given that in O there were some fixes for how the
664 // shared_app_gid is computed.
665 //
666 // Note that by the time we get here we know that we are using a correct uid (otherwise
667 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
668 // are sure that the gid being used belongs to the owning app and not someone else.
669 //
670 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
671 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800672 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
673 return false;
674 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800675
Calin Juravled2affb82017-11-28 17:41:43 -0800676 return true;
677}
678
John Wu84e8f242021-10-21 11:50:41 -0700679static bool chown_app_dir(const std::string& path, uid_t uid, uid_t previousUid, gid_t cacheGid) {
680 FTS* fts;
681 char *argv[] = { (char*) path.c_str(), nullptr };
682 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
683 return false;
684 }
685 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
686 if (p->fts_info == FTS_D && p->fts_level == 1
687 && (strcmp(p->fts_name, "cache") == 0
688 || strcmp(p->fts_name, "code_cache") == 0)) {
689 // Mark cache dirs
690 p->fts_number = 1;
691 } else {
692 // Inherit parent's number
693 p->fts_number = p->fts_parent->fts_number;
694 }
695
696 switch (p->fts_info) {
697 case FTS_D:
698 case FTS_F:
699 case FTS_SL:
700 case FTS_SLNONE:
701 if (p->fts_statp->st_uid == previousUid) {
702 if (lchown(p->fts_path, uid, p->fts_number ? cacheGid : uid) != 0) {
703 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
704 }
705 } else {
706 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected UID "
707 << p->fts_statp->st_uid << " instead of " << previousUid;
708 }
709 break;
710 }
711 }
712 fts_close(fts);
713 return true;
714}
715
716static void chown_app_profile_dir(const std::string &packageName, int32_t appId, int32_t userId) {
717 uid_t uid = multiuser_get_uid(userId, appId);
718 gid_t sharedGid = multiuser_get_shared_gid(userId, appId);
719
720 const std::string profile_dir =
721 create_primary_current_profile_package_dir_path(userId, packageName);
722 char *argv[] = { (char*) profile_dir.c_str(), nullptr };
723 if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
724 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
725 switch (p->fts_info) {
726 case FTS_D:
727 case FTS_F:
728 case FTS_SL:
729 case FTS_SLNONE:
730 if (lchown(p->fts_path, uid, uid) != 0) {
731 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
732 }
733 break;
734 }
735 }
736 fts_close(fts);
737 }
738
739 const std::string ref_profile_path =
740 create_primary_reference_profile_package_dir_path(packageName);
741 argv[0] = (char *) ref_profile_path.c_str();
742 if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
743 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
744 if (p->fts_info == FTS_D && p->fts_level == 0) {
745 if (chown(p->fts_path, AID_SYSTEM, sharedGid) != 0) {
746 PLOG(WARNING) << "Failed to chown " << p->fts_path;
747 }
748 continue;
749 }
750 switch (p->fts_info) {
751 case FTS_D:
752 case FTS_F:
753 case FTS_SL:
754 case FTS_SLNONE:
755 if (lchown(p->fts_path, sharedGid, sharedGid) != 0) {
756 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
757 }
758 break;
759 }
760 }
761 fts_close(fts);
762 }
763}
764
Mohammad Samiul Islama73327a2022-03-09 09:59:32 +0000765static binder::Status createAppDataDirs(const std::string& path, int32_t uid, int32_t gid,
John Wu841a8022022-04-05 21:17:54 +0000766 int32_t previousUid, int32_t cacheGid,
Samiul Islam8621e552022-03-30 16:26:45 +0100767 const std::string& seInfo, mode_t targetMode,
768 long projectIdApp, long projectIdCache) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700769 ScopedTrace tracer("create-dirs");
John Wu84e8f242021-10-21 11:50:41 -0700770 struct stat st{};
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000771 bool parent_dir_exists = (stat(path.c_str(), &st) == 0);
772
773 auto cache_path = StringPrintf("%s/%s", path.c_str(), "cache");
774 auto code_cache_path = StringPrintf("%s/%s", path.c_str(), "code_cache");
775 bool cache_exists = (access(cache_path.c_str(), F_OK) == 0);
776 bool code_cache_exists = (access(code_cache_path.c_str(), F_OK) == 0);
777
778 if (parent_dir_exists) {
John Wu841a8022022-04-05 21:17:54 +0000779 if (previousUid > 0 && previousUid != uid) {
780 if (!chown_app_dir(path, uid, previousUid, cacheGid)) {
John Wu84e8f242021-10-21 11:50:41 -0700781 return error("Failed to chown " + path);
782 }
783 }
784 }
785
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000786 // Prepare only the parent app directory
Samiul Islam8621e552022-03-30 16:26:45 +0100787 if (prepare_app_dir(path, targetMode, uid, gid, projectIdApp) ||
788 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid, projectIdCache) ||
789 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid, projectIdCache)) {
John Wu84e8f242021-10-21 11:50:41 -0700790 return error("Failed to prepare " + path);
791 }
792
793 // Consider restorecon over contents if label changed
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000794 if (restorecon_app_data_lazy(path, seInfo, uid, parent_dir_exists)) {
John Wu84e8f242021-10-21 11:50:41 -0700795 return error("Failed to restorecon " + path);
796 }
797
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000798 // If the parent dir exists, the restorecon would already have been done
799 // as a part of the recursive restorecon above
800 if (parent_dir_exists && !cache_exists
801 && restorecon_app_data_lazy(cache_path, seInfo, uid, false)) {
802 return error("Failed to restorecon " + cache_path);
803 }
804
805 // If the parent dir exists, the restorecon would already have been done
806 // as a part of the recursive restorecon above
807 if (parent_dir_exists && !code_cache_exists
808 && restorecon_app_data_lazy(code_cache_path, seInfo, uid, false)) {
809 return error("Failed to restorecon " + code_cache_path);
810 }
John Wu84e8f242021-10-21 11:50:41 -0700811 return ok();
812}
813
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800814binder::Status InstalldNativeService::createAppDataLocked(
815 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
816 int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000817 int32_t targetSdkVersion, int64_t* ceDataInode, int64_t* deDataInode) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700818 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000819 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700820 CHECK_ARGUMENT_UUID(uuid);
821 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700822
823 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
824 const char* pkgname = packageName.c_str();
825
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700826 // Assume invalid inode unless filled in below
Songchun Fancb567f92023-09-11 17:04:47 +0000827 if (ceDataInode != nullptr) *ceDataInode = -1;
828 if (deDataInode != nullptr) *deDataInode = -1;
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700829
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700830 int32_t uid = multiuser_get_uid(userId, appId);
John Wu84e8f242021-10-21 11:50:41 -0700831
John Wu841a8022022-04-05 21:17:54 +0000832 // If previousAppId > 0, an app is changing its app ID
833 int32_t previousUid =
834 previousAppId > 0 ? (int32_t)multiuser_get_uid(userId, previousAppId) : -1;
John Wu84e8f242021-10-21 11:50:41 -0700835
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700836 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700837 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
838
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700839 // If UID doesn't have a specific cache GID, use UID value
840 if (cacheGid == -1) {
841 cacheGid = uid;
842 }
843
Samiul Islam8621e552022-03-30 16:26:45 +0100844 long projectIdApp = get_project_id(uid, PROJECT_ID_APP_START);
845 long projectIdCache = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
846
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700847 if (flags & FLAG_STORAGE_CE) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700848 ScopedTrace tracer("ce");
Jeff Sharkey0274c972016-12-06 09:32:04 -0700849 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700850
John Wu841a8022022-04-05 21:17:54 +0000851 auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
Samiul Islam8621e552022-03-30 16:26:45 +0100852 projectIdApp, projectIdCache);
John Wu84e8f242021-10-21 11:50:41 -0700853 if (!status.isOk()) {
854 return status;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600855 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600856
857 // Remember inode numbers of cache directories so that we can clear
858 // contents while CE storage is locked
859 if (write_path_inode(path, "cache", kXattrInodeCache) ||
860 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700861 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700862 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700863
864 // And return the CE inode of the top-level data directory so we can
865 // clear contents while CE storage is locked
Songchun Fancb567f92023-09-11 17:04:47 +0000866 if (ceDataInode != nullptr) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000867 ino_t result;
868 if (get_path_inode(path, &result) != 0) {
869 return error("Failed to get_path_inode for " + path);
870 }
Songchun Fancb567f92023-09-11 17:04:47 +0000871 *ceDataInode = static_cast<uint64_t>(result);
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700872 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700873 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700874 if (flags & FLAG_STORAGE_DE) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700875 ScopedTrace tracer("de");
Jeff Sharkey0274c972016-12-06 09:32:04 -0700876 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700877
John Wu841a8022022-04-05 21:17:54 +0000878 auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
Samiul Islam8621e552022-03-30 16:26:45 +0100879 projectIdApp, projectIdCache);
John Wu84e8f242021-10-21 11:50:41 -0700880 if (!status.isOk()) {
881 return status;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600882 }
John Wu841a8022022-04-05 21:17:54 +0000883 if (previousUid > 0 && previousUid != uid) {
John Wu3b383372022-02-09 02:21:39 -0800884 chown_app_profile_dir(packageName, appId, userId);
885 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600886
Calin Juravled2affb82017-11-28 17:41:43 -0800887 if (!prepare_app_profile_dir(packageName, appId, userId)) {
888 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000889 }
Songchun Fancb567f92023-09-11 17:04:47 +0000890
891 if (deDataInode != nullptr) {
892 ino_t result;
893 if (get_path_inode(path, &result) != 0) {
894 return error("Failed to get_path_inode for " + path);
895 }
896 *deDataInode = static_cast<uint64_t>(result);
897 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700898 }
Samiul Islamc40dff52022-01-14 16:24:48 +0000899
Samiul Islam7d5b1da2022-02-21 15:23:36 +0000900 if (flags & FLAG_STORAGE_SDK) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700901 ScopedTrace tracer("sdk");
Samiul Islam92f5cf02022-02-03 12:45:51 +0000902 // Safe to ignore status since we can retry creating this by calling reconcileSdkData
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000903 auto ignore = createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000904 if (!ignore.isOk()) {
905 PLOG(WARNING) << "Failed to create sdk data package directory for " << packageName;
Samiul Islamc40dff52022-01-14 16:24:48 +0000906 }
Samiul Islam92f5cf02022-02-03 12:45:51 +0000907 } else {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700908 ScopedTrace tracer("destroy-sdk");
Samiul Islam92f5cf02022-02-03 12:45:51 +0000909 // Package does not need sdk storage. Remove it.
Rishabh Singhe84b0b12022-02-02 20:56:13 +0000910 destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
Samiul Islamc40dff52022-01-14 16:24:48 +0000911 }
912
913 return ok();
914}
915
916/**
Samiul Islam92f5cf02022-02-03 12:45:51 +0000917 * Responsible for creating /data/misc_{ce|de}/user/0/sdksandbox/<package-name> directory and other
Samiul Islamc40dff52022-01-14 16:24:48 +0000918 * app level sub directories, such as ./shared
919 */
Samiul Islam92f5cf02022-02-03 12:45:51 +0000920binder::Status InstalldNativeService::createSdkSandboxDataPackageDirectory(
Samiul Islamc40dff52022-01-14 16:24:48 +0000921 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000922 int32_t appId, int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +0000923 ENFORCE_VALID_USER(userId);
924
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000925 int32_t sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
926 if (sdkSandboxUid == -1) {
927 // There no valid sdk sandbox process for this app. Skip creation of data directory
Samiul Islamc40dff52022-01-14 16:24:48 +0000928 return ok();
929 }
930
Samiul Islamc40dff52022-01-14 16:24:48 +0000931 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
932
933 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +0000934 for (int currentFlag : storageFlags) {
Samiul Islamc40dff52022-01-14 16:24:48 +0000935 if ((flags & currentFlag) == 0) {
936 continue;
937 }
938 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
939
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000940 // /data/misc_{ce,de}/<user-id>/sdksandbox directory gets created by vold
Samiul Islamc40dff52022-01-14 16:24:48 +0000941 // during user creation
942
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000943 // Prepare the package directory
Samiul Islam92f5cf02022-02-03 12:45:51 +0000944 auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
945 packageName.c_str());
946#if SDK_DEBUG
947 LOG(DEBUG) << "Creating app-level sdk data directory: " << packagePath;
948#endif
949
Shikha Malhotra976ae002022-02-26 15:39:53 +0000950 if (prepare_app_dir(packagePath, 0751, AID_SYSTEM, AID_SYSTEM, 0)) {
Samiul Islam92f5cf02022-02-03 12:45:51 +0000951 return error("Failed to prepare " + packagePath);
Samiul Islamc40dff52022-01-14 16:24:48 +0000952 }
Samiul Islamc40dff52022-01-14 16:24:48 +0000953 }
954
Jeff Sharkey423e7462016-12-09 18:18:43 -0700955 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700956}
957
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600958binder::Status InstalldNativeService::createAppData(
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800959 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
960 int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000961 int32_t targetSdkVersion, int64_t* ceDataInode, int64_t* deDataInode) {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800962 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000963 ENFORCE_VALID_USER(userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800964 CHECK_ARGUMENT_UUID(uuid);
965 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
966 LOCK_PACKAGE_USER();
967 return createAppDataLocked(uuid, packageName, userId, flags, appId, previousAppId, seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000968 targetSdkVersion, ceDataInode, deDataInode);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800969}
970
971binder::Status InstalldNativeService::createAppData(
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600972 const android::os::CreateAppDataArgs& args,
973 android::os::CreateAppDataResult* _aidl_return) {
974 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000975 ENFORCE_VALID_USER(args.userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800976 // Locking is performed depeer in the callstack.
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600977
978 int64_t ceDataInode = -1;
Songchun Fancb567f92023-09-11 17:04:47 +0000979 int64_t deDataInode = -1;
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600980 auto status = createAppData(args.uuid, args.packageName, args.userId, args.flags, args.appId,
Songchun Fancb567f92023-09-11 17:04:47 +0000981 args.previousAppId, args.seInfo, args.targetSdkVersion,
982 &ceDataInode, &deDataInode);
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600983 _aidl_return->ceDataInode = ceDataInode;
Songchun Fancb567f92023-09-11 17:04:47 +0000984 _aidl_return->deDataInode = deDataInode;
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600985 _aidl_return->exceptionCode = status.exceptionCode();
986 _aidl_return->exceptionMessage = status.exceptionMessage();
987 return ok();
988}
989
990binder::Status InstalldNativeService::createAppDataBatched(
991 const std::vector<android::os::CreateAppDataArgs>& args,
992 std::vector<android::os::CreateAppDataResult>* _aidl_return) {
993 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000994 for (const auto& arg : args) {
995 ENFORCE_VALID_USER(arg.userId);
996 }
997
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800998 // Locking is performed depeer in the callstack.
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600999
1000 std::vector<android::os::CreateAppDataResult> results;
John Wu84e8f242021-10-21 11:50:41 -07001001 for (const auto &arg : args) {
Jeff Sharkey8d3848b2020-08-13 14:16:46 -06001002 android::os::CreateAppDataResult result;
1003 createAppData(arg, &result);
1004 results.push_back(result);
1005 }
1006 *_aidl_return = results;
1007 return ok();
1008}
1009
Samiul Islam92f5cf02022-02-03 12:45:51 +00001010binder::Status InstalldNativeService::reconcileSdkData(
1011 const android::os::ReconcileSdkDataArgs& args) {
Steven Moreland36945362023-07-05 20:29:10 +00001012 ENFORCE_VALID_USER(args.userId);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001013 // Locking is performed depeer in the callstack.
1014
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001015 return reconcileSdkData(args.uuid, args.packageName, args.subDirNames, args.userId, args.appId,
1016 args.previousAppId, args.seInfo, args.flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001017}
1018
1019/**
1020 * Reconciles per-sdk directory under app-level sdk data directory.
1021
1022 * E.g. `/data/misc_ce/0/sdksandbox/<package-name>/<sdkPackageName>-<randomSuffix>
1023 *
1024 * - If the sdk data package directory is missing, we create it first.
1025 * - If sdkPackageNames is empty, we delete sdk package directory since it's not needed anymore.
1026 * - If a sdk level directory we need to prepare already exist, we skip creating it again. This
1027 * is to avoid having same per-sdk directory with different suffix.
1028 * - If a sdk level directory exist which is absent from sdkPackageNames, we remove it.
1029 */
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001030binder::Status InstalldNativeService::reconcileSdkData(const std::optional<std::string>& uuid,
1031 const std::string& packageName,
1032 const std::vector<std::string>& subDirNames,
1033 int userId, int appId, int previousAppId,
1034 const std::string& seInfo, int flags) {
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001035 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001036 ENFORCE_VALID_USER(userId);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001037 CHECK_ARGUMENT_UUID(uuid);
1038 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001039 LOCK_PACKAGE_USER();
1040
1041#if SDK_DEBUG
1042 LOG(DEBUG) << "Creating per sdk data directory for: " << packageName;
1043#endif
1044
1045 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1046
Samiul Islam92f5cf02022-02-03 12:45:51 +00001047 // Prepare the sdk package directory in case it's missing
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001048 const auto status =
1049 createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001050 if (!status.isOk()) {
1051 return status;
1052 }
1053
1054 auto res = ok();
1055 // We have to create sdk data for CE and DE storage
1056 const int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1057 for (int currentFlag : storageFlags) {
1058 if ((flags & currentFlag) == 0) {
1059 continue;
1060 }
1061 const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1062
Samiul Islam92f5cf02022-02-03 12:45:51 +00001063 const auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
1064 packageName.c_str());
Samiul Islam92f5cf02022-02-03 12:45:51 +00001065
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001066 // Remove existing sub-directories not referred in subDirNames
1067 const std::unordered_set<std::string> expectedSubDirNames(subDirNames.begin(),
1068 subDirNames.end());
1069 const auto subDirHandler = [&packagePath, &expectedSubDirNames,
1070 &res](const std::string& subDirName) {
Samiul Islam92f5cf02022-02-03 12:45:51 +00001071 // Remove the per-sdk directory if it is not referred in
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001072 // expectedSubDirNames
1073 if (expectedSubDirNames.find(subDirName) == expectedSubDirNames.end()) {
1074 auto path = packagePath + "/" + subDirName;
1075 if (delete_dir_contents_and_dir(path) != 0) {
1076 res = error("Failed to delete " + path);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001077 return;
1078 }
Samiul Islam92f5cf02022-02-03 12:45:51 +00001079 }
1080 };
1081 const int ec = foreach_subdir(packagePath, subDirHandler);
1082 if (ec != 0) {
1083 res = error("Failed to process subdirs for " + packagePath);
1084 continue;
1085 }
1086
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001087 // Now create the subDirNames
1088 for (const auto& subDirName : subDirNames) {
1089 const std::string path =
1090 create_data_misc_sdk_sandbox_sdk_path(uuid_, isCeData, userId,
1091 packageName.c_str(), subDirName.c_str());
Samiul Islam92f5cf02022-02-03 12:45:51 +00001092
1093 // Create the directory along with cache and code_cache
1094 const int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
1095 if (cacheGid == -1) {
1096 return exception(binder::Status::EX_ILLEGAL_STATE,
1097 StringPrintf("cacheGid cannot be -1 for sdk data"));
1098 }
1099 const int32_t sandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
1100 int32_t previousSandboxUid = multiuser_get_sdk_sandbox_uid(userId, previousAppId);
Samiul Islam8621e552022-03-30 16:26:45 +01001101 int32_t appUid = multiuser_get_uid(userId, appId);
1102 long projectIdApp = get_project_id(appUid, PROJECT_ID_APP_START);
1103 long projectIdCache = get_project_id(appUid, PROJECT_ID_APP_CACHE_START);
1104 auto status =
John Wu841a8022022-04-05 21:17:54 +00001105 createAppDataDirs(path, sandboxUid, AID_NOBODY, previousSandboxUid, cacheGid,
Samiul Islam8621e552022-03-30 16:26:45 +01001106 seInfo, 0700 | S_ISGID, projectIdApp, projectIdCache);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001107 if (!status.isOk()) {
1108 res = status;
1109 continue;
1110 }
1111 }
1112 }
1113
1114 return res;
1115}
1116
Jooyung Han149be4a2020-01-23 12:45:10 +09001117binder::Status InstalldNativeService::migrateAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001118 const std::string& packageName, int32_t userId, int32_t flags) {
1119 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001120 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001121 CHECK_ARGUMENT_UUID(uuid);
1122 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001123 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001124
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001125 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1126 const char* pkgname = packageName.c_str();
1127
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001128 // This method only exists to upgrade system apps that have requested
1129 // forceDeviceEncrypted, so their default storage always lives in a
1130 // consistent location. This only works on non-FBE devices, since we
1131 // never want to risk exposing data on a device with real CE/DE storage.
1132
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001133 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
1134 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001135
1136 // If neither directory is marked as default, assume CE is default
1137 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
1138 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
1139 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001140 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001141 }
1142 }
1143
1144 // Migrate default data location if needed
1145 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
1146 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
1147
1148 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
1149 LOG(WARNING) << "Requested default storage " << target
1150 << " is not active; migrating from " << source;
1151 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001152 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001153 }
1154 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001155 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001156 }
1157 }
1158
Jeff Sharkey423e7462016-12-09 18:18:43 -07001159 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001160}
1161
Calin Juravle6a1648e2016-02-01 12:12:16 +00001162
Calin Juravle562de812018-01-20 23:34:18 -08001163binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
1164 const std::string& profileName) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001165 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001166 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyydf2fb612022-08-12 15:42:01 -07001167 CHECK_ARGUMENT_FILE_NAME(profileName);
1168 if (!base::EndsWith(profileName, ".prof")) {
1169 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
1170 StringPrintf("Profile name %s does not end with .prof",
1171 profileName.c_str()));
1172 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001173 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001174
Jeff Sharkey423e7462016-12-09 18:18:43 -07001175 binder::Status res = ok();
Calin Juravle562de812018-01-20 23:34:18 -08001176 if (!clear_primary_reference_profile(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001177 res = error("Failed to clear reference profile for " + packageName);
1178 }
Calin Juravle562de812018-01-20 23:34:18 -08001179 if (!clear_primary_current_profiles(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001180 res = error("Failed to clear current profiles for " + packageName);
1181 }
1182 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001183}
1184
Jooyung Han149be4a2020-01-23 12:45:10 +09001185binder::Status InstalldNativeService::clearAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001186 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1187 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001188 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001189 CHECK_ARGUMENT_UUID(uuid);
1190 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001191 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001192
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001193 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1194 const char* pkgname = packageName.c_str();
1195
Jeff Sharkey423e7462016-12-09 18:18:43 -07001196 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001197 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001198 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001199 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1200 path = read_path_inode(path, "cache", kXattrInodeCache);
1201 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1202 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
1203 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001204 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001205 if (delete_dir_contents(path) != 0) {
1206 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +09001207 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
1208 remove_path_xattr(path, kXattrInodeCache);
1209 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001210 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001211 }
1212 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001213 if (flags & FLAG_STORAGE_DE) {
John Wu84e8f242021-10-21 11:50:41 -07001214 std::string suffix;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001215 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1216 suffix = CACHE_DIR_POSTFIX;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001217 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1218 suffix = CODE_CACHE_DIR_POSTFIX;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001219 }
1220
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001221 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001222 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001223 if (delete_dir_contents(path) != 0) {
1224 res = error("Failed to delete contents of " + path);
1225 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001226 }
1227 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001228 if (flags & FLAG_STORAGE_EXTERNAL) {
1229 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1230 for (const auto& n : mStorageMounts) {
1231 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +00001232
1233 if (android::base::GetBoolProperty(kFuseProp, false)) {
1234 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1235 if (std::regex_match(extPath, re)) {
1236 extPath += "/" + std::to_string(userId);
1237 }
1238 } else {
1239 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1240 extPath += StringPrintf("/%d", userId);
1241 } else if (userId != 0) {
1242 // TODO: support devices mounted under secondary users
1243 continue;
1244 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001245 }
Zim0ce832d2019-12-03 17:03:58 +00001246
Jeff Sharkey6e175692019-05-14 14:55:33 -06001247 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1248 // Clear only cached data from shared storage
1249 auto path = StringPrintf("%s/Android/data/%s/cache", extPath.c_str(), pkgname);
1250 if (delete_dir_contents(path, true) != 0) {
1251 res = error("Failed to delete contents of " + path);
1252 }
1253 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1254 // No code cache on shared storage
1255 } else {
1256 // Clear everything on shared storage
1257 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
1258 if (delete_dir_contents(path, true) != 0) {
1259 res = error("Failed to delete contents of " + path);
1260 }
1261 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
1262 if (delete_dir_contents(path, true) != 0) {
1263 res = error("Failed to delete contents of " + path);
1264 }
Martijn Coenen24a93072020-01-08 10:10:43 +01001265 // Note that we explicitly don't delete OBBs - those are only removed on
1266 // app uninstall.
Jeff Sharkey6e175692019-05-14 14:55:33 -06001267 }
1268 }
1269 }
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001270 auto status = clearSdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1271 if (!status.isOk()) {
1272 res = status;
1273 }
1274 return res;
1275}
1276
1277binder::Status InstalldNativeService::clearSdkSandboxDataPackageDirectory(
1278 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1279 int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00001280 ENFORCE_VALID_USER(userId);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001281 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1282 const char* pkgname = packageName.c_str();
1283
1284 binder::Status res = ok();
1285 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1286 for (int i = 0; i < 2; i++) {
1287 int currentFlag = storageFlags[i];
1288 if ((flags & currentFlag) == 0) {
1289 continue;
1290 }
1291 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1292 std::string suffix;
1293 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1294 suffix = CACHE_DIR_POSTFIX;
1295 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1296 suffix = CODE_CACHE_DIR_POSTFIX;
1297 }
1298
1299 auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1300 if (access(appPath.c_str(), F_OK) != 0) continue;
1301 const auto subDirHandler = [&appPath, &res, &suffix](const std::string& filename) {
1302 auto filepath = appPath + "/" + filename + suffix;
1303 if (delete_dir_contents(filepath, true) != 0) {
1304 res = error("Failed to clear contents of " + filepath);
1305 }
1306 };
1307 const int ec = foreach_subdir(appPath, subDirHandler);
1308 if (ec != 0) {
1309 res = error("Failed to process subdirs for " + appPath);
1310 }
1311 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001312 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001313}
1314
Calin Juravle76268c52017-03-09 13:19:42 -08001315static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +01001316 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -08001317 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +01001318 /*ignore_if_missing*/ true);
1319}
1320
Calin Juravle76268c52017-03-09 13:19:42 -08001321static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +01001322 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -08001323 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +01001324 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +00001325}
1326
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001327binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
1328 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001329 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001330 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001331
Jeff Sharkey423e7462016-12-09 18:18:43 -07001332 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +00001333 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1334 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -08001335 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001336 res = error("Failed to destroy current profiles for " + packageName);
1337 }
Calin Juravleedae6692016-03-23 13:55:31 +00001338 }
Calin Juravle76268c52017-03-09 13:19:42 -08001339 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001340 res = error("Failed to destroy reference profile for " + packageName);
1341 }
1342 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +00001343}
1344
Jiakai Zhangee00e3b2022-03-24 15:03:04 +00001345binder::Status InstalldNativeService::deleteReferenceProfile(const std::string& packageName,
1346 const std::string& profileName) {
1347 ENFORCE_UID(AID_SYSTEM);
1348 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1349 LOCK_PACKAGE();
1350
1351 // This function only supports primary dex'es.
1352 std::string path =
1353 create_reference_profile_path(packageName, profileName, /*is_secondary_dex=*/false);
1354 if (unlink(path.c_str()) != 0) {
1355 if (errno == ENOENT) {
1356 return ok();
1357 } else {
1358 return error("Failed to delete profile " + profileName + " for " + packageName);
1359 }
1360 }
1361 return ok();
1362}
1363
Jooyung Han149be4a2020-01-23 12:45:10 +09001364binder::Status InstalldNativeService::destroyAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001365 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1366 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001367 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001368 CHECK_ARGUMENT_UUID(uuid);
1369 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001370 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001371
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001372 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1373 const char* pkgname = packageName.c_str();
1374
Jeff Sharkey423e7462016-12-09 18:18:43 -07001375 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001376 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001377 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08001378 if (rename_delete_dir_contents_and_dir(path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001379 res = error("Failed to delete " + path);
1380 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001381 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001382 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001383 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08001384 if (rename_delete_dir_contents_and_dir(path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001385 res = error("Failed to delete " + path);
1386 }
Alan Stokesd983cc72020-02-14 14:36:58 +00001387 if ((flags & FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES) == 0) {
1388 destroy_app_current_profiles(packageName, userId);
1389 // TODO(calin): If the package is still installed by other users it's probably
1390 // beneficial to keep the reference profile around.
1391 // Verify if it's ok to do that.
1392 destroy_app_reference_profile(packageName);
1393 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001394 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001395 if (flags & FLAG_STORAGE_EXTERNAL) {
1396 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1397 for (const auto& n : mStorageMounts) {
1398 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +00001399
1400 if (android::base::GetBoolProperty(kFuseProp, false)) {
1401 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1402 if (std::regex_match(extPath, re)) {
1403 extPath += "/" + std::to_string(userId);
1404 }
1405 } else {
1406 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1407 extPath += StringPrintf("/%d", userId);
1408 } else if (userId != 0) {
1409 // TODO: support devices mounted under secondary users
1410 continue;
1411 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001412 }
Zim0ce832d2019-12-03 17:03:58 +00001413
Jeff Sharkey6e175692019-05-14 14:55:33 -06001414 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001415 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001416 res = error("Failed to delete contents of " + path);
1417 }
1418 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001419 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001420 res = error("Failed to delete contents of " + path);
1421 }
1422 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001423 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001424 res = error("Failed to delete contents of " + path);
1425 }
1426 }
1427 }
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001428 auto status = destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1429 if (!status.isOk()) {
1430 res = status;
1431 }
1432 return res;
1433}
1434
1435binder::Status InstalldNativeService::destroySdkSandboxDataPackageDirectory(
1436 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1437 int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00001438 ENFORCE_VALID_USER(userId);
1439
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001440 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1441 const char* pkgname = packageName.c_str();
1442
1443 binder::Status res = ok();
1444 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1445 for (int i = 0; i < 2; i++) {
1446 int currentFlag = storageFlags[i];
1447 if ((flags & currentFlag) == 0) {
1448 continue;
1449 }
1450 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1451 auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1452 if (rename_delete_dir_contents_and_dir(appPath) != 0) {
1453 res = error("Failed to delete " + appPath);
1454 }
1455 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001456 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001457}
1458
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001459static gid_t get_cache_gid(uid_t uid) {
1460 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
1461 return (gid != -1) ? gid : uid;
1462}
1463
Jooyung Han149be4a2020-01-23 12:45:10 +09001464binder::Status InstalldNativeService::fixupAppData(const std::optional<std::string>& uuid,
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001465 int32_t flags) {
1466 ENFORCE_UID(AID_SYSTEM);
1467 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001468
1469 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001470 for (auto userId : get_known_users(uuid_)) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001471 LOCK_USER();
Zim23457d02022-08-17 12:57:41 +01001472 atrace_pm_begin("fixup user");
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001473 FTS* fts;
1474 FTSENT* p;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001475 auto ce_path = create_data_user_ce_path(uuid_, userId);
1476 auto de_path = create_data_user_de_path(uuid_, userId);
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001477 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001478 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001479 return error("Failed to fts_open");
1480 }
1481 while ((p = fts_read(fts)) != nullptr) {
1482 if (p->fts_info == FTS_D && p->fts_level == 1) {
1483 // Track down inodes of cache directories
1484 uint64_t raw = 0;
1485 ino_t inode_cache = 0;
1486 ino_t inode_code_cache = 0;
1487 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1488 inode_cache = raw;
1489 }
1490 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1491 inode_code_cache = raw;
1492 }
1493
1494 // Figure out expected GID of each child
1495 FTSENT* child = fts_children(fts, 0);
1496 while (child != nullptr) {
1497 if ((child->fts_statp->st_ino == inode_cache)
1498 || (child->fts_statp->st_ino == inode_code_cache)
1499 || !strcmp(child->fts_name, "cache")
1500 || !strcmp(child->fts_name, "code_cache")) {
1501 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
1502 } else {
1503 child->fts_number = p->fts_statp->st_uid;
1504 }
1505 child = child->fts_link;
1506 }
1507 } else if (p->fts_level >= 2) {
1508 if (p->fts_level > 2) {
1509 // Inherit GID from parent once we're deeper into tree
1510 p->fts_number = p->fts_parent->fts_number;
1511 }
1512
1513 uid_t uid = p->fts_parent->fts_statp->st_uid;
1514 gid_t cache_gid = get_cache_gid(uid);
1515 gid_t expected = p->fts_number;
1516 gid_t actual = p->fts_statp->st_gid;
1517 if (actual == expected) {
1518#if FIXUP_DEBUG
1519 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
1520#endif
1521 if (!(flags & FLAG_FORCE)) {
1522 fts_set(fts, p, FTS_SKIP);
1523 }
1524 } else if ((actual == uid) || (actual == cache_gid)) {
1525 // Only consider fixing up when current GID belongs to app
1526 if (p->fts_info != FTS_D) {
1527 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
1528 << " instead of " << expected;
1529 }
1530 switch (p->fts_info) {
1531 case FTS_DP:
1532 // If we're moving towards cache GID, we need to set S_ISGID
1533 if (expected == cache_gid) {
1534 if (chmod(p->fts_path, 02771) != 0) {
1535 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1536 }
1537 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001538 [[fallthrough]]; // also set GID
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001539 case FTS_F:
1540 if (chown(p->fts_path, -1, expected) != 0) {
1541 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1542 }
1543 break;
1544 case FTS_SL:
1545 case FTS_SLNONE:
1546 if (lchown(p->fts_path, -1, expected) != 0) {
1547 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1548 }
1549 break;
1550 }
1551 } else {
1552 // Ignore all other GID transitions, since they're kinda shady
1553 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
1554 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -06001555 if (!(flags & FLAG_FORCE)) {
1556 fts_set(fts, p, FTS_SKIP);
1557 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001558 }
1559 }
1560 }
1561 fts_close(fts);
Zim23457d02022-08-17 12:57:41 +01001562 atrace_pm_end();
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001563 }
1564 return ok();
1565}
1566
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001567static int32_t copy_directory_recursive(const char* from, const char* to) {
Dario Freni918beeb2021-12-22 01:00:01 +00001568 char* argv[] =
1569 {(char*)kCpPath,
1570 (char*)"-F", /* delete any existing destination file first (--remove-destination) */
1571 (char*)"--preserve=mode,ownership,timestamps,xattr", /* preserve properties */
1572 (char*)"-R", /* recurse into subdirectories (DEST must be a directory) */
1573 (char*)"-P", /* Do not follow symlinks [default] */
1574 (char*)"-d", /* don't dereference symlinks */
1575 (char*)from,
1576 (char*)to};
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001577
1578 LOG(DEBUG) << "Copying " << from << " to " << to;
Tom Cherrye79cde52019-09-25 16:51:56 -07001579 return logwrap_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, LOG_ALOG, false, nullptr);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001580}
1581
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001582binder::Status InstalldNativeService::snapshotAppData(const std::optional<std::string>& volumeUuid,
1583 const std::string& packageName,
1584 int32_t userId, int32_t snapshotId,
1585 int32_t storageFlags, int64_t* _aidl_return) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001586 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001587 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001588 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001589 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001590 LOCK_PACKAGE_USER();
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001591
1592 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1593 const char* package_name = packageName.c_str();
1594
1595 binder::Status res = ok();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001596 // Default result to 0, it will be populated with inode of ce data snapshot
1597 // if FLAG_STORAGE_CE has been passed.
1598 if (_aidl_return != nullptr) *_aidl_return = 0;
1599
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001600 bool clear_ce_on_exit = false;
1601 bool clear_de_on_exit = false;
1602
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001603 auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &userId, &package_name,
1604 &snapshotId] {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001605 if (clear_de_on_exit) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001606 auto to = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1607 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001608 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1609 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1610 }
1611 }
1612
1613 if (clear_ce_on_exit) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001614 auto to = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1615 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001616 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1617 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1618 }
1619 }
1620 };
1621
1622 auto scope_guard = android::base::make_scope_guard(deleter);
1623
JW Wang1d643c72020-10-06 13:42:41 +08001624 if (storageFlags & FLAG_STORAGE_DE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001625 auto from = create_data_user_de_package_path(volume_uuid, userId, package_name);
1626 auto to = create_data_misc_de_rollback_path(volume_uuid, userId, snapshotId);
1627 auto rollback_package_path =
1628 create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1629 package_name);
JW Wang1d643c72020-10-06 13:42:41 +08001630
1631 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1632 if (rc != 0) {
1633 return error(rc, "Failed to create folder " + to);
1634 }
1635
1636 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1637 if (rc != 0) {
1638 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1639 }
1640
1641 // Check if we have data to copy.
1642 if (access(from.c_str(), F_OK) == 0) {
1643 rc = copy_directory_recursive(from.c_str(), to.c_str());
1644 }
1645 if (rc != 0) {
1646 res = error(rc, "Failed copying " + from + " to " + to);
1647 clear_de_on_exit = true;
1648 return res;
1649 }
1650 }
1651
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001652 // 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 -08001653 auto from_ce = create_data_user_ce_package_path(volume_uuid, userId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001654 if (access(from_ce.c_str(), F_OK) != 0) {
1655 LOG(INFO) << "Missing source " << from_ce;
1656 return ok();
1657 }
1658
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001659 // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001660 binder::Status clear_cache_result =
1661 clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001662 if (!clear_cache_result.isOk()) {
1663 // It should be fine to continue snapshot if we for some reason failed
1664 // to clear cache.
1665 LOG(WARNING) << "Failed to clear cache of app " << packageName;
1666 }
1667
1668 // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001669 binder::Status clear_code_cache_result =
1670 clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY,
1671 0);
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001672 if (!clear_code_cache_result.isOk()) {
1673 // It should be fine to continue snapshot if we for some reason failed
1674 // to clear code_cache.
1675 LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
1676 }
1677
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001678 if (storageFlags & FLAG_STORAGE_CE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001679 auto from = create_data_user_ce_package_path(volume_uuid, userId, package_name);
1680 auto to = create_data_misc_ce_rollback_path(volume_uuid, userId, snapshotId);
1681 auto rollback_package_path =
1682 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1683 package_name);
Nikita Ioffe835ae772019-01-23 16:32:13 +00001684
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001685 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1686 if (rc != 0) {
1687 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +00001688 }
1689
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001690 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1691 if (rc != 0) {
1692 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1693 }
1694
1695 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001696 if (rc != 0) {
1697 res = error(rc, "Failed copying " + from + " to " + to);
1698 clear_ce_on_exit = true;
1699 return res;
1700 }
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001701 if (_aidl_return != nullptr) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001702 auto ce_snapshot_path =
1703 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1704 package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001705 rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
1706 if (rc != 0) {
1707 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
1708 clear_ce_on_exit = true;
1709 return res;
1710 }
1711 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001712 }
1713
1714 return res;
1715}
1716
1717binder::Status InstalldNativeService::restoreAppDataSnapshot(
Jooyung Han149be4a2020-01-23 12:45:10 +09001718 const std::optional<std::string>& volumeUuid, const std::string& packageName,
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001719 const int32_t appId, const std::string& seInfo, const int32_t userId,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001720 const int32_t snapshotId, int32_t storageFlags) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001721 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001722 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001723 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001724 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001725 LOCK_PACKAGE_USER();
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001726
1727 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1728 const char* package_name = packageName.c_str();
1729
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001730 auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1731 package_name);
1732 auto from_de = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1733 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001734
1735 const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
1736 (access(from_ce.c_str(), F_OK) == 0);
1737 const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
1738 (access(from_de.c_str(), F_OK) == 0);
1739
1740 if (!needs_ce_rollback && !needs_de_rollback) {
1741 return ok();
1742 }
1743
1744 // We know we're going to rollback one of the CE or DE data, so we clear
1745 // application data first. Note that it's possible that we're asked to
1746 // restore both CE & DE data but that one of the restores fail. Leaving the
1747 // app with no data in those cases is arguably better than leaving the app
1748 // with mismatched / stale data.
1749 LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001750 // It's fine to pass 0 as ceDataInode here, because restoreAppDataSnapshot
1751 // can only be called when user unlocks the phone, meaning that CE user data
1752 // is decrypted.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001753 binder::Status res =
1754 clearAppData(volumeUuid, packageName, userId, storageFlags, 0 /* ceDataInode */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001755 if (!res.isOk()) {
1756 return res;
1757 }
1758
1759 if (needs_ce_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001760 auto to_ce = create_data_user_ce_path(volume_uuid, userId);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001761 int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
1762 if (rc != 0) {
1763 res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
1764 return res;
1765 }
JW Wangfda19ec2020-05-18 16:54:08 +08001766 delete_dir_contents_and_dir(from_ce, true /* ignore_if_missing */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001767 }
1768
1769 if (needs_de_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001770 auto to_de = create_data_user_de_path(volume_uuid, userId);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001771 int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
1772 if (rc != 0) {
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001773 if (needs_ce_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001774 auto ce_data = create_data_user_ce_package_path(volume_uuid, userId, package_name);
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001775 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
1776 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
1777 LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
1778 }
1779 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001780 res = error(rc, "Failed copying " + from_de + " to " + to_de);
1781 return res;
1782 }
JW Wangfda19ec2020-05-18 16:54:08 +08001783 delete_dir_contents_and_dir(from_de, true /* ignore_if_missing */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001784 }
1785
1786 // Finally, restore the SELinux label on the app data.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001787 return restoreconAppData(volumeUuid, packageName, userId, storageFlags, appId, seInfo);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001788}
1789
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001790binder::Status InstalldNativeService::destroyAppDataSnapshot(
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001791 const std::optional<std::string>& volumeUuid, const std::string& packageName,
1792 const int32_t userId, const int64_t ceSnapshotInode, const int32_t snapshotId,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001793 int32_t storageFlags) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001794 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001795 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001796 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1797 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001798 LOCK_PACKAGE_USER();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001799
1800 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1801 const char* package_name = packageName.c_str();
1802
1803 if (storageFlags & FLAG_STORAGE_DE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001804 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid, userId,
1805 snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001806
1807 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
1808 if (res != 0) {
1809 return error(res, "Failed clearing snapshot " + de_snapshot_path);
1810 }
1811 }
1812
1813 if (storageFlags & FLAG_STORAGE_CE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001814 auto ce_snapshot_path =
1815 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1816 package_name, ceSnapshotInode);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001817 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
1818 if (res != 0) {
1819 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
1820 }
1821 }
1822 return ok();
1823}
1824
Oli Lanc7789572020-03-16 18:18:41 +00001825binder::Status InstalldNativeService::destroyCeSnapshotsNotSpecified(
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001826 const std::optional<std::string>& volumeUuid, const int32_t userId,
Oli Lanc7789572020-03-16 18:18:41 +00001827 const std::vector<int32_t>& retainSnapshotIds) {
1828 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001829 ENFORCE_VALID_USER(userId);
Oli Lanc7789572020-03-16 18:18:41 +00001830 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001831 LOCK_USER();
Oli Lanc7789572020-03-16 18:18:41 +00001832
1833 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1834
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001835 auto base_path = create_data_misc_ce_rollback_base_path(volume_uuid, userId);
Oli Lanc7789572020-03-16 18:18:41 +00001836
1837 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(base_path.c_str()), closedir);
1838 if (!dir) {
1839 return error(-1, "Failed to open rollback base dir " + base_path);
1840 }
1841
1842 struct dirent* ent;
1843 while ((ent = readdir(dir.get()))) {
1844 if (ent->d_type != DT_DIR) {
1845 continue;
1846 }
1847
1848 uint snapshot_id;
1849 bool parse_ok = ParseUint(ent->d_name, &snapshot_id);
1850 if (parse_ok &&
1851 std::find(retainSnapshotIds.begin(), retainSnapshotIds.end(),
1852 snapshot_id) == retainSnapshotIds.end()) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001853 auto rollback_path =
1854 create_data_misc_ce_rollback_path(volume_uuid, userId, snapshot_id);
Oli Lanc7789572020-03-16 18:18:41 +00001855 int res = delete_dir_contents_and_dir(rollback_path, true /* ignore_if_missing */);
1856 if (res != 0) {
1857 return error(res, "Failed clearing snapshot " + rollback_path);
1858 }
1859 }
1860 }
1861 return ok();
1862}
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001863
Jooyung Han149be4a2020-01-23 12:45:10 +09001864binder::Status InstalldNativeService::moveCompleteApp(const std::optional<std::string>& fromUuid,
1865 const std::optional<std::string>& toUuid, const std::string& packageName,
Songchun Fandc2083f2020-02-18 17:45:46 -08001866 int32_t appId, const std::string& seInfo,
Songchun Fanaed33372020-02-05 12:02:22 -08001867 int32_t targetSdkVersion, const std::string& fromCodePath) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001868 ENFORCE_UID(AID_SYSTEM);
1869 CHECK_ARGUMENT_UUID(fromUuid);
1870 CHECK_ARGUMENT_UUID(toUuid);
1871 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001872 LOCK_PACKAGE();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001873
1874 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1875 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1876 const char* package_name = packageName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001877
Jeff Sharkey423e7462016-12-09 18:18:43 -07001878 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001879 std::vector<userid_t> users = get_known_users(from_uuid);
1880
Songchun Fandc2083f2020-02-18 17:45:46 -08001881 auto to_app_package_path_parent = create_data_app_path(to_uuid);
1882 auto to_app_package_path = StringPrintf("%s/%s", to_app_package_path_parent.c_str(),
1883 android::base::Basename(fromCodePath).c_str());
1884
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001885 // Copy app
1886 {
Songchun Fandc2083f2020-02-18 17:45:46 -08001887 int rc = copy_directory_recursive(fromCodePath.c_str(), to_app_package_path_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001888 if (rc != 0) {
Songchun Fandc2083f2020-02-18 17:45:46 -08001889 res = error(rc, "Failed copying " + fromCodePath + " to " + to_app_package_path);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001890 goto fail;
1891 }
1892
Songchun Fandc2083f2020-02-18 17:45:46 -08001893 if (selinux_android_restorecon(to_app_package_path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
1894 res = error("Failed to restorecon " + to_app_package_path);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001895 goto fail;
1896 }
1897 }
1898
1899 // Copy private data for all known users
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001900 for (auto userId : users) {
1901 LOCK_USER();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001902
1903 // Data source may not exist for all users; that's okay
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001904 auto from_ce = create_data_user_ce_package_path(from_uuid, userId, package_name);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001905 if (access(from_ce.c_str(), F_OK) != 0) {
1906 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001907 continue;
1908 }
1909
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001910 if (!createAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
Songchun Fancb567f92023-09-11 17:04:47 +00001911 appId, /* previousAppId */ -1, seInfo, targetSdkVersion, nullptr,
1912 nullptr)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001913 .isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001914 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001915 goto fail;
1916 }
Jeff Sharkey51c94492016-05-10 17:46:39 -06001917 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001918 auto from = create_data_user_de_package_path(from_uuid, userId, package_name);
1919 auto to = create_data_user_de_path(to_uuid, userId);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001920
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001921 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001922 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001923 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001924 goto fail;
1925 }
1926 }
1927 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001928 auto from = create_data_user_ce_package_path(from_uuid, userId, package_name);
1929 auto to = create_data_user_ce_path(to_uuid, userId);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001930
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001931 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001932 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001933 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001934 goto fail;
1935 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001936 }
1937
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001938 if (!restoreconAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1939 appId, seInfo)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001940 .isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001941 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001942 goto fail;
1943 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001944 }
1945
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001946 // Copy sdk data for all known users
1947 for (auto userId : users) {
1948 LOCK_USER();
1949
1950 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1951 for (int currentFlag : storageFlags) {
1952 const bool isCeData = currentFlag == FLAG_STORAGE_CE;
1953
1954 const auto from = create_data_misc_sdk_sandbox_package_path(from_uuid, isCeData, userId,
1955 package_name);
1956 if (access(from.c_str(), F_OK) != 0) {
1957 LOG(INFO) << "Missing source " << from;
1958 continue;
1959 }
1960 const auto to = create_data_misc_sdk_sandbox_path(to_uuid, isCeData, userId);
1961
1962 const int rc = copy_directory_recursive(from.c_str(), to.c_str());
1963 if (rc != 0) {
1964 res = error(rc, "Failed copying " + from + " to " + to);
1965 goto fail;
1966 }
1967 }
1968
1969 if (!restoreconSdkDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1970 appId, seInfo)
1971 .isOk()) {
1972 res = error("Failed to restorecon");
1973 goto fail;
1974 }
1975 }
Jeff Sharkey31f08982015-07-07 13:31:37 -07001976 // We let the framework scan the new location and persist that before
1977 // deleting the data in the old location; this ordering ensures that
1978 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001979 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001980
1981fail:
1982 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001983 {
Songchun Fandc2083f2020-02-18 17:45:46 -08001984 if (delete_dir_contents(to_app_package_path.c_str(), 1, nullptr) != 0) {
1985 LOG(WARNING) << "Failed to rollback " << to_app_package_path;
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001986 }
1987 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001988 for (auto userId : users) {
1989 LOCK_USER();
Jeff Sharkey51c94492016-05-10 17:46:39 -06001990 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001991 auto to = create_data_user_de_package_path(to_uuid, userId, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001992 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001993 LOG(WARNING) << "Failed to rollback " << to;
1994 }
1995 }
1996 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001997 auto to = create_data_user_ce_package_path(to_uuid, userId, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001998 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001999 LOG(WARNING) << "Failed to rollback " << to;
2000 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07002001 }
2002 }
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00002003 for (auto userId : users) {
2004 LOCK_USER();
2005 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
2006 for (int currentFlag : storageFlags) {
2007 const bool isCeData = currentFlag == FLAG_STORAGE_CE;
2008 const auto to = create_data_misc_sdk_sandbox_package_path(to_uuid, isCeData, userId,
2009 package_name);
2010 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
2011 LOG(WARNING) << "Failed to rollback " << to;
2012 }
2013 }
2014 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002015 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07002016}
2017
Jooyung Han149be4a2020-01-23 12:45:10 +09002018binder::Status InstalldNativeService::createUserData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002019 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
2020 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002021 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002022 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002023 LOCK_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07002024
Alex Buynytskyya203d712023-06-08 12:56:15 -07002025 ScopedTrace tracer("create-user-data");
2026
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002027 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06002028 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002029 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002030 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07002031 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07002032 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002033 }
2034 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002035
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07002036 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002037}
2038
Jooyung Han149be4a2020-01-23 12:45:10 +09002039binder::Status InstalldNativeService::destroyUserData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002040 int32_t userId, int32_t flags) {
2041 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002042 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002043 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002044 LOCK_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07002045
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002046 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002047 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002048 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002049 auto path = create_data_user_de_path(uuid_, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00002050 // Contents only, as vold is responsible for the user_de dir itself.
2051 if (delete_dir_contents(path, true) != 0) {
2052 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002053 }
Rishabh Singh8d784372022-03-09 15:54:46 +00002054 auto sdk_sandbox_de_path =
2055 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
2056 if (delete_dir_contents_and_dir(sdk_sandbox_de_path, true) != 0) {
2057 res = error("Failed to delete " + sdk_sandbox_de_path);
2058 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002059 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002060 path = create_data_misc_legacy_path(userId);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08002061 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002062 res = error("Failed to delete " + path);
2063 }
Calin Juravle114f0812017-03-08 19:05:07 -08002064 path = create_primary_cur_profile_dir_path(userId);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08002065 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002066 res = error("Failed to delete " + path);
2067 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002068 }
Robin Lee095c7632014-04-25 15:05:19 +01002069 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06002070 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002071 auto path = create_data_user_ce_path(uuid_, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00002072 // Contents only, as vold is responsible for the user_ce dir itself.
2073 if (delete_dir_contents(path, true) != 0) {
2074 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002075 }
Rishabh Singh8d784372022-03-09 15:54:46 +00002076 auto sdk_sandbox_ce_path =
2077 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2078 if (delete_dir_contents_and_dir(sdk_sandbox_ce_path, true) != 0) {
2079 res = error("Failed to delete " + sdk_sandbox_ce_path);
2080 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002081 path = findDataMediaPath(uuid, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00002082 // Contents only, as vold is responsible for the media dir itself.
2083 if (delete_dir_contents(path, true) != 0) {
2084 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002085 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06002086 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002087 return res;
Robin Lee095c7632014-04-25 15:05:19 +01002088}
2089
Jooyung Han149be4a2020-01-23 12:45:10 +09002090binder::Status InstalldNativeService::freeCache(const std::optional<std::string>& uuid,
Neharika Jali0e542312021-10-25 06:41:24 +00002091 int64_t targetFreeBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002092 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002093 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002094#ifndef GRANULAR_LOCKS
2095 std::lock_guard lock(mLock);
2096#endif // !GRANULAR_LOCKS
Jeff Sharkey423e7462016-12-09 18:18:43 -07002097
Jooyung Han149be4a2020-01-23 12:45:10 +09002098 auto uuidString = uuid.value_or("");
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002099 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002100 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002101 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Neharika Jali1d667a22021-10-25 19:36:18 +00002102 auto defy_target = (flags & FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002103
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002104 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002105 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002106 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002107 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002108
Jeff Sharkey60f8a532017-05-30 14:38:42 -06002109 int64_t needed = targetFreeBytes - free;
Neharika Jali1d667a22021-10-25 19:36:18 +00002110 if (!defy_target) {
2111 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
2112 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002113
Neharika Jali1d667a22021-10-25 19:36:18 +00002114 if (free >= targetFreeBytes) {
2115 return ok();
2116 }
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002117 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002118
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002119 if (flags & FLAG_FREE_CACHE_V2) {
2120 // This new cache strategy fairly removes files from UIDs by deleting
2121 // files from the UIDs which are most over their allocated quota
2122
2123 // 1. Create trackers for every known UID
Zim23457d02022-08-17 12:57:41 +01002124 atrace_pm_begin("create");
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002125 const auto users = get_known_users(uuid_);
2126#ifdef GRANULAR_LOCKS
2127 std::vector<UserLock> userLocks;
2128 userLocks.reserve(users.size());
2129 std::vector<UserWriteLockGuard> lockGuards;
2130 lockGuards.reserve(users.size());
2131#endif // GRANULAR_LOCKS
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002132 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002133 for (auto userId : users) {
2134#ifdef GRANULAR_LOCKS
2135 userLocks.emplace_back(userId, mUserIdLock, mLock);
2136 lockGuards.emplace_back(userLocks.back());
2137#endif // GRANULAR_LOCKS
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002138 FTS *fts;
2139 FTSENT *p;
Samiul Islama2198092022-05-07 23:22:45 +01002140
2141 // Create a list of data paths whose children have cache directories
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002142 auto ce_path = create_data_user_ce_path(uuid_, userId);
2143 auto de_path = create_data_user_de_path(uuid_, userId);
2144 auto media_path = findDataMediaPath(uuid, userId) + "/Android/data/";
Samiul Islama2198092022-05-07 23:22:45 +01002145 auto ce_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2146 auto de_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
2147
2148 std::vector<std::string> dataPaths = {ce_path, de_path, media_path};
2149 foreach_subdir(ce_sdk_path, [&ce_sdk_path, &dataPaths](const std::string subDir) {
2150 const auto fullpath = ce_sdk_path + "/" + subDir;
2151 dataPaths.push_back(fullpath);
2152 });
2153 foreach_subdir(de_sdk_path, [&de_sdk_path, &dataPaths](const std::string subDir) {
2154 const auto fullpath = de_sdk_path + "/" + subDir;
2155 dataPaths.push_back((char*)fullpath.c_str());
2156 });
2157
2158 char* argv[dataPaths.size() + 1];
2159 for (unsigned int i = 0; i < dataPaths.size(); i++) {
2160 argv[i] = (char*)dataPaths[i].c_str();
2161 }
2162 argv[dataPaths.size()] = nullptr;
2163
Yi Konge7bf3772018-07-17 16:16:24 -07002164 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002165 return error("Failed to fts_open");
2166 }
Yi Konge7bf3772018-07-17 16:16:24 -07002167 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002168 if (p->fts_info == FTS_D && p->fts_level == 1) {
2169 uid_t uid = p->fts_statp->st_uid;
Samiul Islama2198092022-05-07 23:22:45 +01002170
2171 // If uid belongs to sdk sandbox, then the cache should be attributed to the
2172 // original client app.
2173 const auto client_uid = multiuser_convert_sdk_sandbox_to_app_uid(uid);
2174 const bool isSandboxUid = (client_uid != (uid_t)-1);
2175 if (isSandboxUid) uid = client_uid;
2176
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002177 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
2178 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
2179 + AID_APP_START;
2180 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002181 auto search = trackers.find(uid);
2182 if (search != trackers.end()) {
2183 search->second->addDataPath(p->fts_path);
2184 } else {
2185 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06002186 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002187 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002188 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002189 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002190 tracker->cacheQuota = mCacheQuotas[uid];
2191 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002192 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002193#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002194 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002195#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002196 tracker->cacheQuota = 67108864;
2197 }
2198 trackers[uid] = tracker;
2199 }
2200 fts_set(fts, p, FTS_SKIP);
2201 }
2202 }
2203 fts_close(fts);
2204 }
Zim23457d02022-08-17 12:57:41 +01002205 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002206
2207 // 2. Populate tracker stats and insert into priority queue
Zim23457d02022-08-17 12:57:41 +01002208 atrace_pm_begin("populate");
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002209 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
2210 return (left->getCacheRatio() < right->getCacheRatio());
2211 };
2212 std::priority_queue<std::shared_ptr<CacheTracker>,
2213 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
2214 for (const auto& it : trackers) {
2215 it.second->loadStats();
2216 queue.push(it.second);
2217 }
Zim23457d02022-08-17 12:57:41 +01002218 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002219
2220 // 3. Bounce across the queue, freeing items from whichever tracker is
2221 // the most over their assigned quota
Zim23457d02022-08-17 12:57:41 +01002222 atrace_pm_begin("bounce");
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002223 std::shared_ptr<CacheTracker> active;
2224 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07002225 // Only look at apps under quota when explicitly requested
2226 if (active && (active->getCacheRatio() < 10000)
2227 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
2228 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
2229 << " isn't over quota, and defy not requested";
2230 break;
2231 }
2232
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002233 // Find the best tracker to work with; this might involve swapping
2234 // if the active tracker is no longer the most over quota
2235 bool nextBetter = active && !queue.empty()
2236 && active->getCacheRatio() < queue.top()->getCacheRatio();
2237 if (!active || nextBetter) {
2238 if (active) {
2239 // Current tracker still has items, so we'll consider it
2240 // again later once it bubbles up to surface
2241 queue.push(active);
2242 }
2243 active = queue.top(); queue.pop();
2244 active->ensureItems();
2245 continue;
2246 }
2247
2248 // If no items remain, go find another tracker
2249 if (active->items.empty()) {
2250 active = nullptr;
2251 continue;
2252 } else {
2253 auto item = active->items.back();
2254 active->items.pop_back();
2255
2256 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
2257 if (!noop) {
2258 item->purge();
2259 }
2260 active->cacheUsed -= item->size;
2261 needed -= item->size;
2262 }
2263
Neharika Jali1d667a22021-10-25 19:36:18 +00002264 if (!defy_target) {
2265 // Verify that we're actually done before bailing, since sneaky
2266 // apps might be using hardlinks
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002267 if (needed <= 0) {
Neharika Jali1d667a22021-10-25 19:36:18 +00002268 free = data_disk_free(data_path);
2269 needed = targetFreeBytes - free;
2270 if (needed <= 0) {
2271 break;
2272 } else {
2273 LOG(WARNING) << "Expected to be done but still need " << needed;
2274 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002275 }
2276 }
2277 }
Zim23457d02022-08-17 12:57:41 +01002278 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002279
2280 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06002281 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07002282 }
2283
Neharika Jali1d667a22021-10-25 19:36:18 +00002284 if (!defy_target) {
2285 free = data_disk_free(data_path);
2286 if (free >= targetFreeBytes) {
2287 return ok();
2288 } else {
2289 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
2290 targetFreeBytes, data_path.c_str(), free));
2291 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002292 } else {
Neharika Jali1d667a22021-10-25 19:36:18 +00002293 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002294 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002295}
2296
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002297binder::Status InstalldNativeService::rmdex(const std::string& codePath,
2298 const std::string& instructionSet) {
2299 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002300 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002301
Mike Lockwood94afecf2012-10-24 10:45:23 -07002302 char dex_path[PKG_PATH_MAX];
2303
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002304 const char* path = codePath.c_str();
2305 const char* instruction_set = instructionSet.c_str();
2306
Jeff Sharkey770180a2014-09-08 17:14:26 -07002307 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002308 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07002309 }
2310
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002311 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002312 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002313 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002314
2315 ALOGV("unlink %s\n", dex_path);
2316 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07002317 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
2318 // but could not be unlinked.
2319 if (errno != ENOENT) {
2320 return error(StringPrintf("Failed to unlink %s", dex_path));
2321 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002322 }
Calin Juravle249f2d32017-05-03 17:22:27 -07002323 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002324}
2325
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002326struct stats {
2327 int64_t codeSize;
2328 int64_t dataSize;
2329 int64_t cacheSize;
2330};
2331
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002332#if MEASURE_DEBUG
2333static std::string toString(std::vector<int64_t> values) {
2334 std::stringstream res;
2335 res << "[";
2336 for (size_t i = 0; i < values.size(); i++) {
2337 res << values[i];
2338 if (i < values.size() - 1) {
2339 res << ",";
2340 }
2341 }
2342 res << "]";
2343 return res.str();
2344}
2345#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002346
Shikha Malhotra976ae002022-02-26 15:39:53 +00002347// On devices without sdcardfs, if internal and external are on
2348// the same volume, a uid such as u0_a123 is used for both
2349// internal and external storage; therefore, subtract that
2350// amount from internal to make sure we don't count it double.
2351// This needs to happen for data, cache and OBB
2352static void deductDoubleSpaceIfNeeded(stats* stats, int64_t doubleSpaceToBeDeleted, uid_t uid,
2353 const std::string& uuid) {
2354 if (!supports_sdcardfs()) {
2355 stats->dataSize -= doubleSpaceToBeDeleted;
2356 long obbProjectId = get_project_id(uid, PROJECT_ID_EXT_OBB_START);
2357 int64_t appObbSize = GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2358 stats->dataSize -= appObbSize;
2359 }
2360}
2361
Risan5f308262018-10-26 12:06:58 -06002362static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002363 int32_t appId, struct stats* stats, struct stats* extStats) {
Shikha Malhotra976ae002022-02-26 15:39:53 +00002364 int64_t space, doubleSpaceToBeDeleted = 0;
Martijn Coenen771cc342020-02-19 23:26:56 +01002365 uid_t uid = multiuser_get_uid(userId, appId);
Shikha Malhotra976ae002022-02-26 15:39:53 +00002366 static const bool supportsProjectId = internal_storage_has_project_id();
2367
2368 if (extStats != nullptr) {
2369 space = get_occupied_app_space_external(uuid, userId, appId);
2370
2371 if (space != -1) {
2372 extStats->dataSize += space;
2373 doubleSpaceToBeDeleted += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002374 }
2375
Shikha Malhotra976ae002022-02-26 15:39:53 +00002376 space = get_occupied_app_cache_space_external(uuid, userId, appId);
2377 if (space != -1) {
2378 extStats->dataSize += space; // cache counts for "data"
2379 extStats->cacheSize += space;
2380 doubleSpaceToBeDeleted += space;
2381 }
2382 }
2383
2384 if (stats != nullptr) {
2385 if (!supportsProjectId) {
2386 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002387 stats->dataSize += space;
2388 }
Shikha Malhotra976ae002022-02-26 15:39:53 +00002389 deductDoubleSpaceIfNeeded(stats, doubleSpaceToBeDeleted, uid, uuid);
2390 int sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
2391 if (sdkSandboxUid != -1) {
2392 if ((space = GetOccupiedSpaceForUid(uuid, sdkSandboxUid)) != -1) {
2393 stats->dataSize += space;
2394 }
2395 }
2396 int cacheGid = multiuser_get_cache_gid(userId, appId);
2397 if (cacheGid != -1) {
2398 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
2399 stats->cacheSize += space;
2400 }
2401 }
2402 } else {
2403 long projectId = get_project_id(uid, PROJECT_ID_APP_START);
2404 if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
2405 stats->dataSize += space;
2406 }
2407 projectId = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
2408 if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
Risan5f308262018-10-26 12:06:58 -06002409 stats->cacheSize += space;
Shikha Malhotra976ae002022-02-26 15:39:53 +00002410 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002411 }
2412 }
2413
2414 int sharedGid = multiuser_get_shared_gid(0, appId);
2415 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06002416 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
2417 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002418 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002419 }
2420 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002421}
2422
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002423static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07002424 DIR *d;
2425 int dfd;
2426 struct dirent *de;
2427 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002428
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002429 d = opendir(path.c_str());
2430 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002431 if (errno != ENOENT) {
2432 PLOG(WARNING) << "Failed to open " << path;
2433 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002434 return;
2435 }
2436 dfd = dirfd(d);
2437 while ((de = readdir(d))) {
2438 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002439
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002440 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002441 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002442 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002443 }
2444
2445 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002446 if (!strcmp(name, ".")) {
2447 // Don't recurse, but still count node size
2448 } else if (!strcmp(name, "..")) {
2449 // Don't recurse or count node size
2450 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002451 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002452 // Measure all children nodes
2453 size = 0;
2454 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002455 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002456
2457 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
2458 stats->cacheSize += size;
2459 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002460 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002461
2462 // Legacy symlink isn't owned by app
2463 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
2464 continue;
2465 }
2466
2467 // Everything found inside is considered data
2468 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002469 }
2470 closedir(d);
2471}
2472
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002473void collectManualStatsForSubDirectories(const std::string& path, struct stats* stats) {
2474 const auto subDirHandler = [&path, &stats](const std::string& subDir) {
2475 auto fullpath = path + "/" + subDir;
2476 collectManualStats(fullpath, stats);
2477 };
2478 foreach_subdir(path, subDirHandler);
2479}
2480
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002481static void collectManualStatsForUser(const std::string& path, struct stats* stats,
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002482 bool exclude_apps = false,
2483 bool is_sdk_sandbox_storage = false) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002484 DIR *d;
2485 int dfd;
2486 struct dirent *de;
2487 struct stat s;
2488
2489 d = opendir(path.c_str());
2490 if (d == nullptr) {
2491 if (errno != ENOENT) {
2492 PLOG(WARNING) << "Failed to open " << path;
2493 }
2494 return;
2495 }
2496 dfd = dirfd(d);
2497 while ((de = readdir(d))) {
2498 if (de->d_type == DT_DIR) {
2499 const char *name = de->d_name;
2500 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
2501 continue;
2502 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002503 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002504 if (!strcmp(name, ".") || !strcmp(name, "..")) {
2505 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002506 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002507 continue;
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002508 } else if (is_sdk_sandbox_storage) {
2509 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2510 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2511 collectManualStatsForSubDirectories(StringPrintf("%s/%s", path.c_str(), name),
2512 stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002513 } else {
2514 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
2515 }
2516 }
2517 }
2518 closedir(d);
2519}
2520
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002521static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
2522 FTS *fts;
2523 FTSENT *p;
2524 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07002525 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002526 PLOG(ERROR) << "Failed to fts_open " << path;
2527 return;
2528 }
Yi Konge7bf3772018-07-17 16:16:24 -07002529 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002530 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002531 switch (p->fts_info) {
2532 case FTS_D:
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002533 if (p->fts_level == 3
2534 && !strcmp(p->fts_parent->fts_name, "obb")
2535 && !strcmp(p->fts_parent->fts_parent->fts_name, "Android")) {
2536 p->fts_number = 1;
2537 } else if (p->fts_level == 4
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002538 && !strcmp(p->fts_name, "cache")
2539 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
2540 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002541 p->fts_number = 2;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002542 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002543 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002544 case FTS_DEFAULT:
2545 case FTS_F:
2546 case FTS_SL:
2547 case FTS_SLNONE:
2548 int64_t size = (p->fts_statp->st_blocks * 512);
2549 if (p->fts_number == 1) {
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002550 stats->codeSize += size;
2551 } else {
2552 if (p->fts_number == 2) {
2553 stats->cacheSize += size;
2554 }
2555 stats->dataSize += size;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002556 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002557 break;
2558 }
2559 }
2560 fts_close(fts);
2561}
Shikha Malhotraaae96442021-11-25 10:52:50 +00002562static bool ownsExternalStorage(int32_t appId) {
Shikha Malhotra976ae002022-02-26 15:39:53 +00002563 // if project id calculation is supported then, there is no need to
2564 // calculate in a different way and project_id based calculation can work
2565 if (internal_storage_has_project_id()) {
2566 return false;
2567 }
2568
Shikha Malhotraaae96442021-11-25 10:52:50 +00002569 // Fetch external storage owner appid and check if it is the same as the
2570 // current appId whose size is calculated
2571 struct stat s;
2572 auto _picDir = StringPrintf("%s/Pictures", create_data_media_path(nullptr, 0).c_str());
2573 // check if the stat are present
2574 if (stat(_picDir.c_str(), &s) == 0) {
2575 // fetch the appId from the uid of the media app
2576 return ((int32_t)multiuser_get_app_id(s.st_uid) == appId);
2577 }
2578 return false;
2579}
Jooyung Han149be4a2020-01-23 12:45:10 +09002580binder::Status InstalldNativeService::getAppSize(const std::optional<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002581 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
2582 int32_t appId, const std::vector<int64_t>& ceDataInodes,
2583 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002584 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002585 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyya6823ef2022-02-28 14:18:19 -08002586 if (packageNames.size() != ceDataInodes.size()) {
2587 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
2588 "packageNames/ceDataInodes size mismatch.");
2589 }
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002590 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002591 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2592 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002593 for (const auto& codePath : codePaths) {
2594 CHECK_ARGUMENT_PATH(codePath);
2595 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002596 // NOTE: Locking is relaxed on this method, since it's limited to
2597 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07002598
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002599 // When modifying this logic, always verify using tests:
2600 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
2601
2602#if MEASURE_DEBUG
2603 LOG(INFO) << "Measuring user " << userId << " app " << appId;
2604#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002605
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002606 // Here's a summary of the common storage locations across the platform,
2607 // and how they're each tagged:
2608 //
2609 // /data/app/com.example UID system
2610 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002611 // /data/user/0/com.example UID u0_a10 GID u0_a10
2612 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
2613 // /data/media/0/foo.txt UID u0_media_rw
2614 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
2615 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
2616 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
2617 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002618
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002619 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002620 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002621 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002622 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002623
Jooyung Han149be4a2020-01-23 12:45:10 +09002624 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002625 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002626
Risan5f308262018-10-26 12:06:58 -06002627 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002628 flags &= ~FLAG_USE_QUOTA;
2629 }
2630
Zim23457d02022-08-17 12:57:41 +01002631 atrace_pm_begin("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002632 for (const auto& packageName : packageNames) {
Jeff Sharkey6d775c52019-03-22 13:46:20 -06002633 auto obbCodePath = create_data_media_package_path(uuid_, userId,
2634 "obb", packageName.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002635 calculate_tree_size(obbCodePath, &extStats.codeSize);
2636 }
Zim23457d02022-08-17 12:57:41 +01002637 atrace_pm_end();
Shikha Malhotraaae96442021-11-25 10:52:50 +00002638 // Calculating the app size of the external storage owning app in a manual way, since
2639 // calculating it through quota apis also includes external media storage in the app storage
2640 // numbers
2641 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START && !ownsExternalStorage(appId)) {
Zim23457d02022-08-17 12:57:41 +01002642 atrace_pm_begin("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002643 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002644 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002645 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002646 }
Zim23457d02022-08-17 12:57:41 +01002647 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002648
Zim23457d02022-08-17 12:57:41 +01002649 atrace_pm_begin("quota");
Risan5f308262018-10-26 12:06:58 -06002650 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Zim23457d02022-08-17 12:57:41 +01002651 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002652 } else {
Zim23457d02022-08-17 12:57:41 +01002653 atrace_pm_begin("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002654 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002655 calculate_tree_size(codePath, &stats.codeSize);
2656 }
Zim23457d02022-08-17 12:57:41 +01002657 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002658
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002659 for (size_t i = 0; i < packageNames.size(); i++) {
2660 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002661
Zim23457d02022-08-17 12:57:41 +01002662 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002663 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
2664 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002665 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
2666 collectManualStats(dePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002667 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002668
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002669 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2670 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2671 if (appId >= AID_APP_START && appId <= AID_APP_END) {
Zim23457d02022-08-17 12:57:41 +01002672 atrace_pm_begin("sdksandbox");
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002673 auto sdkSandboxCePath =
2674 create_data_misc_sdk_sandbox_package_path(uuid_, true, userId, pkgname);
2675 collectManualStatsForSubDirectories(sdkSandboxCePath, &stats);
2676 auto sdkSandboxDePath =
2677 create_data_misc_sdk_sandbox_package_path(uuid_, false, userId, pkgname);
2678 collectManualStatsForSubDirectories(sdkSandboxDePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002679 atrace_pm_end();
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002680 }
2681
Jeff Sharkey06a61842017-04-15 12:03:31 -06002682 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002683 atrace_pm_begin("profiles");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002684 calculate_tree_size(
2685 create_primary_current_profile_package_dir_path(userId, pkgname),
2686 &stats.dataSize);
2687 calculate_tree_size(
2688 create_primary_reference_profile_package_dir_path(pkgname),
2689 &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002690 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002691 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002692
Zim23457d02022-08-17 12:57:41 +01002693 atrace_pm_begin("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002694 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002695 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002696 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002697 calculate_tree_size(mediaPath, &extStats.dataSize);
Zim23457d02022-08-17 12:57:41 +01002698 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002699 }
2700
Jeff Sharkey06a61842017-04-15 12:03:31 -06002701 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002702 atrace_pm_begin("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002703 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06002704 if (sharedGid != -1) {
2705 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2706 sharedGid, -1);
2707 }
Zim23457d02022-08-17 12:57:41 +01002708 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002709 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002710 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002711
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002712 std::vector<int64_t> ret;
2713 ret.push_back(stats.codeSize);
2714 ret.push_back(stats.dataSize);
2715 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002716 ret.push_back(extStats.codeSize);
2717 ret.push_back(extStats.dataSize);
2718 ret.push_back(extStats.cacheSize);
2719#if MEASURE_DEBUG
2720 LOG(DEBUG) << "Final result " << toString(ret);
2721#endif
2722 *_aidl_return = ret;
2723 return ok();
2724}
2725
Martijn Coenen771cc342020-02-19 23:26:56 +01002726struct external_sizes {
2727 int64_t audioSize;
2728 int64_t videoSize;
2729 int64_t imageSize;
2730 int64_t totalSize; // excludes OBBs (Android/obb), but includes app data + cache
2731 int64_t obbSize;
2732};
2733
2734#define PER_USER_RANGE 100000
2735
2736static long getProjectIdForUser(int userId, long projectId) {
2737 return userId * PER_USER_RANGE + projectId;
2738}
2739
2740static external_sizes getExternalSizesForUserWithQuota(const std::string& uuid, int32_t userId, const std::vector<int32_t>& appIds) {
2741 struct external_sizes sizes = {};
2742 int64_t space;
2743
2744 if (supports_sdcardfs()) {
2745 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
2746 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
2747 sizes.totalSize = space;
2748 }
2749
2750 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
2751 if ((space = GetOccupiedSpaceForGid(uuid, audioGid)) != -1) {
2752 sizes.audioSize = space;
2753 }
2754
2755 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
2756 if ((space = GetOccupiedSpaceForGid(uuid, videoGid)) != -1) {
2757 sizes.videoSize = space;
2758 }
2759
2760 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
2761 if ((space = GetOccupiedSpaceForGid(uuid, imageGid)) != -1) {
2762 sizes.imageSize = space;
2763 }
2764
2765 if ((space = GetOccupiedSpaceForGid(uuid, AID_MEDIA_OBB)) != -1) {
2766 sizes.obbSize = space;
2767 }
2768 } else {
2769 int64_t totalSize = 0;
2770 long defaultProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_DEFAULT);
2771 if ((space = GetOccupiedSpaceForProjectId(uuid, defaultProjectId)) != -1) {
2772 // This is all files that are not audio/video/images, excluding
2773 // OBBs and app-private data
2774 totalSize += space;
2775 }
2776
2777 long audioProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_AUDIO);
2778 if ((space = GetOccupiedSpaceForProjectId(uuid, audioProjectId)) != -1) {
2779 sizes.audioSize = space;
2780 totalSize += space;
2781 }
2782
2783 long videoProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_VIDEO);
2784 if ((space = GetOccupiedSpaceForProjectId(uuid, videoProjectId)) != -1) {
2785 sizes.videoSize = space;
2786 totalSize += space;
2787 }
2788
2789 long imageProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_IMAGE);
2790 if ((space = GetOccupiedSpaceForProjectId(uuid, imageProjectId)) != -1) {
2791 sizes.imageSize = space;
2792 totalSize += space;
2793 }
2794
2795 int64_t totalAppDataSize = 0;
2796 int64_t totalAppCacheSize = 0;
2797 int64_t totalAppObbSize = 0;
2798 for (auto appId : appIds) {
2799 if (appId >= AID_APP_START) {
2800 // App data
2801 uid_t uid = multiuser_get_uid(userId, appId);
2802 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
2803 totalAppDataSize += GetOccupiedSpaceForProjectId(uuid, projectId);
2804
2805 // App cache
2806 long cacheProjectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
2807 totalAppCacheSize += GetOccupiedSpaceForProjectId(uuid, cacheProjectId);
2808
2809 // App OBBs
2810 long obbProjectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
2811 totalAppObbSize += GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2812 }
2813 }
2814 // Total size should include app data + cache
2815 totalSize += totalAppDataSize;
2816 totalSize += totalAppCacheSize;
2817 sizes.totalSize = totalSize;
2818
2819 // Only OBB is separate
2820 sizes.obbSize = totalAppObbSize;
2821 }
2822
2823 return sizes;
2824}
2825
Jooyung Han149be4a2020-01-23 12:45:10 +09002826binder::Status InstalldNativeService::getUserSize(const std::optional<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002827 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2828 std::vector<int64_t>* _aidl_return) {
2829 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002830 ENFORCE_VALID_USER(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002831 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002832 // NOTE: Locking is relaxed on this method, since it's limited to
2833 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002834
2835 // When modifying this logic, always verify using tests:
2836 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
2837
2838#if MEASURE_DEBUG
2839 LOG(INFO) << "Measuring user " << userId;
2840#endif
2841
2842 struct stats stats;
2843 struct stats extStats;
2844 memset(&stats, 0, sizeof(stats));
2845 memset(&extStats, 0, sizeof(extStats));
2846
Jooyung Han149be4a2020-01-23 12:45:10 +09002847 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002848 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2849
Risan5f308262018-10-26 12:06:58 -06002850 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002851 flags &= ~FLAG_USE_QUOTA;
2852 }
2853
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002854 if (flags & FLAG_USE_QUOTA) {
Zim23457d02022-08-17 12:57:41 +01002855 atrace_pm_begin("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002856 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002857 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002858
Zim23457d02022-08-17 12:57:41 +01002859 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002860 auto cePath = create_data_user_ce_path(uuid_, userId);
2861 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002862 auto dePath = create_data_user_de_path(uuid_, userId);
2863 collectManualStatsForUser(dePath, &stats, true);
Zim23457d02022-08-17 12:57:41 +01002864 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002865
Jeff Sharkey06a61842017-04-15 12:03:31 -06002866 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002867 atrace_pm_begin("profile");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002868 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2869 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
2870 auto refProfilePath = create_primary_ref_profile_dir_path();
2871 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002872 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002873 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002874
Zim23457d02022-08-17 12:57:41 +01002875 atrace_pm_begin("external");
Martijn Coenen771cc342020-02-19 23:26:56 +01002876 auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2877 extStats.dataSize += sizes.totalSize;
2878 extStats.codeSize += sizes.obbSize;
Zim23457d02022-08-17 12:57:41 +01002879 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002880
Jeff Sharkey06a61842017-04-15 12:03:31 -06002881 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002882 atrace_pm_begin("dalvik");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002883 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2884 -1, -1, true);
2885 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
2886 -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002887 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002888 }
Zim23457d02022-08-17 12:57:41 +01002889 atrace_pm_begin("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002890 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002891 for (auto appId : appIds) {
2892 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06002893 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002894#if MEASURE_DEBUG
2895 // Sleep to make sure we don't lose logs
2896 usleep(1);
2897#endif
2898 }
2899 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002900 extStats.dataSize = dataSize;
Zim23457d02022-08-17 12:57:41 +01002901 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002902 } else {
Zim23457d02022-08-17 12:57:41 +01002903 atrace_pm_begin("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002904 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002905 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002906
Zim23457d02022-08-17 12:57:41 +01002907 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002908 auto cePath = create_data_user_ce_path(uuid_, userId);
2909 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002910 auto dePath = create_data_user_de_path(uuid_, userId);
2911 collectManualStatsForUser(dePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002912 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002913
Zim23457d02022-08-17 12:57:41 +01002914 atrace_pm_begin("sdksandbox");
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002915 auto sdkSandboxCePath = create_data_misc_sdk_sandbox_path(uuid_, true, userId);
2916 collectManualStatsForUser(sdkSandboxCePath, &stats, false, true);
2917 auto sdkSandboxDePath = create_data_misc_sdk_sandbox_path(uuid_, false, userId);
2918 collectManualStatsForUser(sdkSandboxDePath, &stats, false, true);
Zim23457d02022-08-17 12:57:41 +01002919 atrace_pm_end();
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002920
Jeff Sharkey06a61842017-04-15 12:03:31 -06002921 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002922 atrace_pm_begin("profile");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002923 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2924 calculate_tree_size(userProfilePath, &stats.dataSize);
2925 auto refProfilePath = create_primary_ref_profile_dir_path();
2926 calculate_tree_size(refProfilePath, &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002927 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002928 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002929
Zim23457d02022-08-17 12:57:41 +01002930 atrace_pm_begin("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002931 auto dataMediaPath = create_data_media_path(uuid_, userId);
2932 collectManualExternalStatsForUser(dataMediaPath, &extStats);
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002933
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002934#if MEASURE_DEBUG
2935 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002936 << extStats.cacheSize << " code " << extStats.codeSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002937#endif
Zim23457d02022-08-17 12:57:41 +01002938 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002939
Jeff Sharkey06a61842017-04-15 12:03:31 -06002940 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002941 atrace_pm_begin("dalvik");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002942 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
2943 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
Zim23457d02022-08-17 12:57:41 +01002944 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002945 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002946 }
2947
2948 std::vector<int64_t> ret;
2949 ret.push_back(stats.codeSize);
2950 ret.push_back(stats.dataSize);
2951 ret.push_back(stats.cacheSize);
2952 ret.push_back(extStats.codeSize);
2953 ret.push_back(extStats.dataSize);
2954 ret.push_back(extStats.cacheSize);
2955#if MEASURE_DEBUG
2956 LOG(DEBUG) << "Final result " << toString(ret);
2957#endif
2958 *_aidl_return = ret;
2959 return ok();
2960}
2961
Jooyung Han149be4a2020-01-23 12:45:10 +09002962binder::Status InstalldNativeService::getExternalSize(const std::optional<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002963 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2964 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002965 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002966 ENFORCE_VALID_USER(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002967 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002968 // NOTE: Locking is relaxed on this method, since it's limited to
2969 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002970
2971 // When modifying this logic, always verify using tests:
2972 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
2973
2974#if MEASURE_DEBUG
2975 LOG(INFO) << "Measuring external " << userId;
2976#endif
2977
Jooyung Han149be4a2020-01-23 12:45:10 +09002978 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002979 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2980
2981 int64_t totalSize = 0;
2982 int64_t audioSize = 0;
2983 int64_t videoSize = 0;
2984 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002985 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06002986 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002987
Risan5f308262018-10-26 12:06:58 -06002988 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002989 flags &= ~FLAG_USE_QUOTA;
2990 }
2991
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002992 if (flags & FLAG_USE_QUOTA) {
Zim23457d02022-08-17 12:57:41 +01002993 atrace_pm_begin("quota");
Martijn Coenen771cc342020-02-19 23:26:56 +01002994 auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2995 totalSize = sizes.totalSize;
2996 audioSize = sizes.audioSize;
2997 videoSize = sizes.videoSize;
2998 imageSize = sizes.imageSize;
2999 obbSize = sizes.obbSize;
Zim23457d02022-08-17 12:57:41 +01003000 atrace_pm_end();
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06003001
Zim23457d02022-08-17 12:57:41 +01003002 atrace_pm_begin("apps");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06003003 struct stats extStats;
3004 memset(&extStats, 0, sizeof(extStats));
3005 for (auto appId : appIds) {
3006 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06003007 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06003008 }
3009 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06003010 appSize = extStats.dataSize;
Zim23457d02022-08-17 12:57:41 +01003011 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003012 } else {
Zim23457d02022-08-17 12:57:41 +01003013 atrace_pm_begin("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003014 FTS *fts;
3015 FTSENT *p;
3016 auto path = create_data_media_path(uuid_, userId);
3017 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07003018 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003019 return error("Failed to fts_open " + path);
3020 }
Yi Konge7bf3772018-07-17 16:16:24 -07003021 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003022 char* ext;
3023 int64_t size = (p->fts_statp->st_blocks * 512);
3024 switch (p->fts_info) {
3025 case FTS_F:
3026 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06003027 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003028 ext = strrchr(p->fts_name, '.');
3029 if (ext != nullptr) {
3030 switch (MatchExtension(++ext)) {
3031 case AID_MEDIA_AUDIO: audioSize += size; break;
3032 case AID_MEDIA_VIDEO: videoSize += size; break;
3033 case AID_MEDIA_IMAGE: imageSize += size; break;
3034 }
3035 }
3036 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07003037 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003038 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06003039 // Ignore data belonging to specific apps
3040 p->fts_number = p->fts_parent->fts_number;
3041 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
3042 p->fts_number = 1;
3043 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07003044 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003045 case FTS_DEFAULT:
3046 case FTS_SL:
3047 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06003048 if (p->fts_parent->fts_number == 1) {
3049 appSize += size;
3050 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003051 totalSize += size;
3052 break;
3053 }
3054 }
3055 fts_close(fts);
Zim23457d02022-08-17 12:57:41 +01003056 atrace_pm_end();
Jeff Sharkeya0136982017-07-06 11:29:37 -06003057
Zim23457d02022-08-17 12:57:41 +01003058 atrace_pm_begin("obb");
Jeff Sharkey6d775c52019-03-22 13:46:20 -06003059 auto obbPath = StringPrintf("%s/Android/obb",
3060 create_data_media_path(uuid_, userId).c_str());
Jeff Sharkeya0136982017-07-06 11:29:37 -06003061 calculate_tree_size(obbPath, &obbSize);
Chuwei Xu5d64ddf2019-12-04 15:32:18 +08003062 if (!(flags & FLAG_USE_QUOTA)) {
3063 totalSize -= obbSize;
3064 }
Zim23457d02022-08-17 12:57:41 +01003065 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003066 }
3067
3068 std::vector<int64_t> ret;
3069 ret.push_back(totalSize);
3070 ret.push_back(audioSize);
3071 ret.push_back(videoSize);
3072 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06003073 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06003074 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003075#if MEASURE_DEBUG
3076 LOG(DEBUG) << "Final result " << toString(ret);
3077#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07003078 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07003079 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003080}
3081
Felka Chang2a0a2462019-11-20 14:20:40 +08003082binder::Status InstalldNativeService::getAppCrates(
Jooyung Han149be4a2020-01-23 12:45:10 +09003083 const std::optional<std::string>& uuid,
Felka Chang2a0a2462019-11-20 14:20:40 +08003084 const std::vector<std::string>& packageNames, int32_t userId,
Jooyung Han149be4a2020-01-23 12:45:10 +09003085 std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
Felka Chang2a0a2462019-11-20 14:20:40 +08003086 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003087 ENFORCE_VALID_USER(userId);
Felka Chang2a0a2462019-11-20 14:20:40 +08003088 CHECK_ARGUMENT_UUID(uuid);
3089 for (const auto& packageName : packageNames) {
3090 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3091 }
Felka Chang4df87f62020-02-11 19:08:43 +08003092#ifdef ENABLE_STORAGE_CRATES
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003093 LOCK_PACKAGE_USER();
Felka Chang2a0a2462019-11-20 14:20:40 +08003094
Jooyung Han149be4a2020-01-23 12:45:10 +09003095 auto retVector = std::vector<std::optional<CrateMetadata>>();
Felka Chang2a0a2462019-11-20 14:20:40 +08003096 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3097
Jooyung Han149be4a2020-01-23 12:45:10 +09003098 std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3099 [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
Felka Chang2a0a2462019-11-20 14:20:40 +08003100 if (cratedFolder == nullptr) {
3101 return;
3102 }
Jooyung Han149be4a2020-01-23 12:45:10 +09003103 retVector.push_back(std::move(crateMetadata));
Felka Chang2a0a2462019-11-20 14:20:40 +08003104 };
3105
3106 for (const auto& packageName : packageNames) {
3107#if CRATE_DEBUG
3108 LOG(DEBUG) << "packageName = " << packageName;
3109#endif
3110 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageName);
3111 crateManager->traverseAllCrates(onCreateCrate);
3112 }
3113
3114#if CRATE_DEBUG
Jooyung Han149be4a2020-01-23 12:45:10 +09003115 LOG(WARNING) << "retVector.size() =" << retVector.size();
3116 for (auto& item : retVector) {
Jooyung Hand520e802020-03-03 02:56:34 +09003117 CrateManager::dump(*item);
Felka Chang2a0a2462019-11-20 14:20:40 +08003118 }
3119#endif
3120
3121 *_aidl_return = std::move(retVector);
Felka Chang4df87f62020-02-11 19:08:43 +08003122#else // ENABLE_STORAGE_CRATES
Jooyung Han149be4a2020-01-23 12:45:10 +09003123 _aidl_return->reset();
Felka Chang4df87f62020-02-11 19:08:43 +08003124
3125 /* prevent compile warning fail */
3126 if (userId < 0) {
3127 return error();
3128 }
3129#endif // ENABLE_STORAGE_CRATES
Felka Chang2a0a2462019-11-20 14:20:40 +08003130 return ok();
3131}
3132
3133binder::Status InstalldNativeService::getUserCrates(
Jooyung Han149be4a2020-01-23 12:45:10 +09003134 const std::optional<std::string>& uuid, int32_t userId,
3135 std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
Felka Chang2a0a2462019-11-20 14:20:40 +08003136 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003137 ENFORCE_VALID_USER(userId);
Felka Chang2a0a2462019-11-20 14:20:40 +08003138 CHECK_ARGUMENT_UUID(uuid);
Felka Chang4df87f62020-02-11 19:08:43 +08003139#ifdef ENABLE_STORAGE_CRATES
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003140 LOCK_USER();
Felka Chang2a0a2462019-11-20 14:20:40 +08003141
3142 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jooyung Han149be4a2020-01-23 12:45:10 +09003143 auto retVector = std::vector<std::optional<CrateMetadata>>();
Felka Chang2a0a2462019-11-20 14:20:40 +08003144
Jooyung Han149be4a2020-01-23 12:45:10 +09003145 std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3146 [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
Felka Chang2a0a2462019-11-20 14:20:40 +08003147 if (cratedFolder == nullptr) {
3148 return;
3149 }
Jooyung Hand520e802020-03-03 02:56:34 +09003150 retVector.push_back(std::move(crateMetadata));
Felka Chang2a0a2462019-11-20 14:20:40 +08003151 };
3152
3153 std::function<void(FTSENT*)> onHandingPackage = [&](FTSENT* packageDir) -> void {
3154 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageDir->fts_name);
3155 crateManager->traverseAllCrates(onCreateCrate);
3156 };
3157 CrateManager::traverseAllPackagesForUser(uuid, userId, onHandingPackage);
3158
3159#if CRATE_DEBUG
Jooyung Han149be4a2020-01-23 12:45:10 +09003160 LOG(DEBUG) << "retVector.size() =" << retVector.size();
3161 for (auto& item : retVector) {
Jooyung Hand520e802020-03-03 02:56:34 +09003162 CrateManager::dump(*item);
Felka Chang2a0a2462019-11-20 14:20:40 +08003163 }
3164#endif
3165
3166 *_aidl_return = std::move(retVector);
Felka Chang4df87f62020-02-11 19:08:43 +08003167#else // ENABLE_STORAGE_CRATES
Jooyung Han149be4a2020-01-23 12:45:10 +09003168 _aidl_return->reset();
Felka Chang4df87f62020-02-11 19:08:43 +08003169
3170 /* prevent compile warning fail */
3171 if (userId < 0) {
3172 return error();
3173 }
3174#endif // ENABLE_STORAGE_CRATES
Felka Chang2a0a2462019-11-20 14:20:40 +08003175 return ok();
3176}
3177
Jooyung Han149be4a2020-01-23 12:45:10 +09003178binder::Status InstalldNativeService::setAppQuota(const std::optional<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003179 int32_t userId, int32_t appId, int64_t cacheQuota) {
3180 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003181 ENFORCE_VALID_USER(userId);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003182 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003183 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003184
3185 int32_t uid = multiuser_get_uid(userId, appId);
3186 mCacheQuotas[uid] = cacheQuota;
3187
3188 return ok();
3189}
3190
David Sehr6727c2d2016-05-17 16:06:22 -07003191// Dumps the contents of a profile file, using pkgname's dex files for pretty
3192// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003193binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Martin Stjernholmfd000402022-04-11 18:04:59 +01003194 const std::string& profileName,
3195 const std::string& codePath,
3196 bool dumpClassesAndMethods, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003197 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003198 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003199 CHECK_ARGUMENT_PATH(codePath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003200 LOCK_PACKAGE();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003201
Martin Stjernholmfd000402022-04-11 18:04:59 +01003202 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath, dumpClassesAndMethods);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003203 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07003204}
3205
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003206// Copy the contents of a system profile over the data profile.
3207binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08003208 int32_t packageUid, const std::string& packageName, const std::string& profileName,
3209 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003210 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyyd04631f2022-08-12 15:14:41 -07003211 CHECK_ARGUMENT_PATH(systemProfile);
3212 if (!base::EndsWith(systemProfile, ".prof")) {
3213 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3214 StringPrintf("System profile path %s does not end with .prof",
3215 systemProfile.c_str()));
3216 }
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003217 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyyd04631f2022-08-12 15:14:41 -07003218 CHECK_ARGUMENT_FILE_NAME(profileName);
3219 if (!base::EndsWith(profileName, ".prof")) {
3220 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3221 StringPrintf("Profile name %s does not end with .prof",
3222 profileName.c_str()));
3223 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003224 LOCK_PACKAGE();
Calin Juravle562de812018-01-20 23:34:18 -08003225 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003226 return ok();
3227}
3228
Andreas Gampe4d0f8252016-03-20 11:30:28 -07003229// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003230binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle3b758282021-06-08 08:04:52 -07003231 const std::string& profileName, int* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003232 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003233 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003234 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07003235
Calin Juravle562de812018-01-20 23:34:18 -08003236 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003237 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07003238}
3239
Calin Juravlec41dac22017-12-05 12:29:15 -08003240binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08003241 const std::string& packageName, const std::string& profileName,
3242 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08003243 ENFORCE_UID(AID_SYSTEM);
3244 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003245 LOCK_PACKAGE();
Calin Juravle29591732017-11-20 17:46:19 -08003246
Calin Juravlee61189e2018-01-23 19:54:11 -08003247 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08003248 return ok();
3249}
3250
3251binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003252 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08003253 ENFORCE_UID(AID_SYSTEM);
3254 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003255 LOCK_PACKAGE();
Calin Juravle29591732017-11-20 17:46:19 -08003256
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003257 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08003258 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003259 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08003260 }
3261 return ok();
3262}
3263
Jooyung Han149be4a2020-01-23 12:45:10 +09003264static const char* getCStr(const std::optional<std::string>& data,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003265 const char* default_value = nullptr) {
Jooyung Han149be4a2020-01-23 12:45:10 +09003266 return data ? data->c_str() : default_value;
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003267}
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003268binder::Status InstalldNativeService::dexopt(
3269 const std::string& apkPath, int32_t uid, const std::string& packageName,
3270 const std::string& instructionSet, int32_t dexoptNeeded,
3271 const std::optional<std::string>& outputPath, int32_t dexFlags,
Jooyung Han149be4a2020-01-23 12:45:10 +09003272 const std::string& compilerFilter, const std::optional<std::string>& uuid,
3273 const std::optional<std::string>& classLoaderContext,
3274 const std::optional<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
3275 const std::optional<std::string>& profileName,
3276 const std::optional<std::string>& dexMetadataPath,
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003277 const std::optional<std::string>& compilationReason, bool* aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003278 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003279 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07003280 CHECK_ARGUMENT_PATH(apkPath);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003281 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003282 CHECK_ARGUMENT_PATH(outputPath);
3283 CHECK_ARGUMENT_PATH(dexMetadataPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003284 const auto userId = multiuser_get_user_id(uid);
3285 LOCK_PACKAGE_USER();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003286
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07003287 const char* oat_dir = getCStr(outputPath);
3288 const char* instruction_set = instructionSet.c_str();
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003289 if (oat_dir != nullptr && !createOatDir(packageName, oat_dir, instruction_set).isOk()) {
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07003290 // Can't create oat dir - let dexopt use cache dir.
3291 oat_dir = nullptr;
3292 }
3293
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003294 const char* apk_path = apkPath.c_str();
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003295 const char* pkgname = packageName.c_str();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003296 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003297 const char* volume_uuid = getCStr(uuid);
3298 const char* class_loader_context = getCStr(classLoaderContext);
3299 const char* se_info = getCStr(seInfo);
3300 const char* profile_name = getCStr(profileName);
3301 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08003302 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08003303 std::string error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07003304 bool completed = false; // not necessary but for compiler
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003305 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07003306 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Keun young Park65578d62021-06-28 17:52:05 -07003307 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg,
3308 &completed);
3309 *aidl_return = completed;
Andreas Gampe023b2242018-02-28 16:03:25 -08003310 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003311}
3312
Keun young Park65578d62021-06-28 17:52:05 -07003313binder::Status InstalldNativeService::controlDexOptBlocking(bool block) {
3314 android::installd::control_dexopt_blocking(block);
3315 return ok();
3316}
3317
Eric Holk0ebbe0f2019-01-09 18:17:27 -08003318binder::Status InstalldNativeService::compileLayouts(const std::string& apkPath,
3319 const std::string& packageName,
3320 const std ::string& outDexFile, int uid,
3321 bool* _aidl_return) {
3322 const char* apk_path = apkPath.c_str();
3323 const char* package_name = packageName.c_str();
3324 const char* out_dex_file = outDexFile.c_str();
3325 *_aidl_return = android::installd::view_compiler(apk_path, package_name, out_dex_file, uid);
3326 return *_aidl_return ? ok() : error("viewcompiler failed");
3327}
3328
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003329binder::Status InstalldNativeService::linkNativeLibraryDirectory(
Jooyung Han149be4a2020-01-23 12:45:10 +09003330 const std::optional<std::string>& uuid, const std::string& packageName,
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003331 const std::string& nativeLibPath32, int32_t userId) {
3332 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003333 CHECK_ARGUMENT_UUID(uuid);
3334 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003335 CHECK_ARGUMENT_PATH(nativeLibPath32);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003336 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07003337
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003338 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3339 const char* pkgname = packageName.c_str();
3340 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003341 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07003342 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003343
Jeff Sharkey423e7462016-12-09 18:18:43 -07003344 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
3345 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07003346
3347 const char* pkgdir = _pkgdir.c_str();
3348 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003349
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003350 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003351 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003352 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003353
Nick Kralevich85958b62019-01-30 12:32:21 -08003354 char *con = nullptr;
Alex Buynytskyyc668d562023-11-10 22:53:46 +00003355 if (::lgetfilecon(pkgdir, &con) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08003356 return error("Failed to lgetfilecon " + _pkgdir);
3357 }
3358
Mike Lockwood94afecf2012-10-24 10:45:23 -07003359 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08003360 res = error("Failed to chown " + _pkgdir);
3361 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07003362 }
3363
3364 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003365 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003366 goto out;
3367 }
3368
3369 if (lstat(libsymlink, &libStat) < 0) {
3370 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003371 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003372 goto out;
3373 }
3374 } else {
3375 if (S_ISDIR(libStat.st_mode)) {
Yi Konge7bf3772018-07-17 16:16:24 -07003376 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003377 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003378 goto out;
3379 }
3380 } else if (S_ISLNK(libStat.st_mode)) {
3381 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003382 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003383 goto out;
3384 }
3385 }
3386 }
3387
3388 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003389 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003390 goto out;
3391 }
3392
Nick Kralevich85958b62019-01-30 12:32:21 -08003393 if (lsetfilecon(libsymlink, con) < 0) {
3394 res = error("Failed to lsetfilecon " + _libsymlink);
3395 goto out;
3396 }
3397
Mike Lockwood94afecf2012-10-24 10:45:23 -07003398out:
Nick Kralevich85958b62019-01-30 12:32:21 -08003399 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003400 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003401 auto msg = "Failed to cleanup chmod " + _pkgdir;
3402 if (res.isOk()) {
3403 res = error(msg);
3404 } else {
3405 PLOG(ERROR) << msg;
3406 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003407 }
3408
3409 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003410 auto msg = "Failed to cleanup chown " + _pkgdir;
3411 if (res.isOk()) {
3412 res = error(msg);
3413 } else {
3414 PLOG(ERROR) << msg;
3415 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003416 }
3417
Jeff Sharkey423e7462016-12-09 18:18:43 -07003418 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07003419}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01003420
Jooyung Han149be4a2020-01-23 12:45:10 +09003421binder::Status InstalldNativeService::restoreconAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003422 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
3423 const std::string& seInfo) {
3424 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003425 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003426 CHECK_ARGUMENT_UUID(uuid);
3427 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003428 LOCK_PACKAGE_USER();
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08003429 return restoreconAppDataLocked(uuid, packageName, userId, flags, appId, seInfo);
3430}
3431
3432binder::Status InstalldNativeService::restoreconAppDataLocked(
3433 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3434 int32_t flags, int32_t appId, const std::string& seInfo) {
3435 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003436 ENFORCE_VALID_USER(userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08003437 CHECK_ARGUMENT_UUID(uuid);
3438 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003439
3440 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05003441
Robert Craigda30dc72014-03-27 10:21:12 -04003442 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003443 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003444 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3445 const char* pkgName = packageName.c_str();
3446 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04003447
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003448 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07003449 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003450 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003451 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003452 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07003453 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003454 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07003455 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003456 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003457 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003458 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07003459 }
Robert Craige9887e42014-02-20 10:25:56 -05003460 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07003461 return res;
Robert Craige9887e42014-02-20 10:25:56 -05003462}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01003463
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00003464binder::Status InstalldNativeService::restoreconSdkDataLocked(
3465 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3466 int32_t flags, int32_t appId, const std::string& seInfo) {
3467 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003468 ENFORCE_VALID_USER(userId);
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00003469 CHECK_ARGUMENT_UUID(uuid);
3470 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3471
3472 binder::Status res = ok();
3473
3474 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
3475 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
3476 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3477 const char* pkgName = packageName.c_str();
3478 const char* seinfo = seInfo.c_str();
3479
3480 uid_t uid = multiuser_get_sdk_sandbox_uid(userId, appId);
3481 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
3482 for (int currentFlag : storageFlags) {
3483 if ((flags & currentFlag) == 0) {
3484 continue;
3485 }
3486 const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
3487 const auto packagePath =
3488 create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgName);
3489 if (access(packagePath.c_str(), F_OK) != 0) {
3490 LOG(INFO) << "Missing source " << packagePath;
3491 continue;
3492 }
3493 const auto subDirHandler = [&packagePath, &seinfo, &uid, &seflags,
3494 &res](const std::string& subDir) {
3495 const auto& fullpath = packagePath + "/" + subDir;
3496 if (selinux_android_restorecon_pkgdir(fullpath.c_str(), seinfo, uid, seflags) < 0) {
3497 res = error("restorecon failed for " + fullpath);
3498 }
3499 };
3500 const auto ec = foreach_subdir(packagePath, subDirHandler);
3501 if (ec != 0) {
3502 res = error("Failed to restorecon for subdirs of " + packagePath);
3503 }
3504 }
3505 return res;
3506}
3507
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003508binder::Status InstalldNativeService::createOatDir(const std::string& packageName,
3509 const std::string& oatDir,
3510 const std::string& instructionSet) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003511 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003512 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003513 CHECK_ARGUMENT_PATH(oatDir);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003514 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003515
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003516 const char* oat_dir = oatDir.c_str();
3517 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003518 char oat_instr_dir[PKG_PATH_MAX];
3519
3520 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003521 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003522 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07003523 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003524 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003525 }
3526 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003527 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003528 }
3529 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07003530 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003531 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003532 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07003533 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003534}
3535
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003536binder::Status InstalldNativeService::rmPackageDir(const std::string& packageName,
3537 const std::string& packageDir) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003538 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07003539 CHECK_ARGUMENT_PATH(packageDir);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003540 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003541
Jeff Sharkey423e7462016-12-09 18:18:43 -07003542 if (validate_apk_path(packageDir.c_str())) {
3543 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003544 }
Oleksandr Peletskyid2be6322019-01-24 17:59:45 +01003545 if (rm_package_dir(packageDir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003546 return error("Failed to delete " + packageDir);
3547 }
3548 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003549}
3550
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003551binder::Status InstalldNativeService::linkFile(const std::string& packageName,
3552 const std::string& relativePath,
3553 const std::string& fromBase,
3554 const std::string& toBase) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003555 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003556 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003557 CHECK_ARGUMENT_PATH(fromBase);
3558 CHECK_ARGUMENT_PATH(toBase);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003559 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003560
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003561 const char* relative_path = relativePath.c_str();
3562 const char* from_base = fromBase.c_str();
3563 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01003564 char from_path[PKG_PATH_MAX];
3565 char to_path[PKG_PATH_MAX];
3566 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
3567 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
3568
3569 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003570 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003571 }
3572
3573 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003574 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003575 }
3576
Jeff Sharkey423e7462016-12-09 18:18:43 -07003577 if (link(from_path, to_path) < 0) {
3578 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003579 }
3580
Jeff Sharkey423e7462016-12-09 18:18:43 -07003581 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01003582}
3583
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003584binder::Status InstalldNativeService::moveAb(const std::string& packageName,
3585 const std::string& apkPath,
3586 const std::string& instructionSet,
3587 const std::string& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003588 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003589 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003590 CHECK_ARGUMENT_PATH(apkPath);
3591 CHECK_ARGUMENT_PATH(outputPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003592 LOCK_PACKAGE();
Jeff Sharkey90aff262016-12-12 14:28:24 -07003593
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003594 const char* apk_path = apkPath.c_str();
3595 const char* instruction_set = instructionSet.c_str();
3596 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07003597
Jeff Sharkey90aff262016-12-12 14:28:24 -07003598 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003599 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08003600}
3601
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003602binder::Status InstalldNativeService::deleteOdex(const std::string& packageName,
3603 const std::string& apkPath,
3604 const std::string& instructionSet,
3605 const std::optional<std::string>& outputPath,
3606 int64_t* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003607 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003608 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003609 CHECK_ARGUMENT_PATH(apkPath);
3610 CHECK_ARGUMENT_PATH(outputPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003611 LOCK_PACKAGE();
Jeff Sharkey90aff262016-12-12 14:28:24 -07003612
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003613 const char* apk_path = apkPath.c_str();
3614 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07003615 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003616
Calin Juravleea214ad2021-06-11 09:17:20 -07003617 *_aidl_return = delete_odex(apk_path, instruction_set, oat_dir);
3618 return *_aidl_return == -1 ? error() : ok();
Andreas Gampe3964da02016-09-09 17:07:04 -07003619}
3620
Calin Juravlebd968362017-01-25 01:17:17 -08003621binder::Status InstalldNativeService::reconcileSecondaryDexFile(
3622 const std::string& dexPath, const std::string& packageName, int32_t uid,
Jooyung Han149be4a2020-01-23 12:45:10 +09003623 const std::vector<std::string>& isas, const std::optional<std::string>& volumeUuid,
Calin Juravlebd968362017-01-25 01:17:17 -08003624 int32_t storage_flag, bool* _aidl_return) {
3625 ENFORCE_UID(AID_SYSTEM);
3626 CHECK_ARGUMENT_UUID(volumeUuid);
3627 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003628 CHECK_ARGUMENT_PATH(dexPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003629 const auto userId = multiuser_get_user_id(uid);
3630 LOCK_PACKAGE_USER();
Jeff Sharkey53594302018-02-24 18:59:39 -07003631
Calin Juravlebd968362017-01-25 01:17:17 -08003632 bool result = android::installd::reconcile_secondary_dex_file(
3633 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
3634 return result ? ok() : error();
3635}
3636
Alan Stokes753dc712017-10-16 10:56:00 +01003637binder::Status InstalldNativeService::hashSecondaryDexFile(
3638 const std::string& dexPath, const std::string& packageName, int32_t uid,
Jooyung Han149be4a2020-01-23 12:45:10 +09003639 const std::optional<std::string>& volumeUuid, int32_t storageFlag,
Alan Stokes753dc712017-10-16 10:56:00 +01003640 std::vector<uint8_t>* _aidl_return) {
3641 ENFORCE_UID(AID_SYSTEM);
3642 CHECK_ARGUMENT_UUID(volumeUuid);
3643 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003644 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01003645
3646 // mLock is not taken here since we will never modify the file system.
3647 // If a file is modified just as we are reading it this may result in an
3648 // anomalous hash, but that's ok.
3649 bool result = android::installd::hash_secondary_dex_file(
3650 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
3651 return result ? ok() : error();
3652}
Shikha Malhotra976ae002022-02-26 15:39:53 +00003653/**
3654 * Returns true if ioctl feature (F2FS_IOC_FS{GET,SET}XATTR) is supported as
3655 * these were introduced in Linux 4.14, so kernel versions before that will fail
3656 * while setting project id attributes. Only when these features are enabled,
3657 * storage calculation using project_id is enabled
3658 */
3659bool check_if_ioctl_feature_is_supported() {
3660 bool result = false;
3661 auto temp_path = StringPrintf("%smisc/installd/ioctl_check", android_data_dir.c_str());
3662 if (access(temp_path.c_str(), F_OK) != 0) {
3663 int fd = open(temp_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644);
Shikha Malhotrac18afa82022-04-01 22:13:39 +00003664 result = set_quota_project_id(temp_path, 0, false) == 0;
Shikha Malhotra976ae002022-02-26 15:39:53 +00003665 close(fd);
3666 // delete the temp file
3667 remove(temp_path.c_str());
3668 }
3669 return result;
3670}
3671
3672binder::Status InstalldNativeService::setFirstBoot() {
3673 ENFORCE_UID(AID_SYSTEM);
3674 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3675 std::string uuid;
3676 if (GetOccupiedSpaceForProjectId(uuid, 0) != -1 && check_if_ioctl_feature_is_supported()) {
3677 auto first_boot_path =
3678 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
3679 if (access(first_boot_path.c_str(), F_OK) != 0) {
3680 close(open(first_boot_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644));
3681 }
3682 }
3683 return ok();
3684}
Alan Stokes753dc712017-10-16 10:56:00 +01003685
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003686binder::Status InstalldNativeService::invalidateMounts() {
3687 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003688 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003689
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003690 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06003691
3692#if !BYPASS_QUOTA
3693 if (!InvalidateQuotaMounts()) {
3694 return error("Failed to read mounts");
3695 }
3696#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003697
3698 std::ifstream in("/proc/mounts");
3699 if (!in.is_open()) {
3700 return error("Failed to read mounts");
3701 }
3702
3703 std::string source;
3704 std::string target;
3705 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003706 while (!in.eof()) {
3707 std::getline(in, source, ' ');
3708 std::getline(in, target, ' ');
3709 std::getline(in, ignored);
3710
Zim0ce832d2019-12-03 17:03:58 +00003711 if (android::base::GetBoolProperty(kFuseProp, false)) {
Zim1edb92a2020-01-09 08:48:00 +00003712 if (target.find(kMntFuse) == 0) {
Zim0ce832d2019-12-03 17:03:58 +00003713 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3714 mStorageMounts[source] = target;
3715 }
3716 } else {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003717#if !BYPASS_SDCARDFS
Zim1edb92a2020-01-09 08:48:00 +00003718 if (target.find(kMntSdcardfs) == 0) {
Zim0ce832d2019-12-03 17:03:58 +00003719 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3720 mStorageMounts[source] = target;
3721 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003722#endif
Zim0ce832d2019-12-03 17:03:58 +00003723 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003724 }
3725 return ok();
3726}
3727
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003728// Mount volume's CE and DE storage to mirror
Ricky Wai2a4983f2020-02-07 14:25:45 +00003729binder::Status InstalldNativeService::tryMountDataMirror(
Jooyung Han149be4a2020-01-23 12:45:10 +09003730 const std::optional<std::string>& uuid) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003731 ENFORCE_UID(AID_SYSTEM);
3732 CHECK_ARGUMENT_UUID(uuid);
3733 if (!sAppDataIsolationEnabled) {
3734 return ok();
3735 }
3736 if (!uuid) {
3737 return error("Should not happen, mounting uuid == null");
3738 }
3739
3740 const char* uuid_ = uuid->c_str();
Ricky Wai2a4983f2020-02-07 14:25:45 +00003741
Alex Buynytskyy40c45ba2021-11-18 15:16:27 -08003742 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3743
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003744 std::string mirrorVolCePath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003745 if (fs_prepare_dir(mirrorVolCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003746 return error("Failed to create CE data mirror");
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003747 }
Ricky Wai2a4983f2020-02-07 14:25:45 +00003748
3749 std::string mirrorVolDePath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003750 if (fs_prepare_dir(mirrorVolDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003751 return error("Failed to create DE data mirror");
3752 }
3753
3754 std::string mirrorVolMiscCePath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003755 if (fs_prepare_dir(mirrorVolMiscCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003756 return error("Failed to create CE misc mirror");
3757 }
3758
3759 std::string mirrorVolMiscDePath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003760 if (fs_prepare_dir(mirrorVolMiscDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003761 return error("Failed to create DE misc mirror");
Ricky Wai2a4983f2020-02-07 14:25:45 +00003762 }
3763
3764 auto cePath = StringPrintf("%s/user", create_data_path(uuid_).c_str());
3765 auto dePath = StringPrintf("%s/user_de", create_data_path(uuid_).c_str());
Sanjana Sunil691163d2022-03-28 19:15:54 +00003766 auto miscCePath = StringPrintf("%s/misc_ce", create_data_path(uuid_).c_str());
3767 auto miscDePath = StringPrintf("%s/misc_de", create_data_path(uuid_).c_str());
Ricky Wai2a4983f2020-02-07 14:25:45 +00003768
3769 if (access(cePath.c_str(), F_OK) != 0) {
3770 return error("Cannot access CE path: " + cePath);
3771 }
3772 if (access(dePath.c_str(), F_OK) != 0) {
3773 return error("Cannot access DE path: " + dePath);
3774 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003775 if (access(miscCePath.c_str(), F_OK) != 0) {
3776 return error("Cannot access misc CE path: " + cePath);
3777 }
3778 if (access(miscDePath.c_str(), F_OK) != 0) {
3779 return error("Cannot access misc DE path: " + dePath);
3780 }
Ricky Wai2a4983f2020-02-07 14:25:45 +00003781
3782 struct stat ceStat, mirrorCeStat;
3783 if (stat(cePath.c_str(), &ceStat) != 0) {
3784 return error("Failed to stat " + cePath);
3785 }
3786 if (stat(mirrorVolCePath.c_str(), &mirrorCeStat) != 0) {
3787 return error("Failed to stat " + mirrorVolCePath);
3788 }
3789
Eric Biggersab9ea462022-05-26 00:28:09 +00003790 if (mirrorCeStat.st_ino == ceStat.st_ino && mirrorCeStat.st_dev == ceStat.st_dev) {
Ricky Wai2a4983f2020-02-07 14:25:45 +00003791 // As it's being called by prepareUserStorage, it can be called multiple times.
3792 // Hence, we if we mount it already, we should skip it.
Eric Biggersab9ea462022-05-26 00:28:09 +00003793 LOG(INFO) << "CE dir is mounted already: " + cePath;
Ricky Wai2a4983f2020-02-07 14:25:45 +00003794 return ok();
3795 }
3796
3797 // Mount CE mirror
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003798 if (TEMP_FAILURE_RETRY(mount(cePath.c_str(), mirrorVolCePath.c_str(), NULL,
3799 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3800 return error("Failed to mount " + mirrorVolCePath);
3801 }
3802
3803 // Mount DE mirror
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003804 if (TEMP_FAILURE_RETRY(mount(dePath.c_str(), mirrorVolDePath.c_str(), NULL,
3805 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3806 return error("Failed to mount " + mirrorVolDePath);
3807 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003808
3809 // Mount misc CE mirror
3810 if (TEMP_FAILURE_RETRY(mount(miscCePath.c_str(), mirrorVolMiscCePath.c_str(), NULL,
3811 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3812 nullptr)) == -1) {
3813 return error("Failed to mount " + mirrorVolMiscCePath);
3814 }
3815
3816 // Mount misc DE mirror
3817 if (TEMP_FAILURE_RETRY(mount(miscDePath.c_str(), mirrorVolMiscDePath.c_str(), NULL,
3818 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3819 nullptr)) == -1) {
3820 return error("Failed to mount " + mirrorVolMiscDePath);
3821 }
3822
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003823 return ok();
3824}
3825
3826// Unmount volume's CE and DE storage from mirror
3827binder::Status InstalldNativeService::onPrivateVolumeRemoved(
Jooyung Han149be4a2020-01-23 12:45:10 +09003828 const std::optional<std::string>& uuid) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003829 ENFORCE_UID(AID_SYSTEM);
3830 CHECK_ARGUMENT_UUID(uuid);
3831 if (!sAppDataIsolationEnabled) {
3832 return ok();
3833 }
3834 if (!uuid) {
3835 // It happens when private volume failed to mount.
3836 LOG(INFO) << "Ignore unmount uuid=null";
3837 return ok();
3838 }
3839 const char* uuid_ = uuid->c_str();
3840
3841 binder::Status res = ok();
3842
3843 std::string mirrorCeVolPath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
3844 std::string mirrorDeVolPath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
Sanjana Sunil691163d2022-03-28 19:15:54 +00003845 std::string mirrorMiscCeVolPath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
3846 std::string mirrorMiscDeVolPath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003847
Alex Buynytskyy40c45ba2021-11-18 15:16:27 -08003848 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3849
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003850 // Unmount CE storage
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003851 if (TEMP_FAILURE_RETRY(umount(mirrorCeVolPath.c_str())) != 0) {
3852 if (errno != ENOENT) {
3853 res = error(StringPrintf("Failed to umount %s %s", mirrorCeVolPath.c_str(),
3854 strerror(errno)));
3855 }
3856 }
3857 if (delete_dir_contents_and_dir(mirrorCeVolPath, true) != 0) {
3858 res = error("Failed to delete " + mirrorCeVolPath);
3859 }
3860
3861 // Unmount DE storage
3862 if (TEMP_FAILURE_RETRY(umount(mirrorDeVolPath.c_str())) != 0) {
3863 if (errno != ENOENT) {
3864 res = error(StringPrintf("Failed to umount %s %s", mirrorDeVolPath.c_str(),
3865 strerror(errno)));
3866 }
3867 }
3868 if (delete_dir_contents_and_dir(mirrorDeVolPath, true) != 0) {
3869 res = error("Failed to delete " + mirrorDeVolPath);
3870 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003871
3872 // Unmount misc CE storage
3873 if (TEMP_FAILURE_RETRY(umount(mirrorMiscCeVolPath.c_str())) != 0) {
3874 if (errno != ENOENT) {
3875 res = error(StringPrintf("Failed to umount %s %s", mirrorMiscCeVolPath.c_str(),
3876 strerror(errno)));
3877 }
3878 }
3879 if (delete_dir_contents_and_dir(mirrorMiscCeVolPath, true) != 0) {
3880 res = error("Failed to delete " + mirrorMiscCeVolPath);
3881 }
3882
3883 // Unmount misc DE storage
3884 if (TEMP_FAILURE_RETRY(umount(mirrorMiscDeVolPath.c_str())) != 0) {
3885 if (errno != ENOENT) {
3886 res = error(StringPrintf("Failed to umount %s %s", mirrorMiscDeVolPath.c_str(),
3887 strerror(errno)));
3888 }
3889 }
3890 if (delete_dir_contents_and_dir(mirrorMiscDeVolPath, true) != 0) {
3891 res = error("Failed to delete " + mirrorMiscDeVolPath);
3892 }
3893
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003894 return res;
3895}
3896
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003897std::string InstalldNativeService::findDataMediaPath(
Jooyung Han149be4a2020-01-23 12:45:10 +09003898 const std::optional<std::string>& uuid, userid_t userid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003899 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3900 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3901 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
3902 auto resolved = mStorageMounts[path];
3903 if (resolved.empty()) {
3904 LOG(WARNING) << "Failed to find storage mount for " << path;
3905 resolved = path;
3906 }
3907 return StringPrintf("%s/%u", resolved.c_str(), userid);
3908}
3909
Jeff Sharkey325b8c92017-02-21 10:00:53 -07003910binder::Status InstalldNativeService::isQuotaSupported(
Jooyung Han149be4a2020-01-23 12:45:10 +09003911 const std::optional<std::string>& uuid, bool* _aidl_return) {
3912 *_aidl_return = IsQuotaSupported(uuid.value_or(""));
Jeff Sharkey325b8c92017-02-21 10:00:53 -07003913 return ok();
3914}
3915
Calin Juravlebc5ab872018-01-18 22:32:58 -08003916binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
3917 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
Jooyung Han149be4a2020-01-23 12:45:10 +09003918 const std::optional<std::string>& dexMetadata, bool* _aidl_return) {
Calin Juravlebc5ab872018-01-18 22:32:58 -08003919 ENFORCE_UID(AID_SYSTEM);
Steven Moreland3e543b92023-09-07 20:08:15 +00003920 ENFORCE_VALID_USER_OR_NULL(userId);
Calin Juravlebc5ab872018-01-18 22:32:58 -08003921 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003922 CHECK_ARGUMENT_PATH(codePath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003923 LOCK_PACKAGE_USER();
Calin Juravlebc5ab872018-01-18 22:32:58 -08003924
3925 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
3926 dexMetadata);
3927 return ok();
3928}
3929
Narayan Kamath28ab93b2019-05-15 18:29:44 +01003930binder::Status InstalldNativeService::migrateLegacyObbData() {
3931 ENFORCE_UID(AID_SYSTEM);
3932 // NOTE: The lint warning doesn't apply to the use of system(3) with
3933 // absolute parse and no command line arguments.
Cole Faustf6cd58a2022-09-01 17:34:36 -07003934 if (system("/system/bin/migrate_legacy_obb_data") != 0) { // NOLINT(cert-env33-c)
Narayan Kamath28ab93b2019-05-15 18:29:44 +01003935 LOG(ERROR) << "Unable to migrate legacy obb data";
3936 }
3937
3938 return ok();
3939}
3940
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003941binder::Status InstalldNativeService::cleanupInvalidPackageDirs(
3942 const std::optional<std::string>& uuid, int32_t userId, int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00003943 ENFORCE_VALID_USER(userId);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003944 const char* uuid_cstr = uuid ? uuid->c_str() : nullptr;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003945
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003946 if (flags & FLAG_STORAGE_CE) {
3947 auto ce_path = create_data_user_ce_path(uuid_cstr, userId);
3948 cleanup_invalid_package_dirs_under_path(ce_path);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00003949 auto sdksandbox_ce_path =
3950 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/true, userId);
3951 cleanup_invalid_package_dirs_under_path(sdksandbox_ce_path);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003952 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003953
3954 if (flags & FLAG_STORAGE_DE) {
3955 auto de_path = create_data_user_de_path(uuid_cstr, userId);
3956 cleanup_invalid_package_dirs_under_path(de_path);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00003957 auto sdksandbox_de_path =
3958 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/false, userId);
3959 cleanup_invalid_package_dirs_under_path(sdksandbox_de_path);
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003960 }
3961
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003962 return ok();
3963}
3964
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00003965binder::Status InstalldNativeService::getOdexVisibility(
3966 const std::string& packageName, const std::string& apkPath,
3967 const std::string& instructionSet, const std::optional<std::string>& outputPath,
3968 int32_t* _aidl_return) {
3969 ENFORCE_UID(AID_SYSTEM);
3970 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3971 CHECK_ARGUMENT_PATH(apkPath);
3972 CHECK_ARGUMENT_PATH(outputPath);
3973 LOCK_PACKAGE();
3974
3975 const char* apk_path = apkPath.c_str();
3976 const char* instruction_set = instructionSet.c_str();
3977 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
3978
3979 *_aidl_return = get_odex_visibility(apk_path, instruction_set, oat_dir);
3980 return *_aidl_return == -1 ? error() : ok();
3981}
3982
Victor Hsiehc7ab5642023-07-28 15:07:55 -07003983// Creates an auth token to be used in enableFsverity. This token is really to store a proof that
3984// the caller can write to a file, represented by the authFd. Effectively, system_server as the
3985// attacker-in-the-middle cannot enable fs-verity on arbitrary app files. If the FD is not writable,
3986// return null.
3987//
Victor Hsiehc72e4d72024-01-09 15:46:00 -08003988// app process uid is passed for additional ownership check, such that one app can not be
Victor Hsiehc7ab5642023-07-28 15:07:55 -07003989// authenticated for another app's file. These parameters are assumed trusted for this purpose of
3990// consistency check.
3991//
3992// Notably, creating the token allows us to manage the writable FD easily during enableFsverity.
3993// Since enabling fs-verity to a file requires no outstanding writable FD, passing the authFd to the
3994// server allows the server to hold the only reference (as long as the client app doesn't).
3995binder::Status InstalldNativeService::createFsveritySetupAuthToken(
Victor Hsiehc72e4d72024-01-09 15:46:00 -08003996 const ParcelFileDescriptor& authFd, int32_t uid,
Victor Hsiehc7ab5642023-07-28 15:07:55 -07003997 sp<IFsveritySetupAuthToken>* _aidl_return) {
Victor Hsiehc72e4d72024-01-09 15:46:00 -08003998 CHECK_ARGUMENT_APP_ID(multiuser_get_app_id(uid));
3999 ENFORCE_VALID_USER(multiuser_get_user_id(uid));
Victor Hsiehc7ab5642023-07-28 15:07:55 -07004000
4001 auto token = sp<FsveritySetupAuthToken>::make();
Victor Hsiehc72e4d72024-01-09 15:46:00 -08004002 binder::Status status = token->authenticate(authFd, uid);
Victor Hsiehc7ab5642023-07-28 15:07:55 -07004003 if (!status.isOk()) {
4004 return status;
4005 }
4006 *_aidl_return = token;
4007 return ok();
4008}
4009
4010// Enables fs-verity for filePath, which must be an absolute path and the same inode as in the auth
4011// token previously returned from createFsveritySetupAuthToken, and owned by the app uid. As
4012// installd is more privileged than its client / system server, we attempt to limit what a
4013// (compromised) client can do.
4014//
4015// The reason for this app request to go through installd is to avoid exposing a risky area (PKCS#7
4016// signature verification) in the kernel to the app as an attack surface (it can't be system server
4017// because it can't override DAC and manipulate app files). Note that we should be able to drop
4018// these hops and simply the app calls the ioctl, once all upgrading devices run with a kernel
4019// without fs-verity built-in signature (https://r.android.com/2650402).
4020binder::Status InstalldNativeService::enableFsverity(const sp<IFsveritySetupAuthToken>& authToken,
4021 const std::string& filePath,
4022 const std::string& packageName,
4023 int32_t* _aidl_return) {
4024 ENFORCE_UID(AID_SYSTEM);
4025 CHECK_ARGUMENT_PATH(filePath);
4026 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
4027 LOCK_PACKAGE();
4028 if (authToken == nullptr) {
4029 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Received a null auth token");
4030 }
4031
Victor Hsiehc4cff3d2024-01-17 09:02:47 -08004032 // Authenticate to check the targeting file is the same inode as the authFd. With O_PATH, we
4033 // prevent a malicious client from blocking installd by providing a path to FIFO. After the
4034 // authentication, the actual open is safe.
Victor Hsiehc7ab5642023-07-28 15:07:55 -07004035 sp<IBinder> authTokenBinder = IInterface::asBinder(authToken)->localBinder();
4036 if (authTokenBinder == nullptr) {
4037 return exception(binder::Status::EX_SECURITY, "Received a non-local auth token");
4038 }
Victor Hsiehc4cff3d2024-01-17 09:02:47 -08004039 unique_fd pathFd(open(filePath.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_PATH));
4040 // Returns a constant errno to avoid one app probing file existence of the others, before the
4041 // authentication is done.
4042 const int kFixedErrno = EPERM;
4043 if (pathFd.get() < 0) {
4044 PLOG(DEBUG) << "Failed to open the path";
4045 *_aidl_return = kFixedErrno;
Victor Hsiehc7ab5642023-07-28 15:07:55 -07004046 return ok();
4047 }
Victor Hsiehc4cff3d2024-01-17 09:02:47 -08004048 std::string procFdPath(StringPrintf("/proc/self/fd/%d", pathFd.get()));
4049 struct stat stFromPath;
4050 if (stat(procFdPath.c_str(), &stFromPath) < 0) {
4051 PLOG(DEBUG) << "Failed to stat proc fd " << pathFd.get() << " -> " << filePath;
4052 *_aidl_return = kFixedErrno;
4053 return ok();
4054 }
4055 auto authTokenInstance = sp<FsveritySetupAuthToken>::cast(authTokenBinder);
Victor Hsiehc7ab5642023-07-28 15:07:55 -07004056 if (!authTokenInstance->isSameStat(stFromPath)) {
4057 LOG(DEBUG) << "FD authentication failed";
Victor Hsiehc4cff3d2024-01-17 09:02:47 -08004058 *_aidl_return = kFixedErrno;
Victor Hsiehc7ab5642023-07-28 15:07:55 -07004059 return ok();
4060 }
4061
Victor Hsiehc4cff3d2024-01-17 09:02:47 -08004062 unique_fd rfd(open(procFdPath.c_str(), O_RDONLY | O_CLOEXEC));
Victor Hsiehc7ab5642023-07-28 15:07:55 -07004063 fsverity_enable_arg arg = {};
4064 arg.version = 1;
4065 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
4066 arg.block_size = 4096;
4067 if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, &arg) < 0) {
4068 *_aidl_return = errno;
4069 } else {
4070 *_aidl_return = 0;
4071 }
4072 return ok();
4073}
4074
Andreas Gampe02d0de52015-11-11 20:43:16 -08004075} // namespace installd
4076} // namespace android