xref: /aosp_15_r20/frameworks/native/cmds/installd/InstalldNativeService.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1*38e8c45fSAndroid Build Coastguard Worker /*
2*38e8c45fSAndroid Build Coastguard Worker ** Copyright 2008, The Android Open Source Project
3*38e8c45fSAndroid Build Coastguard Worker **
4*38e8c45fSAndroid Build Coastguard Worker ** Licensed under the Apache License, Version 2.0 (the "License");
5*38e8c45fSAndroid Build Coastguard Worker ** you may not use this file except in compliance with the License.
6*38e8c45fSAndroid Build Coastguard Worker ** You may obtain a copy of the License at
7*38e8c45fSAndroid Build Coastguard Worker **
8*38e8c45fSAndroid Build Coastguard Worker **     http://www.apache.org/licenses/LICENSE-2.0
9*38e8c45fSAndroid Build Coastguard Worker **
10*38e8c45fSAndroid Build Coastguard Worker ** Unless required by applicable law or agreed to in writing, software
11*38e8c45fSAndroid Build Coastguard Worker ** distributed under the License is distributed on an "AS IS" BASIS,
12*38e8c45fSAndroid Build Coastguard Worker ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*38e8c45fSAndroid Build Coastguard Worker ** See the License for the specific language governing permissions and
14*38e8c45fSAndroid Build Coastguard Worker ** limitations under the License.
15*38e8c45fSAndroid Build Coastguard Worker */
16*38e8c45fSAndroid Build Coastguard Worker 
17*38e8c45fSAndroid Build Coastguard Worker #include "InstalldNativeService.h"
18*38e8c45fSAndroid Build Coastguard Worker 
19*38e8c45fSAndroid Build Coastguard Worker #include <errno.h>
20*38e8c45fSAndroid Build Coastguard Worker #include <fts.h>
21*38e8c45fSAndroid Build Coastguard Worker #include <inttypes.h>
22*38e8c45fSAndroid Build Coastguard Worker #include <linux/fsverity.h>
23*38e8c45fSAndroid Build Coastguard Worker #include <stdio.h>
24*38e8c45fSAndroid Build Coastguard Worker #include <stdlib.h>
25*38e8c45fSAndroid Build Coastguard Worker #include <string.h>
26*38e8c45fSAndroid Build Coastguard Worker #include <sys/capability.h>
27*38e8c45fSAndroid Build Coastguard Worker #include <sys/file.h>
28*38e8c45fSAndroid Build Coastguard Worker #include <sys/ioctl.h>
29*38e8c45fSAndroid Build Coastguard Worker #include <sys/mman.h>
30*38e8c45fSAndroid Build Coastguard Worker #include <sys/mount.h>
31*38e8c45fSAndroid Build Coastguard Worker #include <sys/resource.h>
32*38e8c45fSAndroid Build Coastguard Worker #include <sys/stat.h>
33*38e8c45fSAndroid Build Coastguard Worker #include <sys/statvfs.h>
34*38e8c45fSAndroid Build Coastguard Worker #include <sys/types.h>
35*38e8c45fSAndroid Build Coastguard Worker #include <sys/wait.h>
36*38e8c45fSAndroid Build Coastguard Worker #include <sys/xattr.h>
37*38e8c45fSAndroid Build Coastguard Worker #include <unistd.h>
38*38e8c45fSAndroid Build Coastguard Worker #include <algorithm>
39*38e8c45fSAndroid Build Coastguard Worker #include <filesystem>
40*38e8c45fSAndroid Build Coastguard Worker #include <fstream>
41*38e8c45fSAndroid Build Coastguard Worker #include <functional>
42*38e8c45fSAndroid Build Coastguard Worker #include <regex>
43*38e8c45fSAndroid Build Coastguard Worker #include <thread>
44*38e8c45fSAndroid Build Coastguard Worker #include <unordered_set>
45*38e8c45fSAndroid Build Coastguard Worker 
46*38e8c45fSAndroid Build Coastguard Worker #include <android-base/file.h>
47*38e8c45fSAndroid Build Coastguard Worker #include <android-base/logging.h>
48*38e8c45fSAndroid Build Coastguard Worker #include <android-base/parseint.h>
49*38e8c45fSAndroid Build Coastguard Worker #include <android-base/properties.h>
50*38e8c45fSAndroid Build Coastguard Worker #include <android-base/scopeguard.h>
51*38e8c45fSAndroid Build Coastguard Worker #include <android-base/stringprintf.h>
52*38e8c45fSAndroid Build Coastguard Worker #include <android-base/strings.h>
53*38e8c45fSAndroid Build Coastguard Worker #include <android-base/unique_fd.h>
54*38e8c45fSAndroid Build Coastguard Worker #include <cutils/ashmem.h>
55*38e8c45fSAndroid Build Coastguard Worker #include <cutils/fs.h>
56*38e8c45fSAndroid Build Coastguard Worker #include <cutils/misc.h>
57*38e8c45fSAndroid Build Coastguard Worker #include <cutils/properties.h>
58*38e8c45fSAndroid Build Coastguard Worker #include <cutils/sched_policy.h>
59*38e8c45fSAndroid Build Coastguard Worker #include <linux/quota.h>
60*38e8c45fSAndroid Build Coastguard Worker #include <log/log.h>               // TODO: Move everything to base/logging.
61*38e8c45fSAndroid Build Coastguard Worker #include <logwrap/logwrap.h>
62*38e8c45fSAndroid Build Coastguard Worker #include <private/android_filesystem_config.h>
63*38e8c45fSAndroid Build Coastguard Worker #include <private/android_projectid_config.h>
64*38e8c45fSAndroid Build Coastguard Worker #include <selinux/android.h>
65*38e8c45fSAndroid Build Coastguard Worker #include <system/thread_defs.h>
66*38e8c45fSAndroid Build Coastguard Worker #include <utils/Trace.h>
67*38e8c45fSAndroid Build Coastguard Worker 
68*38e8c45fSAndroid Build Coastguard Worker #include "dexopt.h"
69*38e8c45fSAndroid Build Coastguard Worker #include "globals.h"
70*38e8c45fSAndroid Build Coastguard Worker #include "installd_deps.h"
71*38e8c45fSAndroid Build Coastguard Worker #include "otapreopt_utils.h"
72*38e8c45fSAndroid Build Coastguard Worker #include "utils.h"
73*38e8c45fSAndroid Build Coastguard Worker 
74*38e8c45fSAndroid Build Coastguard Worker #include "CacheTracker.h"
75*38e8c45fSAndroid Build Coastguard Worker #include "CrateManager.h"
76*38e8c45fSAndroid Build Coastguard Worker #include "MatchExtensionGen.h"
77*38e8c45fSAndroid Build Coastguard Worker #include "QuotaUtils.h"
78*38e8c45fSAndroid Build Coastguard Worker #include "SysTrace.h"
79*38e8c45fSAndroid Build Coastguard Worker 
80*38e8c45fSAndroid Build Coastguard Worker #ifndef LOG_TAG
81*38e8c45fSAndroid Build Coastguard Worker #define LOG_TAG "installd"
82*38e8c45fSAndroid Build Coastguard Worker #endif
83*38e8c45fSAndroid Build Coastguard Worker 
84*38e8c45fSAndroid Build Coastguard Worker #define GRANULAR_LOCKS
85*38e8c45fSAndroid Build Coastguard Worker 
86*38e8c45fSAndroid Build Coastguard Worker using android::base::ParseUint;
87*38e8c45fSAndroid Build Coastguard Worker using android::base::Split;
88*38e8c45fSAndroid Build Coastguard Worker using android::base::StringPrintf;
89*38e8c45fSAndroid Build Coastguard Worker using android::base::unique_fd;
90*38e8c45fSAndroid Build Coastguard Worker using android::os::ParcelFileDescriptor;
91*38e8c45fSAndroid Build Coastguard Worker using std::endl;
92*38e8c45fSAndroid Build Coastguard Worker 
93*38e8c45fSAndroid Build Coastguard Worker namespace android {
94*38e8c45fSAndroid Build Coastguard Worker namespace installd {
95*38e8c45fSAndroid Build Coastguard Worker 
96*38e8c45fSAndroid Build Coastguard Worker // An uuid used in unit tests.
97*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kTestUuid = "TEST";
98*38e8c45fSAndroid Build Coastguard Worker 
99*38e8c45fSAndroid Build Coastguard Worker static constexpr const mode_t kRollbackFolderMode = 0700;
100*38e8c45fSAndroid Build Coastguard Worker 
101*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kCpPath = "/system/bin/cp";
102*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kXattrDefault = "user.default";
103*38e8c45fSAndroid Build Coastguard Worker 
104*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kDataMirrorCePath = "/data_mirror/data_ce";
105*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kDataMirrorDePath = "/data_mirror/data_de";
106*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kMiscMirrorCePath = "/data_mirror/misc_ce";
107*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kMiscMirrorDePath = "/data_mirror/misc_de";
108*38e8c45fSAndroid Build Coastguard Worker 
109*38e8c45fSAndroid Build Coastguard Worker static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
110*38e8c45fSAndroid Build Coastguard Worker 
111*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* PKG_LIB_POSTFIX = "/lib";
112*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
113*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
114*38e8c45fSAndroid Build Coastguard Worker 
115*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kFuseProp = "persist.sys.fuse";
116*38e8c45fSAndroid Build Coastguard Worker 
117*38e8c45fSAndroid Build Coastguard Worker /**
118*38e8c45fSAndroid Build Coastguard Worker  * Property to control if app data isolation is enabled.
119*38e8c45fSAndroid Build Coastguard Worker  */
120*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kAppDataIsolationEnabledProperty = "persist.zygote.app_data_isolation";
121*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kMntSdcardfs = "/mnt/runtime/default/";
122*38e8c45fSAndroid Build Coastguard Worker static constexpr const char* kMntFuse = "/mnt/pass_through/0/";
123*38e8c45fSAndroid Build Coastguard Worker 
124*38e8c45fSAndroid Build Coastguard Worker static std::atomic<bool> sAppDataIsolationEnabled(false);
125*38e8c45fSAndroid Build Coastguard Worker 
126*38e8c45fSAndroid Build Coastguard Worker /**
127*38e8c45fSAndroid Build Coastguard Worker  * Flag to control if project ids are supported for internal storage
128*38e8c45fSAndroid Build Coastguard Worker  */
129*38e8c45fSAndroid Build Coastguard Worker static std::atomic<bool> sUsingProjectIdsFlag(false);
130*38e8c45fSAndroid Build Coastguard Worker static std::once_flag flag;
131*38e8c45fSAndroid Build Coastguard Worker 
132*38e8c45fSAndroid Build Coastguard Worker namespace {
133*38e8c45fSAndroid Build Coastguard Worker 
ok()134*38e8c45fSAndroid Build Coastguard Worker static binder::Status ok() {
135*38e8c45fSAndroid Build Coastguard Worker     return binder::Status::ok();
136*38e8c45fSAndroid Build Coastguard Worker }
137*38e8c45fSAndroid Build Coastguard Worker 
exception(uint32_t code,const std::string & msg)138*38e8c45fSAndroid Build Coastguard Worker static binder::Status exception(uint32_t code, const std::string& msg) {
139*38e8c45fSAndroid Build Coastguard Worker     LOG(ERROR) << msg << " (" << code << ")";
140*38e8c45fSAndroid Build Coastguard Worker     return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
141*38e8c45fSAndroid Build Coastguard Worker }
142*38e8c45fSAndroid Build Coastguard Worker 
error()143*38e8c45fSAndroid Build Coastguard Worker static binder::Status error() {
144*38e8c45fSAndroid Build Coastguard Worker     return binder::Status::fromServiceSpecificError(errno);
145*38e8c45fSAndroid Build Coastguard Worker }
146*38e8c45fSAndroid Build Coastguard Worker 
error(const std::string & msg)147*38e8c45fSAndroid Build Coastguard Worker static binder::Status error(const std::string& msg) {
148*38e8c45fSAndroid Build Coastguard Worker     PLOG(ERROR) << msg;
149*38e8c45fSAndroid Build Coastguard Worker     return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
150*38e8c45fSAndroid Build Coastguard Worker }
151*38e8c45fSAndroid Build Coastguard Worker 
error(uint32_t code,const std::string & msg)152*38e8c45fSAndroid Build Coastguard Worker static binder::Status error(uint32_t code, const std::string& msg) {
153*38e8c45fSAndroid Build Coastguard Worker     LOG(ERROR) << msg << " (" << code << ")";
154*38e8c45fSAndroid Build Coastguard Worker     return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
155*38e8c45fSAndroid Build Coastguard Worker }
156*38e8c45fSAndroid Build Coastguard Worker 
checkUid(uid_t expectedUid)157*38e8c45fSAndroid Build Coastguard Worker binder::Status checkUid(uid_t expectedUid) {
158*38e8c45fSAndroid Build Coastguard Worker     uid_t uid = IPCThreadState::self()->getCallingUid();
159*38e8c45fSAndroid Build Coastguard Worker     if (uid == expectedUid || uid == AID_ROOT) {
160*38e8c45fSAndroid Build Coastguard Worker         return ok();
161*38e8c45fSAndroid Build Coastguard Worker     } else {
162*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_SECURITY,
163*38e8c45fSAndroid Build Coastguard Worker                 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
164*38e8c45fSAndroid Build Coastguard Worker     }
165*38e8c45fSAndroid Build Coastguard Worker }
166*38e8c45fSAndroid Build Coastguard Worker 
checkArgumentUuid(const std::optional<std::string> & uuid)167*38e8c45fSAndroid Build Coastguard Worker binder::Status checkArgumentUuid(const std::optional<std::string>& uuid) {
168*38e8c45fSAndroid Build Coastguard Worker     if (!uuid || is_valid_filename(*uuid)) {
169*38e8c45fSAndroid Build Coastguard Worker         return ok();
170*38e8c45fSAndroid Build Coastguard Worker     } else {
171*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
172*38e8c45fSAndroid Build Coastguard Worker                 StringPrintf("UUID %s is malformed", uuid->c_str()));
173*38e8c45fSAndroid Build Coastguard Worker     }
174*38e8c45fSAndroid Build Coastguard Worker }
175*38e8c45fSAndroid Build Coastguard Worker 
checkArgumentUuidTestOrNull(const std::optional<std::string> & uuid)176*38e8c45fSAndroid Build Coastguard Worker binder::Status checkArgumentUuidTestOrNull(const std::optional<std::string>& uuid) {
177*38e8c45fSAndroid Build Coastguard Worker     if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
178*38e8c45fSAndroid Build Coastguard Worker         return ok();
179*38e8c45fSAndroid Build Coastguard Worker     } else {
180*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
181*38e8c45fSAndroid Build Coastguard Worker                 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
182*38e8c45fSAndroid Build Coastguard Worker     }
183*38e8c45fSAndroid Build Coastguard Worker }
184*38e8c45fSAndroid Build Coastguard Worker 
checkArgumentPackageName(const std::string & packageName)185*38e8c45fSAndroid Build Coastguard Worker binder::Status checkArgumentPackageName(const std::string& packageName) {
186*38e8c45fSAndroid Build Coastguard Worker     if (is_valid_package_name(packageName)) {
187*38e8c45fSAndroid Build Coastguard Worker         return ok();
188*38e8c45fSAndroid Build Coastguard Worker     } else {
189*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
190*38e8c45fSAndroid Build Coastguard Worker                 StringPrintf("Package name %s is malformed", packageName.c_str()));
191*38e8c45fSAndroid Build Coastguard Worker     }
192*38e8c45fSAndroid Build Coastguard Worker }
193*38e8c45fSAndroid Build Coastguard Worker 
checkArgumentPath(const std::string & path)194*38e8c45fSAndroid Build Coastguard Worker binder::Status checkArgumentPath(const std::string& path) {
195*38e8c45fSAndroid Build Coastguard Worker     if (path.empty()) {
196*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
197*38e8c45fSAndroid Build Coastguard Worker     }
198*38e8c45fSAndroid Build Coastguard Worker     if (path[0] != '/') {
199*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
200*38e8c45fSAndroid Build Coastguard Worker                 StringPrintf("Path %s is relative", path.c_str()));
201*38e8c45fSAndroid Build Coastguard Worker     }
202*38e8c45fSAndroid Build Coastguard Worker     if ((path + '/').find("/../") != std::string::npos) {
203*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
204*38e8c45fSAndroid Build Coastguard Worker                 StringPrintf("Path %s is shady", path.c_str()));
205*38e8c45fSAndroid Build Coastguard Worker     }
206*38e8c45fSAndroid Build Coastguard Worker     for (const char& c : path) {
207*38e8c45fSAndroid Build Coastguard Worker         if (c == '\0' || c == '\n') {
208*38e8c45fSAndroid Build Coastguard Worker             return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
209*38e8c45fSAndroid Build Coastguard Worker                     StringPrintf("Path %s is malformed", path.c_str()));
210*38e8c45fSAndroid Build Coastguard Worker         }
211*38e8c45fSAndroid Build Coastguard Worker     }
212*38e8c45fSAndroid Build Coastguard Worker     return ok();
213*38e8c45fSAndroid Build Coastguard Worker }
214*38e8c45fSAndroid Build Coastguard Worker 
checkArgumentPath(const std::optional<std::string> & path)215*38e8c45fSAndroid Build Coastguard Worker binder::Status checkArgumentPath(const std::optional<std::string>& path) {
216*38e8c45fSAndroid Build Coastguard Worker     if (path) {
217*38e8c45fSAndroid Build Coastguard Worker         return checkArgumentPath(*path);
218*38e8c45fSAndroid Build Coastguard Worker     } else {
219*38e8c45fSAndroid Build Coastguard Worker         return ok();
220*38e8c45fSAndroid Build Coastguard Worker     }
221*38e8c45fSAndroid Build Coastguard Worker }
222*38e8c45fSAndroid Build Coastguard Worker 
checkArgumentFileName(const std::string & path)223*38e8c45fSAndroid Build Coastguard Worker binder::Status checkArgumentFileName(const std::string& path) {
224*38e8c45fSAndroid Build Coastguard Worker     if (path.empty()) {
225*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing name");
226*38e8c45fSAndroid Build Coastguard Worker     }
227*38e8c45fSAndroid Build Coastguard Worker     for (const char& c : path) {
228*38e8c45fSAndroid Build Coastguard Worker         if (c == '\0' || c == '\n' || c == '/') {
229*38e8c45fSAndroid Build Coastguard Worker             return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
230*38e8c45fSAndroid Build Coastguard Worker                              StringPrintf("Name %s is malformed", path.c_str()));
231*38e8c45fSAndroid Build Coastguard Worker         }
232*38e8c45fSAndroid Build Coastguard Worker     }
233*38e8c45fSAndroid Build Coastguard Worker     return ok();
234*38e8c45fSAndroid Build Coastguard Worker }
235*38e8c45fSAndroid Build Coastguard Worker 
checkArgumentAppId(int32_t appId)236*38e8c45fSAndroid Build Coastguard Worker binder::Status checkArgumentAppId(int32_t appId) {
237*38e8c45fSAndroid Build Coastguard Worker     if (FIRST_APPLICATION_UID <= appId && appId <= LAST_APPLICATION_UID) {
238*38e8c45fSAndroid Build Coastguard Worker         return ok();
239*38e8c45fSAndroid Build Coastguard Worker     }
240*38e8c45fSAndroid Build Coastguard Worker     return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
241*38e8c45fSAndroid Build Coastguard Worker                      StringPrintf("appId %d is outside of the range", appId));
242*38e8c45fSAndroid Build Coastguard Worker }
243*38e8c45fSAndroid Build Coastguard Worker 
244*38e8c45fSAndroid Build Coastguard Worker #define ENFORCE_UID(uid) {                                  \
245*38e8c45fSAndroid Build Coastguard Worker     binder::Status status = checkUid((uid));                \
246*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {                                   \
247*38e8c45fSAndroid Build Coastguard Worker         return status;                                      \
248*38e8c45fSAndroid Build Coastguard Worker     }                                                       \
249*38e8c45fSAndroid Build Coastguard Worker }
250*38e8c45fSAndroid Build Coastguard Worker 
251*38e8c45fSAndroid Build Coastguard Worker // we could have tighter checks, but this is only to avoid hard errors. Negative values are defined
252*38e8c45fSAndroid Build Coastguard Worker // in UserHandle.java and carry specific meanings that may not be handled by certain APIs here.
253*38e8c45fSAndroid Build Coastguard Worker #define ENFORCE_VALID_USER(userId)                                                               \
254*38e8c45fSAndroid Build Coastguard Worker     {                                                                                            \
255*38e8c45fSAndroid Build Coastguard Worker         if (static_cast<uid_t>(userId) >= std::numeric_limits<uid_t>::max() / AID_USER_OFFSET) { \
256*38e8c45fSAndroid Build Coastguard Worker             return error("userId invalid: " + std::to_string(userId));                           \
257*38e8c45fSAndroid Build Coastguard Worker         }                                                                                        \
258*38e8c45fSAndroid Build Coastguard Worker     }
259*38e8c45fSAndroid Build Coastguard Worker 
260*38e8c45fSAndroid Build Coastguard Worker #define ENFORCE_VALID_USER_OR_NULL(userId)             \
261*38e8c45fSAndroid Build Coastguard Worker     {                                                  \
262*38e8c45fSAndroid Build Coastguard Worker         if (static_cast<uid_t>(userId) != USER_NULL) { \
263*38e8c45fSAndroid Build Coastguard Worker             ENFORCE_VALID_USER(userId);                \
264*38e8c45fSAndroid Build Coastguard Worker         }                                              \
265*38e8c45fSAndroid Build Coastguard Worker     }
266*38e8c45fSAndroid Build Coastguard Worker 
267*38e8c45fSAndroid Build Coastguard Worker #define CHECK_ARGUMENT_UUID(uuid) {                         \
268*38e8c45fSAndroid Build Coastguard Worker     binder::Status status = checkArgumentUuid((uuid));      \
269*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {                                   \
270*38e8c45fSAndroid Build Coastguard Worker         return status;                                      \
271*38e8c45fSAndroid Build Coastguard Worker     }                                                       \
272*38e8c45fSAndroid Build Coastguard Worker }
273*38e8c45fSAndroid Build Coastguard Worker 
274*38e8c45fSAndroid Build Coastguard Worker #define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) {         \
275*38e8c45fSAndroid Build Coastguard Worker     auto status = checkArgumentUuidTestOrNull(uuid);        \
276*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {                                   \
277*38e8c45fSAndroid Build Coastguard Worker         return status;                                      \
278*38e8c45fSAndroid Build Coastguard Worker     }                                                       \
279*38e8c45fSAndroid Build Coastguard Worker }                                                           \
280*38e8c45fSAndroid Build Coastguard Worker 
281*38e8c45fSAndroid Build Coastguard Worker #define CHECK_ARGUMENT_PACKAGE_NAME(packageName) {          \
282*38e8c45fSAndroid Build Coastguard Worker     binder::Status status =                                 \
283*38e8c45fSAndroid Build Coastguard Worker             checkArgumentPackageName((packageName));        \
284*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {                                   \
285*38e8c45fSAndroid Build Coastguard Worker         return status;                                      \
286*38e8c45fSAndroid Build Coastguard Worker     }                                                       \
287*38e8c45fSAndroid Build Coastguard Worker }
288*38e8c45fSAndroid Build Coastguard Worker 
289*38e8c45fSAndroid Build Coastguard Worker #define CHECK_ARGUMENT_PATH(path) {                         \
290*38e8c45fSAndroid Build Coastguard Worker     binder::Status status = checkArgumentPath((path));      \
291*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {                                   \
292*38e8c45fSAndroid Build Coastguard Worker         return status;                                      \
293*38e8c45fSAndroid Build Coastguard Worker     }                                                       \
294*38e8c45fSAndroid Build Coastguard Worker }
295*38e8c45fSAndroid Build Coastguard Worker 
296*38e8c45fSAndroid Build Coastguard Worker #define CHECK_ARGUMENT_FILE_NAME(path)                         \
297*38e8c45fSAndroid Build Coastguard Worker     {                                                          \
298*38e8c45fSAndroid Build Coastguard Worker         binder::Status status = checkArgumentFileName((path)); \
299*38e8c45fSAndroid Build Coastguard Worker         if (!status.isOk()) {                                  \
300*38e8c45fSAndroid Build Coastguard Worker             return status;                                     \
301*38e8c45fSAndroid Build Coastguard Worker         }                                                      \
302*38e8c45fSAndroid Build Coastguard Worker     }
303*38e8c45fSAndroid Build Coastguard Worker 
304*38e8c45fSAndroid Build Coastguard Worker #define CHECK_ARGUMENT_APP_ID(appId)                         \
305*38e8c45fSAndroid Build Coastguard Worker     {                                                        \
306*38e8c45fSAndroid Build Coastguard Worker         binder::Status status = checkArgumentAppId((appId)); \
307*38e8c45fSAndroid Build Coastguard Worker         if (!status.isOk()) {                                \
308*38e8c45fSAndroid Build Coastguard Worker             return status;                                   \
309*38e8c45fSAndroid Build Coastguard Worker         }                                                    \
310*38e8c45fSAndroid Build Coastguard Worker     }
311*38e8c45fSAndroid Build Coastguard Worker 
312*38e8c45fSAndroid Build Coastguard Worker #ifdef GRANULAR_LOCKS
313*38e8c45fSAndroid Build Coastguard Worker 
314*38e8c45fSAndroid Build Coastguard Worker /**
315*38e8c45fSAndroid Build Coastguard Worker  * This class obtains in constructor and keeps the local strong pointer to the RefLock.
316*38e8c45fSAndroid Build Coastguard Worker  * On destruction, it checks if there are any other strong pointers, and remove the map entry if
317*38e8c45fSAndroid Build Coastguard Worker  * this was the last one.
318*38e8c45fSAndroid Build Coastguard Worker  */
319*38e8c45fSAndroid Build Coastguard Worker template <class Key, class Mutex>
320*38e8c45fSAndroid Build Coastguard Worker struct LocalLockHolder {
321*38e8c45fSAndroid Build Coastguard Worker     using WeakPointer = std::weak_ptr<Mutex>;
322*38e8c45fSAndroid Build Coastguard Worker     using StrongPointer = std::shared_ptr<Mutex>;
323*38e8c45fSAndroid Build Coastguard Worker     using Map = std::unordered_map<Key, WeakPointer>;
324*38e8c45fSAndroid Build Coastguard Worker     using MapLock = std::recursive_mutex;
325*38e8c45fSAndroid Build Coastguard Worker 
LocalLockHolderandroid::installd::__anonc696d79f0111::LocalLockHolder326*38e8c45fSAndroid Build Coastguard Worker     LocalLockHolder(Key key, Map& map, MapLock& mapLock)
327*38e8c45fSAndroid Build Coastguard Worker           : mKey(std::move(key)), mMap(map), mMapLock(mapLock) {
328*38e8c45fSAndroid Build Coastguard Worker         std::lock_guard lock(mMapLock);
329*38e8c45fSAndroid Build Coastguard Worker         auto& weakPtr = mMap[mKey];
330*38e8c45fSAndroid Build Coastguard Worker 
331*38e8c45fSAndroid Build Coastguard Worker         // Check if the RefLock is still alive.
332*38e8c45fSAndroid Build Coastguard Worker         mRefLock = weakPtr.lock();
333*38e8c45fSAndroid Build Coastguard Worker         if (!mRefLock) {
334*38e8c45fSAndroid Build Coastguard Worker             // Create a new lock.
335*38e8c45fSAndroid Build Coastguard Worker             mRefLock = std::make_shared<Mutex>();
336*38e8c45fSAndroid Build Coastguard Worker             weakPtr = mRefLock;
337*38e8c45fSAndroid Build Coastguard Worker         }
338*38e8c45fSAndroid Build Coastguard Worker     }
LocalLockHolderandroid::installd::__anonc696d79f0111::LocalLockHolder339*38e8c45fSAndroid Build Coastguard Worker     LocalLockHolder(LocalLockHolder&& other) noexcept
340*38e8c45fSAndroid Build Coastguard Worker           : mKey(std::move(other.mKey)),
341*38e8c45fSAndroid Build Coastguard Worker             mMap(other.mMap),
342*38e8c45fSAndroid Build Coastguard Worker             mMapLock(other.mMapLock),
343*38e8c45fSAndroid Build Coastguard Worker             mRefLock(std::move(other.mRefLock)) {
344*38e8c45fSAndroid Build Coastguard Worker         other.mRefLock.reset();
345*38e8c45fSAndroid Build Coastguard Worker     }
~LocalLockHolderandroid::installd::__anonc696d79f0111::LocalLockHolder346*38e8c45fSAndroid Build Coastguard Worker     ~LocalLockHolder() {
347*38e8c45fSAndroid Build Coastguard Worker         if (!mRefLock) {
348*38e8c45fSAndroid Build Coastguard Worker             return;
349*38e8c45fSAndroid Build Coastguard Worker         }
350*38e8c45fSAndroid Build Coastguard Worker 
351*38e8c45fSAndroid Build Coastguard Worker         std::lock_guard lock(mMapLock);
352*38e8c45fSAndroid Build Coastguard Worker         // Clear the strong pointer.
353*38e8c45fSAndroid Build Coastguard Worker         mRefLock.reset();
354*38e8c45fSAndroid Build Coastguard Worker         auto found = mMap.find(mKey);
355*38e8c45fSAndroid Build Coastguard Worker         if (found == mMap.end()) {
356*38e8c45fSAndroid Build Coastguard Worker             return;
357*38e8c45fSAndroid Build Coastguard Worker         }
358*38e8c45fSAndroid Build Coastguard Worker         const auto& weakPtr = found->second;
359*38e8c45fSAndroid Build Coastguard Worker         // If this was the last pointer then it's ok to remove the map entry.
360*38e8c45fSAndroid Build Coastguard Worker         if (weakPtr.expired()) {
361*38e8c45fSAndroid Build Coastguard Worker             mMap.erase(found);
362*38e8c45fSAndroid Build Coastguard Worker         }
363*38e8c45fSAndroid Build Coastguard Worker     }
364*38e8c45fSAndroid Build Coastguard Worker 
lockandroid::installd::__anonc696d79f0111::LocalLockHolder365*38e8c45fSAndroid Build Coastguard Worker     void lock() { mRefLock->lock(); }
unlockandroid::installd::__anonc696d79f0111::LocalLockHolder366*38e8c45fSAndroid Build Coastguard Worker     void unlock() { mRefLock->unlock(); }
lock_sharedandroid::installd::__anonc696d79f0111::LocalLockHolder367*38e8c45fSAndroid Build Coastguard Worker     void lock_shared() { mRefLock->lock_shared(); }
unlock_sharedandroid::installd::__anonc696d79f0111::LocalLockHolder368*38e8c45fSAndroid Build Coastguard Worker     void unlock_shared() { mRefLock->unlock_shared(); }
369*38e8c45fSAndroid Build Coastguard Worker 
370*38e8c45fSAndroid Build Coastguard Worker private:
371*38e8c45fSAndroid Build Coastguard Worker     Key mKey;
372*38e8c45fSAndroid Build Coastguard Worker     Map& mMap;
373*38e8c45fSAndroid Build Coastguard Worker     MapLock& mMapLock;
374*38e8c45fSAndroid Build Coastguard Worker     StrongPointer mRefLock;
375*38e8c45fSAndroid Build Coastguard Worker };
376*38e8c45fSAndroid Build Coastguard Worker 
377*38e8c45fSAndroid Build Coastguard Worker using UserLock = LocalLockHolder<userid_t, std::shared_mutex>;
378*38e8c45fSAndroid Build Coastguard Worker using UserWriteLockGuard = std::unique_lock<UserLock>;
379*38e8c45fSAndroid Build Coastguard Worker using UserReadLockGuard = std::shared_lock<UserLock>;
380*38e8c45fSAndroid Build Coastguard Worker 
381*38e8c45fSAndroid Build Coastguard Worker using PackageLock = LocalLockHolder<std::string, std::recursive_mutex>;
382*38e8c45fSAndroid Build Coastguard Worker using PackageLockGuard = std::lock_guard<PackageLock>;
383*38e8c45fSAndroid Build Coastguard Worker 
384*38e8c45fSAndroid Build Coastguard Worker #define LOCK_USER()                                     \
385*38e8c45fSAndroid Build Coastguard Worker     UserLock localUserLock(userId, mUserIdLock, mLock); \
386*38e8c45fSAndroid Build Coastguard Worker     UserWriteLockGuard userLock(localUserLock)
387*38e8c45fSAndroid Build Coastguard Worker 
388*38e8c45fSAndroid Build Coastguard Worker #define LOCK_USER_READ()                                \
389*38e8c45fSAndroid Build Coastguard Worker     UserLock localUserLock(userId, mUserIdLock, mLock); \
390*38e8c45fSAndroid Build Coastguard Worker     UserReadLockGuard userLock(localUserLock)
391*38e8c45fSAndroid Build Coastguard Worker 
392*38e8c45fSAndroid Build Coastguard Worker #define LOCK_PACKAGE()                                                  \
393*38e8c45fSAndroid Build Coastguard Worker     PackageLock localPackageLock(packageName, mPackageNameLock, mLock); \
394*38e8c45fSAndroid Build Coastguard Worker     PackageLockGuard packageLock(localPackageLock)
395*38e8c45fSAndroid Build Coastguard Worker 
396*38e8c45fSAndroid Build Coastguard Worker #define LOCK_PACKAGE_USER() \
397*38e8c45fSAndroid Build Coastguard Worker     LOCK_USER_READ();       \
398*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE()
399*38e8c45fSAndroid Build Coastguard Worker 
400*38e8c45fSAndroid Build Coastguard Worker #else
401*38e8c45fSAndroid Build Coastguard Worker 
402*38e8c45fSAndroid Build Coastguard Worker #define LOCK_USER() std::lock_guard lock(mLock)
403*38e8c45fSAndroid Build Coastguard Worker #define LOCK_PACKAGE() std::lock_guard lock(mLock)
404*38e8c45fSAndroid Build Coastguard Worker #define LOCK_PACKAGE_USER() \
405*38e8c45fSAndroid Build Coastguard Worker     (void)userId;           \
406*38e8c45fSAndroid Build Coastguard Worker     std::lock_guard lock(mLock)
407*38e8c45fSAndroid Build Coastguard Worker 
408*38e8c45fSAndroid Build Coastguard Worker #endif // GRANULAR_LOCKS
409*38e8c45fSAndroid Build Coastguard Worker 
410*38e8c45fSAndroid Build Coastguard Worker }  // namespace
411*38e8c45fSAndroid Build Coastguard Worker 
authenticate(const ParcelFileDescriptor & authFd,int32_t uid)412*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::FsveritySetupAuthToken::authenticate(
413*38e8c45fSAndroid Build Coastguard Worker         const ParcelFileDescriptor& authFd, int32_t uid) {
414*38e8c45fSAndroid Build Coastguard Worker     int open_flags = fcntl(authFd.get(), F_GETFL);
415*38e8c45fSAndroid Build Coastguard Worker     if (open_flags < 0) {
416*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_SERVICE_SPECIFIC, "fcntl failed");
417*38e8c45fSAndroid Build Coastguard Worker     }
418*38e8c45fSAndroid Build Coastguard Worker     if ((open_flags & O_ACCMODE) != O_WRONLY && (open_flags & O_ACCMODE) != O_RDWR) {
419*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_SECURITY, "Received FD with unexpected open flag");
420*38e8c45fSAndroid Build Coastguard Worker     }
421*38e8c45fSAndroid Build Coastguard Worker     if (fstat(authFd.get(), &this->mStatFromAuthFd) < 0) {
422*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_SERVICE_SPECIFIC, "fstat failed");
423*38e8c45fSAndroid Build Coastguard Worker     }
424*38e8c45fSAndroid Build Coastguard Worker     if (!S_ISREG(this->mStatFromAuthFd.st_mode)) {
425*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_SECURITY, "Not a regular file");
426*38e8c45fSAndroid Build Coastguard Worker     }
427*38e8c45fSAndroid Build Coastguard Worker     // Don't accept a file owned by a different app.
428*38e8c45fSAndroid Build Coastguard Worker     if (this->mStatFromAuthFd.st_uid != (uid_t)uid) {
429*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_SERVICE_SPECIFIC, "File not owned by uid");
430*38e8c45fSAndroid Build Coastguard Worker     }
431*38e8c45fSAndroid Build Coastguard Worker     return ok();
432*38e8c45fSAndroid Build Coastguard Worker }
433*38e8c45fSAndroid Build Coastguard Worker 
isSameStat(const struct stat & st) const434*38e8c45fSAndroid Build Coastguard Worker bool InstalldNativeService::FsveritySetupAuthToken::isSameStat(const struct stat& st) const {
435*38e8c45fSAndroid Build Coastguard Worker     return memcmp(&st, &mStatFromAuthFd, sizeof(st)) == 0;
436*38e8c45fSAndroid Build Coastguard Worker }
437*38e8c45fSAndroid Build Coastguard Worker 
start()438*38e8c45fSAndroid Build Coastguard Worker status_t InstalldNativeService::start() {
439*38e8c45fSAndroid Build Coastguard Worker     IPCThreadState::self()->disableBackgroundScheduling(true);
440*38e8c45fSAndroid Build Coastguard Worker     status_t ret = BinderService<InstalldNativeService>::publish();
441*38e8c45fSAndroid Build Coastguard Worker     if (ret != android::OK) {
442*38e8c45fSAndroid Build Coastguard Worker         return ret;
443*38e8c45fSAndroid Build Coastguard Worker     }
444*38e8c45fSAndroid Build Coastguard Worker     sp<ProcessState> ps(ProcessState::self());
445*38e8c45fSAndroid Build Coastguard Worker     ps->startThreadPool();
446*38e8c45fSAndroid Build Coastguard Worker     ps->giveThreadPoolName();
447*38e8c45fSAndroid Build Coastguard Worker     sAppDataIsolationEnabled = android::base::GetBoolProperty(
448*38e8c45fSAndroid Build Coastguard Worker             kAppDataIsolationEnabledProperty, true);
449*38e8c45fSAndroid Build Coastguard Worker     return android::OK;
450*38e8c45fSAndroid Build Coastguard Worker }
451*38e8c45fSAndroid Build Coastguard Worker 
dump(int fd,const Vector<String16> &)452*38e8c45fSAndroid Build Coastguard Worker status_t InstalldNativeService::dump(int fd, const Vector<String16>& /* args */) {
453*38e8c45fSAndroid Build Coastguard Worker     {
454*38e8c45fSAndroid Build Coastguard Worker         std::lock_guard<std::recursive_mutex> lock(mMountsLock);
455*38e8c45fSAndroid Build Coastguard Worker         dprintf(fd, "Storage mounts:\n");
456*38e8c45fSAndroid Build Coastguard Worker         for (const auto& n : mStorageMounts) {
457*38e8c45fSAndroid Build Coastguard Worker             dprintf(fd, "    %s = %s\n", n.first.c_str(), n.second.c_str());
458*38e8c45fSAndroid Build Coastguard Worker         }
459*38e8c45fSAndroid Build Coastguard Worker     }
460*38e8c45fSAndroid Build Coastguard Worker 
461*38e8c45fSAndroid Build Coastguard Worker     {
462*38e8c45fSAndroid Build Coastguard Worker         std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
463*38e8c45fSAndroid Build Coastguard Worker         dprintf(fd, "Per-UID cache quotas:\n");
464*38e8c45fSAndroid Build Coastguard Worker         for (const auto& n : mCacheQuotas) {
465*38e8c45fSAndroid Build Coastguard Worker             dprintf(fd, "    %d = %" PRId64 "\n", n.first, n.second);
466*38e8c45fSAndroid Build Coastguard Worker         }
467*38e8c45fSAndroid Build Coastguard Worker     }
468*38e8c45fSAndroid Build Coastguard Worker 
469*38e8c45fSAndroid Build Coastguard Worker     dprintf(fd, "is_dexopt_blocked:%d\n", android::installd::is_dexopt_blocked());
470*38e8c45fSAndroid Build Coastguard Worker 
471*38e8c45fSAndroid Build Coastguard Worker     return NO_ERROR;
472*38e8c45fSAndroid Build Coastguard Worker }
473*38e8c45fSAndroid Build Coastguard Worker 
474*38e8c45fSAndroid Build Coastguard Worker constexpr const char kXattrRestoreconInProgress[] = "user.restorecon_in_progress";
475*38e8c45fSAndroid Build Coastguard Worker 
lgetfilecon(const std::string & path)476*38e8c45fSAndroid Build Coastguard Worker static std::string lgetfilecon(const std::string& path) {
477*38e8c45fSAndroid Build Coastguard Worker     char* context;
478*38e8c45fSAndroid Build Coastguard Worker     if (::lgetfilecon(path.c_str(), &context) < 0) {
479*38e8c45fSAndroid Build Coastguard Worker         PLOG(ERROR) << "Failed to lgetfilecon for " << path;
480*38e8c45fSAndroid Build Coastguard Worker         return {};
481*38e8c45fSAndroid Build Coastguard Worker     }
482*38e8c45fSAndroid Build Coastguard Worker     std::string result{context};
483*38e8c45fSAndroid Build Coastguard Worker     free(context);
484*38e8c45fSAndroid Build Coastguard Worker     return result;
485*38e8c45fSAndroid Build Coastguard Worker }
486*38e8c45fSAndroid Build Coastguard Worker 
getRestoreconInProgress(const std::string & path)487*38e8c45fSAndroid Build Coastguard Worker static bool getRestoreconInProgress(const std::string& path) {
488*38e8c45fSAndroid Build Coastguard Worker     bool inProgress = false;
489*38e8c45fSAndroid Build Coastguard Worker     if (getxattr(path.c_str(), kXattrRestoreconInProgress, &inProgress, sizeof(inProgress)) !=
490*38e8c45fSAndroid Build Coastguard Worker         sizeof(inProgress)) {
491*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENODATA) {
492*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << "Failed to check in-progress restorecon for " << path;
493*38e8c45fSAndroid Build Coastguard Worker         }
494*38e8c45fSAndroid Build Coastguard Worker         return false;
495*38e8c45fSAndroid Build Coastguard Worker     }
496*38e8c45fSAndroid Build Coastguard Worker     return inProgress;
497*38e8c45fSAndroid Build Coastguard Worker }
498*38e8c45fSAndroid Build Coastguard Worker 
499*38e8c45fSAndroid Build Coastguard Worker struct RestoreconInProgress {
RestoreconInProgressandroid::installd::RestoreconInProgress500*38e8c45fSAndroid Build Coastguard Worker     explicit RestoreconInProgress(const std::string& path) : mPath(path) {
501*38e8c45fSAndroid Build Coastguard Worker         bool inProgress = true;
502*38e8c45fSAndroid Build Coastguard Worker         if (setxattr(mPath.c_str(), kXattrRestoreconInProgress, &inProgress, sizeof(inProgress),
503*38e8c45fSAndroid Build Coastguard Worker                      0) != 0) {
504*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << "Failed to set in-progress restorecon for " << path;
505*38e8c45fSAndroid Build Coastguard Worker         }
506*38e8c45fSAndroid Build Coastguard Worker     }
~RestoreconInProgressandroid::installd::RestoreconInProgress507*38e8c45fSAndroid Build Coastguard Worker     ~RestoreconInProgress() {
508*38e8c45fSAndroid Build Coastguard Worker         if (removexattr(mPath.c_str(), kXattrRestoreconInProgress) < 0) {
509*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << "Failed to clear in-progress restorecon for " << mPath;
510*38e8c45fSAndroid Build Coastguard Worker         }
511*38e8c45fSAndroid Build Coastguard Worker     }
512*38e8c45fSAndroid Build Coastguard Worker 
513*38e8c45fSAndroid Build Coastguard Worker private:
514*38e8c45fSAndroid Build Coastguard Worker     const std::string& mPath;
515*38e8c45fSAndroid Build Coastguard Worker };
516*38e8c45fSAndroid Build Coastguard Worker 
517*38e8c45fSAndroid Build Coastguard Worker /**
518*38e8c45fSAndroid Build Coastguard Worker  * Perform restorecon of the given path, but only perform recursive restorecon
519*38e8c45fSAndroid Build Coastguard Worker  * if the label of that top-level file actually changed.  This can save us
520*38e8c45fSAndroid Build Coastguard Worker  * significant time by avoiding no-op traversals of large filesystem trees.
521*38e8c45fSAndroid Build Coastguard Worker  */
restorecon_app_data_lazy(const std::string & path,const std::string & seInfo,uid_t uid,bool existing)522*38e8c45fSAndroid Build Coastguard Worker static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
523*38e8c45fSAndroid Build Coastguard Worker         bool existing) {
524*38e8c45fSAndroid Build Coastguard Worker     ScopedTrace tracer("restorecon-lazy");
525*38e8c45fSAndroid Build Coastguard Worker     if (!existing) {
526*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("new-path");
527*38e8c45fSAndroid Build Coastguard Worker         if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
528*38e8c45fSAndroid Build Coastguard Worker                 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
529*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << "Failed recursive restorecon for " << path;
530*38e8c45fSAndroid Build Coastguard Worker             return -1;
531*38e8c45fSAndroid Build Coastguard Worker         }
532*38e8c45fSAndroid Build Coastguard Worker         return 0;
533*38e8c45fSAndroid Build Coastguard Worker     }
534*38e8c45fSAndroid Build Coastguard Worker 
535*38e8c45fSAndroid Build Coastguard Worker     // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
536*38e8c45fSAndroid Build Coastguard Worker 
537*38e8c45fSAndroid Build Coastguard Worker     // Check to see if there was an interrupted operation.
538*38e8c45fSAndroid Build Coastguard Worker     bool inProgress = getRestoreconInProgress(path);
539*38e8c45fSAndroid Build Coastguard Worker     std::string before, after;
540*38e8c45fSAndroid Build Coastguard Worker     if (!inProgress) {
541*38e8c45fSAndroid Build Coastguard Worker         if (before = lgetfilecon(path); before.empty()) {
542*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << "Failed before getfilecon for " << path;
543*38e8c45fSAndroid Build Coastguard Worker             return -1;
544*38e8c45fSAndroid Build Coastguard Worker         }
545*38e8c45fSAndroid Build Coastguard Worker         if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
546*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << "Failed top-level restorecon for " << path;
547*38e8c45fSAndroid Build Coastguard Worker             return -1;
548*38e8c45fSAndroid Build Coastguard Worker         }
549*38e8c45fSAndroid Build Coastguard Worker         if (after = lgetfilecon(path); after.empty()) {
550*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << "Failed after getfilecon for " << path;
551*38e8c45fSAndroid Build Coastguard Worker             return -1;
552*38e8c45fSAndroid Build Coastguard Worker         }
553*38e8c45fSAndroid Build Coastguard Worker     }
554*38e8c45fSAndroid Build Coastguard Worker 
555*38e8c45fSAndroid Build Coastguard Worker     // If the initial top-level restorecon above changed the label, then go
556*38e8c45fSAndroid Build Coastguard Worker     // back and restorecon everything recursively
557*38e8c45fSAndroid Build Coastguard Worker     if (inProgress || before != after) {
558*38e8c45fSAndroid Build Coastguard Worker         if (existing) {
559*38e8c45fSAndroid Build Coastguard Worker             LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
560*38e8c45fSAndroid Build Coastguard Worker                        << path << "; running recursive restorecon";
561*38e8c45fSAndroid Build Coastguard Worker         }
562*38e8c45fSAndroid Build Coastguard Worker 
563*38e8c45fSAndroid Build Coastguard Worker         auto restorecon = [path, seInfo, uid]() {
564*38e8c45fSAndroid Build Coastguard Worker             ScopedTrace tracer("label-change");
565*38e8c45fSAndroid Build Coastguard Worker 
566*38e8c45fSAndroid Build Coastguard Worker             // Temporary mark the folder as "in-progress" to resume in case of reboot/other failure.
567*38e8c45fSAndroid Build Coastguard Worker             RestoreconInProgress fence(path);
568*38e8c45fSAndroid Build Coastguard Worker 
569*38e8c45fSAndroid Build Coastguard Worker             if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
570*38e8c45fSAndroid Build Coastguard Worker                                                   SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
571*38e8c45fSAndroid Build Coastguard Worker                 PLOG(ERROR) << "Failed recursive restorecon for " << path;
572*38e8c45fSAndroid Build Coastguard Worker                 return -1;
573*38e8c45fSAndroid Build Coastguard Worker             }
574*38e8c45fSAndroid Build Coastguard Worker             return 0;
575*38e8c45fSAndroid Build Coastguard Worker         };
576*38e8c45fSAndroid Build Coastguard Worker         if (inProgress) {
577*38e8c45fSAndroid Build Coastguard Worker             // The previous restorecon was interrupted. It's either crashed (unlikely), or the phone
578*38e8c45fSAndroid Build Coastguard Worker             // was rebooted. Possibly because it took too much time. This time let's move it to a
579*38e8c45fSAndroid Build Coastguard Worker             // separate thread - so it won't block the rest of the OS.
580*38e8c45fSAndroid Build Coastguard Worker             std::thread(restorecon).detach();
581*38e8c45fSAndroid Build Coastguard Worker         } else {
582*38e8c45fSAndroid Build Coastguard Worker             if (int result = restorecon(); result) {
583*38e8c45fSAndroid Build Coastguard Worker                 return result;
584*38e8c45fSAndroid Build Coastguard Worker             }
585*38e8c45fSAndroid Build Coastguard Worker         }
586*38e8c45fSAndroid Build Coastguard Worker     }
587*38e8c45fSAndroid Build Coastguard Worker 
588*38e8c45fSAndroid Build Coastguard Worker     return 0;
589*38e8c45fSAndroid Build Coastguard Worker }
internal_storage_has_project_id()590*38e8c45fSAndroid Build Coastguard Worker static bool internal_storage_has_project_id() {
591*38e8c45fSAndroid Build Coastguard Worker     // The following path is populated in setFirstBoot, so if this file is present
592*38e8c45fSAndroid Build Coastguard Worker     // then project ids can be used. Using call once to cache the result of this check
593*38e8c45fSAndroid Build Coastguard Worker     // to avoid having to check the file presence again and again.
594*38e8c45fSAndroid Build Coastguard Worker     std::call_once(flag, []() {
595*38e8c45fSAndroid Build Coastguard Worker         auto using_project_ids =
596*38e8c45fSAndroid Build Coastguard Worker                 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
597*38e8c45fSAndroid Build Coastguard Worker         sUsingProjectIdsFlag = access(using_project_ids.c_str(), F_OK) == 0;
598*38e8c45fSAndroid Build Coastguard Worker     });
599*38e8c45fSAndroid Build Coastguard Worker     // return sUsingProjectIdsFlag;
600*38e8c45fSAndroid Build Coastguard Worker     return false;
601*38e8c45fSAndroid Build Coastguard Worker }
602*38e8c45fSAndroid Build Coastguard Worker 
prepare_app_dir(const std::string & path,mode_t target_mode,uid_t uid,gid_t gid,long project_id)603*38e8c45fSAndroid Build Coastguard Worker static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid, gid_t gid,
604*38e8c45fSAndroid Build Coastguard Worker                            long project_id) {
605*38e8c45fSAndroid Build Coastguard Worker     {
606*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("prepare-dir");
607*38e8c45fSAndroid Build Coastguard Worker         if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
608*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << "Failed to prepare " << path;
609*38e8c45fSAndroid Build Coastguard Worker             return -1;
610*38e8c45fSAndroid Build Coastguard Worker         }
611*38e8c45fSAndroid Build Coastguard Worker     }
612*38e8c45fSAndroid Build Coastguard Worker     if (internal_storage_has_project_id()) {
613*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("set-quota");
614*38e8c45fSAndroid Build Coastguard Worker         return set_quota_project_id(path, project_id, true);
615*38e8c45fSAndroid Build Coastguard Worker     }
616*38e8c45fSAndroid Build Coastguard Worker     return 0;
617*38e8c45fSAndroid Build Coastguard Worker }
618*38e8c45fSAndroid Build Coastguard Worker 
prepare_app_cache_dir(const std::string & parent,const char * name,mode_t target_mode,uid_t uid,gid_t gid,long project_id)619*38e8c45fSAndroid Build Coastguard Worker static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
620*38e8c45fSAndroid Build Coastguard Worker                                  uid_t uid, gid_t gid, long project_id) {
621*38e8c45fSAndroid Build Coastguard Worker     auto path = StringPrintf("%s/%s", parent.c_str(), name);
622*38e8c45fSAndroid Build Coastguard Worker     int ret;
623*38e8c45fSAndroid Build Coastguard Worker     {
624*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("prepare-cache-dir");
625*38e8c45fSAndroid Build Coastguard Worker         ret = prepare_app_cache_dir(parent, name, target_mode, uid, gid);
626*38e8c45fSAndroid Build Coastguard Worker     }
627*38e8c45fSAndroid Build Coastguard Worker     if (ret == 0 && internal_storage_has_project_id()) {
628*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("set-quota-cache-dir");
629*38e8c45fSAndroid Build Coastguard Worker         return set_quota_project_id(path, project_id, true);
630*38e8c45fSAndroid Build Coastguard Worker     }
631*38e8c45fSAndroid Build Coastguard Worker     return ret;
632*38e8c45fSAndroid Build Coastguard Worker }
633*38e8c45fSAndroid Build Coastguard Worker 
prepare_app_profile_dir(const std::string & packageName,int32_t appId,int32_t userId)634*38e8c45fSAndroid Build Coastguard Worker static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
635*38e8c45fSAndroid Build Coastguard Worker     ScopedTrace tracer("prepare-app-profile");
636*38e8c45fSAndroid Build Coastguard Worker     int32_t uid = multiuser_get_uid(userId, appId);
637*38e8c45fSAndroid Build Coastguard Worker     int shared_app_gid = multiuser_get_shared_gid(userId, appId);
638*38e8c45fSAndroid Build Coastguard Worker     if (shared_app_gid == -1) {
639*38e8c45fSAndroid Build Coastguard Worker         // TODO(calin): this should no longer be possible but do not continue if we don't get
640*38e8c45fSAndroid Build Coastguard Worker         // a valid shared gid.
641*38e8c45fSAndroid Build Coastguard Worker         PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
642*38e8c45fSAndroid Build Coastguard Worker         return true;
643*38e8c45fSAndroid Build Coastguard Worker     }
644*38e8c45fSAndroid Build Coastguard Worker 
645*38e8c45fSAndroid Build Coastguard Worker     const std::string profile_dir =
646*38e8c45fSAndroid Build Coastguard Worker             create_primary_current_profile_package_dir_path(userId, packageName);
647*38e8c45fSAndroid Build Coastguard Worker     // read-write-execute only for the app user.
648*38e8c45fSAndroid Build Coastguard Worker     if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
649*38e8c45fSAndroid Build Coastguard Worker         PLOG(ERROR) << "Failed to prepare " << profile_dir;
650*38e8c45fSAndroid Build Coastguard Worker         return false;
651*38e8c45fSAndroid Build Coastguard Worker     }
652*38e8c45fSAndroid Build Coastguard Worker     if (selinux_android_restorecon(profile_dir.c_str(), 0)) {
653*38e8c45fSAndroid Build Coastguard Worker         PLOG(ERROR) << "Failed to restorecon " << profile_dir;
654*38e8c45fSAndroid Build Coastguard Worker         return false;
655*38e8c45fSAndroid Build Coastguard Worker     }
656*38e8c45fSAndroid Build Coastguard Worker 
657*38e8c45fSAndroid Build Coastguard Worker     const std::string ref_profile_path =
658*38e8c45fSAndroid Build Coastguard Worker             create_primary_reference_profile_package_dir_path(packageName);
659*38e8c45fSAndroid Build Coastguard Worker 
660*38e8c45fSAndroid Build Coastguard Worker     // Prepare the reference profile directory. Note that we use the non strict version of
661*38e8c45fSAndroid Build Coastguard Worker     // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
662*38e8c45fSAndroid Build Coastguard Worker     // This is particularly important given that in O there were some fixes for how the
663*38e8c45fSAndroid Build Coastguard Worker     // shared_app_gid is computed.
664*38e8c45fSAndroid Build Coastguard Worker     //
665*38e8c45fSAndroid Build Coastguard Worker     // Note that by the time we get here we know that we are using a correct uid (otherwise
666*38e8c45fSAndroid Build Coastguard Worker     // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
667*38e8c45fSAndroid Build Coastguard Worker     // are sure that the gid being used belongs to the owning app and not someone else.
668*38e8c45fSAndroid Build Coastguard Worker     //
669*38e8c45fSAndroid Build Coastguard Worker     // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
670*38e8c45fSAndroid Build Coastguard Worker     if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
671*38e8c45fSAndroid Build Coastguard Worker         PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
672*38e8c45fSAndroid Build Coastguard Worker         return false;
673*38e8c45fSAndroid Build Coastguard Worker     }
674*38e8c45fSAndroid Build Coastguard Worker 
675*38e8c45fSAndroid Build Coastguard Worker     return true;
676*38e8c45fSAndroid Build Coastguard Worker }
677*38e8c45fSAndroid Build Coastguard Worker 
chown_app_dir(const std::string & path,uid_t uid,uid_t previousUid,gid_t cacheGid)678*38e8c45fSAndroid Build Coastguard Worker static bool chown_app_dir(const std::string& path, uid_t uid, uid_t previousUid, gid_t cacheGid) {
679*38e8c45fSAndroid Build Coastguard Worker     FTS* fts;
680*38e8c45fSAndroid Build Coastguard Worker     char *argv[] = { (char*) path.c_str(), nullptr };
681*38e8c45fSAndroid Build Coastguard Worker     if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
682*38e8c45fSAndroid Build Coastguard Worker         return false;
683*38e8c45fSAndroid Build Coastguard Worker     }
684*38e8c45fSAndroid Build Coastguard Worker     for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
685*38e8c45fSAndroid Build Coastguard Worker         if (p->fts_info == FTS_D && p->fts_level == 1
686*38e8c45fSAndroid Build Coastguard Worker             && (strcmp(p->fts_name, "cache") == 0
687*38e8c45fSAndroid Build Coastguard Worker                 || strcmp(p->fts_name, "code_cache") == 0)) {
688*38e8c45fSAndroid Build Coastguard Worker             // Mark cache dirs
689*38e8c45fSAndroid Build Coastguard Worker             p->fts_number = 1;
690*38e8c45fSAndroid Build Coastguard Worker         } else {
691*38e8c45fSAndroid Build Coastguard Worker             // Inherit parent's number
692*38e8c45fSAndroid Build Coastguard Worker             p->fts_number = p->fts_parent->fts_number;
693*38e8c45fSAndroid Build Coastguard Worker         }
694*38e8c45fSAndroid Build Coastguard Worker 
695*38e8c45fSAndroid Build Coastguard Worker         switch (p->fts_info) {
696*38e8c45fSAndroid Build Coastguard Worker         case FTS_D:
697*38e8c45fSAndroid Build Coastguard Worker         case FTS_F:
698*38e8c45fSAndroid Build Coastguard Worker         case FTS_SL:
699*38e8c45fSAndroid Build Coastguard Worker         case FTS_SLNONE:
700*38e8c45fSAndroid Build Coastguard Worker             if (p->fts_statp->st_uid == previousUid) {
701*38e8c45fSAndroid Build Coastguard Worker                 if (lchown(p->fts_path, uid, p->fts_number ? cacheGid : uid) != 0) {
702*38e8c45fSAndroid Build Coastguard Worker                     PLOG(WARNING) << "Failed to lchown " << p->fts_path;
703*38e8c45fSAndroid Build Coastguard Worker                 }
704*38e8c45fSAndroid Build Coastguard Worker             } else {
705*38e8c45fSAndroid Build Coastguard Worker                 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected UID "
706*38e8c45fSAndroid Build Coastguard Worker                         << p->fts_statp->st_uid << " instead of " << previousUid;
707*38e8c45fSAndroid Build Coastguard Worker             }
708*38e8c45fSAndroid Build Coastguard Worker             break;
709*38e8c45fSAndroid Build Coastguard Worker         }
710*38e8c45fSAndroid Build Coastguard Worker     }
711*38e8c45fSAndroid Build Coastguard Worker     fts_close(fts);
712*38e8c45fSAndroid Build Coastguard Worker     return true;
713*38e8c45fSAndroid Build Coastguard Worker }
714*38e8c45fSAndroid Build Coastguard Worker 
chown_app_profile_dir(const std::string & packageName,int32_t appId,int32_t userId)715*38e8c45fSAndroid Build Coastguard Worker static void chown_app_profile_dir(const std::string &packageName, int32_t appId, int32_t userId) {
716*38e8c45fSAndroid Build Coastguard Worker     uid_t uid = multiuser_get_uid(userId, appId);
717*38e8c45fSAndroid Build Coastguard Worker     gid_t sharedGid = multiuser_get_shared_gid(userId, appId);
718*38e8c45fSAndroid Build Coastguard Worker 
719*38e8c45fSAndroid Build Coastguard Worker     const std::string profile_dir =
720*38e8c45fSAndroid Build Coastguard Worker             create_primary_current_profile_package_dir_path(userId, packageName);
721*38e8c45fSAndroid Build Coastguard Worker     char *argv[] = { (char*) profile_dir.c_str(), nullptr };
722*38e8c45fSAndroid Build Coastguard Worker     if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
723*38e8c45fSAndroid Build Coastguard Worker         for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
724*38e8c45fSAndroid Build Coastguard Worker             switch (p->fts_info) {
725*38e8c45fSAndroid Build Coastguard Worker             case FTS_D:
726*38e8c45fSAndroid Build Coastguard Worker             case FTS_F:
727*38e8c45fSAndroid Build Coastguard Worker             case FTS_SL:
728*38e8c45fSAndroid Build Coastguard Worker             case FTS_SLNONE:
729*38e8c45fSAndroid Build Coastguard Worker                 if (lchown(p->fts_path, uid, uid) != 0) {
730*38e8c45fSAndroid Build Coastguard Worker                     PLOG(WARNING) << "Failed to lchown " << p->fts_path;
731*38e8c45fSAndroid Build Coastguard Worker                 }
732*38e8c45fSAndroid Build Coastguard Worker                 break;
733*38e8c45fSAndroid Build Coastguard Worker             }
734*38e8c45fSAndroid Build Coastguard Worker         }
735*38e8c45fSAndroid Build Coastguard Worker         fts_close(fts);
736*38e8c45fSAndroid Build Coastguard Worker     }
737*38e8c45fSAndroid Build Coastguard Worker 
738*38e8c45fSAndroid Build Coastguard Worker     const std::string ref_profile_path =
739*38e8c45fSAndroid Build Coastguard Worker             create_primary_reference_profile_package_dir_path(packageName);
740*38e8c45fSAndroid Build Coastguard Worker     argv[0] = (char *) ref_profile_path.c_str();
741*38e8c45fSAndroid Build Coastguard Worker     if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
742*38e8c45fSAndroid Build Coastguard Worker         for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
743*38e8c45fSAndroid Build Coastguard Worker             if (p->fts_info == FTS_D && p->fts_level == 0) {
744*38e8c45fSAndroid Build Coastguard Worker                 if (chown(p->fts_path, AID_SYSTEM, sharedGid) != 0) {
745*38e8c45fSAndroid Build Coastguard Worker                     PLOG(WARNING) << "Failed to chown " << p->fts_path;
746*38e8c45fSAndroid Build Coastguard Worker                 }
747*38e8c45fSAndroid Build Coastguard Worker                 continue;
748*38e8c45fSAndroid Build Coastguard Worker             }
749*38e8c45fSAndroid Build Coastguard Worker             switch (p->fts_info) {
750*38e8c45fSAndroid Build Coastguard Worker             case FTS_D:
751*38e8c45fSAndroid Build Coastguard Worker             case FTS_F:
752*38e8c45fSAndroid Build Coastguard Worker             case FTS_SL:
753*38e8c45fSAndroid Build Coastguard Worker             case FTS_SLNONE:
754*38e8c45fSAndroid Build Coastguard Worker                 if (lchown(p->fts_path, sharedGid, sharedGid) != 0) {
755*38e8c45fSAndroid Build Coastguard Worker                     PLOG(WARNING) << "Failed to lchown " << p->fts_path;
756*38e8c45fSAndroid Build Coastguard Worker                 }
757*38e8c45fSAndroid Build Coastguard Worker                 break;
758*38e8c45fSAndroid Build Coastguard Worker             }
759*38e8c45fSAndroid Build Coastguard Worker         }
760*38e8c45fSAndroid Build Coastguard Worker         fts_close(fts);
761*38e8c45fSAndroid Build Coastguard Worker     }
762*38e8c45fSAndroid Build Coastguard Worker }
763*38e8c45fSAndroid Build Coastguard Worker 
createAppDataDirs(const std::string & path,int32_t uid,int32_t gid,int32_t previousUid,int32_t cacheGid,const std::string & seInfo,mode_t targetMode,long projectIdApp,long projectIdCache)764*38e8c45fSAndroid Build Coastguard Worker static binder::Status createAppDataDirs(const std::string& path, int32_t uid, int32_t gid,
765*38e8c45fSAndroid Build Coastguard Worker                                         int32_t previousUid, int32_t cacheGid,
766*38e8c45fSAndroid Build Coastguard Worker                                         const std::string& seInfo, mode_t targetMode,
767*38e8c45fSAndroid Build Coastguard Worker                                         long projectIdApp, long projectIdCache) {
768*38e8c45fSAndroid Build Coastguard Worker     ScopedTrace tracer("create-dirs");
769*38e8c45fSAndroid Build Coastguard Worker     struct stat st{};
770*38e8c45fSAndroid Build Coastguard Worker     bool parent_dir_exists = (stat(path.c_str(), &st) == 0);
771*38e8c45fSAndroid Build Coastguard Worker 
772*38e8c45fSAndroid Build Coastguard Worker     auto cache_path = StringPrintf("%s/%s", path.c_str(), "cache");
773*38e8c45fSAndroid Build Coastguard Worker     auto code_cache_path = StringPrintf("%s/%s", path.c_str(), "code_cache");
774*38e8c45fSAndroid Build Coastguard Worker     bool cache_exists = (access(cache_path.c_str(), F_OK) == 0);
775*38e8c45fSAndroid Build Coastguard Worker     bool code_cache_exists = (access(code_cache_path.c_str(), F_OK) == 0);
776*38e8c45fSAndroid Build Coastguard Worker 
777*38e8c45fSAndroid Build Coastguard Worker     if (parent_dir_exists) {
778*38e8c45fSAndroid Build Coastguard Worker         if (previousUid > 0 && previousUid != uid) {
779*38e8c45fSAndroid Build Coastguard Worker             if (!chown_app_dir(path, uid, previousUid, cacheGid)) {
780*38e8c45fSAndroid Build Coastguard Worker                 return error("Failed to chown " + path);
781*38e8c45fSAndroid Build Coastguard Worker             }
782*38e8c45fSAndroid Build Coastguard Worker         }
783*38e8c45fSAndroid Build Coastguard Worker     }
784*38e8c45fSAndroid Build Coastguard Worker 
785*38e8c45fSAndroid Build Coastguard Worker     // Prepare only the parent app directory
786*38e8c45fSAndroid Build Coastguard Worker     if (prepare_app_dir(path, targetMode, uid, gid, projectIdApp) ||
787*38e8c45fSAndroid Build Coastguard Worker         prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid, projectIdCache) ||
788*38e8c45fSAndroid Build Coastguard Worker         prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid, projectIdCache)) {
789*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to prepare " + path);
790*38e8c45fSAndroid Build Coastguard Worker     }
791*38e8c45fSAndroid Build Coastguard Worker 
792*38e8c45fSAndroid Build Coastguard Worker     // Consider restorecon over contents if label changed
793*38e8c45fSAndroid Build Coastguard Worker     if (restorecon_app_data_lazy(path, seInfo, uid, parent_dir_exists)) {
794*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to restorecon " + path);
795*38e8c45fSAndroid Build Coastguard Worker     }
796*38e8c45fSAndroid Build Coastguard Worker 
797*38e8c45fSAndroid Build Coastguard Worker     // If the parent dir exists, the restorecon would already have been done
798*38e8c45fSAndroid Build Coastguard Worker     // as a part of the recursive restorecon above
799*38e8c45fSAndroid Build Coastguard Worker     if (parent_dir_exists && !cache_exists
800*38e8c45fSAndroid Build Coastguard Worker             && restorecon_app_data_lazy(cache_path, seInfo, uid, false)) {
801*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to restorecon " + cache_path);
802*38e8c45fSAndroid Build Coastguard Worker     }
803*38e8c45fSAndroid Build Coastguard Worker 
804*38e8c45fSAndroid Build Coastguard Worker     // If the parent dir exists, the restorecon would already have been done
805*38e8c45fSAndroid Build Coastguard Worker     // as a part of the recursive restorecon above
806*38e8c45fSAndroid Build Coastguard Worker     if (parent_dir_exists && !code_cache_exists
807*38e8c45fSAndroid Build Coastguard Worker             && restorecon_app_data_lazy(code_cache_path, seInfo, uid, false)) {
808*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to restorecon " + code_cache_path);
809*38e8c45fSAndroid Build Coastguard Worker     }
810*38e8c45fSAndroid Build Coastguard Worker     return ok();
811*38e8c45fSAndroid Build Coastguard Worker }
812*38e8c45fSAndroid Build Coastguard Worker 
createAppDataLocked(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags,int32_t appId,int32_t previousAppId,const std::string & seInfo,int32_t targetSdkVersion,int64_t * ceDataInode,int64_t * deDataInode)813*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createAppDataLocked(
814*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
815*38e8c45fSAndroid Build Coastguard Worker         int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
816*38e8c45fSAndroid Build Coastguard Worker         int32_t targetSdkVersion, int64_t* ceDataInode, int64_t* deDataInode) {
817*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
818*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
819*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
820*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
821*38e8c45fSAndroid Build Coastguard Worker 
822*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
823*38e8c45fSAndroid Build Coastguard Worker     const char* pkgname = packageName.c_str();
824*38e8c45fSAndroid Build Coastguard Worker 
825*38e8c45fSAndroid Build Coastguard Worker     // Assume invalid inode unless filled in below
826*38e8c45fSAndroid Build Coastguard Worker     if (ceDataInode != nullptr) *ceDataInode = -1;
827*38e8c45fSAndroid Build Coastguard Worker     if (deDataInode != nullptr) *deDataInode = -1;
828*38e8c45fSAndroid Build Coastguard Worker 
829*38e8c45fSAndroid Build Coastguard Worker     int32_t uid = multiuser_get_uid(userId, appId);
830*38e8c45fSAndroid Build Coastguard Worker 
831*38e8c45fSAndroid Build Coastguard Worker     // If previousAppId > 0, an app is changing its app ID
832*38e8c45fSAndroid Build Coastguard Worker     int32_t previousUid =
833*38e8c45fSAndroid Build Coastguard Worker             previousAppId > 0 ? (int32_t)multiuser_get_uid(userId, previousAppId) : -1;
834*38e8c45fSAndroid Build Coastguard Worker 
835*38e8c45fSAndroid Build Coastguard Worker     int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
836*38e8c45fSAndroid Build Coastguard Worker     mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
837*38e8c45fSAndroid Build Coastguard Worker 
838*38e8c45fSAndroid Build Coastguard Worker     // If UID doesn't have a specific cache GID, use UID value
839*38e8c45fSAndroid Build Coastguard Worker     if (cacheGid == -1) {
840*38e8c45fSAndroid Build Coastguard Worker         cacheGid = uid;
841*38e8c45fSAndroid Build Coastguard Worker     }
842*38e8c45fSAndroid Build Coastguard Worker 
843*38e8c45fSAndroid Build Coastguard Worker     long projectIdApp = get_project_id(uid, PROJECT_ID_APP_START);
844*38e8c45fSAndroid Build Coastguard Worker     long projectIdCache = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
845*38e8c45fSAndroid Build Coastguard Worker 
846*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_CE) {
847*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("ce");
848*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
849*38e8c45fSAndroid Build Coastguard Worker 
850*38e8c45fSAndroid Build Coastguard Worker         auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
851*38e8c45fSAndroid Build Coastguard Worker                                         projectIdApp, projectIdCache);
852*38e8c45fSAndroid Build Coastguard Worker         if (!status.isOk()) {
853*38e8c45fSAndroid Build Coastguard Worker             return status;
854*38e8c45fSAndroid Build Coastguard Worker         }
855*38e8c45fSAndroid Build Coastguard Worker 
856*38e8c45fSAndroid Build Coastguard Worker         // Remember inode numbers of cache directories so that we can clear
857*38e8c45fSAndroid Build Coastguard Worker         // contents while CE storage is locked
858*38e8c45fSAndroid Build Coastguard Worker         if (write_path_inode(path, "cache", kXattrInodeCache) ||
859*38e8c45fSAndroid Build Coastguard Worker                 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
860*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to write_path_inode for " + path);
861*38e8c45fSAndroid Build Coastguard Worker         }
862*38e8c45fSAndroid Build Coastguard Worker 
863*38e8c45fSAndroid Build Coastguard Worker         // And return the CE inode of the top-level data directory so we can
864*38e8c45fSAndroid Build Coastguard Worker         // clear contents while CE storage is locked
865*38e8c45fSAndroid Build Coastguard Worker         if (ceDataInode != nullptr) {
866*38e8c45fSAndroid Build Coastguard Worker             ino_t result;
867*38e8c45fSAndroid Build Coastguard Worker             if (get_path_inode(path, &result) != 0) {
868*38e8c45fSAndroid Build Coastguard Worker                 return error("Failed to get_path_inode for " + path);
869*38e8c45fSAndroid Build Coastguard Worker             }
870*38e8c45fSAndroid Build Coastguard Worker             *ceDataInode = static_cast<uint64_t>(result);
871*38e8c45fSAndroid Build Coastguard Worker         }
872*38e8c45fSAndroid Build Coastguard Worker     }
873*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_DE) {
874*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("de");
875*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
876*38e8c45fSAndroid Build Coastguard Worker 
877*38e8c45fSAndroid Build Coastguard Worker         auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
878*38e8c45fSAndroid Build Coastguard Worker                                         projectIdApp, projectIdCache);
879*38e8c45fSAndroid Build Coastguard Worker         if (!status.isOk()) {
880*38e8c45fSAndroid Build Coastguard Worker             return status;
881*38e8c45fSAndroid Build Coastguard Worker         }
882*38e8c45fSAndroid Build Coastguard Worker         if (previousUid > 0 && previousUid != uid) {
883*38e8c45fSAndroid Build Coastguard Worker             chown_app_profile_dir(packageName, appId, userId);
884*38e8c45fSAndroid Build Coastguard Worker         }
885*38e8c45fSAndroid Build Coastguard Worker 
886*38e8c45fSAndroid Build Coastguard Worker         if (!prepare_app_profile_dir(packageName, appId, userId)) {
887*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to prepare profiles for " + packageName);
888*38e8c45fSAndroid Build Coastguard Worker         }
889*38e8c45fSAndroid Build Coastguard Worker 
890*38e8c45fSAndroid Build Coastguard Worker         if (deDataInode != nullptr) {
891*38e8c45fSAndroid Build Coastguard Worker             ino_t result;
892*38e8c45fSAndroid Build Coastguard Worker             if (get_path_inode(path, &result) != 0) {
893*38e8c45fSAndroid Build Coastguard Worker                 return error("Failed to get_path_inode for " + path);
894*38e8c45fSAndroid Build Coastguard Worker             }
895*38e8c45fSAndroid Build Coastguard Worker             *deDataInode = static_cast<uint64_t>(result);
896*38e8c45fSAndroid Build Coastguard Worker         }
897*38e8c45fSAndroid Build Coastguard Worker     }
898*38e8c45fSAndroid Build Coastguard Worker 
899*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_SDK) {
900*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("sdk");
901*38e8c45fSAndroid Build Coastguard Worker         // Safe to ignore status since we can retry creating this by calling reconcileSdkData
902*38e8c45fSAndroid Build Coastguard Worker         auto ignore = createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
903*38e8c45fSAndroid Build Coastguard Worker         if (!ignore.isOk()) {
904*38e8c45fSAndroid Build Coastguard Worker             PLOG(WARNING) << "Failed to create sdk data package directory for " << packageName;
905*38e8c45fSAndroid Build Coastguard Worker         }
906*38e8c45fSAndroid Build Coastguard Worker     } else {
907*38e8c45fSAndroid Build Coastguard Worker         ScopedTrace tracer("destroy-sdk");
908*38e8c45fSAndroid Build Coastguard Worker         // Package does not need sdk storage. Remove it.
909*38e8c45fSAndroid Build Coastguard Worker         destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
910*38e8c45fSAndroid Build Coastguard Worker     }
911*38e8c45fSAndroid Build Coastguard Worker 
912*38e8c45fSAndroid Build Coastguard Worker     return ok();
913*38e8c45fSAndroid Build Coastguard Worker }
914*38e8c45fSAndroid Build Coastguard Worker 
915*38e8c45fSAndroid Build Coastguard Worker /**
916*38e8c45fSAndroid Build Coastguard Worker  * Responsible for creating /data/misc_{ce|de}/user/0/sdksandbox/<package-name> directory and other
917*38e8c45fSAndroid Build Coastguard Worker  * app level sub directories, such as ./shared
918*38e8c45fSAndroid Build Coastguard Worker  */
createSdkSandboxDataPackageDirectory(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t appId,int32_t flags)919*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createSdkSandboxDataPackageDirectory(
920*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
921*38e8c45fSAndroid Build Coastguard Worker         int32_t appId, int32_t flags) {
922*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
923*38e8c45fSAndroid Build Coastguard Worker 
924*38e8c45fSAndroid Build Coastguard Worker     int32_t sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
925*38e8c45fSAndroid Build Coastguard Worker     if (sdkSandboxUid == -1) {
926*38e8c45fSAndroid Build Coastguard Worker         // There no valid sdk sandbox process for this app. Skip creation of data directory
927*38e8c45fSAndroid Build Coastguard Worker         return ok();
928*38e8c45fSAndroid Build Coastguard Worker     }
929*38e8c45fSAndroid Build Coastguard Worker 
930*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
931*38e8c45fSAndroid Build Coastguard Worker 
932*38e8c45fSAndroid Build Coastguard Worker     constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
933*38e8c45fSAndroid Build Coastguard Worker     for (int currentFlag : storageFlags) {
934*38e8c45fSAndroid Build Coastguard Worker         if ((flags & currentFlag) == 0) {
935*38e8c45fSAndroid Build Coastguard Worker             continue;
936*38e8c45fSAndroid Build Coastguard Worker         }
937*38e8c45fSAndroid Build Coastguard Worker         bool isCeData = (currentFlag == FLAG_STORAGE_CE);
938*38e8c45fSAndroid Build Coastguard Worker 
939*38e8c45fSAndroid Build Coastguard Worker         // /data/misc_{ce,de}/<user-id>/sdksandbox directory gets created by vold
940*38e8c45fSAndroid Build Coastguard Worker         // during user creation
941*38e8c45fSAndroid Build Coastguard Worker 
942*38e8c45fSAndroid Build Coastguard Worker         // Prepare the package directory
943*38e8c45fSAndroid Build Coastguard Worker         auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
944*38e8c45fSAndroid Build Coastguard Worker                                                                      packageName.c_str());
945*38e8c45fSAndroid Build Coastguard Worker #if SDK_DEBUG
946*38e8c45fSAndroid Build Coastguard Worker         LOG(DEBUG) << "Creating app-level sdk data directory: " << packagePath;
947*38e8c45fSAndroid Build Coastguard Worker #endif
948*38e8c45fSAndroid Build Coastguard Worker 
949*38e8c45fSAndroid Build Coastguard Worker         if (prepare_app_dir(packagePath, 0751, AID_SYSTEM, AID_SYSTEM, 0)) {
950*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to prepare " + packagePath);
951*38e8c45fSAndroid Build Coastguard Worker         }
952*38e8c45fSAndroid Build Coastguard Worker     }
953*38e8c45fSAndroid Build Coastguard Worker 
954*38e8c45fSAndroid Build Coastguard Worker     return ok();
955*38e8c45fSAndroid Build Coastguard Worker }
956*38e8c45fSAndroid Build Coastguard Worker 
createAppData(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags,int32_t appId,int32_t previousAppId,const std::string & seInfo,int32_t targetSdkVersion,int64_t * ceDataInode,int64_t * deDataInode)957*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createAppData(
958*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
959*38e8c45fSAndroid Build Coastguard Worker         int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
960*38e8c45fSAndroid Build Coastguard Worker         int32_t targetSdkVersion, int64_t* ceDataInode, int64_t* deDataInode) {
961*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
962*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
963*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
964*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
965*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
966*38e8c45fSAndroid Build Coastguard Worker     return createAppDataLocked(uuid, packageName, userId, flags, appId, previousAppId, seInfo,
967*38e8c45fSAndroid Build Coastguard Worker                                targetSdkVersion, ceDataInode, deDataInode);
968*38e8c45fSAndroid Build Coastguard Worker }
969*38e8c45fSAndroid Build Coastguard Worker 
createAppData(const android::os::CreateAppDataArgs & args,android::os::CreateAppDataResult * _aidl_return)970*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createAppData(
971*38e8c45fSAndroid Build Coastguard Worker         const android::os::CreateAppDataArgs& args,
972*38e8c45fSAndroid Build Coastguard Worker         android::os::CreateAppDataResult* _aidl_return) {
973*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
974*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(args.userId);
975*38e8c45fSAndroid Build Coastguard Worker     // Locking is performed depeer in the callstack.
976*38e8c45fSAndroid Build Coastguard Worker 
977*38e8c45fSAndroid Build Coastguard Worker     int64_t ceDataInode = -1;
978*38e8c45fSAndroid Build Coastguard Worker     int64_t deDataInode = -1;
979*38e8c45fSAndroid Build Coastguard Worker     auto status = createAppData(args.uuid, args.packageName, args.userId, args.flags, args.appId,
980*38e8c45fSAndroid Build Coastguard Worker                                 args.previousAppId, args.seInfo, args.targetSdkVersion,
981*38e8c45fSAndroid Build Coastguard Worker                                 &ceDataInode, &deDataInode);
982*38e8c45fSAndroid Build Coastguard Worker     _aidl_return->ceDataInode = ceDataInode;
983*38e8c45fSAndroid Build Coastguard Worker     _aidl_return->deDataInode = deDataInode;
984*38e8c45fSAndroid Build Coastguard Worker     _aidl_return->exceptionCode = status.exceptionCode();
985*38e8c45fSAndroid Build Coastguard Worker     _aidl_return->exceptionMessage = status.exceptionMessage();
986*38e8c45fSAndroid Build Coastguard Worker     return ok();
987*38e8c45fSAndroid Build Coastguard Worker }
988*38e8c45fSAndroid Build Coastguard Worker 
createAppDataBatched(const std::vector<android::os::CreateAppDataArgs> & args,std::vector<android::os::CreateAppDataResult> * _aidl_return)989*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createAppDataBatched(
990*38e8c45fSAndroid Build Coastguard Worker         const std::vector<android::os::CreateAppDataArgs>& args,
991*38e8c45fSAndroid Build Coastguard Worker         std::vector<android::os::CreateAppDataResult>* _aidl_return) {
992*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
993*38e8c45fSAndroid Build Coastguard Worker     for (const auto& arg : args) {
994*38e8c45fSAndroid Build Coastguard Worker         ENFORCE_VALID_USER(arg.userId);
995*38e8c45fSAndroid Build Coastguard Worker     }
996*38e8c45fSAndroid Build Coastguard Worker 
997*38e8c45fSAndroid Build Coastguard Worker     // Locking is performed depeer in the callstack.
998*38e8c45fSAndroid Build Coastguard Worker 
999*38e8c45fSAndroid Build Coastguard Worker     std::vector<android::os::CreateAppDataResult> results;
1000*38e8c45fSAndroid Build Coastguard Worker     for (const auto &arg : args) {
1001*38e8c45fSAndroid Build Coastguard Worker         android::os::CreateAppDataResult result;
1002*38e8c45fSAndroid Build Coastguard Worker         createAppData(arg, &result);
1003*38e8c45fSAndroid Build Coastguard Worker         results.push_back(result);
1004*38e8c45fSAndroid Build Coastguard Worker     }
1005*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = results;
1006*38e8c45fSAndroid Build Coastguard Worker     return ok();
1007*38e8c45fSAndroid Build Coastguard Worker }
1008*38e8c45fSAndroid Build Coastguard Worker 
reconcileSdkData(const android::os::ReconcileSdkDataArgs & args)1009*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::reconcileSdkData(
1010*38e8c45fSAndroid Build Coastguard Worker         const android::os::ReconcileSdkDataArgs& args) {
1011*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(args.userId);
1012*38e8c45fSAndroid Build Coastguard Worker     // Locking is performed depeer in the callstack.
1013*38e8c45fSAndroid Build Coastguard Worker 
1014*38e8c45fSAndroid Build Coastguard Worker     return reconcileSdkData(args.uuid, args.packageName, args.subDirNames, args.userId, args.appId,
1015*38e8c45fSAndroid Build Coastguard Worker                             args.previousAppId, args.seInfo, args.flags);
1016*38e8c45fSAndroid Build Coastguard Worker }
1017*38e8c45fSAndroid Build Coastguard Worker 
1018*38e8c45fSAndroid Build Coastguard Worker /**
1019*38e8c45fSAndroid Build Coastguard Worker  * Reconciles per-sdk directory under app-level sdk data directory.
1020*38e8c45fSAndroid Build Coastguard Worker 
1021*38e8c45fSAndroid Build Coastguard Worker  * E.g. `/data/misc_ce/0/sdksandbox/<package-name>/<sdkPackageName>-<randomSuffix>
1022*38e8c45fSAndroid Build Coastguard Worker  *
1023*38e8c45fSAndroid Build Coastguard Worker  * - If the sdk data package directory is missing, we create it first.
1024*38e8c45fSAndroid Build Coastguard Worker  * - If sdkPackageNames is empty, we delete sdk package directory since it's not needed anymore.
1025*38e8c45fSAndroid Build Coastguard Worker  * - If a sdk level directory we need to prepare already exist, we skip creating it again. This
1026*38e8c45fSAndroid Build Coastguard Worker  *   is to avoid having same per-sdk directory with different suffix.
1027*38e8c45fSAndroid Build Coastguard Worker  * - If a sdk level directory exist which is absent from sdkPackageNames, we remove it.
1028*38e8c45fSAndroid Build Coastguard Worker  */
reconcileSdkData(const std::optional<std::string> & uuid,const std::string & packageName,const std::vector<std::string> & subDirNames,int userId,int appId,int previousAppId,const std::string & seInfo,int flags)1029*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::reconcileSdkData(const std::optional<std::string>& uuid,
1030*38e8c45fSAndroid Build Coastguard Worker                                                        const std::string& packageName,
1031*38e8c45fSAndroid Build Coastguard Worker                                                        const std::vector<std::string>& subDirNames,
1032*38e8c45fSAndroid Build Coastguard Worker                                                        int userId, int appId, int previousAppId,
1033*38e8c45fSAndroid Build Coastguard Worker                                                        const std::string& seInfo, int flags) {
1034*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1035*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1036*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
1037*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1038*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
1039*38e8c45fSAndroid Build Coastguard Worker 
1040*38e8c45fSAndroid Build Coastguard Worker #if SDK_DEBUG
1041*38e8c45fSAndroid Build Coastguard Worker     LOG(DEBUG) << "Creating per sdk data directory for: " << packageName;
1042*38e8c45fSAndroid Build Coastguard Worker #endif
1043*38e8c45fSAndroid Build Coastguard Worker 
1044*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1045*38e8c45fSAndroid Build Coastguard Worker 
1046*38e8c45fSAndroid Build Coastguard Worker     // Prepare the sdk package directory in case it's missing
1047*38e8c45fSAndroid Build Coastguard Worker     const auto status =
1048*38e8c45fSAndroid Build Coastguard Worker             createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
1049*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {
1050*38e8c45fSAndroid Build Coastguard Worker         return status;
1051*38e8c45fSAndroid Build Coastguard Worker     }
1052*38e8c45fSAndroid Build Coastguard Worker 
1053*38e8c45fSAndroid Build Coastguard Worker     auto res = ok();
1054*38e8c45fSAndroid Build Coastguard Worker     // We have to create sdk data for CE and DE storage
1055*38e8c45fSAndroid Build Coastguard Worker     const int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1056*38e8c45fSAndroid Build Coastguard Worker     for (int currentFlag : storageFlags) {
1057*38e8c45fSAndroid Build Coastguard Worker         if ((flags & currentFlag) == 0) {
1058*38e8c45fSAndroid Build Coastguard Worker             continue;
1059*38e8c45fSAndroid Build Coastguard Worker         }
1060*38e8c45fSAndroid Build Coastguard Worker         const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1061*38e8c45fSAndroid Build Coastguard Worker 
1062*38e8c45fSAndroid Build Coastguard Worker         const auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
1063*38e8c45fSAndroid Build Coastguard Worker                                                                            packageName.c_str());
1064*38e8c45fSAndroid Build Coastguard Worker 
1065*38e8c45fSAndroid Build Coastguard Worker         // Remove existing sub-directories not referred in subDirNames
1066*38e8c45fSAndroid Build Coastguard Worker         const std::unordered_set<std::string> expectedSubDirNames(subDirNames.begin(),
1067*38e8c45fSAndroid Build Coastguard Worker                                                                   subDirNames.end());
1068*38e8c45fSAndroid Build Coastguard Worker         const auto subDirHandler = [&packagePath, &expectedSubDirNames,
1069*38e8c45fSAndroid Build Coastguard Worker                                     &res](const std::string& subDirName) {
1070*38e8c45fSAndroid Build Coastguard Worker             // Remove the per-sdk directory if it is not referred in
1071*38e8c45fSAndroid Build Coastguard Worker             // expectedSubDirNames
1072*38e8c45fSAndroid Build Coastguard Worker             if (expectedSubDirNames.find(subDirName) == expectedSubDirNames.end()) {
1073*38e8c45fSAndroid Build Coastguard Worker                 auto path = packagePath + "/" + subDirName;
1074*38e8c45fSAndroid Build Coastguard Worker                 if (delete_dir_contents_and_dir(path) != 0) {
1075*38e8c45fSAndroid Build Coastguard Worker                     res = error("Failed to delete " + path);
1076*38e8c45fSAndroid Build Coastguard Worker                     return;
1077*38e8c45fSAndroid Build Coastguard Worker                 }
1078*38e8c45fSAndroid Build Coastguard Worker             }
1079*38e8c45fSAndroid Build Coastguard Worker         };
1080*38e8c45fSAndroid Build Coastguard Worker         const int ec = foreach_subdir(packagePath, subDirHandler);
1081*38e8c45fSAndroid Build Coastguard Worker         if (ec != 0) {
1082*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to process subdirs for " + packagePath);
1083*38e8c45fSAndroid Build Coastguard Worker             continue;
1084*38e8c45fSAndroid Build Coastguard Worker         }
1085*38e8c45fSAndroid Build Coastguard Worker 
1086*38e8c45fSAndroid Build Coastguard Worker         // Now create the subDirNames
1087*38e8c45fSAndroid Build Coastguard Worker         for (const auto& subDirName : subDirNames) {
1088*38e8c45fSAndroid Build Coastguard Worker             const std::string path =
1089*38e8c45fSAndroid Build Coastguard Worker                     create_data_misc_sdk_sandbox_sdk_path(uuid_, isCeData, userId,
1090*38e8c45fSAndroid Build Coastguard Worker                                                           packageName.c_str(), subDirName.c_str());
1091*38e8c45fSAndroid Build Coastguard Worker 
1092*38e8c45fSAndroid Build Coastguard Worker             // Create the directory along with cache and code_cache
1093*38e8c45fSAndroid Build Coastguard Worker             const int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
1094*38e8c45fSAndroid Build Coastguard Worker             if (cacheGid == -1) {
1095*38e8c45fSAndroid Build Coastguard Worker                 return exception(binder::Status::EX_ILLEGAL_STATE,
1096*38e8c45fSAndroid Build Coastguard Worker                                  StringPrintf("cacheGid cannot be -1 for sdk data"));
1097*38e8c45fSAndroid Build Coastguard Worker             }
1098*38e8c45fSAndroid Build Coastguard Worker             const int32_t sandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
1099*38e8c45fSAndroid Build Coastguard Worker             int32_t previousSandboxUid = multiuser_get_sdk_sandbox_uid(userId, previousAppId);
1100*38e8c45fSAndroid Build Coastguard Worker             int32_t appUid = multiuser_get_uid(userId, appId);
1101*38e8c45fSAndroid Build Coastguard Worker             long projectIdApp = get_project_id(appUid, PROJECT_ID_APP_START);
1102*38e8c45fSAndroid Build Coastguard Worker             long projectIdCache = get_project_id(appUid, PROJECT_ID_APP_CACHE_START);
1103*38e8c45fSAndroid Build Coastguard Worker             auto status =
1104*38e8c45fSAndroid Build Coastguard Worker                     createAppDataDirs(path, sandboxUid, AID_NOBODY, previousSandboxUid, cacheGid,
1105*38e8c45fSAndroid Build Coastguard Worker                                       seInfo, 0700 | S_ISGID, projectIdApp, projectIdCache);
1106*38e8c45fSAndroid Build Coastguard Worker             if (!status.isOk()) {
1107*38e8c45fSAndroid Build Coastguard Worker                 res = status;
1108*38e8c45fSAndroid Build Coastguard Worker                 continue;
1109*38e8c45fSAndroid Build Coastguard Worker             }
1110*38e8c45fSAndroid Build Coastguard Worker         }
1111*38e8c45fSAndroid Build Coastguard Worker     }
1112*38e8c45fSAndroid Build Coastguard Worker 
1113*38e8c45fSAndroid Build Coastguard Worker     return res;
1114*38e8c45fSAndroid Build Coastguard Worker }
1115*38e8c45fSAndroid Build Coastguard Worker 
migrateAppData(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags)1116*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::migrateAppData(const std::optional<std::string>& uuid,
1117*38e8c45fSAndroid Build Coastguard Worker         const std::string& packageName, int32_t userId, int32_t flags) {
1118*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1119*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1120*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
1121*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1122*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
1123*38e8c45fSAndroid Build Coastguard Worker 
1124*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1125*38e8c45fSAndroid Build Coastguard Worker     const char* pkgname = packageName.c_str();
1126*38e8c45fSAndroid Build Coastguard Worker 
1127*38e8c45fSAndroid Build Coastguard Worker     // This method only exists to upgrade system apps that have requested
1128*38e8c45fSAndroid Build Coastguard Worker     // forceDeviceEncrypted, so their default storage always lives in a
1129*38e8c45fSAndroid Build Coastguard Worker     // consistent location.  This only works on non-FBE devices, since we
1130*38e8c45fSAndroid Build Coastguard Worker     // never want to risk exposing data on a device with real CE/DE storage.
1131*38e8c45fSAndroid Build Coastguard Worker 
1132*38e8c45fSAndroid Build Coastguard Worker     auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
1133*38e8c45fSAndroid Build Coastguard Worker     auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
1134*38e8c45fSAndroid Build Coastguard Worker 
1135*38e8c45fSAndroid Build Coastguard Worker     // If neither directory is marked as default, assume CE is default
1136*38e8c45fSAndroid Build Coastguard Worker     if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
1137*38e8c45fSAndroid Build Coastguard Worker             && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
1138*38e8c45fSAndroid Build Coastguard Worker         if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
1139*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to mark default storage " + ce_path);
1140*38e8c45fSAndroid Build Coastguard Worker         }
1141*38e8c45fSAndroid Build Coastguard Worker     }
1142*38e8c45fSAndroid Build Coastguard Worker 
1143*38e8c45fSAndroid Build Coastguard Worker     // Migrate default data location if needed
1144*38e8c45fSAndroid Build Coastguard Worker     auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
1145*38e8c45fSAndroid Build Coastguard Worker     auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
1146*38e8c45fSAndroid Build Coastguard Worker 
1147*38e8c45fSAndroid Build Coastguard Worker     if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
1148*38e8c45fSAndroid Build Coastguard Worker         LOG(WARNING) << "Requested default storage " << target
1149*38e8c45fSAndroid Build Coastguard Worker                 << " is not active; migrating from " << source;
1150*38e8c45fSAndroid Build Coastguard Worker         if (delete_dir_contents_and_dir(target) != 0) {
1151*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to delete " + target);
1152*38e8c45fSAndroid Build Coastguard Worker         }
1153*38e8c45fSAndroid Build Coastguard Worker         if (rename(source.c_str(), target.c_str()) != 0) {
1154*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to rename " + source + " to " + target);
1155*38e8c45fSAndroid Build Coastguard Worker         }
1156*38e8c45fSAndroid Build Coastguard Worker     }
1157*38e8c45fSAndroid Build Coastguard Worker 
1158*38e8c45fSAndroid Build Coastguard Worker     return ok();
1159*38e8c45fSAndroid Build Coastguard Worker }
1160*38e8c45fSAndroid Build Coastguard Worker 
1161*38e8c45fSAndroid Build Coastguard Worker 
clearAppProfiles(const std::string & packageName,const std::string & profileName)1162*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
1163*38e8c45fSAndroid Build Coastguard Worker         const std::string& profileName) {
1164*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1165*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1166*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_FILE_NAME(profileName);
1167*38e8c45fSAndroid Build Coastguard Worker     if (!base::EndsWith(profileName, ".prof")) {
1168*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
1169*38e8c45fSAndroid Build Coastguard Worker                          StringPrintf("Profile name %s does not end with .prof",
1170*38e8c45fSAndroid Build Coastguard Worker                                       profileName.c_str()));
1171*38e8c45fSAndroid Build Coastguard Worker     }
1172*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
1173*38e8c45fSAndroid Build Coastguard Worker 
1174*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
1175*38e8c45fSAndroid Build Coastguard Worker     if (!clear_primary_reference_profile(packageName, profileName)) {
1176*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to clear reference profile for " + packageName);
1177*38e8c45fSAndroid Build Coastguard Worker     }
1178*38e8c45fSAndroid Build Coastguard Worker     if (!clear_primary_current_profiles(packageName, profileName)) {
1179*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to clear current profiles for " + packageName);
1180*38e8c45fSAndroid Build Coastguard Worker     }
1181*38e8c45fSAndroid Build Coastguard Worker     return res;
1182*38e8c45fSAndroid Build Coastguard Worker }
1183*38e8c45fSAndroid Build Coastguard Worker 
clearAppData(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags,int64_t ceDataInode)1184*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::clearAppData(const std::optional<std::string>& uuid,
1185*38e8c45fSAndroid Build Coastguard Worker         const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1186*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1187*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1188*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
1189*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1190*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
1191*38e8c45fSAndroid Build Coastguard Worker 
1192*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1193*38e8c45fSAndroid Build Coastguard Worker     const char* pkgname = packageName.c_str();
1194*38e8c45fSAndroid Build Coastguard Worker 
1195*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
1196*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_CE) {
1197*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
1198*38e8c45fSAndroid Build Coastguard Worker         if (flags & FLAG_CLEAR_CACHE_ONLY) {
1199*38e8c45fSAndroid Build Coastguard Worker             path = read_path_inode(path, "cache", kXattrInodeCache);
1200*38e8c45fSAndroid Build Coastguard Worker         } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1201*38e8c45fSAndroid Build Coastguard Worker             path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
1202*38e8c45fSAndroid Build Coastguard Worker         }
1203*38e8c45fSAndroid Build Coastguard Worker         if (access(path.c_str(), F_OK) == 0) {
1204*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(path) != 0) {
1205*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to delete contents of " + path);
1206*38e8c45fSAndroid Build Coastguard Worker             } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
1207*38e8c45fSAndroid Build Coastguard Worker                 remove_path_xattr(path, kXattrInodeCache);
1208*38e8c45fSAndroid Build Coastguard Worker                 remove_path_xattr(path, kXattrInodeCodeCache);
1209*38e8c45fSAndroid Build Coastguard Worker             }
1210*38e8c45fSAndroid Build Coastguard Worker         }
1211*38e8c45fSAndroid Build Coastguard Worker     }
1212*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_DE) {
1213*38e8c45fSAndroid Build Coastguard Worker         std::string suffix;
1214*38e8c45fSAndroid Build Coastguard Worker         if (flags & FLAG_CLEAR_CACHE_ONLY) {
1215*38e8c45fSAndroid Build Coastguard Worker             suffix = CACHE_DIR_POSTFIX;
1216*38e8c45fSAndroid Build Coastguard Worker         } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1217*38e8c45fSAndroid Build Coastguard Worker             suffix = CODE_CACHE_DIR_POSTFIX;
1218*38e8c45fSAndroid Build Coastguard Worker         }
1219*38e8c45fSAndroid Build Coastguard Worker 
1220*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
1221*38e8c45fSAndroid Build Coastguard Worker         if (access(path.c_str(), F_OK) == 0) {
1222*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(path) != 0) {
1223*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to delete contents of " + path);
1224*38e8c45fSAndroid Build Coastguard Worker             }
1225*38e8c45fSAndroid Build Coastguard Worker         }
1226*38e8c45fSAndroid Build Coastguard Worker     }
1227*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_EXTERNAL) {
1228*38e8c45fSAndroid Build Coastguard Worker         std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1229*38e8c45fSAndroid Build Coastguard Worker         for (const auto& n : mStorageMounts) {
1230*38e8c45fSAndroid Build Coastguard Worker             auto extPath = n.second;
1231*38e8c45fSAndroid Build Coastguard Worker 
1232*38e8c45fSAndroid Build Coastguard Worker             if (android::base::GetBoolProperty(kFuseProp, false)) {
1233*38e8c45fSAndroid Build Coastguard Worker                 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1234*38e8c45fSAndroid Build Coastguard Worker                 if (std::regex_match(extPath, re)) {
1235*38e8c45fSAndroid Build Coastguard Worker                     extPath += "/" + std::to_string(userId);
1236*38e8c45fSAndroid Build Coastguard Worker                 }
1237*38e8c45fSAndroid Build Coastguard Worker             } else {
1238*38e8c45fSAndroid Build Coastguard Worker                 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1239*38e8c45fSAndroid Build Coastguard Worker                     extPath += StringPrintf("/%d", userId);
1240*38e8c45fSAndroid Build Coastguard Worker                 } else if (userId != 0) {
1241*38e8c45fSAndroid Build Coastguard Worker                     // TODO: support devices mounted under secondary users
1242*38e8c45fSAndroid Build Coastguard Worker                     continue;
1243*38e8c45fSAndroid Build Coastguard Worker                 }
1244*38e8c45fSAndroid Build Coastguard Worker             }
1245*38e8c45fSAndroid Build Coastguard Worker 
1246*38e8c45fSAndroid Build Coastguard Worker             if (flags & FLAG_CLEAR_CACHE_ONLY) {
1247*38e8c45fSAndroid Build Coastguard Worker                 // Clear only cached data from shared storage
1248*38e8c45fSAndroid Build Coastguard Worker                 auto path = StringPrintf("%s/Android/data/%s/cache", extPath.c_str(), pkgname);
1249*38e8c45fSAndroid Build Coastguard Worker                 if (delete_dir_contents(path, true) != 0) {
1250*38e8c45fSAndroid Build Coastguard Worker                     res = error("Failed to delete contents of " + path);
1251*38e8c45fSAndroid Build Coastguard Worker                 }
1252*38e8c45fSAndroid Build Coastguard Worker             } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1253*38e8c45fSAndroid Build Coastguard Worker                 // No code cache on shared storage
1254*38e8c45fSAndroid Build Coastguard Worker             } else {
1255*38e8c45fSAndroid Build Coastguard Worker                 // Clear everything on shared storage
1256*38e8c45fSAndroid Build Coastguard Worker                 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
1257*38e8c45fSAndroid Build Coastguard Worker                 if (delete_dir_contents(path, true) != 0) {
1258*38e8c45fSAndroid Build Coastguard Worker                     res = error("Failed to delete contents of " + path);
1259*38e8c45fSAndroid Build Coastguard Worker                 }
1260*38e8c45fSAndroid Build Coastguard Worker                 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
1261*38e8c45fSAndroid Build Coastguard Worker                 if (delete_dir_contents(path, true) != 0) {
1262*38e8c45fSAndroid Build Coastguard Worker                     res = error("Failed to delete contents of " + path);
1263*38e8c45fSAndroid Build Coastguard Worker                 }
1264*38e8c45fSAndroid Build Coastguard Worker                 // Note that we explicitly don't delete OBBs - those are only removed on
1265*38e8c45fSAndroid Build Coastguard Worker                 // app uninstall.
1266*38e8c45fSAndroid Build Coastguard Worker             }
1267*38e8c45fSAndroid Build Coastguard Worker         }
1268*38e8c45fSAndroid Build Coastguard Worker     }
1269*38e8c45fSAndroid Build Coastguard Worker     auto status = clearSdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1270*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {
1271*38e8c45fSAndroid Build Coastguard Worker         res = status;
1272*38e8c45fSAndroid Build Coastguard Worker     }
1273*38e8c45fSAndroid Build Coastguard Worker     return res;
1274*38e8c45fSAndroid Build Coastguard Worker }
1275*38e8c45fSAndroid Build Coastguard Worker 
clearSdkSandboxDataPackageDirectory(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags)1276*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::clearSdkSandboxDataPackageDirectory(
1277*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1278*38e8c45fSAndroid Build Coastguard Worker         int32_t flags) {
1279*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1280*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1281*38e8c45fSAndroid Build Coastguard Worker     const char* pkgname = packageName.c_str();
1282*38e8c45fSAndroid Build Coastguard Worker 
1283*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
1284*38e8c45fSAndroid Build Coastguard Worker     constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1285*38e8c45fSAndroid Build Coastguard Worker     for (int i = 0; i < 2; i++) {
1286*38e8c45fSAndroid Build Coastguard Worker         int currentFlag = storageFlags[i];
1287*38e8c45fSAndroid Build Coastguard Worker         if ((flags & currentFlag) == 0) {
1288*38e8c45fSAndroid Build Coastguard Worker             continue;
1289*38e8c45fSAndroid Build Coastguard Worker         }
1290*38e8c45fSAndroid Build Coastguard Worker         bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1291*38e8c45fSAndroid Build Coastguard Worker         std::string suffix;
1292*38e8c45fSAndroid Build Coastguard Worker         if (flags & FLAG_CLEAR_CACHE_ONLY) {
1293*38e8c45fSAndroid Build Coastguard Worker             suffix = CACHE_DIR_POSTFIX;
1294*38e8c45fSAndroid Build Coastguard Worker         } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1295*38e8c45fSAndroid Build Coastguard Worker             suffix = CODE_CACHE_DIR_POSTFIX;
1296*38e8c45fSAndroid Build Coastguard Worker         }
1297*38e8c45fSAndroid Build Coastguard Worker 
1298*38e8c45fSAndroid Build Coastguard Worker         auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1299*38e8c45fSAndroid Build Coastguard Worker         if (access(appPath.c_str(), F_OK) != 0) continue;
1300*38e8c45fSAndroid Build Coastguard Worker         const auto subDirHandler = [&appPath, &res, &suffix](const std::string& filename) {
1301*38e8c45fSAndroid Build Coastguard Worker             auto filepath = appPath + "/" + filename + suffix;
1302*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(filepath, true) != 0) {
1303*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to clear contents of " + filepath);
1304*38e8c45fSAndroid Build Coastguard Worker             }
1305*38e8c45fSAndroid Build Coastguard Worker         };
1306*38e8c45fSAndroid Build Coastguard Worker         const int ec = foreach_subdir(appPath, subDirHandler);
1307*38e8c45fSAndroid Build Coastguard Worker         if (ec != 0) {
1308*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to process subdirs for " + appPath);
1309*38e8c45fSAndroid Build Coastguard Worker         }
1310*38e8c45fSAndroid Build Coastguard Worker     }
1311*38e8c45fSAndroid Build Coastguard Worker     return res;
1312*38e8c45fSAndroid Build Coastguard Worker }
1313*38e8c45fSAndroid Build Coastguard Worker 
destroy_app_reference_profile(const std::string & pkgname)1314*38e8c45fSAndroid Build Coastguard Worker static int destroy_app_reference_profile(const std::string& pkgname) {
1315*38e8c45fSAndroid Build Coastguard Worker     return delete_dir_contents_and_dir(
1316*38e8c45fSAndroid Build Coastguard Worker         create_primary_reference_profile_package_dir_path(pkgname),
1317*38e8c45fSAndroid Build Coastguard Worker         /*ignore_if_missing*/ true);
1318*38e8c45fSAndroid Build Coastguard Worker }
1319*38e8c45fSAndroid Build Coastguard Worker 
destroy_app_current_profiles(const std::string & pkgname,userid_t userid)1320*38e8c45fSAndroid Build Coastguard Worker static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
1321*38e8c45fSAndroid Build Coastguard Worker     return delete_dir_contents_and_dir(
1322*38e8c45fSAndroid Build Coastguard Worker         create_primary_current_profile_package_dir_path(userid, pkgname),
1323*38e8c45fSAndroid Build Coastguard Worker         /*ignore_if_missing*/ true);
1324*38e8c45fSAndroid Build Coastguard Worker }
1325*38e8c45fSAndroid Build Coastguard Worker 
destroyAppProfiles(const std::string & packageName)1326*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
1327*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1328*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1329*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
1330*38e8c45fSAndroid Build Coastguard Worker 
1331*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
1332*38e8c45fSAndroid Build Coastguard Worker     std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1333*38e8c45fSAndroid Build Coastguard Worker     for (auto user : users) {
1334*38e8c45fSAndroid Build Coastguard Worker         if (destroy_app_current_profiles(packageName, user) != 0) {
1335*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to destroy current profiles for " + packageName);
1336*38e8c45fSAndroid Build Coastguard Worker         }
1337*38e8c45fSAndroid Build Coastguard Worker     }
1338*38e8c45fSAndroid Build Coastguard Worker     if (destroy_app_reference_profile(packageName) != 0) {
1339*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to destroy reference profile for " + packageName);
1340*38e8c45fSAndroid Build Coastguard Worker     }
1341*38e8c45fSAndroid Build Coastguard Worker     return res;
1342*38e8c45fSAndroid Build Coastguard Worker }
1343*38e8c45fSAndroid Build Coastguard Worker 
deleteReferenceProfile(const std::string & packageName,const std::string & profileName)1344*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::deleteReferenceProfile(const std::string& packageName,
1345*38e8c45fSAndroid Build Coastguard Worker                                                              const std::string& profileName) {
1346*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1347*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1348*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
1349*38e8c45fSAndroid Build Coastguard Worker 
1350*38e8c45fSAndroid Build Coastguard Worker     // This function only supports primary dex'es.
1351*38e8c45fSAndroid Build Coastguard Worker     std::string path =
1352*38e8c45fSAndroid Build Coastguard Worker             create_reference_profile_path(packageName, profileName, /*is_secondary_dex=*/false);
1353*38e8c45fSAndroid Build Coastguard Worker     if (unlink(path.c_str()) != 0) {
1354*38e8c45fSAndroid Build Coastguard Worker         if (errno == ENOENT) {
1355*38e8c45fSAndroid Build Coastguard Worker             return ok();
1356*38e8c45fSAndroid Build Coastguard Worker         } else {
1357*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to delete profile " + profileName + " for " + packageName);
1358*38e8c45fSAndroid Build Coastguard Worker         }
1359*38e8c45fSAndroid Build Coastguard Worker     }
1360*38e8c45fSAndroid Build Coastguard Worker     return ok();
1361*38e8c45fSAndroid Build Coastguard Worker }
1362*38e8c45fSAndroid Build Coastguard Worker 
destroyAppData(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags,int64_t ceDataInode)1363*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::destroyAppData(const std::optional<std::string>& uuid,
1364*38e8c45fSAndroid Build Coastguard Worker         const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1365*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1366*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1367*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
1368*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1369*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
1370*38e8c45fSAndroid Build Coastguard Worker 
1371*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1372*38e8c45fSAndroid Build Coastguard Worker     const char* pkgname = packageName.c_str();
1373*38e8c45fSAndroid Build Coastguard Worker 
1374*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
1375*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_CE) {
1376*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
1377*38e8c45fSAndroid Build Coastguard Worker         if (rename_delete_dir_contents_and_dir(path) != 0) {
1378*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to delete " + path);
1379*38e8c45fSAndroid Build Coastguard Worker         }
1380*38e8c45fSAndroid Build Coastguard Worker     }
1381*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_DE) {
1382*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
1383*38e8c45fSAndroid Build Coastguard Worker         if (rename_delete_dir_contents_and_dir(path) != 0) {
1384*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to delete " + path);
1385*38e8c45fSAndroid Build Coastguard Worker         }
1386*38e8c45fSAndroid Build Coastguard Worker         if ((flags & FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES) == 0) {
1387*38e8c45fSAndroid Build Coastguard Worker             destroy_app_current_profiles(packageName, userId);
1388*38e8c45fSAndroid Build Coastguard Worker             // TODO(calin): If the package is still installed by other users it's probably
1389*38e8c45fSAndroid Build Coastguard Worker             // beneficial to keep the reference profile around.
1390*38e8c45fSAndroid Build Coastguard Worker             // Verify if it's ok to do that.
1391*38e8c45fSAndroid Build Coastguard Worker             destroy_app_reference_profile(packageName);
1392*38e8c45fSAndroid Build Coastguard Worker         }
1393*38e8c45fSAndroid Build Coastguard Worker     }
1394*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_EXTERNAL) {
1395*38e8c45fSAndroid Build Coastguard Worker         std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1396*38e8c45fSAndroid Build Coastguard Worker         for (const auto& n : mStorageMounts) {
1397*38e8c45fSAndroid Build Coastguard Worker             auto extPath = n.second;
1398*38e8c45fSAndroid Build Coastguard Worker 
1399*38e8c45fSAndroid Build Coastguard Worker             if (android::base::GetBoolProperty(kFuseProp, false)) {
1400*38e8c45fSAndroid Build Coastguard Worker                 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1401*38e8c45fSAndroid Build Coastguard Worker                 if (std::regex_match(extPath, re)) {
1402*38e8c45fSAndroid Build Coastguard Worker                     extPath += "/" + std::to_string(userId);
1403*38e8c45fSAndroid Build Coastguard Worker                 }
1404*38e8c45fSAndroid Build Coastguard Worker             } else {
1405*38e8c45fSAndroid Build Coastguard Worker                 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1406*38e8c45fSAndroid Build Coastguard Worker                     extPath += StringPrintf("/%d", userId);
1407*38e8c45fSAndroid Build Coastguard Worker                 } else if (userId != 0) {
1408*38e8c45fSAndroid Build Coastguard Worker                     // TODO: support devices mounted under secondary users
1409*38e8c45fSAndroid Build Coastguard Worker                     continue;
1410*38e8c45fSAndroid Build Coastguard Worker                 }
1411*38e8c45fSAndroid Build Coastguard Worker             }
1412*38e8c45fSAndroid Build Coastguard Worker 
1413*38e8c45fSAndroid Build Coastguard Worker             auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
1414*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents_and_dir(path, true) != 0) {
1415*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to delete contents of " + path);
1416*38e8c45fSAndroid Build Coastguard Worker             }
1417*38e8c45fSAndroid Build Coastguard Worker             path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
1418*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents_and_dir(path, true) != 0) {
1419*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to delete contents of " + path);
1420*38e8c45fSAndroid Build Coastguard Worker             }
1421*38e8c45fSAndroid Build Coastguard Worker             path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
1422*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents_and_dir(path, true) != 0) {
1423*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to delete contents of " + path);
1424*38e8c45fSAndroid Build Coastguard Worker             }
1425*38e8c45fSAndroid Build Coastguard Worker         }
1426*38e8c45fSAndroid Build Coastguard Worker     }
1427*38e8c45fSAndroid Build Coastguard Worker     auto status = destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1428*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {
1429*38e8c45fSAndroid Build Coastguard Worker         res = status;
1430*38e8c45fSAndroid Build Coastguard Worker     }
1431*38e8c45fSAndroid Build Coastguard Worker     return res;
1432*38e8c45fSAndroid Build Coastguard Worker }
1433*38e8c45fSAndroid Build Coastguard Worker 
destroySdkSandboxDataPackageDirectory(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags)1434*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::destroySdkSandboxDataPackageDirectory(
1435*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1436*38e8c45fSAndroid Build Coastguard Worker         int32_t flags) {
1437*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1438*38e8c45fSAndroid Build Coastguard Worker 
1439*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1440*38e8c45fSAndroid Build Coastguard Worker     const char* pkgname = packageName.c_str();
1441*38e8c45fSAndroid Build Coastguard Worker 
1442*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
1443*38e8c45fSAndroid Build Coastguard Worker     constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1444*38e8c45fSAndroid Build Coastguard Worker     for (int i = 0; i < 2; i++) {
1445*38e8c45fSAndroid Build Coastguard Worker         int currentFlag = storageFlags[i];
1446*38e8c45fSAndroid Build Coastguard Worker         if ((flags & currentFlag) == 0) {
1447*38e8c45fSAndroid Build Coastguard Worker             continue;
1448*38e8c45fSAndroid Build Coastguard Worker         }
1449*38e8c45fSAndroid Build Coastguard Worker         bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1450*38e8c45fSAndroid Build Coastguard Worker         auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1451*38e8c45fSAndroid Build Coastguard Worker         if (rename_delete_dir_contents_and_dir(appPath) != 0) {
1452*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to delete " + appPath);
1453*38e8c45fSAndroid Build Coastguard Worker         }
1454*38e8c45fSAndroid Build Coastguard Worker     }
1455*38e8c45fSAndroid Build Coastguard Worker     return res;
1456*38e8c45fSAndroid Build Coastguard Worker }
1457*38e8c45fSAndroid Build Coastguard Worker 
get_cache_gid(uid_t uid)1458*38e8c45fSAndroid Build Coastguard Worker static gid_t get_cache_gid(uid_t uid) {
1459*38e8c45fSAndroid Build Coastguard Worker     int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
1460*38e8c45fSAndroid Build Coastguard Worker     return (gid != -1) ? gid : uid;
1461*38e8c45fSAndroid Build Coastguard Worker }
1462*38e8c45fSAndroid Build Coastguard Worker 
fixupAppData(const std::optional<std::string> & uuid,int32_t flags)1463*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::fixupAppData(const std::optional<std::string>& uuid,
1464*38e8c45fSAndroid Build Coastguard Worker         int32_t flags) {
1465*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1466*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
1467*38e8c45fSAndroid Build Coastguard Worker 
1468*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1469*38e8c45fSAndroid Build Coastguard Worker     for (auto userId : get_known_users(uuid_)) {
1470*38e8c45fSAndroid Build Coastguard Worker         LOCK_USER();
1471*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("fixup user");
1472*38e8c45fSAndroid Build Coastguard Worker         FTS* fts;
1473*38e8c45fSAndroid Build Coastguard Worker         FTSENT* p;
1474*38e8c45fSAndroid Build Coastguard Worker         auto ce_path = create_data_user_ce_path(uuid_, userId);
1475*38e8c45fSAndroid Build Coastguard Worker         auto de_path = create_data_user_de_path(uuid_, userId);
1476*38e8c45fSAndroid Build Coastguard Worker         char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
1477*38e8c45fSAndroid Build Coastguard Worker         if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
1478*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to fts_open");
1479*38e8c45fSAndroid Build Coastguard Worker         }
1480*38e8c45fSAndroid Build Coastguard Worker         while ((p = fts_read(fts)) != nullptr) {
1481*38e8c45fSAndroid Build Coastguard Worker             if (p->fts_info == FTS_D && p->fts_level == 1) {
1482*38e8c45fSAndroid Build Coastguard Worker                 // Track down inodes of cache directories
1483*38e8c45fSAndroid Build Coastguard Worker                 uint64_t raw = 0;
1484*38e8c45fSAndroid Build Coastguard Worker                 ino_t inode_cache = 0;
1485*38e8c45fSAndroid Build Coastguard Worker                 ino_t inode_code_cache = 0;
1486*38e8c45fSAndroid Build Coastguard Worker                 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1487*38e8c45fSAndroid Build Coastguard Worker                     inode_cache = raw;
1488*38e8c45fSAndroid Build Coastguard Worker                 }
1489*38e8c45fSAndroid Build Coastguard Worker                 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1490*38e8c45fSAndroid Build Coastguard Worker                     inode_code_cache = raw;
1491*38e8c45fSAndroid Build Coastguard Worker                 }
1492*38e8c45fSAndroid Build Coastguard Worker 
1493*38e8c45fSAndroid Build Coastguard Worker                 // Figure out expected GID of each child
1494*38e8c45fSAndroid Build Coastguard Worker                 FTSENT* child = fts_children(fts, 0);
1495*38e8c45fSAndroid Build Coastguard Worker                 while (child != nullptr) {
1496*38e8c45fSAndroid Build Coastguard Worker                     if ((child->fts_statp->st_ino == inode_cache)
1497*38e8c45fSAndroid Build Coastguard Worker                             || (child->fts_statp->st_ino == inode_code_cache)
1498*38e8c45fSAndroid Build Coastguard Worker                             || !strcmp(child->fts_name, "cache")
1499*38e8c45fSAndroid Build Coastguard Worker                             || !strcmp(child->fts_name, "code_cache")) {
1500*38e8c45fSAndroid Build Coastguard Worker                         child->fts_number = get_cache_gid(p->fts_statp->st_uid);
1501*38e8c45fSAndroid Build Coastguard Worker                     } else {
1502*38e8c45fSAndroid Build Coastguard Worker                         child->fts_number = p->fts_statp->st_uid;
1503*38e8c45fSAndroid Build Coastguard Worker                     }
1504*38e8c45fSAndroid Build Coastguard Worker                     child = child->fts_link;
1505*38e8c45fSAndroid Build Coastguard Worker                 }
1506*38e8c45fSAndroid Build Coastguard Worker             } else if (p->fts_level >= 2) {
1507*38e8c45fSAndroid Build Coastguard Worker                 if (p->fts_level > 2) {
1508*38e8c45fSAndroid Build Coastguard Worker                     // Inherit GID from parent once we're deeper into tree
1509*38e8c45fSAndroid Build Coastguard Worker                     p->fts_number = p->fts_parent->fts_number;
1510*38e8c45fSAndroid Build Coastguard Worker                 }
1511*38e8c45fSAndroid Build Coastguard Worker 
1512*38e8c45fSAndroid Build Coastguard Worker                 uid_t uid = p->fts_parent->fts_statp->st_uid;
1513*38e8c45fSAndroid Build Coastguard Worker                 gid_t cache_gid = get_cache_gid(uid);
1514*38e8c45fSAndroid Build Coastguard Worker                 gid_t expected = p->fts_number;
1515*38e8c45fSAndroid Build Coastguard Worker                 gid_t actual = p->fts_statp->st_gid;
1516*38e8c45fSAndroid Build Coastguard Worker                 if (actual == expected) {
1517*38e8c45fSAndroid Build Coastguard Worker #if FIXUP_DEBUG
1518*38e8c45fSAndroid Build Coastguard Worker                     LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
1519*38e8c45fSAndroid Build Coastguard Worker #endif
1520*38e8c45fSAndroid Build Coastguard Worker                     if (!(flags & FLAG_FORCE)) {
1521*38e8c45fSAndroid Build Coastguard Worker                         fts_set(fts, p, FTS_SKIP);
1522*38e8c45fSAndroid Build Coastguard Worker                     }
1523*38e8c45fSAndroid Build Coastguard Worker                 } else if ((actual == uid) || (actual == cache_gid)) {
1524*38e8c45fSAndroid Build Coastguard Worker                     // Only consider fixing up when current GID belongs to app
1525*38e8c45fSAndroid Build Coastguard Worker                     if (p->fts_info != FTS_D) {
1526*38e8c45fSAndroid Build Coastguard Worker                         LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
1527*38e8c45fSAndroid Build Coastguard Worker                                 << " instead of " << expected;
1528*38e8c45fSAndroid Build Coastguard Worker                     }
1529*38e8c45fSAndroid Build Coastguard Worker                     switch (p->fts_info) {
1530*38e8c45fSAndroid Build Coastguard Worker                     case FTS_DP:
1531*38e8c45fSAndroid Build Coastguard Worker                         // If we're moving towards cache GID, we need to set S_ISGID
1532*38e8c45fSAndroid Build Coastguard Worker                         if (expected == cache_gid) {
1533*38e8c45fSAndroid Build Coastguard Worker                             if (chmod(p->fts_path, 02771) != 0) {
1534*38e8c45fSAndroid Build Coastguard Worker                                 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1535*38e8c45fSAndroid Build Coastguard Worker                             }
1536*38e8c45fSAndroid Build Coastguard Worker                         }
1537*38e8c45fSAndroid Build Coastguard Worker                         [[fallthrough]]; // also set GID
1538*38e8c45fSAndroid Build Coastguard Worker                     case FTS_F:
1539*38e8c45fSAndroid Build Coastguard Worker                         if (chown(p->fts_path, -1, expected) != 0) {
1540*38e8c45fSAndroid Build Coastguard Worker                             PLOG(WARNING) << "Failed to chown " << p->fts_path;
1541*38e8c45fSAndroid Build Coastguard Worker                         }
1542*38e8c45fSAndroid Build Coastguard Worker                         break;
1543*38e8c45fSAndroid Build Coastguard Worker                     case FTS_SL:
1544*38e8c45fSAndroid Build Coastguard Worker                     case FTS_SLNONE:
1545*38e8c45fSAndroid Build Coastguard Worker                         if (lchown(p->fts_path, -1, expected) != 0) {
1546*38e8c45fSAndroid Build Coastguard Worker                             PLOG(WARNING) << "Failed to chown " << p->fts_path;
1547*38e8c45fSAndroid Build Coastguard Worker                         }
1548*38e8c45fSAndroid Build Coastguard Worker                         break;
1549*38e8c45fSAndroid Build Coastguard Worker                     }
1550*38e8c45fSAndroid Build Coastguard Worker                 } else {
1551*38e8c45fSAndroid Build Coastguard Worker                     // Ignore all other GID transitions, since they're kinda shady
1552*38e8c45fSAndroid Build Coastguard Worker                     LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
1553*38e8c45fSAndroid Build Coastguard Worker                             << " instead of " << expected;
1554*38e8c45fSAndroid Build Coastguard Worker                     if (!(flags & FLAG_FORCE)) {
1555*38e8c45fSAndroid Build Coastguard Worker                         fts_set(fts, p, FTS_SKIP);
1556*38e8c45fSAndroid Build Coastguard Worker                     }
1557*38e8c45fSAndroid Build Coastguard Worker                 }
1558*38e8c45fSAndroid Build Coastguard Worker             }
1559*38e8c45fSAndroid Build Coastguard Worker         }
1560*38e8c45fSAndroid Build Coastguard Worker         fts_close(fts);
1561*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
1562*38e8c45fSAndroid Build Coastguard Worker     }
1563*38e8c45fSAndroid Build Coastguard Worker     return ok();
1564*38e8c45fSAndroid Build Coastguard Worker }
1565*38e8c45fSAndroid Build Coastguard Worker 
copy_directory_recursive(const char * from,const char * to)1566*38e8c45fSAndroid Build Coastguard Worker static int32_t copy_directory_recursive(const char* from, const char* to) {
1567*38e8c45fSAndroid Build Coastguard Worker     char* argv[] =
1568*38e8c45fSAndroid Build Coastguard Worker             {(char*)kCpPath,
1569*38e8c45fSAndroid Build Coastguard Worker              (char*)"-F", /* delete any existing destination file first (--remove-destination) */
1570*38e8c45fSAndroid Build Coastguard Worker              (char*)"--preserve=mode,ownership,timestamps,xattr", /* preserve properties */
1571*38e8c45fSAndroid Build Coastguard Worker              (char*)"-R", /* recurse into subdirectories (DEST must be a directory) */
1572*38e8c45fSAndroid Build Coastguard Worker              (char*)"-P", /* Do not follow symlinks [default] */
1573*38e8c45fSAndroid Build Coastguard Worker              (char*)"-d", /* don't dereference symlinks */
1574*38e8c45fSAndroid Build Coastguard Worker              (char*)from,
1575*38e8c45fSAndroid Build Coastguard Worker              (char*)to};
1576*38e8c45fSAndroid Build Coastguard Worker 
1577*38e8c45fSAndroid Build Coastguard Worker     LOG(DEBUG) << "Copying " << from << " to " << to;
1578*38e8c45fSAndroid Build Coastguard Worker     return logwrap_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, LOG_ALOG, false, nullptr);
1579*38e8c45fSAndroid Build Coastguard Worker }
1580*38e8c45fSAndroid Build Coastguard Worker 
snapshotAppData(const std::optional<std::string> & volumeUuid,const std::string & packageName,int32_t userId,int32_t snapshotId,int32_t storageFlags,int64_t * _aidl_return)1581*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::snapshotAppData(const std::optional<std::string>& volumeUuid,
1582*38e8c45fSAndroid Build Coastguard Worker                                                       const std::string& packageName,
1583*38e8c45fSAndroid Build Coastguard Worker                                                       int32_t userId, int32_t snapshotId,
1584*38e8c45fSAndroid Build Coastguard Worker                                                       int32_t storageFlags, int64_t* _aidl_return) {
1585*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1586*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1587*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1588*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1589*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
1590*38e8c45fSAndroid Build Coastguard Worker 
1591*38e8c45fSAndroid Build Coastguard Worker     const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1592*38e8c45fSAndroid Build Coastguard Worker     const char* package_name = packageName.c_str();
1593*38e8c45fSAndroid Build Coastguard Worker 
1594*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
1595*38e8c45fSAndroid Build Coastguard Worker     // Default result to 0, it will be populated with inode of ce data snapshot
1596*38e8c45fSAndroid Build Coastguard Worker     // if FLAG_STORAGE_CE has been passed.
1597*38e8c45fSAndroid Build Coastguard Worker     if (_aidl_return != nullptr) *_aidl_return = 0;
1598*38e8c45fSAndroid Build Coastguard Worker 
1599*38e8c45fSAndroid Build Coastguard Worker     bool clear_ce_on_exit = false;
1600*38e8c45fSAndroid Build Coastguard Worker     bool clear_de_on_exit = false;
1601*38e8c45fSAndroid Build Coastguard Worker 
1602*38e8c45fSAndroid Build Coastguard Worker     auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &userId, &package_name,
1603*38e8c45fSAndroid Build Coastguard Worker                     &snapshotId] {
1604*38e8c45fSAndroid Build Coastguard Worker         if (clear_de_on_exit) {
1605*38e8c45fSAndroid Build Coastguard Worker             auto to = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1606*38e8c45fSAndroid Build Coastguard Worker                                                                 package_name);
1607*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1608*38e8c45fSAndroid Build Coastguard Worker                 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1609*38e8c45fSAndroid Build Coastguard Worker             }
1610*38e8c45fSAndroid Build Coastguard Worker         }
1611*38e8c45fSAndroid Build Coastguard Worker 
1612*38e8c45fSAndroid Build Coastguard Worker         if (clear_ce_on_exit) {
1613*38e8c45fSAndroid Build Coastguard Worker             auto to = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1614*38e8c45fSAndroid Build Coastguard Worker                                                                 package_name);
1615*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1616*38e8c45fSAndroid Build Coastguard Worker                 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1617*38e8c45fSAndroid Build Coastguard Worker             }
1618*38e8c45fSAndroid Build Coastguard Worker         }
1619*38e8c45fSAndroid Build Coastguard Worker     };
1620*38e8c45fSAndroid Build Coastguard Worker 
1621*38e8c45fSAndroid Build Coastguard Worker     auto scope_guard = android::base::make_scope_guard(deleter);
1622*38e8c45fSAndroid Build Coastguard Worker 
1623*38e8c45fSAndroid Build Coastguard Worker     if (storageFlags & FLAG_STORAGE_DE) {
1624*38e8c45fSAndroid Build Coastguard Worker         auto from = create_data_user_de_package_path(volume_uuid, userId, package_name);
1625*38e8c45fSAndroid Build Coastguard Worker         auto to = create_data_misc_de_rollback_path(volume_uuid, userId, snapshotId);
1626*38e8c45fSAndroid Build Coastguard Worker         auto rollback_package_path =
1627*38e8c45fSAndroid Build Coastguard Worker                 create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1628*38e8c45fSAndroid Build Coastguard Worker                                                           package_name);
1629*38e8c45fSAndroid Build Coastguard Worker 
1630*38e8c45fSAndroid Build Coastguard Worker         int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1631*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1632*38e8c45fSAndroid Build Coastguard Worker             return error(rc, "Failed to create folder " + to);
1633*38e8c45fSAndroid Build Coastguard Worker         }
1634*38e8c45fSAndroid Build Coastguard Worker 
1635*38e8c45fSAndroid Build Coastguard Worker         rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1636*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1637*38e8c45fSAndroid Build Coastguard Worker             return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1638*38e8c45fSAndroid Build Coastguard Worker         }
1639*38e8c45fSAndroid Build Coastguard Worker 
1640*38e8c45fSAndroid Build Coastguard Worker         // Check if we have data to copy.
1641*38e8c45fSAndroid Build Coastguard Worker         if (access(from.c_str(), F_OK) == 0) {
1642*38e8c45fSAndroid Build Coastguard Worker           rc = copy_directory_recursive(from.c_str(), to.c_str());
1643*38e8c45fSAndroid Build Coastguard Worker         }
1644*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1645*38e8c45fSAndroid Build Coastguard Worker             res = error(rc, "Failed copying " + from + " to " + to);
1646*38e8c45fSAndroid Build Coastguard Worker             clear_de_on_exit = true;
1647*38e8c45fSAndroid Build Coastguard Worker             return res;
1648*38e8c45fSAndroid Build Coastguard Worker         }
1649*38e8c45fSAndroid Build Coastguard Worker     }
1650*38e8c45fSAndroid Build Coastguard Worker 
1651*38e8c45fSAndroid Build Coastguard Worker     // The app may not have any data at all, in which case it's OK to skip here.
1652*38e8c45fSAndroid Build Coastguard Worker     auto from_ce = create_data_user_ce_package_path(volume_uuid, userId, package_name);
1653*38e8c45fSAndroid Build Coastguard Worker     if (access(from_ce.c_str(), F_OK) != 0) {
1654*38e8c45fSAndroid Build Coastguard Worker         LOG(INFO) << "Missing source " << from_ce;
1655*38e8c45fSAndroid Build Coastguard Worker         return ok();
1656*38e8c45fSAndroid Build Coastguard Worker     }
1657*38e8c45fSAndroid Build Coastguard Worker 
1658*38e8c45fSAndroid Build Coastguard Worker     // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
1659*38e8c45fSAndroid Build Coastguard Worker     binder::Status clear_cache_result =
1660*38e8c45fSAndroid Build Coastguard Worker             clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
1661*38e8c45fSAndroid Build Coastguard Worker     if (!clear_cache_result.isOk()) {
1662*38e8c45fSAndroid Build Coastguard Worker         // It should be fine to continue snapshot if we for some reason failed
1663*38e8c45fSAndroid Build Coastguard Worker         // to clear cache.
1664*38e8c45fSAndroid Build Coastguard Worker         LOG(WARNING) << "Failed to clear cache of app " << packageName;
1665*38e8c45fSAndroid Build Coastguard Worker     }
1666*38e8c45fSAndroid Build Coastguard Worker 
1667*38e8c45fSAndroid Build Coastguard Worker     // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
1668*38e8c45fSAndroid Build Coastguard Worker     binder::Status clear_code_cache_result =
1669*38e8c45fSAndroid Build Coastguard Worker             clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY,
1670*38e8c45fSAndroid Build Coastguard Worker                          0);
1671*38e8c45fSAndroid Build Coastguard Worker     if (!clear_code_cache_result.isOk()) {
1672*38e8c45fSAndroid Build Coastguard Worker         // It should be fine to continue snapshot if we for some reason failed
1673*38e8c45fSAndroid Build Coastguard Worker         // to clear code_cache.
1674*38e8c45fSAndroid Build Coastguard Worker         LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
1675*38e8c45fSAndroid Build Coastguard Worker     }
1676*38e8c45fSAndroid Build Coastguard Worker 
1677*38e8c45fSAndroid Build Coastguard Worker     if (storageFlags & FLAG_STORAGE_CE) {
1678*38e8c45fSAndroid Build Coastguard Worker         auto from = create_data_user_ce_package_path(volume_uuid, userId, package_name);
1679*38e8c45fSAndroid Build Coastguard Worker         auto to = create_data_misc_ce_rollback_path(volume_uuid, userId, snapshotId);
1680*38e8c45fSAndroid Build Coastguard Worker         auto rollback_package_path =
1681*38e8c45fSAndroid Build Coastguard Worker                 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1682*38e8c45fSAndroid Build Coastguard Worker                                                           package_name);
1683*38e8c45fSAndroid Build Coastguard Worker 
1684*38e8c45fSAndroid Build Coastguard Worker         int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1685*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1686*38e8c45fSAndroid Build Coastguard Worker             return error(rc, "Failed to create folder " + to);
1687*38e8c45fSAndroid Build Coastguard Worker         }
1688*38e8c45fSAndroid Build Coastguard Worker 
1689*38e8c45fSAndroid Build Coastguard Worker         rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1690*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1691*38e8c45fSAndroid Build Coastguard Worker             return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1692*38e8c45fSAndroid Build Coastguard Worker         }
1693*38e8c45fSAndroid Build Coastguard Worker 
1694*38e8c45fSAndroid Build Coastguard Worker         rc = copy_directory_recursive(from.c_str(), to.c_str());
1695*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1696*38e8c45fSAndroid Build Coastguard Worker             res = error(rc, "Failed copying " + from + " to " + to);
1697*38e8c45fSAndroid Build Coastguard Worker             clear_ce_on_exit = true;
1698*38e8c45fSAndroid Build Coastguard Worker             return res;
1699*38e8c45fSAndroid Build Coastguard Worker         }
1700*38e8c45fSAndroid Build Coastguard Worker         if (_aidl_return != nullptr) {
1701*38e8c45fSAndroid Build Coastguard Worker             auto ce_snapshot_path =
1702*38e8c45fSAndroid Build Coastguard Worker                     create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1703*38e8c45fSAndroid Build Coastguard Worker                                                               package_name);
1704*38e8c45fSAndroid Build Coastguard Worker             rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
1705*38e8c45fSAndroid Build Coastguard Worker             if (rc != 0) {
1706*38e8c45fSAndroid Build Coastguard Worker                 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
1707*38e8c45fSAndroid Build Coastguard Worker                 clear_ce_on_exit = true;
1708*38e8c45fSAndroid Build Coastguard Worker                 return res;
1709*38e8c45fSAndroid Build Coastguard Worker             }
1710*38e8c45fSAndroid Build Coastguard Worker         }
1711*38e8c45fSAndroid Build Coastguard Worker     }
1712*38e8c45fSAndroid Build Coastguard Worker 
1713*38e8c45fSAndroid Build Coastguard Worker     return res;
1714*38e8c45fSAndroid Build Coastguard Worker }
1715*38e8c45fSAndroid Build Coastguard Worker 
restoreAppDataSnapshot(const std::optional<std::string> & volumeUuid,const std::string & packageName,const int32_t appId,const std::string & seInfo,const int32_t userId,const int32_t snapshotId,int32_t storageFlags)1716*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::restoreAppDataSnapshot(
1717*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& volumeUuid, const std::string& packageName,
1718*38e8c45fSAndroid Build Coastguard Worker         const int32_t appId, const std::string& seInfo, const int32_t userId,
1719*38e8c45fSAndroid Build Coastguard Worker         const int32_t snapshotId, int32_t storageFlags) {
1720*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1721*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1722*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1723*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1724*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
1725*38e8c45fSAndroid Build Coastguard Worker 
1726*38e8c45fSAndroid Build Coastguard Worker     const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1727*38e8c45fSAndroid Build Coastguard Worker     const char* package_name = packageName.c_str();
1728*38e8c45fSAndroid Build Coastguard Worker 
1729*38e8c45fSAndroid Build Coastguard Worker     auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1730*38e8c45fSAndroid Build Coastguard Worker                                                              package_name);
1731*38e8c45fSAndroid Build Coastguard Worker     auto from_de = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1732*38e8c45fSAndroid Build Coastguard Worker                                                              package_name);
1733*38e8c45fSAndroid Build Coastguard Worker 
1734*38e8c45fSAndroid Build Coastguard Worker     const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
1735*38e8c45fSAndroid Build Coastguard Worker         (access(from_ce.c_str(), F_OK) == 0);
1736*38e8c45fSAndroid Build Coastguard Worker     const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
1737*38e8c45fSAndroid Build Coastguard Worker         (access(from_de.c_str(), F_OK) == 0);
1738*38e8c45fSAndroid Build Coastguard Worker 
1739*38e8c45fSAndroid Build Coastguard Worker     if (!needs_ce_rollback && !needs_de_rollback) {
1740*38e8c45fSAndroid Build Coastguard Worker         return ok();
1741*38e8c45fSAndroid Build Coastguard Worker     }
1742*38e8c45fSAndroid Build Coastguard Worker 
1743*38e8c45fSAndroid Build Coastguard Worker     // We know we're going to rollback one of the CE or DE data, so we clear
1744*38e8c45fSAndroid Build Coastguard Worker     // application data first. Note that it's possible that we're asked to
1745*38e8c45fSAndroid Build Coastguard Worker     // restore both CE & DE data but that one of the restores fail. Leaving the
1746*38e8c45fSAndroid Build Coastguard Worker     // app with no data in those cases is arguably better than leaving the app
1747*38e8c45fSAndroid Build Coastguard Worker     // with mismatched / stale data.
1748*38e8c45fSAndroid Build Coastguard Worker     LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
1749*38e8c45fSAndroid Build Coastguard Worker     // It's fine to pass 0 as ceDataInode here, because restoreAppDataSnapshot
1750*38e8c45fSAndroid Build Coastguard Worker     // can only be called when user unlocks the phone, meaning that CE user data
1751*38e8c45fSAndroid Build Coastguard Worker     // is decrypted.
1752*38e8c45fSAndroid Build Coastguard Worker     binder::Status res =
1753*38e8c45fSAndroid Build Coastguard Worker             clearAppData(volumeUuid, packageName, userId, storageFlags, 0 /* ceDataInode */);
1754*38e8c45fSAndroid Build Coastguard Worker     if (!res.isOk()) {
1755*38e8c45fSAndroid Build Coastguard Worker         return res;
1756*38e8c45fSAndroid Build Coastguard Worker     }
1757*38e8c45fSAndroid Build Coastguard Worker 
1758*38e8c45fSAndroid Build Coastguard Worker     if (needs_ce_rollback) {
1759*38e8c45fSAndroid Build Coastguard Worker         auto to_ce = create_data_user_ce_path(volume_uuid, userId);
1760*38e8c45fSAndroid Build Coastguard Worker         int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
1761*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1762*38e8c45fSAndroid Build Coastguard Worker             res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
1763*38e8c45fSAndroid Build Coastguard Worker             return res;
1764*38e8c45fSAndroid Build Coastguard Worker         }
1765*38e8c45fSAndroid Build Coastguard Worker         delete_dir_contents_and_dir(from_ce, true /* ignore_if_missing */);
1766*38e8c45fSAndroid Build Coastguard Worker     }
1767*38e8c45fSAndroid Build Coastguard Worker 
1768*38e8c45fSAndroid Build Coastguard Worker     if (needs_de_rollback) {
1769*38e8c45fSAndroid Build Coastguard Worker         auto to_de = create_data_user_de_path(volume_uuid, userId);
1770*38e8c45fSAndroid Build Coastguard Worker         int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
1771*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1772*38e8c45fSAndroid Build Coastguard Worker             if (needs_ce_rollback) {
1773*38e8c45fSAndroid Build Coastguard Worker                 auto ce_data = create_data_user_ce_package_path(volume_uuid, userId, package_name);
1774*38e8c45fSAndroid Build Coastguard Worker                 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
1775*38e8c45fSAndroid Build Coastguard Worker                 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
1776*38e8c45fSAndroid Build Coastguard Worker                     LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
1777*38e8c45fSAndroid Build Coastguard Worker                 }
1778*38e8c45fSAndroid Build Coastguard Worker             }
1779*38e8c45fSAndroid Build Coastguard Worker             res = error(rc, "Failed copying " + from_de + " to " + to_de);
1780*38e8c45fSAndroid Build Coastguard Worker             return res;
1781*38e8c45fSAndroid Build Coastguard Worker         }
1782*38e8c45fSAndroid Build Coastguard Worker         delete_dir_contents_and_dir(from_de, true /* ignore_if_missing */);
1783*38e8c45fSAndroid Build Coastguard Worker     }
1784*38e8c45fSAndroid Build Coastguard Worker 
1785*38e8c45fSAndroid Build Coastguard Worker     // Finally, restore the SELinux label on the app data.
1786*38e8c45fSAndroid Build Coastguard Worker     return restoreconAppData(volumeUuid, packageName, userId, storageFlags, appId, seInfo);
1787*38e8c45fSAndroid Build Coastguard Worker }
1788*38e8c45fSAndroid Build Coastguard Worker 
destroyAppDataSnapshot(const std::optional<std::string> & volumeUuid,const std::string & packageName,const int32_t userId,const int64_t ceSnapshotInode,const int32_t snapshotId,int32_t storageFlags)1789*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::destroyAppDataSnapshot(
1790*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& volumeUuid, const std::string& packageName,
1791*38e8c45fSAndroid Build Coastguard Worker         const int32_t userId, const int64_t ceSnapshotInode, const int32_t snapshotId,
1792*38e8c45fSAndroid Build Coastguard Worker         int32_t storageFlags) {
1793*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1794*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1795*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1796*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1797*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
1798*38e8c45fSAndroid Build Coastguard Worker 
1799*38e8c45fSAndroid Build Coastguard Worker     const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1800*38e8c45fSAndroid Build Coastguard Worker     const char* package_name = packageName.c_str();
1801*38e8c45fSAndroid Build Coastguard Worker 
1802*38e8c45fSAndroid Build Coastguard Worker     if (storageFlags & FLAG_STORAGE_DE) {
1803*38e8c45fSAndroid Build Coastguard Worker         auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid, userId,
1804*38e8c45fSAndroid Build Coastguard Worker                                                                           snapshotId, package_name);
1805*38e8c45fSAndroid Build Coastguard Worker 
1806*38e8c45fSAndroid Build Coastguard Worker         int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
1807*38e8c45fSAndroid Build Coastguard Worker         if (res != 0) {
1808*38e8c45fSAndroid Build Coastguard Worker             return error(res, "Failed clearing snapshot " + de_snapshot_path);
1809*38e8c45fSAndroid Build Coastguard Worker         }
1810*38e8c45fSAndroid Build Coastguard Worker     }
1811*38e8c45fSAndroid Build Coastguard Worker 
1812*38e8c45fSAndroid Build Coastguard Worker     if (storageFlags & FLAG_STORAGE_CE) {
1813*38e8c45fSAndroid Build Coastguard Worker         auto ce_snapshot_path =
1814*38e8c45fSAndroid Build Coastguard Worker                 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1815*38e8c45fSAndroid Build Coastguard Worker                                                           package_name, ceSnapshotInode);
1816*38e8c45fSAndroid Build Coastguard Worker         int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
1817*38e8c45fSAndroid Build Coastguard Worker         if (res != 0) {
1818*38e8c45fSAndroid Build Coastguard Worker             return error(res, "Failed clearing snapshot " + ce_snapshot_path);
1819*38e8c45fSAndroid Build Coastguard Worker         }
1820*38e8c45fSAndroid Build Coastguard Worker     }
1821*38e8c45fSAndroid Build Coastguard Worker     return ok();
1822*38e8c45fSAndroid Build Coastguard Worker }
1823*38e8c45fSAndroid Build Coastguard Worker 
destroyCeSnapshotsNotSpecified(const std::optional<std::string> & volumeUuid,const int32_t userId,const std::vector<int32_t> & retainSnapshotIds)1824*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::destroyCeSnapshotsNotSpecified(
1825*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& volumeUuid, const int32_t userId,
1826*38e8c45fSAndroid Build Coastguard Worker         const std::vector<int32_t>& retainSnapshotIds) {
1827*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1828*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
1829*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1830*38e8c45fSAndroid Build Coastguard Worker     LOCK_USER();
1831*38e8c45fSAndroid Build Coastguard Worker 
1832*38e8c45fSAndroid Build Coastguard Worker     const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1833*38e8c45fSAndroid Build Coastguard Worker 
1834*38e8c45fSAndroid Build Coastguard Worker     auto base_path = create_data_misc_ce_rollback_base_path(volume_uuid, userId);
1835*38e8c45fSAndroid Build Coastguard Worker 
1836*38e8c45fSAndroid Build Coastguard Worker     std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(base_path.c_str()), closedir);
1837*38e8c45fSAndroid Build Coastguard Worker     if (!dir) {
1838*38e8c45fSAndroid Build Coastguard Worker         return error(-1, "Failed to open rollback base dir " + base_path);
1839*38e8c45fSAndroid Build Coastguard Worker     }
1840*38e8c45fSAndroid Build Coastguard Worker 
1841*38e8c45fSAndroid Build Coastguard Worker     struct dirent* ent;
1842*38e8c45fSAndroid Build Coastguard Worker     while ((ent = readdir(dir.get()))) {
1843*38e8c45fSAndroid Build Coastguard Worker         if (ent->d_type != DT_DIR) {
1844*38e8c45fSAndroid Build Coastguard Worker             continue;
1845*38e8c45fSAndroid Build Coastguard Worker         }
1846*38e8c45fSAndroid Build Coastguard Worker 
1847*38e8c45fSAndroid Build Coastguard Worker         uint snapshot_id;
1848*38e8c45fSAndroid Build Coastguard Worker         bool parse_ok = ParseUint(ent->d_name, &snapshot_id);
1849*38e8c45fSAndroid Build Coastguard Worker         if (parse_ok &&
1850*38e8c45fSAndroid Build Coastguard Worker                 std::find(retainSnapshotIds.begin(), retainSnapshotIds.end(),
1851*38e8c45fSAndroid Build Coastguard Worker                           snapshot_id) == retainSnapshotIds.end()) {
1852*38e8c45fSAndroid Build Coastguard Worker             auto rollback_path =
1853*38e8c45fSAndroid Build Coastguard Worker                     create_data_misc_ce_rollback_path(volume_uuid, userId, snapshot_id);
1854*38e8c45fSAndroid Build Coastguard Worker             int res = delete_dir_contents_and_dir(rollback_path, true /* ignore_if_missing */);
1855*38e8c45fSAndroid Build Coastguard Worker             if (res != 0) {
1856*38e8c45fSAndroid Build Coastguard Worker                 return error(res, "Failed clearing snapshot " + rollback_path);
1857*38e8c45fSAndroid Build Coastguard Worker             }
1858*38e8c45fSAndroid Build Coastguard Worker         }
1859*38e8c45fSAndroid Build Coastguard Worker     }
1860*38e8c45fSAndroid Build Coastguard Worker     return ok();
1861*38e8c45fSAndroid Build Coastguard Worker }
1862*38e8c45fSAndroid Build Coastguard Worker 
moveCompleteApp(const std::optional<std::string> & fromUuid,const std::optional<std::string> & toUuid,const std::string & packageName,int32_t appId,const std::string & seInfo,int32_t targetSdkVersion,const std::string & fromCodePath)1863*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::moveCompleteApp(const std::optional<std::string>& fromUuid,
1864*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& toUuid, const std::string& packageName,
1865*38e8c45fSAndroid Build Coastguard Worker         int32_t appId, const std::string& seInfo,
1866*38e8c45fSAndroid Build Coastguard Worker         int32_t targetSdkVersion, const std::string& fromCodePath) {
1867*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
1868*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(fromUuid);
1869*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(toUuid);
1870*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1871*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
1872*38e8c45fSAndroid Build Coastguard Worker 
1873*38e8c45fSAndroid Build Coastguard Worker     const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1874*38e8c45fSAndroid Build Coastguard Worker     const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1875*38e8c45fSAndroid Build Coastguard Worker     const char* package_name = packageName.c_str();
1876*38e8c45fSAndroid Build Coastguard Worker 
1877*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
1878*38e8c45fSAndroid Build Coastguard Worker     std::vector<userid_t> users = get_known_users(from_uuid);
1879*38e8c45fSAndroid Build Coastguard Worker 
1880*38e8c45fSAndroid Build Coastguard Worker     auto to_app_package_path_parent = create_data_app_path(to_uuid);
1881*38e8c45fSAndroid Build Coastguard Worker     auto to_app_package_path = StringPrintf("%s/%s", to_app_package_path_parent.c_str(),
1882*38e8c45fSAndroid Build Coastguard Worker                                             android::base::Basename(fromCodePath).c_str());
1883*38e8c45fSAndroid Build Coastguard Worker 
1884*38e8c45fSAndroid Build Coastguard Worker     // Copy app
1885*38e8c45fSAndroid Build Coastguard Worker     {
1886*38e8c45fSAndroid Build Coastguard Worker         int rc = copy_directory_recursive(fromCodePath.c_str(), to_app_package_path_parent.c_str());
1887*38e8c45fSAndroid Build Coastguard Worker         if (rc != 0) {
1888*38e8c45fSAndroid Build Coastguard Worker             res = error(rc, "Failed copying " + fromCodePath + " to " + to_app_package_path);
1889*38e8c45fSAndroid Build Coastguard Worker             goto fail;
1890*38e8c45fSAndroid Build Coastguard Worker         }
1891*38e8c45fSAndroid Build Coastguard Worker 
1892*38e8c45fSAndroid Build Coastguard Worker         if (selinux_android_restorecon(to_app_package_path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
1893*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to restorecon " + to_app_package_path);
1894*38e8c45fSAndroid Build Coastguard Worker             goto fail;
1895*38e8c45fSAndroid Build Coastguard Worker         }
1896*38e8c45fSAndroid Build Coastguard Worker     }
1897*38e8c45fSAndroid Build Coastguard Worker 
1898*38e8c45fSAndroid Build Coastguard Worker     // Copy private data for all known users
1899*38e8c45fSAndroid Build Coastguard Worker     for (auto userId : users) {
1900*38e8c45fSAndroid Build Coastguard Worker         LOCK_USER();
1901*38e8c45fSAndroid Build Coastguard Worker 
1902*38e8c45fSAndroid Build Coastguard Worker         // Data source may not exist for all users; that's okay
1903*38e8c45fSAndroid Build Coastguard Worker         auto from_ce = create_data_user_ce_package_path(from_uuid, userId, package_name);
1904*38e8c45fSAndroid Build Coastguard Worker         if (access(from_ce.c_str(), F_OK) != 0) {
1905*38e8c45fSAndroid Build Coastguard Worker             LOG(INFO) << "Missing source " << from_ce;
1906*38e8c45fSAndroid Build Coastguard Worker             continue;
1907*38e8c45fSAndroid Build Coastguard Worker         }
1908*38e8c45fSAndroid Build Coastguard Worker 
1909*38e8c45fSAndroid Build Coastguard Worker         if (!createAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1910*38e8c45fSAndroid Build Coastguard Worker                                  appId, /* previousAppId */ -1, seInfo, targetSdkVersion, nullptr,
1911*38e8c45fSAndroid Build Coastguard Worker                                  nullptr)
1912*38e8c45fSAndroid Build Coastguard Worker                      .isOk()) {
1913*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to create package target");
1914*38e8c45fSAndroid Build Coastguard Worker             goto fail;
1915*38e8c45fSAndroid Build Coastguard Worker         }
1916*38e8c45fSAndroid Build Coastguard Worker         {
1917*38e8c45fSAndroid Build Coastguard Worker             auto from = create_data_user_de_package_path(from_uuid, userId, package_name);
1918*38e8c45fSAndroid Build Coastguard Worker             auto to = create_data_user_de_path(to_uuid, userId);
1919*38e8c45fSAndroid Build Coastguard Worker 
1920*38e8c45fSAndroid Build Coastguard Worker             int rc = copy_directory_recursive(from.c_str(), to.c_str());
1921*38e8c45fSAndroid Build Coastguard Worker             if (rc != 0) {
1922*38e8c45fSAndroid Build Coastguard Worker                 res = error(rc, "Failed copying " + from + " to " + to);
1923*38e8c45fSAndroid Build Coastguard Worker                 goto fail;
1924*38e8c45fSAndroid Build Coastguard Worker             }
1925*38e8c45fSAndroid Build Coastguard Worker         }
1926*38e8c45fSAndroid Build Coastguard Worker         {
1927*38e8c45fSAndroid Build Coastguard Worker             auto from = create_data_user_ce_package_path(from_uuid, userId, package_name);
1928*38e8c45fSAndroid Build Coastguard Worker             auto to = create_data_user_ce_path(to_uuid, userId);
1929*38e8c45fSAndroid Build Coastguard Worker 
1930*38e8c45fSAndroid Build Coastguard Worker             int rc = copy_directory_recursive(from.c_str(), to.c_str());
1931*38e8c45fSAndroid Build Coastguard Worker             if (rc != 0) {
1932*38e8c45fSAndroid Build Coastguard Worker                 res = error(rc, "Failed copying " + from + " to " + to);
1933*38e8c45fSAndroid Build Coastguard Worker                 goto fail;
1934*38e8c45fSAndroid Build Coastguard Worker             }
1935*38e8c45fSAndroid Build Coastguard Worker         }
1936*38e8c45fSAndroid Build Coastguard Worker 
1937*38e8c45fSAndroid Build Coastguard Worker         if (!restoreconAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1938*38e8c45fSAndroid Build Coastguard Worker                                      appId, seInfo)
1939*38e8c45fSAndroid Build Coastguard Worker                      .isOk()) {
1940*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to restorecon");
1941*38e8c45fSAndroid Build Coastguard Worker             goto fail;
1942*38e8c45fSAndroid Build Coastguard Worker         }
1943*38e8c45fSAndroid Build Coastguard Worker     }
1944*38e8c45fSAndroid Build Coastguard Worker 
1945*38e8c45fSAndroid Build Coastguard Worker     // Copy sdk data for all known users
1946*38e8c45fSAndroid Build Coastguard Worker     for (auto userId : users) {
1947*38e8c45fSAndroid Build Coastguard Worker         LOCK_USER();
1948*38e8c45fSAndroid Build Coastguard Worker 
1949*38e8c45fSAndroid Build Coastguard Worker         constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1950*38e8c45fSAndroid Build Coastguard Worker         for (int currentFlag : storageFlags) {
1951*38e8c45fSAndroid Build Coastguard Worker             const bool isCeData = currentFlag == FLAG_STORAGE_CE;
1952*38e8c45fSAndroid Build Coastguard Worker 
1953*38e8c45fSAndroid Build Coastguard Worker             const auto from = create_data_misc_sdk_sandbox_package_path(from_uuid, isCeData, userId,
1954*38e8c45fSAndroid Build Coastguard Worker                                                                         package_name);
1955*38e8c45fSAndroid Build Coastguard Worker             if (access(from.c_str(), F_OK) != 0) {
1956*38e8c45fSAndroid Build Coastguard Worker                 LOG(INFO) << "Missing source " << from;
1957*38e8c45fSAndroid Build Coastguard Worker                 continue;
1958*38e8c45fSAndroid Build Coastguard Worker             }
1959*38e8c45fSAndroid Build Coastguard Worker             const auto to = create_data_misc_sdk_sandbox_path(to_uuid, isCeData, userId);
1960*38e8c45fSAndroid Build Coastguard Worker 
1961*38e8c45fSAndroid Build Coastguard Worker             const int rc = copy_directory_recursive(from.c_str(), to.c_str());
1962*38e8c45fSAndroid Build Coastguard Worker             if (rc != 0) {
1963*38e8c45fSAndroid Build Coastguard Worker                 res = error(rc, "Failed copying " + from + " to " + to);
1964*38e8c45fSAndroid Build Coastguard Worker                 goto fail;
1965*38e8c45fSAndroid Build Coastguard Worker             }
1966*38e8c45fSAndroid Build Coastguard Worker         }
1967*38e8c45fSAndroid Build Coastguard Worker 
1968*38e8c45fSAndroid Build Coastguard Worker         if (!restoreconSdkDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1969*38e8c45fSAndroid Build Coastguard Worker                                      appId, seInfo)
1970*38e8c45fSAndroid Build Coastguard Worker                      .isOk()) {
1971*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to restorecon");
1972*38e8c45fSAndroid Build Coastguard Worker             goto fail;
1973*38e8c45fSAndroid Build Coastguard Worker         }
1974*38e8c45fSAndroid Build Coastguard Worker     }
1975*38e8c45fSAndroid Build Coastguard Worker     // We let the framework scan the new location and persist that before
1976*38e8c45fSAndroid Build Coastguard Worker     // deleting the data in the old location; this ordering ensures that
1977*38e8c45fSAndroid Build Coastguard Worker     // we can recover from things like battery pulls.
1978*38e8c45fSAndroid Build Coastguard Worker     return ok();
1979*38e8c45fSAndroid Build Coastguard Worker 
1980*38e8c45fSAndroid Build Coastguard Worker fail:
1981*38e8c45fSAndroid Build Coastguard Worker     // Nuke everything we might have already copied
1982*38e8c45fSAndroid Build Coastguard Worker     {
1983*38e8c45fSAndroid Build Coastguard Worker         if (delete_dir_contents(to_app_package_path.c_str(), 1, nullptr) != 0) {
1984*38e8c45fSAndroid Build Coastguard Worker             LOG(WARNING) << "Failed to rollback " << to_app_package_path;
1985*38e8c45fSAndroid Build Coastguard Worker         }
1986*38e8c45fSAndroid Build Coastguard Worker     }
1987*38e8c45fSAndroid Build Coastguard Worker     for (auto userId : users) {
1988*38e8c45fSAndroid Build Coastguard Worker         LOCK_USER();
1989*38e8c45fSAndroid Build Coastguard Worker         {
1990*38e8c45fSAndroid Build Coastguard Worker             auto to = create_data_user_de_package_path(to_uuid, userId, package_name);
1991*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1992*38e8c45fSAndroid Build Coastguard Worker                 LOG(WARNING) << "Failed to rollback " << to;
1993*38e8c45fSAndroid Build Coastguard Worker             }
1994*38e8c45fSAndroid Build Coastguard Worker         }
1995*38e8c45fSAndroid Build Coastguard Worker         {
1996*38e8c45fSAndroid Build Coastguard Worker             auto to = create_data_user_ce_package_path(to_uuid, userId, package_name);
1997*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1998*38e8c45fSAndroid Build Coastguard Worker                 LOG(WARNING) << "Failed to rollback " << to;
1999*38e8c45fSAndroid Build Coastguard Worker             }
2000*38e8c45fSAndroid Build Coastguard Worker         }
2001*38e8c45fSAndroid Build Coastguard Worker     }
2002*38e8c45fSAndroid Build Coastguard Worker     for (auto userId : users) {
2003*38e8c45fSAndroid Build Coastguard Worker         LOCK_USER();
2004*38e8c45fSAndroid Build Coastguard Worker         constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
2005*38e8c45fSAndroid Build Coastguard Worker         for (int currentFlag : storageFlags) {
2006*38e8c45fSAndroid Build Coastguard Worker             const bool isCeData = currentFlag == FLAG_STORAGE_CE;
2007*38e8c45fSAndroid Build Coastguard Worker             const auto to = create_data_misc_sdk_sandbox_package_path(to_uuid, isCeData, userId,
2008*38e8c45fSAndroid Build Coastguard Worker                                                                       package_name);
2009*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
2010*38e8c45fSAndroid Build Coastguard Worker                 LOG(WARNING) << "Failed to rollback " << to;
2011*38e8c45fSAndroid Build Coastguard Worker             }
2012*38e8c45fSAndroid Build Coastguard Worker         }
2013*38e8c45fSAndroid Build Coastguard Worker     }
2014*38e8c45fSAndroid Build Coastguard Worker     return res;
2015*38e8c45fSAndroid Build Coastguard Worker }
2016*38e8c45fSAndroid Build Coastguard Worker 
createUserData(const std::optional<std::string> & uuid,int32_t userId,int32_t userSerial ATTRIBUTE_UNUSED,int32_t flags)2017*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createUserData(const std::optional<std::string>& uuid,
2018*38e8c45fSAndroid Build Coastguard Worker         int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
2019*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
2020*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
2021*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
2022*38e8c45fSAndroid Build Coastguard Worker     LOCK_USER();
2023*38e8c45fSAndroid Build Coastguard Worker 
2024*38e8c45fSAndroid Build Coastguard Worker     ScopedTrace tracer("create-user-data");
2025*38e8c45fSAndroid Build Coastguard Worker 
2026*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2027*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_DE) {
2028*38e8c45fSAndroid Build Coastguard Worker         if (uuid_ == nullptr) {
2029*38e8c45fSAndroid Build Coastguard Worker             if (ensure_config_user_dirs(userId) != 0) {
2030*38e8c45fSAndroid Build Coastguard Worker                 return error(StringPrintf("Failed to ensure dirs for %d", userId));
2031*38e8c45fSAndroid Build Coastguard Worker             }
2032*38e8c45fSAndroid Build Coastguard Worker         }
2033*38e8c45fSAndroid Build Coastguard Worker     }
2034*38e8c45fSAndroid Build Coastguard Worker 
2035*38e8c45fSAndroid Build Coastguard Worker     return ok();
2036*38e8c45fSAndroid Build Coastguard Worker }
2037*38e8c45fSAndroid Build Coastguard Worker 
destroyUserData(const std::optional<std::string> & uuid,int32_t userId,int32_t flags)2038*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::destroyUserData(const std::optional<std::string>& uuid,
2039*38e8c45fSAndroid Build Coastguard Worker         int32_t userId, int32_t flags) {
2040*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
2041*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
2042*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
2043*38e8c45fSAndroid Build Coastguard Worker     LOCK_USER();
2044*38e8c45fSAndroid Build Coastguard Worker 
2045*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2046*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
2047*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_DE) {
2048*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_de_path(uuid_, userId);
2049*38e8c45fSAndroid Build Coastguard Worker         // Contents only, as vold is responsible for the user_de dir itself.
2050*38e8c45fSAndroid Build Coastguard Worker         if (delete_dir_contents(path, true) != 0) {
2051*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to delete contents of " + path);
2052*38e8c45fSAndroid Build Coastguard Worker         }
2053*38e8c45fSAndroid Build Coastguard Worker         auto sdk_sandbox_de_path =
2054*38e8c45fSAndroid Build Coastguard Worker                 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
2055*38e8c45fSAndroid Build Coastguard Worker         if (delete_dir_contents_and_dir(sdk_sandbox_de_path, true) != 0) {
2056*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to delete " + sdk_sandbox_de_path);
2057*38e8c45fSAndroid Build Coastguard Worker         }
2058*38e8c45fSAndroid Build Coastguard Worker         if (uuid_ == nullptr) {
2059*38e8c45fSAndroid Build Coastguard Worker             path = create_data_misc_legacy_path(userId);
2060*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents_and_dir(path, true) != 0) {
2061*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to delete " + path);
2062*38e8c45fSAndroid Build Coastguard Worker             }
2063*38e8c45fSAndroid Build Coastguard Worker             path = create_primary_cur_profile_dir_path(userId);
2064*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents_and_dir(path, true) != 0) {
2065*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to delete " + path);
2066*38e8c45fSAndroid Build Coastguard Worker             }
2067*38e8c45fSAndroid Build Coastguard Worker         }
2068*38e8c45fSAndroid Build Coastguard Worker     }
2069*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_CE) {
2070*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_ce_path(uuid_, userId);
2071*38e8c45fSAndroid Build Coastguard Worker         // Contents only, as vold is responsible for the user_ce dir itself.
2072*38e8c45fSAndroid Build Coastguard Worker         if (delete_dir_contents(path, true) != 0) {
2073*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to delete contents of " + path);
2074*38e8c45fSAndroid Build Coastguard Worker         }
2075*38e8c45fSAndroid Build Coastguard Worker         auto sdk_sandbox_ce_path =
2076*38e8c45fSAndroid Build Coastguard Worker                 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2077*38e8c45fSAndroid Build Coastguard Worker         if (delete_dir_contents_and_dir(sdk_sandbox_ce_path, true) != 0) {
2078*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to delete " + sdk_sandbox_ce_path);
2079*38e8c45fSAndroid Build Coastguard Worker         }
2080*38e8c45fSAndroid Build Coastguard Worker         path = findDataMediaPath(uuid, userId);
2081*38e8c45fSAndroid Build Coastguard Worker         // Contents only, as vold is responsible for the media dir itself.
2082*38e8c45fSAndroid Build Coastguard Worker         if (delete_dir_contents(path, true) != 0) {
2083*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to delete contents of " + path);
2084*38e8c45fSAndroid Build Coastguard Worker         }
2085*38e8c45fSAndroid Build Coastguard Worker     }
2086*38e8c45fSAndroid Build Coastguard Worker     return res;
2087*38e8c45fSAndroid Build Coastguard Worker }
2088*38e8c45fSAndroid Build Coastguard Worker 
freeCache(const std::optional<std::string> & uuid,int64_t targetFreeBytes,int32_t flags)2089*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::freeCache(const std::optional<std::string>& uuid,
2090*38e8c45fSAndroid Build Coastguard Worker         int64_t targetFreeBytes, int32_t flags) {
2091*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
2092*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
2093*38e8c45fSAndroid Build Coastguard Worker #ifndef GRANULAR_LOCKS
2094*38e8c45fSAndroid Build Coastguard Worker     std::lock_guard lock(mLock);
2095*38e8c45fSAndroid Build Coastguard Worker #endif // !GRANULAR_LOCKS
2096*38e8c45fSAndroid Build Coastguard Worker 
2097*38e8c45fSAndroid Build Coastguard Worker     auto uuidString = uuid.value_or("");
2098*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2099*38e8c45fSAndroid Build Coastguard Worker     auto data_path = create_data_path(uuid_);
2100*38e8c45fSAndroid Build Coastguard Worker     auto noop = (flags & FLAG_FREE_CACHE_NOOP);
2101*38e8c45fSAndroid Build Coastguard Worker     auto defy_target = (flags & FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES);
2102*38e8c45fSAndroid Build Coastguard Worker 
2103*38e8c45fSAndroid Build Coastguard Worker     int64_t free = data_disk_free(data_path);
2104*38e8c45fSAndroid Build Coastguard Worker     if (free < 0) {
2105*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to determine free space for " + data_path);
2106*38e8c45fSAndroid Build Coastguard Worker     }
2107*38e8c45fSAndroid Build Coastguard Worker 
2108*38e8c45fSAndroid Build Coastguard Worker     int64_t needed = targetFreeBytes - free;
2109*38e8c45fSAndroid Build Coastguard Worker     if (!defy_target) {
2110*38e8c45fSAndroid Build Coastguard Worker         LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
2111*38e8c45fSAndroid Build Coastguard Worker                 << targetFreeBytes << "; needed " << needed;
2112*38e8c45fSAndroid Build Coastguard Worker 
2113*38e8c45fSAndroid Build Coastguard Worker         if (free >= targetFreeBytes) {
2114*38e8c45fSAndroid Build Coastguard Worker             return ok();
2115*38e8c45fSAndroid Build Coastguard Worker         }
2116*38e8c45fSAndroid Build Coastguard Worker     }
2117*38e8c45fSAndroid Build Coastguard Worker 
2118*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_FREE_CACHE_V2) {
2119*38e8c45fSAndroid Build Coastguard Worker         // This new cache strategy fairly removes files from UIDs by deleting
2120*38e8c45fSAndroid Build Coastguard Worker         // files from the UIDs which are most over their allocated quota
2121*38e8c45fSAndroid Build Coastguard Worker 
2122*38e8c45fSAndroid Build Coastguard Worker         // 1. Create trackers for every known UID
2123*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("create");
2124*38e8c45fSAndroid Build Coastguard Worker         const auto users = get_known_users(uuid_);
2125*38e8c45fSAndroid Build Coastguard Worker #ifdef GRANULAR_LOCKS
2126*38e8c45fSAndroid Build Coastguard Worker         std::vector<UserLock> userLocks;
2127*38e8c45fSAndroid Build Coastguard Worker         userLocks.reserve(users.size());
2128*38e8c45fSAndroid Build Coastguard Worker         std::vector<UserWriteLockGuard> lockGuards;
2129*38e8c45fSAndroid Build Coastguard Worker         lockGuards.reserve(users.size());
2130*38e8c45fSAndroid Build Coastguard Worker #endif // GRANULAR_LOCKS
2131*38e8c45fSAndroid Build Coastguard Worker         std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
2132*38e8c45fSAndroid Build Coastguard Worker         for (auto userId : users) {
2133*38e8c45fSAndroid Build Coastguard Worker #ifdef GRANULAR_LOCKS
2134*38e8c45fSAndroid Build Coastguard Worker             userLocks.emplace_back(userId, mUserIdLock, mLock);
2135*38e8c45fSAndroid Build Coastguard Worker             lockGuards.emplace_back(userLocks.back());
2136*38e8c45fSAndroid Build Coastguard Worker #endif // GRANULAR_LOCKS
2137*38e8c45fSAndroid Build Coastguard Worker             FTS *fts;
2138*38e8c45fSAndroid Build Coastguard Worker             FTSENT *p;
2139*38e8c45fSAndroid Build Coastguard Worker 
2140*38e8c45fSAndroid Build Coastguard Worker             // Create a list of data paths whose children have cache directories
2141*38e8c45fSAndroid Build Coastguard Worker             auto ce_path = create_data_user_ce_path(uuid_, userId);
2142*38e8c45fSAndroid Build Coastguard Worker             auto de_path = create_data_user_de_path(uuid_, userId);
2143*38e8c45fSAndroid Build Coastguard Worker             auto media_path = findDataMediaPath(uuid, userId) + "/Android/data/";
2144*38e8c45fSAndroid Build Coastguard Worker             auto ce_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2145*38e8c45fSAndroid Build Coastguard Worker             auto de_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
2146*38e8c45fSAndroid Build Coastguard Worker 
2147*38e8c45fSAndroid Build Coastguard Worker             std::vector<std::string> dataPaths = {ce_path, de_path, media_path};
2148*38e8c45fSAndroid Build Coastguard Worker             foreach_subdir(ce_sdk_path, [&ce_sdk_path, &dataPaths](const std::string subDir) {
2149*38e8c45fSAndroid Build Coastguard Worker                 const auto fullpath = ce_sdk_path + "/" + subDir;
2150*38e8c45fSAndroid Build Coastguard Worker                 dataPaths.push_back(fullpath);
2151*38e8c45fSAndroid Build Coastguard Worker             });
2152*38e8c45fSAndroid Build Coastguard Worker             foreach_subdir(de_sdk_path, [&de_sdk_path, &dataPaths](const std::string subDir) {
2153*38e8c45fSAndroid Build Coastguard Worker                 const auto fullpath = de_sdk_path + "/" + subDir;
2154*38e8c45fSAndroid Build Coastguard Worker                 dataPaths.push_back((char*)fullpath.c_str());
2155*38e8c45fSAndroid Build Coastguard Worker             });
2156*38e8c45fSAndroid Build Coastguard Worker 
2157*38e8c45fSAndroid Build Coastguard Worker             char* argv[dataPaths.size() + 1];
2158*38e8c45fSAndroid Build Coastguard Worker             for (unsigned int i = 0; i < dataPaths.size(); i++) {
2159*38e8c45fSAndroid Build Coastguard Worker                 argv[i] = (char*)dataPaths[i].c_str();
2160*38e8c45fSAndroid Build Coastguard Worker             }
2161*38e8c45fSAndroid Build Coastguard Worker             argv[dataPaths.size()] = nullptr;
2162*38e8c45fSAndroid Build Coastguard Worker 
2163*38e8c45fSAndroid Build Coastguard Worker             if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
2164*38e8c45fSAndroid Build Coastguard Worker                 return error("Failed to fts_open");
2165*38e8c45fSAndroid Build Coastguard Worker             }
2166*38e8c45fSAndroid Build Coastguard Worker             while ((p = fts_read(fts)) != nullptr) {
2167*38e8c45fSAndroid Build Coastguard Worker                 if (p->fts_info == FTS_D && p->fts_level == 1) {
2168*38e8c45fSAndroid Build Coastguard Worker                     uid_t uid = p->fts_statp->st_uid;
2169*38e8c45fSAndroid Build Coastguard Worker 
2170*38e8c45fSAndroid Build Coastguard Worker                     // If uid belongs to sdk sandbox, then the cache should be attributed to the
2171*38e8c45fSAndroid Build Coastguard Worker                     // original client app.
2172*38e8c45fSAndroid Build Coastguard Worker                     const auto client_uid = multiuser_convert_sdk_sandbox_to_app_uid(uid);
2173*38e8c45fSAndroid Build Coastguard Worker                     const bool isSandboxUid = (client_uid != (uid_t)-1);
2174*38e8c45fSAndroid Build Coastguard Worker                     if (isSandboxUid) uid = client_uid;
2175*38e8c45fSAndroid Build Coastguard Worker 
2176*38e8c45fSAndroid Build Coastguard Worker                     if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
2177*38e8c45fSAndroid Build Coastguard Worker                         uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
2178*38e8c45fSAndroid Build Coastguard Worker                                 + AID_APP_START;
2179*38e8c45fSAndroid Build Coastguard Worker                     }
2180*38e8c45fSAndroid Build Coastguard Worker                     auto search = trackers.find(uid);
2181*38e8c45fSAndroid Build Coastguard Worker                     if (search != trackers.end()) {
2182*38e8c45fSAndroid Build Coastguard Worker                         search->second->addDataPath(p->fts_path);
2183*38e8c45fSAndroid Build Coastguard Worker                     } else {
2184*38e8c45fSAndroid Build Coastguard Worker                         auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
2185*38e8c45fSAndroid Build Coastguard Worker                                 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
2186*38e8c45fSAndroid Build Coastguard Worker                         tracker->addDataPath(p->fts_path);
2187*38e8c45fSAndroid Build Coastguard Worker                         {
2188*38e8c45fSAndroid Build Coastguard Worker                             std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
2189*38e8c45fSAndroid Build Coastguard Worker                             tracker->cacheQuota = mCacheQuotas[uid];
2190*38e8c45fSAndroid Build Coastguard Worker                         }
2191*38e8c45fSAndroid Build Coastguard Worker                         if (tracker->cacheQuota == 0) {
2192*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
2193*38e8c45fSAndroid Build Coastguard Worker                             LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
2194*38e8c45fSAndroid Build Coastguard Worker #endif
2195*38e8c45fSAndroid Build Coastguard Worker                             tracker->cacheQuota = 67108864;
2196*38e8c45fSAndroid Build Coastguard Worker                         }
2197*38e8c45fSAndroid Build Coastguard Worker                         trackers[uid] = tracker;
2198*38e8c45fSAndroid Build Coastguard Worker                     }
2199*38e8c45fSAndroid Build Coastguard Worker                     fts_set(fts, p, FTS_SKIP);
2200*38e8c45fSAndroid Build Coastguard Worker                 }
2201*38e8c45fSAndroid Build Coastguard Worker             }
2202*38e8c45fSAndroid Build Coastguard Worker             fts_close(fts);
2203*38e8c45fSAndroid Build Coastguard Worker         }
2204*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2205*38e8c45fSAndroid Build Coastguard Worker 
2206*38e8c45fSAndroid Build Coastguard Worker         // 2. Populate tracker stats and insert into priority queue
2207*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("populate");
2208*38e8c45fSAndroid Build Coastguard Worker         auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
2209*38e8c45fSAndroid Build Coastguard Worker             return (left->getCacheRatio() < right->getCacheRatio());
2210*38e8c45fSAndroid Build Coastguard Worker         };
2211*38e8c45fSAndroid Build Coastguard Worker         std::priority_queue<std::shared_ptr<CacheTracker>,
2212*38e8c45fSAndroid Build Coastguard Worker                 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
2213*38e8c45fSAndroid Build Coastguard Worker         for (const auto& it : trackers) {
2214*38e8c45fSAndroid Build Coastguard Worker             it.second->loadStats();
2215*38e8c45fSAndroid Build Coastguard Worker             queue.push(it.second);
2216*38e8c45fSAndroid Build Coastguard Worker         }
2217*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2218*38e8c45fSAndroid Build Coastguard Worker 
2219*38e8c45fSAndroid Build Coastguard Worker         // 3. Bounce across the queue, freeing items from whichever tracker is
2220*38e8c45fSAndroid Build Coastguard Worker         // the most over their assigned quota
2221*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("bounce");
2222*38e8c45fSAndroid Build Coastguard Worker         std::shared_ptr<CacheTracker> active;
2223*38e8c45fSAndroid Build Coastguard Worker         while (active || !queue.empty()) {
2224*38e8c45fSAndroid Build Coastguard Worker             // Only look at apps under quota when explicitly requested
2225*38e8c45fSAndroid Build Coastguard Worker             if (active && (active->getCacheRatio() < 10000)
2226*38e8c45fSAndroid Build Coastguard Worker                     && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
2227*38e8c45fSAndroid Build Coastguard Worker                 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
2228*38e8c45fSAndroid Build Coastguard Worker                         << " isn't over quota, and defy not requested";
2229*38e8c45fSAndroid Build Coastguard Worker                 break;
2230*38e8c45fSAndroid Build Coastguard Worker             }
2231*38e8c45fSAndroid Build Coastguard Worker 
2232*38e8c45fSAndroid Build Coastguard Worker             // Find the best tracker to work with; this might involve swapping
2233*38e8c45fSAndroid Build Coastguard Worker             // if the active tracker is no longer the most over quota
2234*38e8c45fSAndroid Build Coastguard Worker             bool nextBetter = active && !queue.empty()
2235*38e8c45fSAndroid Build Coastguard Worker                     && active->getCacheRatio() < queue.top()->getCacheRatio();
2236*38e8c45fSAndroid Build Coastguard Worker             if (!active || nextBetter) {
2237*38e8c45fSAndroid Build Coastguard Worker                 if (active) {
2238*38e8c45fSAndroid Build Coastguard Worker                     // Current tracker still has items, so we'll consider it
2239*38e8c45fSAndroid Build Coastguard Worker                     // again later once it bubbles up to surface
2240*38e8c45fSAndroid Build Coastguard Worker                     queue.push(active);
2241*38e8c45fSAndroid Build Coastguard Worker                 }
2242*38e8c45fSAndroid Build Coastguard Worker                 active = queue.top(); queue.pop();
2243*38e8c45fSAndroid Build Coastguard Worker                 active->ensureItems();
2244*38e8c45fSAndroid Build Coastguard Worker                 continue;
2245*38e8c45fSAndroid Build Coastguard Worker             }
2246*38e8c45fSAndroid Build Coastguard Worker 
2247*38e8c45fSAndroid Build Coastguard Worker             // If no items remain, go find another tracker
2248*38e8c45fSAndroid Build Coastguard Worker             if (active->items.empty()) {
2249*38e8c45fSAndroid Build Coastguard Worker                 active = nullptr;
2250*38e8c45fSAndroid Build Coastguard Worker                 continue;
2251*38e8c45fSAndroid Build Coastguard Worker             } else {
2252*38e8c45fSAndroid Build Coastguard Worker                 auto item = active->items.back();
2253*38e8c45fSAndroid Build Coastguard Worker                 active->items.pop_back();
2254*38e8c45fSAndroid Build Coastguard Worker 
2255*38e8c45fSAndroid Build Coastguard Worker                 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
2256*38e8c45fSAndroid Build Coastguard Worker                 if (!noop) {
2257*38e8c45fSAndroid Build Coastguard Worker                     item->purge();
2258*38e8c45fSAndroid Build Coastguard Worker                 }
2259*38e8c45fSAndroid Build Coastguard Worker                 active->cacheUsed -= item->size;
2260*38e8c45fSAndroid Build Coastguard Worker                 needed -= item->size;
2261*38e8c45fSAndroid Build Coastguard Worker             }
2262*38e8c45fSAndroid Build Coastguard Worker 
2263*38e8c45fSAndroid Build Coastguard Worker             if (!defy_target) {
2264*38e8c45fSAndroid Build Coastguard Worker                 // Verify that we're actually done before bailing, since sneaky
2265*38e8c45fSAndroid Build Coastguard Worker                 // apps might be using hardlinks
2266*38e8c45fSAndroid Build Coastguard Worker                 if (needed <= 0) {
2267*38e8c45fSAndroid Build Coastguard Worker                     free = data_disk_free(data_path);
2268*38e8c45fSAndroid Build Coastguard Worker                     needed = targetFreeBytes - free;
2269*38e8c45fSAndroid Build Coastguard Worker                     if (needed <= 0) {
2270*38e8c45fSAndroid Build Coastguard Worker                         break;
2271*38e8c45fSAndroid Build Coastguard Worker                     } else {
2272*38e8c45fSAndroid Build Coastguard Worker                         LOG(WARNING) << "Expected to be done but still need " << needed;
2273*38e8c45fSAndroid Build Coastguard Worker                     }
2274*38e8c45fSAndroid Build Coastguard Worker                 }
2275*38e8c45fSAndroid Build Coastguard Worker             }
2276*38e8c45fSAndroid Build Coastguard Worker         }
2277*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2278*38e8c45fSAndroid Build Coastguard Worker 
2279*38e8c45fSAndroid Build Coastguard Worker     } else {
2280*38e8c45fSAndroid Build Coastguard Worker         return error("Legacy cache logic no longer supported");
2281*38e8c45fSAndroid Build Coastguard Worker     }
2282*38e8c45fSAndroid Build Coastguard Worker 
2283*38e8c45fSAndroid Build Coastguard Worker     if (!defy_target) {
2284*38e8c45fSAndroid Build Coastguard Worker         free = data_disk_free(data_path);
2285*38e8c45fSAndroid Build Coastguard Worker         if (free >= targetFreeBytes) {
2286*38e8c45fSAndroid Build Coastguard Worker             return ok();
2287*38e8c45fSAndroid Build Coastguard Worker         } else {
2288*38e8c45fSAndroid Build Coastguard Worker             return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
2289*38e8c45fSAndroid Build Coastguard Worker                     targetFreeBytes, data_path.c_str(), free));
2290*38e8c45fSAndroid Build Coastguard Worker         }
2291*38e8c45fSAndroid Build Coastguard Worker     } else {
2292*38e8c45fSAndroid Build Coastguard Worker         return ok();
2293*38e8c45fSAndroid Build Coastguard Worker     }
2294*38e8c45fSAndroid Build Coastguard Worker }
2295*38e8c45fSAndroid Build Coastguard Worker 
rmdex(const std::string & codePath,const std::string & instructionSet)2296*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::rmdex(const std::string& codePath,
2297*38e8c45fSAndroid Build Coastguard Worker         const std::string& instructionSet) {
2298*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
2299*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(codePath);
2300*38e8c45fSAndroid Build Coastguard Worker 
2301*38e8c45fSAndroid Build Coastguard Worker     char dex_path[PKG_PATH_MAX];
2302*38e8c45fSAndroid Build Coastguard Worker 
2303*38e8c45fSAndroid Build Coastguard Worker     const char* path = codePath.c_str();
2304*38e8c45fSAndroid Build Coastguard Worker     const char* instruction_set = instructionSet.c_str();
2305*38e8c45fSAndroid Build Coastguard Worker 
2306*38e8c45fSAndroid Build Coastguard Worker     if (validate_apk_path(path) && validate_system_app_path(path)) {
2307*38e8c45fSAndroid Build Coastguard Worker         return error("Invalid path " + codePath);
2308*38e8c45fSAndroid Build Coastguard Worker     }
2309*38e8c45fSAndroid Build Coastguard Worker 
2310*38e8c45fSAndroid Build Coastguard Worker     if (!create_cache_path(dex_path, path, instruction_set)) {
2311*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to create cache path for " + codePath);
2312*38e8c45fSAndroid Build Coastguard Worker     }
2313*38e8c45fSAndroid Build Coastguard Worker 
2314*38e8c45fSAndroid Build Coastguard Worker     ALOGV("unlink %s\n", dex_path);
2315*38e8c45fSAndroid Build Coastguard Worker     if (unlink(dex_path) < 0) {
2316*38e8c45fSAndroid Build Coastguard Worker         // It's ok if we don't have a dalvik cache path. Report error only when the path exists
2317*38e8c45fSAndroid Build Coastguard Worker         // but could not be unlinked.
2318*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENOENT) {
2319*38e8c45fSAndroid Build Coastguard Worker             return error(StringPrintf("Failed to unlink %s", dex_path));
2320*38e8c45fSAndroid Build Coastguard Worker         }
2321*38e8c45fSAndroid Build Coastguard Worker     }
2322*38e8c45fSAndroid Build Coastguard Worker     return ok();
2323*38e8c45fSAndroid Build Coastguard Worker }
2324*38e8c45fSAndroid Build Coastguard Worker 
2325*38e8c45fSAndroid Build Coastguard Worker struct stats {
2326*38e8c45fSAndroid Build Coastguard Worker     int64_t codeSize;
2327*38e8c45fSAndroid Build Coastguard Worker     int64_t dataSize;
2328*38e8c45fSAndroid Build Coastguard Worker     int64_t cacheSize;
2329*38e8c45fSAndroid Build Coastguard Worker };
2330*38e8c45fSAndroid Build Coastguard Worker 
2331*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
toString(std::vector<int64_t> values)2332*38e8c45fSAndroid Build Coastguard Worker static std::string toString(std::vector<int64_t> values) {
2333*38e8c45fSAndroid Build Coastguard Worker     std::stringstream res;
2334*38e8c45fSAndroid Build Coastguard Worker     res << "[";
2335*38e8c45fSAndroid Build Coastguard Worker     for (size_t i = 0; i < values.size(); i++) {
2336*38e8c45fSAndroid Build Coastguard Worker         res << values[i];
2337*38e8c45fSAndroid Build Coastguard Worker         if (i < values.size() - 1) {
2338*38e8c45fSAndroid Build Coastguard Worker             res << ",";
2339*38e8c45fSAndroid Build Coastguard Worker         }
2340*38e8c45fSAndroid Build Coastguard Worker     }
2341*38e8c45fSAndroid Build Coastguard Worker     res << "]";
2342*38e8c45fSAndroid Build Coastguard Worker     return res.str();
2343*38e8c45fSAndroid Build Coastguard Worker }
2344*38e8c45fSAndroid Build Coastguard Worker #endif
2345*38e8c45fSAndroid Build Coastguard Worker 
2346*38e8c45fSAndroid Build Coastguard Worker // On devices without sdcardfs, if internal and external are on
2347*38e8c45fSAndroid Build Coastguard Worker // the same volume, a uid such as u0_a123 is used for both
2348*38e8c45fSAndroid Build Coastguard Worker // internal and external storage; therefore, subtract that
2349*38e8c45fSAndroid Build Coastguard Worker // amount from internal to make sure we don't count it double.
2350*38e8c45fSAndroid Build Coastguard Worker // This needs to happen for data, cache and OBB
deductDoubleSpaceIfNeeded(stats * stats,int64_t doubleSpaceToBeDeleted,uid_t uid,const std::string & uuid)2351*38e8c45fSAndroid Build Coastguard Worker static void deductDoubleSpaceIfNeeded(stats* stats, int64_t doubleSpaceToBeDeleted, uid_t uid,
2352*38e8c45fSAndroid Build Coastguard Worker                                       const std::string& uuid) {
2353*38e8c45fSAndroid Build Coastguard Worker     if (!supports_sdcardfs()) {
2354*38e8c45fSAndroid Build Coastguard Worker         stats->dataSize -= doubleSpaceToBeDeleted;
2355*38e8c45fSAndroid Build Coastguard Worker         long obbProjectId = get_project_id(uid, PROJECT_ID_EXT_OBB_START);
2356*38e8c45fSAndroid Build Coastguard Worker         int64_t appObbSize = GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2357*38e8c45fSAndroid Build Coastguard Worker         stats->dataSize -= appObbSize;
2358*38e8c45fSAndroid Build Coastguard Worker     }
2359*38e8c45fSAndroid Build Coastguard Worker }
2360*38e8c45fSAndroid Build Coastguard Worker 
collectQuotaStats(const std::string & uuid,int32_t userId,int32_t appId,struct stats * stats,struct stats * extStats)2361*38e8c45fSAndroid Build Coastguard Worker static void collectQuotaStats(const std::string& uuid, int32_t userId,
2362*38e8c45fSAndroid Build Coastguard Worker         int32_t appId, struct stats* stats, struct stats* extStats) {
2363*38e8c45fSAndroid Build Coastguard Worker     int64_t space, doubleSpaceToBeDeleted = 0;
2364*38e8c45fSAndroid Build Coastguard Worker     uid_t uid = multiuser_get_uid(userId, appId);
2365*38e8c45fSAndroid Build Coastguard Worker     static const bool supportsProjectId = internal_storage_has_project_id();
2366*38e8c45fSAndroid Build Coastguard Worker 
2367*38e8c45fSAndroid Build Coastguard Worker     if (extStats != nullptr) {
2368*38e8c45fSAndroid Build Coastguard Worker         space = get_occupied_app_space_external(uuid, userId, appId);
2369*38e8c45fSAndroid Build Coastguard Worker 
2370*38e8c45fSAndroid Build Coastguard Worker         if (space != -1) {
2371*38e8c45fSAndroid Build Coastguard Worker             extStats->dataSize += space;
2372*38e8c45fSAndroid Build Coastguard Worker             doubleSpaceToBeDeleted += space;
2373*38e8c45fSAndroid Build Coastguard Worker         }
2374*38e8c45fSAndroid Build Coastguard Worker 
2375*38e8c45fSAndroid Build Coastguard Worker         space = get_occupied_app_cache_space_external(uuid, userId, appId);
2376*38e8c45fSAndroid Build Coastguard Worker         if (space != -1) {
2377*38e8c45fSAndroid Build Coastguard Worker             extStats->dataSize += space; // cache counts for "data"
2378*38e8c45fSAndroid Build Coastguard Worker             extStats->cacheSize += space;
2379*38e8c45fSAndroid Build Coastguard Worker             doubleSpaceToBeDeleted += space;
2380*38e8c45fSAndroid Build Coastguard Worker         }
2381*38e8c45fSAndroid Build Coastguard Worker     }
2382*38e8c45fSAndroid Build Coastguard Worker 
2383*38e8c45fSAndroid Build Coastguard Worker     if (stats != nullptr) {
2384*38e8c45fSAndroid Build Coastguard Worker         if (!supportsProjectId) {
2385*38e8c45fSAndroid Build Coastguard Worker             if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
2386*38e8c45fSAndroid Build Coastguard Worker                 stats->dataSize += space;
2387*38e8c45fSAndroid Build Coastguard Worker             }
2388*38e8c45fSAndroid Build Coastguard Worker             deductDoubleSpaceIfNeeded(stats, doubleSpaceToBeDeleted, uid, uuid);
2389*38e8c45fSAndroid Build Coastguard Worker             int sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
2390*38e8c45fSAndroid Build Coastguard Worker             if (sdkSandboxUid != -1) {
2391*38e8c45fSAndroid Build Coastguard Worker                 if ((space = GetOccupiedSpaceForUid(uuid, sdkSandboxUid)) != -1) {
2392*38e8c45fSAndroid Build Coastguard Worker                     stats->dataSize += space;
2393*38e8c45fSAndroid Build Coastguard Worker                 }
2394*38e8c45fSAndroid Build Coastguard Worker             }
2395*38e8c45fSAndroid Build Coastguard Worker             int cacheGid = multiuser_get_cache_gid(userId, appId);
2396*38e8c45fSAndroid Build Coastguard Worker             if (cacheGid != -1) {
2397*38e8c45fSAndroid Build Coastguard Worker                 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
2398*38e8c45fSAndroid Build Coastguard Worker                     stats->cacheSize += space;
2399*38e8c45fSAndroid Build Coastguard Worker                 }
2400*38e8c45fSAndroid Build Coastguard Worker             }
2401*38e8c45fSAndroid Build Coastguard Worker         } else {
2402*38e8c45fSAndroid Build Coastguard Worker             long projectId = get_project_id(uid, PROJECT_ID_APP_START);
2403*38e8c45fSAndroid Build Coastguard Worker             if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
2404*38e8c45fSAndroid Build Coastguard Worker                 stats->dataSize += space;
2405*38e8c45fSAndroid Build Coastguard Worker             }
2406*38e8c45fSAndroid Build Coastguard Worker             projectId = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
2407*38e8c45fSAndroid Build Coastguard Worker             if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
2408*38e8c45fSAndroid Build Coastguard Worker                 stats->cacheSize += space;
2409*38e8c45fSAndroid Build Coastguard Worker                 stats->dataSize += space;
2410*38e8c45fSAndroid Build Coastguard Worker             }
2411*38e8c45fSAndroid Build Coastguard Worker         }
2412*38e8c45fSAndroid Build Coastguard Worker 
2413*38e8c45fSAndroid Build Coastguard Worker         int sharedGid = multiuser_get_shared_gid(0, appId);
2414*38e8c45fSAndroid Build Coastguard Worker         if (sharedGid != -1) {
2415*38e8c45fSAndroid Build Coastguard Worker             if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
2416*38e8c45fSAndroid Build Coastguard Worker                 stats->codeSize += space;
2417*38e8c45fSAndroid Build Coastguard Worker             }
2418*38e8c45fSAndroid Build Coastguard Worker         }
2419*38e8c45fSAndroid Build Coastguard Worker     }
2420*38e8c45fSAndroid Build Coastguard Worker }
2421*38e8c45fSAndroid Build Coastguard Worker 
collectManualStats(const std::string & path,struct stats * stats)2422*38e8c45fSAndroid Build Coastguard Worker static void collectManualStats(const std::string& path, struct stats* stats) {
2423*38e8c45fSAndroid Build Coastguard Worker     DIR *d;
2424*38e8c45fSAndroid Build Coastguard Worker     int dfd;
2425*38e8c45fSAndroid Build Coastguard Worker     struct dirent *de;
2426*38e8c45fSAndroid Build Coastguard Worker     struct stat s;
2427*38e8c45fSAndroid Build Coastguard Worker 
2428*38e8c45fSAndroid Build Coastguard Worker     d = opendir(path.c_str());
2429*38e8c45fSAndroid Build Coastguard Worker     if (d == nullptr) {
2430*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENOENT) {
2431*38e8c45fSAndroid Build Coastguard Worker             PLOG(WARNING) << "Failed to open " << path;
2432*38e8c45fSAndroid Build Coastguard Worker         }
2433*38e8c45fSAndroid Build Coastguard Worker         return;
2434*38e8c45fSAndroid Build Coastguard Worker     }
2435*38e8c45fSAndroid Build Coastguard Worker     dfd = dirfd(d);
2436*38e8c45fSAndroid Build Coastguard Worker     while ((de = readdir(d))) {
2437*38e8c45fSAndroid Build Coastguard Worker         const char *name = de->d_name;
2438*38e8c45fSAndroid Build Coastguard Worker 
2439*38e8c45fSAndroid Build Coastguard Worker         int64_t size = 0;
2440*38e8c45fSAndroid Build Coastguard Worker         if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
2441*38e8c45fSAndroid Build Coastguard Worker             size = s.st_blocks * 512;
2442*38e8c45fSAndroid Build Coastguard Worker         }
2443*38e8c45fSAndroid Build Coastguard Worker 
2444*38e8c45fSAndroid Build Coastguard Worker         if (de->d_type == DT_DIR) {
2445*38e8c45fSAndroid Build Coastguard Worker             if (!strcmp(name, ".")) {
2446*38e8c45fSAndroid Build Coastguard Worker                 // Don't recurse, but still count node size
2447*38e8c45fSAndroid Build Coastguard Worker             } else if (!strcmp(name, "..")) {
2448*38e8c45fSAndroid Build Coastguard Worker                 // Don't recurse or count node size
2449*38e8c45fSAndroid Build Coastguard Worker                 continue;
2450*38e8c45fSAndroid Build Coastguard Worker             } else {
2451*38e8c45fSAndroid Build Coastguard Worker                 // Measure all children nodes
2452*38e8c45fSAndroid Build Coastguard Worker                 size = 0;
2453*38e8c45fSAndroid Build Coastguard Worker                 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
2454*38e8c45fSAndroid Build Coastguard Worker             }
2455*38e8c45fSAndroid Build Coastguard Worker 
2456*38e8c45fSAndroid Build Coastguard Worker             if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
2457*38e8c45fSAndroid Build Coastguard Worker                 stats->cacheSize += size;
2458*38e8c45fSAndroid Build Coastguard Worker             }
2459*38e8c45fSAndroid Build Coastguard Worker         }
2460*38e8c45fSAndroid Build Coastguard Worker 
2461*38e8c45fSAndroid Build Coastguard Worker         // Legacy symlink isn't owned by app
2462*38e8c45fSAndroid Build Coastguard Worker         if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
2463*38e8c45fSAndroid Build Coastguard Worker             continue;
2464*38e8c45fSAndroid Build Coastguard Worker         }
2465*38e8c45fSAndroid Build Coastguard Worker 
2466*38e8c45fSAndroid Build Coastguard Worker         // Everything found inside is considered data
2467*38e8c45fSAndroid Build Coastguard Worker         stats->dataSize += size;
2468*38e8c45fSAndroid Build Coastguard Worker     }
2469*38e8c45fSAndroid Build Coastguard Worker     closedir(d);
2470*38e8c45fSAndroid Build Coastguard Worker }
2471*38e8c45fSAndroid Build Coastguard Worker 
collectManualStatsForSubDirectories(const std::string & path,struct stats * stats)2472*38e8c45fSAndroid Build Coastguard Worker void collectManualStatsForSubDirectories(const std::string& path, struct stats* stats) {
2473*38e8c45fSAndroid Build Coastguard Worker     const auto subDirHandler = [&path, &stats](const std::string& subDir) {
2474*38e8c45fSAndroid Build Coastguard Worker         auto fullpath = path + "/" + subDir;
2475*38e8c45fSAndroid Build Coastguard Worker         collectManualStats(fullpath, stats);
2476*38e8c45fSAndroid Build Coastguard Worker     };
2477*38e8c45fSAndroid Build Coastguard Worker     foreach_subdir(path, subDirHandler);
2478*38e8c45fSAndroid Build Coastguard Worker }
2479*38e8c45fSAndroid Build Coastguard Worker 
collectManualStatsForUser(const std::string & path,struct stats * stats,bool exclude_apps=false,bool is_sdk_sandbox_storage=false)2480*38e8c45fSAndroid Build Coastguard Worker static void collectManualStatsForUser(const std::string& path, struct stats* stats,
2481*38e8c45fSAndroid Build Coastguard Worker                                       bool exclude_apps = false,
2482*38e8c45fSAndroid Build Coastguard Worker                                       bool is_sdk_sandbox_storage = false) {
2483*38e8c45fSAndroid Build Coastguard Worker     DIR *d;
2484*38e8c45fSAndroid Build Coastguard Worker     int dfd;
2485*38e8c45fSAndroid Build Coastguard Worker     struct dirent *de;
2486*38e8c45fSAndroid Build Coastguard Worker     struct stat s;
2487*38e8c45fSAndroid Build Coastguard Worker 
2488*38e8c45fSAndroid Build Coastguard Worker     d = opendir(path.c_str());
2489*38e8c45fSAndroid Build Coastguard Worker     if (d == nullptr) {
2490*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENOENT) {
2491*38e8c45fSAndroid Build Coastguard Worker             PLOG(WARNING) << "Failed to open " << path;
2492*38e8c45fSAndroid Build Coastguard Worker         }
2493*38e8c45fSAndroid Build Coastguard Worker         return;
2494*38e8c45fSAndroid Build Coastguard Worker     }
2495*38e8c45fSAndroid Build Coastguard Worker     dfd = dirfd(d);
2496*38e8c45fSAndroid Build Coastguard Worker     while ((de = readdir(d))) {
2497*38e8c45fSAndroid Build Coastguard Worker         if (de->d_type == DT_DIR) {
2498*38e8c45fSAndroid Build Coastguard Worker             const char *name = de->d_name;
2499*38e8c45fSAndroid Build Coastguard Worker             if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
2500*38e8c45fSAndroid Build Coastguard Worker                 continue;
2501*38e8c45fSAndroid Build Coastguard Worker             }
2502*38e8c45fSAndroid Build Coastguard Worker             int32_t user_uid = multiuser_get_app_id(s.st_uid);
2503*38e8c45fSAndroid Build Coastguard Worker             if (!strcmp(name, ".") || !strcmp(name, "..")) {
2504*38e8c45fSAndroid Build Coastguard Worker                 continue;
2505*38e8c45fSAndroid Build Coastguard Worker             } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
2506*38e8c45fSAndroid Build Coastguard Worker                 continue;
2507*38e8c45fSAndroid Build Coastguard Worker             } else if (is_sdk_sandbox_storage) {
2508*38e8c45fSAndroid Build Coastguard Worker                 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2509*38e8c45fSAndroid Build Coastguard Worker                 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2510*38e8c45fSAndroid Build Coastguard Worker                 collectManualStatsForSubDirectories(StringPrintf("%s/%s", path.c_str(), name),
2511*38e8c45fSAndroid Build Coastguard Worker                                                     stats);
2512*38e8c45fSAndroid Build Coastguard Worker             } else {
2513*38e8c45fSAndroid Build Coastguard Worker                 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
2514*38e8c45fSAndroid Build Coastguard Worker             }
2515*38e8c45fSAndroid Build Coastguard Worker         }
2516*38e8c45fSAndroid Build Coastguard Worker     }
2517*38e8c45fSAndroid Build Coastguard Worker     closedir(d);
2518*38e8c45fSAndroid Build Coastguard Worker }
2519*38e8c45fSAndroid Build Coastguard Worker 
collectManualExternalStatsForUser(const std::string & path,struct stats * stats)2520*38e8c45fSAndroid Build Coastguard Worker static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
2521*38e8c45fSAndroid Build Coastguard Worker     FTS *fts;
2522*38e8c45fSAndroid Build Coastguard Worker     FTSENT *p;
2523*38e8c45fSAndroid Build Coastguard Worker     char *argv[] = { (char*) path.c_str(), nullptr };
2524*38e8c45fSAndroid Build Coastguard Worker     if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
2525*38e8c45fSAndroid Build Coastguard Worker         PLOG(ERROR) << "Failed to fts_open " << path;
2526*38e8c45fSAndroid Build Coastguard Worker         return;
2527*38e8c45fSAndroid Build Coastguard Worker     }
2528*38e8c45fSAndroid Build Coastguard Worker     while ((p = fts_read(fts)) != nullptr) {
2529*38e8c45fSAndroid Build Coastguard Worker         p->fts_number = p->fts_parent->fts_number;
2530*38e8c45fSAndroid Build Coastguard Worker         switch (p->fts_info) {
2531*38e8c45fSAndroid Build Coastguard Worker         case FTS_D:
2532*38e8c45fSAndroid Build Coastguard Worker             if (p->fts_level == 3
2533*38e8c45fSAndroid Build Coastguard Worker                     && !strcmp(p->fts_parent->fts_name, "obb")
2534*38e8c45fSAndroid Build Coastguard Worker                     && !strcmp(p->fts_parent->fts_parent->fts_name, "Android")) {
2535*38e8c45fSAndroid Build Coastguard Worker                 p->fts_number = 1;
2536*38e8c45fSAndroid Build Coastguard Worker             } else if (p->fts_level == 4
2537*38e8c45fSAndroid Build Coastguard Worker                     && !strcmp(p->fts_name, "cache")
2538*38e8c45fSAndroid Build Coastguard Worker                     && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
2539*38e8c45fSAndroid Build Coastguard Worker                     && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
2540*38e8c45fSAndroid Build Coastguard Worker                 p->fts_number = 2;
2541*38e8c45fSAndroid Build Coastguard Worker             }
2542*38e8c45fSAndroid Build Coastguard Worker             [[fallthrough]]; // to count the directory
2543*38e8c45fSAndroid Build Coastguard Worker         case FTS_DEFAULT:
2544*38e8c45fSAndroid Build Coastguard Worker         case FTS_F:
2545*38e8c45fSAndroid Build Coastguard Worker         case FTS_SL:
2546*38e8c45fSAndroid Build Coastguard Worker         case FTS_SLNONE:
2547*38e8c45fSAndroid Build Coastguard Worker             int64_t size = (p->fts_statp->st_blocks * 512);
2548*38e8c45fSAndroid Build Coastguard Worker             if (p->fts_number == 1) {
2549*38e8c45fSAndroid Build Coastguard Worker                 stats->codeSize += size;
2550*38e8c45fSAndroid Build Coastguard Worker             } else {
2551*38e8c45fSAndroid Build Coastguard Worker                 if (p->fts_number == 2) {
2552*38e8c45fSAndroid Build Coastguard Worker                     stats->cacheSize += size;
2553*38e8c45fSAndroid Build Coastguard Worker                 }
2554*38e8c45fSAndroid Build Coastguard Worker                 stats->dataSize += size;
2555*38e8c45fSAndroid Build Coastguard Worker             }
2556*38e8c45fSAndroid Build Coastguard Worker             break;
2557*38e8c45fSAndroid Build Coastguard Worker         }
2558*38e8c45fSAndroid Build Coastguard Worker     }
2559*38e8c45fSAndroid Build Coastguard Worker     fts_close(fts);
2560*38e8c45fSAndroid Build Coastguard Worker }
ownsExternalStorage(int32_t appId)2561*38e8c45fSAndroid Build Coastguard Worker static bool ownsExternalStorage(int32_t appId) {
2562*38e8c45fSAndroid Build Coastguard Worker     // if project id calculation is supported then, there is no need to
2563*38e8c45fSAndroid Build Coastguard Worker     // calculate in a different way and project_id based calculation can work
2564*38e8c45fSAndroid Build Coastguard Worker     if (internal_storage_has_project_id()) {
2565*38e8c45fSAndroid Build Coastguard Worker         return false;
2566*38e8c45fSAndroid Build Coastguard Worker     }
2567*38e8c45fSAndroid Build Coastguard Worker 
2568*38e8c45fSAndroid Build Coastguard Worker     //  Fetch external storage owner appid  and check if it is the same as the
2569*38e8c45fSAndroid Build Coastguard Worker     //  current appId whose size is calculated
2570*38e8c45fSAndroid Build Coastguard Worker     struct stat s;
2571*38e8c45fSAndroid Build Coastguard Worker     auto _picDir = StringPrintf("%s/Pictures", create_data_media_path(nullptr, 0).c_str());
2572*38e8c45fSAndroid Build Coastguard Worker     // check if the stat are present
2573*38e8c45fSAndroid Build Coastguard Worker     if (stat(_picDir.c_str(), &s) == 0) {
2574*38e8c45fSAndroid Build Coastguard Worker         // fetch the appId from the uid of the media app
2575*38e8c45fSAndroid Build Coastguard Worker         return ((int32_t)multiuser_get_app_id(s.st_uid) == appId);
2576*38e8c45fSAndroid Build Coastguard Worker     }
2577*38e8c45fSAndroid Build Coastguard Worker     return false;
2578*38e8c45fSAndroid Build Coastguard Worker }
getAppSize(const std::optional<std::string> & uuid,const std::vector<std::string> & packageNames,int32_t userId,int32_t flags,int32_t appId,const std::vector<int64_t> & ceDataInodes,const std::vector<std::string> & codePaths,std::vector<int64_t> * _aidl_return)2579*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::getAppSize(const std::optional<std::string>& uuid,
2580*38e8c45fSAndroid Build Coastguard Worker         const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
2581*38e8c45fSAndroid Build Coastguard Worker         int32_t appId, const std::vector<int64_t>& ceDataInodes,
2582*38e8c45fSAndroid Build Coastguard Worker         const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
2583*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
2584*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
2585*38e8c45fSAndroid Build Coastguard Worker     if (packageNames.size() != ceDataInodes.size()) {
2586*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
2587*38e8c45fSAndroid Build Coastguard Worker                          "packageNames/ceDataInodes size mismatch.");
2588*38e8c45fSAndroid Build Coastguard Worker     }
2589*38e8c45fSAndroid Build Coastguard Worker     for (const auto& packageName : packageNames) {
2590*38e8c45fSAndroid Build Coastguard Worker         CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2591*38e8c45fSAndroid Build Coastguard Worker     }
2592*38e8c45fSAndroid Build Coastguard Worker     for (const auto& codePath : codePaths) {
2593*38e8c45fSAndroid Build Coastguard Worker         CHECK_ARGUMENT_PATH(codePath);
2594*38e8c45fSAndroid Build Coastguard Worker     }
2595*38e8c45fSAndroid Build Coastguard Worker     // NOTE: Locking is relaxed on this method, since it's limited to
2596*38e8c45fSAndroid Build Coastguard Worker     // read-only measurements without mutation.
2597*38e8c45fSAndroid Build Coastguard Worker 
2598*38e8c45fSAndroid Build Coastguard Worker     // When modifying this logic, always verify using tests:
2599*38e8c45fSAndroid Build Coastguard Worker     // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
2600*38e8c45fSAndroid Build Coastguard Worker 
2601*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
2602*38e8c45fSAndroid Build Coastguard Worker     LOG(INFO) << "Measuring user " << userId << " app " << appId;
2603*38e8c45fSAndroid Build Coastguard Worker #endif
2604*38e8c45fSAndroid Build Coastguard Worker 
2605*38e8c45fSAndroid Build Coastguard Worker     // Here's a summary of the common storage locations across the platform,
2606*38e8c45fSAndroid Build Coastguard Worker     // and how they're each tagged:
2607*38e8c45fSAndroid Build Coastguard Worker     //
2608*38e8c45fSAndroid Build Coastguard Worker     // /data/app/com.example                           UID system
2609*38e8c45fSAndroid Build Coastguard Worker     // /data/app/com.example/oat                       UID system
2610*38e8c45fSAndroid Build Coastguard Worker     // /data/user/0/com.example                        UID u0_a10      GID u0_a10
2611*38e8c45fSAndroid Build Coastguard Worker     // /data/user/0/com.example/cache                  UID u0_a10      GID u0_a10_cache
2612*38e8c45fSAndroid Build Coastguard Worker     // /data/media/0/foo.txt                           UID u0_media_rw
2613*38e8c45fSAndroid Build Coastguard Worker     // /data/media/0/bar.jpg                           UID u0_media_rw GID u0_media_image
2614*38e8c45fSAndroid Build Coastguard Worker     // /data/media/0/Android/data/com.example          UID u0_media_rw GID u0_a10_ext
2615*38e8c45fSAndroid Build Coastguard Worker     // /data/media/0/Android/data/com.example/cache    UID u0_media_rw GID u0_a10_ext_cache
2616*38e8c45fSAndroid Build Coastguard Worker     // /data/media/obb/com.example                     UID system
2617*38e8c45fSAndroid Build Coastguard Worker 
2618*38e8c45fSAndroid Build Coastguard Worker     struct stats stats;
2619*38e8c45fSAndroid Build Coastguard Worker     struct stats extStats;
2620*38e8c45fSAndroid Build Coastguard Worker     memset(&stats, 0, sizeof(stats));
2621*38e8c45fSAndroid Build Coastguard Worker     memset(&extStats, 0, sizeof(extStats));
2622*38e8c45fSAndroid Build Coastguard Worker 
2623*38e8c45fSAndroid Build Coastguard Worker     auto uuidString = uuid.value_or("");
2624*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2625*38e8c45fSAndroid Build Coastguard Worker 
2626*38e8c45fSAndroid Build Coastguard Worker     if (!IsQuotaSupported(uuidString)) {
2627*38e8c45fSAndroid Build Coastguard Worker         flags &= ~FLAG_USE_QUOTA;
2628*38e8c45fSAndroid Build Coastguard Worker     }
2629*38e8c45fSAndroid Build Coastguard Worker 
2630*38e8c45fSAndroid Build Coastguard Worker     atrace_pm_begin("obb");
2631*38e8c45fSAndroid Build Coastguard Worker     for (const auto& packageName : packageNames) {
2632*38e8c45fSAndroid Build Coastguard Worker         auto obbCodePath = create_data_media_package_path(uuid_, userId,
2633*38e8c45fSAndroid Build Coastguard Worker                 "obb", packageName.c_str());
2634*38e8c45fSAndroid Build Coastguard Worker         calculate_tree_size(obbCodePath, &extStats.codeSize);
2635*38e8c45fSAndroid Build Coastguard Worker     }
2636*38e8c45fSAndroid Build Coastguard Worker     atrace_pm_end();
2637*38e8c45fSAndroid Build Coastguard Worker     // Calculating the app size of the external storage owning app in a manual way, since
2638*38e8c45fSAndroid Build Coastguard Worker     // calculating it through quota apis also includes external media storage in the app storage
2639*38e8c45fSAndroid Build Coastguard Worker     // numbers
2640*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START && !ownsExternalStorage(appId)) {
2641*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("code");
2642*38e8c45fSAndroid Build Coastguard Worker         for (const auto& codePath : codePaths) {
2643*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(codePath, &stats.codeSize, -1,
2644*38e8c45fSAndroid Build Coastguard Worker                     multiuser_get_shared_gid(0, appId));
2645*38e8c45fSAndroid Build Coastguard Worker         }
2646*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2647*38e8c45fSAndroid Build Coastguard Worker 
2648*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("quota");
2649*38e8c45fSAndroid Build Coastguard Worker         collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
2650*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2651*38e8c45fSAndroid Build Coastguard Worker     } else {
2652*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("code");
2653*38e8c45fSAndroid Build Coastguard Worker         for (const auto& codePath : codePaths) {
2654*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(codePath, &stats.codeSize);
2655*38e8c45fSAndroid Build Coastguard Worker         }
2656*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2657*38e8c45fSAndroid Build Coastguard Worker 
2658*38e8c45fSAndroid Build Coastguard Worker         for (size_t i = 0; i < packageNames.size(); i++) {
2659*38e8c45fSAndroid Build Coastguard Worker             const char* pkgname = packageNames[i].c_str();
2660*38e8c45fSAndroid Build Coastguard Worker 
2661*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_begin("data");
2662*38e8c45fSAndroid Build Coastguard Worker             auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
2663*38e8c45fSAndroid Build Coastguard Worker             collectManualStats(cePath, &stats);
2664*38e8c45fSAndroid Build Coastguard Worker             auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
2665*38e8c45fSAndroid Build Coastguard Worker             collectManualStats(dePath, &stats);
2666*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_end();
2667*38e8c45fSAndroid Build Coastguard Worker 
2668*38e8c45fSAndroid Build Coastguard Worker             // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2669*38e8c45fSAndroid Build Coastguard Worker             // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2670*38e8c45fSAndroid Build Coastguard Worker             if (appId >= AID_APP_START && appId <= AID_APP_END) {
2671*38e8c45fSAndroid Build Coastguard Worker                 atrace_pm_begin("sdksandbox");
2672*38e8c45fSAndroid Build Coastguard Worker                 auto sdkSandboxCePath =
2673*38e8c45fSAndroid Build Coastguard Worker                         create_data_misc_sdk_sandbox_package_path(uuid_, true, userId, pkgname);
2674*38e8c45fSAndroid Build Coastguard Worker                 collectManualStatsForSubDirectories(sdkSandboxCePath, &stats);
2675*38e8c45fSAndroid Build Coastguard Worker                 auto sdkSandboxDePath =
2676*38e8c45fSAndroid Build Coastguard Worker                         create_data_misc_sdk_sandbox_package_path(uuid_, false, userId, pkgname);
2677*38e8c45fSAndroid Build Coastguard Worker                 collectManualStatsForSubDirectories(sdkSandboxDePath, &stats);
2678*38e8c45fSAndroid Build Coastguard Worker                 atrace_pm_end();
2679*38e8c45fSAndroid Build Coastguard Worker             }
2680*38e8c45fSAndroid Build Coastguard Worker 
2681*38e8c45fSAndroid Build Coastguard Worker             if (!uuid) {
2682*38e8c45fSAndroid Build Coastguard Worker                 atrace_pm_begin("profiles");
2683*38e8c45fSAndroid Build Coastguard Worker                 calculate_tree_size(
2684*38e8c45fSAndroid Build Coastguard Worker                         create_primary_current_profile_package_dir_path(userId, pkgname),
2685*38e8c45fSAndroid Build Coastguard Worker                         &stats.dataSize);
2686*38e8c45fSAndroid Build Coastguard Worker                 calculate_tree_size(
2687*38e8c45fSAndroid Build Coastguard Worker                         create_primary_reference_profile_package_dir_path(pkgname),
2688*38e8c45fSAndroid Build Coastguard Worker                         &stats.codeSize);
2689*38e8c45fSAndroid Build Coastguard Worker                 atrace_pm_end();
2690*38e8c45fSAndroid Build Coastguard Worker             }
2691*38e8c45fSAndroid Build Coastguard Worker 
2692*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_begin("external");
2693*38e8c45fSAndroid Build Coastguard Worker             auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
2694*38e8c45fSAndroid Build Coastguard Worker             collectManualStats(extPath, &extStats);
2695*38e8c45fSAndroid Build Coastguard Worker             auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
2696*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(mediaPath, &extStats.dataSize);
2697*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_end();
2698*38e8c45fSAndroid Build Coastguard Worker         }
2699*38e8c45fSAndroid Build Coastguard Worker 
2700*38e8c45fSAndroid Build Coastguard Worker         if (!uuid) {
2701*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_begin("dalvik");
2702*38e8c45fSAndroid Build Coastguard Worker             int32_t sharedGid = multiuser_get_shared_gid(0, appId);
2703*38e8c45fSAndroid Build Coastguard Worker             if (sharedGid != -1) {
2704*38e8c45fSAndroid Build Coastguard Worker                 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2705*38e8c45fSAndroid Build Coastguard Worker                         sharedGid, -1);
2706*38e8c45fSAndroid Build Coastguard Worker             }
2707*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_end();
2708*38e8c45fSAndroid Build Coastguard Worker         }
2709*38e8c45fSAndroid Build Coastguard Worker     }
2710*38e8c45fSAndroid Build Coastguard Worker 
2711*38e8c45fSAndroid Build Coastguard Worker     std::vector<int64_t> ret;
2712*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(stats.codeSize);
2713*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(stats.dataSize);
2714*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(stats.cacheSize);
2715*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(extStats.codeSize);
2716*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(extStats.dataSize);
2717*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(extStats.cacheSize);
2718*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
2719*38e8c45fSAndroid Build Coastguard Worker     LOG(DEBUG) << "Final result " << toString(ret);
2720*38e8c45fSAndroid Build Coastguard Worker #endif
2721*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = ret;
2722*38e8c45fSAndroid Build Coastguard Worker     return ok();
2723*38e8c45fSAndroid Build Coastguard Worker }
2724*38e8c45fSAndroid Build Coastguard Worker 
2725*38e8c45fSAndroid Build Coastguard Worker struct external_sizes {
2726*38e8c45fSAndroid Build Coastguard Worker     int64_t audioSize;
2727*38e8c45fSAndroid Build Coastguard Worker     int64_t videoSize;
2728*38e8c45fSAndroid Build Coastguard Worker     int64_t imageSize;
2729*38e8c45fSAndroid Build Coastguard Worker     int64_t totalSize; // excludes OBBs (Android/obb), but includes app data + cache
2730*38e8c45fSAndroid Build Coastguard Worker     int64_t obbSize;
2731*38e8c45fSAndroid Build Coastguard Worker };
2732*38e8c45fSAndroid Build Coastguard Worker 
2733*38e8c45fSAndroid Build Coastguard Worker #define PER_USER_RANGE 100000
2734*38e8c45fSAndroid Build Coastguard Worker 
getProjectIdForUser(int userId,long projectId)2735*38e8c45fSAndroid Build Coastguard Worker static long getProjectIdForUser(int userId, long projectId) {
2736*38e8c45fSAndroid Build Coastguard Worker     return userId * PER_USER_RANGE + projectId;
2737*38e8c45fSAndroid Build Coastguard Worker }
2738*38e8c45fSAndroid Build Coastguard Worker 
getExternalSizesForUserWithQuota(const std::string & uuid,int32_t userId,const std::vector<int32_t> & appIds)2739*38e8c45fSAndroid Build Coastguard Worker static external_sizes getExternalSizesForUserWithQuota(const std::string& uuid, int32_t userId, const std::vector<int32_t>& appIds) {
2740*38e8c45fSAndroid Build Coastguard Worker     struct external_sizes sizes = {};
2741*38e8c45fSAndroid Build Coastguard Worker     int64_t space;
2742*38e8c45fSAndroid Build Coastguard Worker 
2743*38e8c45fSAndroid Build Coastguard Worker     if (supports_sdcardfs()) {
2744*38e8c45fSAndroid Build Coastguard Worker         uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
2745*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
2746*38e8c45fSAndroid Build Coastguard Worker             sizes.totalSize = space;
2747*38e8c45fSAndroid Build Coastguard Worker         }
2748*38e8c45fSAndroid Build Coastguard Worker 
2749*38e8c45fSAndroid Build Coastguard Worker         gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
2750*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForGid(uuid, audioGid)) != -1) {
2751*38e8c45fSAndroid Build Coastguard Worker             sizes.audioSize = space;
2752*38e8c45fSAndroid Build Coastguard Worker         }
2753*38e8c45fSAndroid Build Coastguard Worker 
2754*38e8c45fSAndroid Build Coastguard Worker         gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
2755*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForGid(uuid, videoGid)) != -1) {
2756*38e8c45fSAndroid Build Coastguard Worker             sizes.videoSize = space;
2757*38e8c45fSAndroid Build Coastguard Worker         }
2758*38e8c45fSAndroid Build Coastguard Worker 
2759*38e8c45fSAndroid Build Coastguard Worker         gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
2760*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForGid(uuid, imageGid)) != -1) {
2761*38e8c45fSAndroid Build Coastguard Worker             sizes.imageSize = space;
2762*38e8c45fSAndroid Build Coastguard Worker         }
2763*38e8c45fSAndroid Build Coastguard Worker 
2764*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForGid(uuid, AID_MEDIA_OBB)) != -1) {
2765*38e8c45fSAndroid Build Coastguard Worker             sizes.obbSize = space;
2766*38e8c45fSAndroid Build Coastguard Worker         }
2767*38e8c45fSAndroid Build Coastguard Worker     } else {
2768*38e8c45fSAndroid Build Coastguard Worker         int64_t totalSize = 0;
2769*38e8c45fSAndroid Build Coastguard Worker         long defaultProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_DEFAULT);
2770*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForProjectId(uuid, defaultProjectId)) != -1) {
2771*38e8c45fSAndroid Build Coastguard Worker             // This is all files that are not audio/video/images, excluding
2772*38e8c45fSAndroid Build Coastguard Worker             // OBBs and app-private data
2773*38e8c45fSAndroid Build Coastguard Worker             totalSize += space;
2774*38e8c45fSAndroid Build Coastguard Worker         }
2775*38e8c45fSAndroid Build Coastguard Worker 
2776*38e8c45fSAndroid Build Coastguard Worker         long audioProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_AUDIO);
2777*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForProjectId(uuid, audioProjectId)) != -1) {
2778*38e8c45fSAndroid Build Coastguard Worker             sizes.audioSize = space;
2779*38e8c45fSAndroid Build Coastguard Worker             totalSize += space;
2780*38e8c45fSAndroid Build Coastguard Worker         }
2781*38e8c45fSAndroid Build Coastguard Worker 
2782*38e8c45fSAndroid Build Coastguard Worker         long videoProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_VIDEO);
2783*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForProjectId(uuid, videoProjectId)) != -1) {
2784*38e8c45fSAndroid Build Coastguard Worker             sizes.videoSize = space;
2785*38e8c45fSAndroid Build Coastguard Worker             totalSize += space;
2786*38e8c45fSAndroid Build Coastguard Worker         }
2787*38e8c45fSAndroid Build Coastguard Worker 
2788*38e8c45fSAndroid Build Coastguard Worker         long imageProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_IMAGE);
2789*38e8c45fSAndroid Build Coastguard Worker         if ((space = GetOccupiedSpaceForProjectId(uuid, imageProjectId)) != -1) {
2790*38e8c45fSAndroid Build Coastguard Worker             sizes.imageSize = space;
2791*38e8c45fSAndroid Build Coastguard Worker             totalSize += space;
2792*38e8c45fSAndroid Build Coastguard Worker         }
2793*38e8c45fSAndroid Build Coastguard Worker 
2794*38e8c45fSAndroid Build Coastguard Worker         int64_t totalAppDataSize = 0;
2795*38e8c45fSAndroid Build Coastguard Worker         int64_t totalAppCacheSize = 0;
2796*38e8c45fSAndroid Build Coastguard Worker         int64_t totalAppObbSize = 0;
2797*38e8c45fSAndroid Build Coastguard Worker         for (auto appId : appIds) {
2798*38e8c45fSAndroid Build Coastguard Worker             if (appId >= AID_APP_START) {
2799*38e8c45fSAndroid Build Coastguard Worker                 // App data
2800*38e8c45fSAndroid Build Coastguard Worker                 uid_t uid = multiuser_get_uid(userId, appId);
2801*38e8c45fSAndroid Build Coastguard Worker                 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
2802*38e8c45fSAndroid Build Coastguard Worker                 totalAppDataSize += GetOccupiedSpaceForProjectId(uuid, projectId);
2803*38e8c45fSAndroid Build Coastguard Worker 
2804*38e8c45fSAndroid Build Coastguard Worker                 // App cache
2805*38e8c45fSAndroid Build Coastguard Worker                 long cacheProjectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
2806*38e8c45fSAndroid Build Coastguard Worker                 totalAppCacheSize += GetOccupiedSpaceForProjectId(uuid, cacheProjectId);
2807*38e8c45fSAndroid Build Coastguard Worker 
2808*38e8c45fSAndroid Build Coastguard Worker                 // App OBBs
2809*38e8c45fSAndroid Build Coastguard Worker                 long obbProjectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
2810*38e8c45fSAndroid Build Coastguard Worker                 totalAppObbSize += GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2811*38e8c45fSAndroid Build Coastguard Worker             }
2812*38e8c45fSAndroid Build Coastguard Worker         }
2813*38e8c45fSAndroid Build Coastguard Worker         // Total size should include app data + cache
2814*38e8c45fSAndroid Build Coastguard Worker         totalSize += totalAppDataSize;
2815*38e8c45fSAndroid Build Coastguard Worker         totalSize += totalAppCacheSize;
2816*38e8c45fSAndroid Build Coastguard Worker         sizes.totalSize = totalSize;
2817*38e8c45fSAndroid Build Coastguard Worker 
2818*38e8c45fSAndroid Build Coastguard Worker         // Only OBB is separate
2819*38e8c45fSAndroid Build Coastguard Worker         sizes.obbSize = totalAppObbSize;
2820*38e8c45fSAndroid Build Coastguard Worker     }
2821*38e8c45fSAndroid Build Coastguard Worker 
2822*38e8c45fSAndroid Build Coastguard Worker     return sizes;
2823*38e8c45fSAndroid Build Coastguard Worker }
2824*38e8c45fSAndroid Build Coastguard Worker 
getUserSize(const std::optional<std::string> & uuid,int32_t userId,int32_t flags,const std::vector<int32_t> & appIds,std::vector<int64_t> * _aidl_return)2825*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::getUserSize(const std::optional<std::string>& uuid,
2826*38e8c45fSAndroid Build Coastguard Worker         int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2827*38e8c45fSAndroid Build Coastguard Worker         std::vector<int64_t>* _aidl_return) {
2828*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
2829*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
2830*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
2831*38e8c45fSAndroid Build Coastguard Worker     // NOTE: Locking is relaxed on this method, since it's limited to
2832*38e8c45fSAndroid Build Coastguard Worker     // read-only measurements without mutation.
2833*38e8c45fSAndroid Build Coastguard Worker 
2834*38e8c45fSAndroid Build Coastguard Worker     // When modifying this logic, always verify using tests:
2835*38e8c45fSAndroid Build Coastguard Worker     // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
2836*38e8c45fSAndroid Build Coastguard Worker 
2837*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
2838*38e8c45fSAndroid Build Coastguard Worker     LOG(INFO) << "Measuring user " << userId;
2839*38e8c45fSAndroid Build Coastguard Worker #endif
2840*38e8c45fSAndroid Build Coastguard Worker 
2841*38e8c45fSAndroid Build Coastguard Worker     struct stats stats;
2842*38e8c45fSAndroid Build Coastguard Worker     struct stats extStats;
2843*38e8c45fSAndroid Build Coastguard Worker     memset(&stats, 0, sizeof(stats));
2844*38e8c45fSAndroid Build Coastguard Worker     memset(&extStats, 0, sizeof(extStats));
2845*38e8c45fSAndroid Build Coastguard Worker 
2846*38e8c45fSAndroid Build Coastguard Worker     auto uuidString = uuid.value_or("");
2847*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2848*38e8c45fSAndroid Build Coastguard Worker 
2849*38e8c45fSAndroid Build Coastguard Worker     if (!IsQuotaSupported(uuidString)) {
2850*38e8c45fSAndroid Build Coastguard Worker         flags &= ~FLAG_USE_QUOTA;
2851*38e8c45fSAndroid Build Coastguard Worker     }
2852*38e8c45fSAndroid Build Coastguard Worker 
2853*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_USE_QUOTA) {
2854*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("code");
2855*38e8c45fSAndroid Build Coastguard Worker         calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
2856*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2857*38e8c45fSAndroid Build Coastguard Worker 
2858*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("data");
2859*38e8c45fSAndroid Build Coastguard Worker         auto cePath = create_data_user_ce_path(uuid_, userId);
2860*38e8c45fSAndroid Build Coastguard Worker         collectManualStatsForUser(cePath, &stats, true);
2861*38e8c45fSAndroid Build Coastguard Worker         auto dePath = create_data_user_de_path(uuid_, userId);
2862*38e8c45fSAndroid Build Coastguard Worker         collectManualStatsForUser(dePath, &stats, true);
2863*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2864*38e8c45fSAndroid Build Coastguard Worker 
2865*38e8c45fSAndroid Build Coastguard Worker         if (!uuid) {
2866*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_begin("profile");
2867*38e8c45fSAndroid Build Coastguard Worker             auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2868*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
2869*38e8c45fSAndroid Build Coastguard Worker             auto refProfilePath = create_primary_ref_profile_dir_path();
2870*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
2871*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_end();
2872*38e8c45fSAndroid Build Coastguard Worker         }
2873*38e8c45fSAndroid Build Coastguard Worker 
2874*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("external");
2875*38e8c45fSAndroid Build Coastguard Worker         auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2876*38e8c45fSAndroid Build Coastguard Worker         extStats.dataSize += sizes.totalSize;
2877*38e8c45fSAndroid Build Coastguard Worker         extStats.codeSize += sizes.obbSize;
2878*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2879*38e8c45fSAndroid Build Coastguard Worker 
2880*38e8c45fSAndroid Build Coastguard Worker         if (!uuid) {
2881*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_begin("dalvik");
2882*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2883*38e8c45fSAndroid Build Coastguard Worker                     -1, -1, true);
2884*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
2885*38e8c45fSAndroid Build Coastguard Worker                     -1, -1, true);
2886*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_end();
2887*38e8c45fSAndroid Build Coastguard Worker         }
2888*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("quota");
2889*38e8c45fSAndroid Build Coastguard Worker         int64_t dataSize = extStats.dataSize;
2890*38e8c45fSAndroid Build Coastguard Worker         for (auto appId : appIds) {
2891*38e8c45fSAndroid Build Coastguard Worker             if (appId >= AID_APP_START) {
2892*38e8c45fSAndroid Build Coastguard Worker                 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
2893*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
2894*38e8c45fSAndroid Build Coastguard Worker                 // Sleep to make sure we don't lose logs
2895*38e8c45fSAndroid Build Coastguard Worker                 usleep(1);
2896*38e8c45fSAndroid Build Coastguard Worker #endif
2897*38e8c45fSAndroid Build Coastguard Worker             }
2898*38e8c45fSAndroid Build Coastguard Worker         }
2899*38e8c45fSAndroid Build Coastguard Worker         extStats.dataSize = dataSize;
2900*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2901*38e8c45fSAndroid Build Coastguard Worker     } else {
2902*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("code");
2903*38e8c45fSAndroid Build Coastguard Worker         calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
2904*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2905*38e8c45fSAndroid Build Coastguard Worker 
2906*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("data");
2907*38e8c45fSAndroid Build Coastguard Worker         auto cePath = create_data_user_ce_path(uuid_, userId);
2908*38e8c45fSAndroid Build Coastguard Worker         collectManualStatsForUser(cePath, &stats);
2909*38e8c45fSAndroid Build Coastguard Worker         auto dePath = create_data_user_de_path(uuid_, userId);
2910*38e8c45fSAndroid Build Coastguard Worker         collectManualStatsForUser(dePath, &stats);
2911*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2912*38e8c45fSAndroid Build Coastguard Worker 
2913*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("sdksandbox");
2914*38e8c45fSAndroid Build Coastguard Worker         auto sdkSandboxCePath = create_data_misc_sdk_sandbox_path(uuid_, true, userId);
2915*38e8c45fSAndroid Build Coastguard Worker         collectManualStatsForUser(sdkSandboxCePath, &stats, false, true);
2916*38e8c45fSAndroid Build Coastguard Worker         auto sdkSandboxDePath = create_data_misc_sdk_sandbox_path(uuid_, false, userId);
2917*38e8c45fSAndroid Build Coastguard Worker         collectManualStatsForUser(sdkSandboxDePath, &stats, false, true);
2918*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2919*38e8c45fSAndroid Build Coastguard Worker 
2920*38e8c45fSAndroid Build Coastguard Worker         if (!uuid) {
2921*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_begin("profile");
2922*38e8c45fSAndroid Build Coastguard Worker             auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2923*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(userProfilePath, &stats.dataSize);
2924*38e8c45fSAndroid Build Coastguard Worker             auto refProfilePath = create_primary_ref_profile_dir_path();
2925*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(refProfilePath, &stats.codeSize);
2926*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_end();
2927*38e8c45fSAndroid Build Coastguard Worker         }
2928*38e8c45fSAndroid Build Coastguard Worker 
2929*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("external");
2930*38e8c45fSAndroid Build Coastguard Worker         auto dataMediaPath = create_data_media_path(uuid_, userId);
2931*38e8c45fSAndroid Build Coastguard Worker         collectManualExternalStatsForUser(dataMediaPath, &extStats);
2932*38e8c45fSAndroid Build Coastguard Worker 
2933*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
2934*38e8c45fSAndroid Build Coastguard Worker         LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
2935*38e8c45fSAndroid Build Coastguard Worker                 << extStats.cacheSize << " code " << extStats.codeSize;
2936*38e8c45fSAndroid Build Coastguard Worker #endif
2937*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
2938*38e8c45fSAndroid Build Coastguard Worker 
2939*38e8c45fSAndroid Build Coastguard Worker         if (!uuid) {
2940*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_begin("dalvik");
2941*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
2942*38e8c45fSAndroid Build Coastguard Worker             calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
2943*38e8c45fSAndroid Build Coastguard Worker             atrace_pm_end();
2944*38e8c45fSAndroid Build Coastguard Worker         }
2945*38e8c45fSAndroid Build Coastguard Worker     }
2946*38e8c45fSAndroid Build Coastguard Worker 
2947*38e8c45fSAndroid Build Coastguard Worker     std::vector<int64_t> ret;
2948*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(stats.codeSize);
2949*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(stats.dataSize);
2950*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(stats.cacheSize);
2951*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(extStats.codeSize);
2952*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(extStats.dataSize);
2953*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(extStats.cacheSize);
2954*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
2955*38e8c45fSAndroid Build Coastguard Worker     LOG(DEBUG) << "Final result " << toString(ret);
2956*38e8c45fSAndroid Build Coastguard Worker #endif
2957*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = ret;
2958*38e8c45fSAndroid Build Coastguard Worker     return ok();
2959*38e8c45fSAndroid Build Coastguard Worker }
2960*38e8c45fSAndroid Build Coastguard Worker 
getExternalSize(const std::optional<std::string> & uuid,int32_t userId,int32_t flags,const std::vector<int32_t> & appIds,std::vector<int64_t> * _aidl_return)2961*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::getExternalSize(const std::optional<std::string>& uuid,
2962*38e8c45fSAndroid Build Coastguard Worker         int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2963*38e8c45fSAndroid Build Coastguard Worker         std::vector<int64_t>* _aidl_return) {
2964*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
2965*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
2966*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
2967*38e8c45fSAndroid Build Coastguard Worker     // NOTE: Locking is relaxed on this method, since it's limited to
2968*38e8c45fSAndroid Build Coastguard Worker     // read-only measurements without mutation.
2969*38e8c45fSAndroid Build Coastguard Worker 
2970*38e8c45fSAndroid Build Coastguard Worker     // When modifying this logic, always verify using tests:
2971*38e8c45fSAndroid Build Coastguard Worker     // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
2972*38e8c45fSAndroid Build Coastguard Worker 
2973*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
2974*38e8c45fSAndroid Build Coastguard Worker     LOG(INFO) << "Measuring external " << userId;
2975*38e8c45fSAndroid Build Coastguard Worker #endif
2976*38e8c45fSAndroid Build Coastguard Worker 
2977*38e8c45fSAndroid Build Coastguard Worker     auto uuidString = uuid.value_or("");
2978*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2979*38e8c45fSAndroid Build Coastguard Worker 
2980*38e8c45fSAndroid Build Coastguard Worker     int64_t totalSize = 0;
2981*38e8c45fSAndroid Build Coastguard Worker     int64_t audioSize = 0;
2982*38e8c45fSAndroid Build Coastguard Worker     int64_t videoSize = 0;
2983*38e8c45fSAndroid Build Coastguard Worker     int64_t imageSize = 0;
2984*38e8c45fSAndroid Build Coastguard Worker     int64_t appSize = 0;
2985*38e8c45fSAndroid Build Coastguard Worker     int64_t obbSize = 0;
2986*38e8c45fSAndroid Build Coastguard Worker 
2987*38e8c45fSAndroid Build Coastguard Worker     if (!IsQuotaSupported(uuidString)) {
2988*38e8c45fSAndroid Build Coastguard Worker         flags &= ~FLAG_USE_QUOTA;
2989*38e8c45fSAndroid Build Coastguard Worker     }
2990*38e8c45fSAndroid Build Coastguard Worker 
2991*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_USE_QUOTA) {
2992*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("quota");
2993*38e8c45fSAndroid Build Coastguard Worker         auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2994*38e8c45fSAndroid Build Coastguard Worker         totalSize = sizes.totalSize;
2995*38e8c45fSAndroid Build Coastguard Worker         audioSize = sizes.audioSize;
2996*38e8c45fSAndroid Build Coastguard Worker         videoSize = sizes.videoSize;
2997*38e8c45fSAndroid Build Coastguard Worker         imageSize = sizes.imageSize;
2998*38e8c45fSAndroid Build Coastguard Worker         obbSize = sizes.obbSize;
2999*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
3000*38e8c45fSAndroid Build Coastguard Worker 
3001*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("apps");
3002*38e8c45fSAndroid Build Coastguard Worker         struct stats extStats;
3003*38e8c45fSAndroid Build Coastguard Worker         memset(&extStats, 0, sizeof(extStats));
3004*38e8c45fSAndroid Build Coastguard Worker         for (auto appId : appIds) {
3005*38e8c45fSAndroid Build Coastguard Worker             if (appId >= AID_APP_START) {
3006*38e8c45fSAndroid Build Coastguard Worker                 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
3007*38e8c45fSAndroid Build Coastguard Worker             }
3008*38e8c45fSAndroid Build Coastguard Worker         }
3009*38e8c45fSAndroid Build Coastguard Worker         appSize = extStats.dataSize;
3010*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
3011*38e8c45fSAndroid Build Coastguard Worker     } else {
3012*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("manual");
3013*38e8c45fSAndroid Build Coastguard Worker         FTS *fts;
3014*38e8c45fSAndroid Build Coastguard Worker         FTSENT *p;
3015*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_media_path(uuid_, userId);
3016*38e8c45fSAndroid Build Coastguard Worker         char *argv[] = { (char*) path.c_str(), nullptr };
3017*38e8c45fSAndroid Build Coastguard Worker         if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
3018*38e8c45fSAndroid Build Coastguard Worker             return error("Failed to fts_open " + path);
3019*38e8c45fSAndroid Build Coastguard Worker         }
3020*38e8c45fSAndroid Build Coastguard Worker         while ((p = fts_read(fts)) != nullptr) {
3021*38e8c45fSAndroid Build Coastguard Worker             char* ext;
3022*38e8c45fSAndroid Build Coastguard Worker             int64_t size = (p->fts_statp->st_blocks * 512);
3023*38e8c45fSAndroid Build Coastguard Worker             switch (p->fts_info) {
3024*38e8c45fSAndroid Build Coastguard Worker             case FTS_F:
3025*38e8c45fSAndroid Build Coastguard Worker                 // Only categorize files not belonging to apps
3026*38e8c45fSAndroid Build Coastguard Worker                 if (p->fts_parent->fts_number == 0) {
3027*38e8c45fSAndroid Build Coastguard Worker                     ext = strrchr(p->fts_name, '.');
3028*38e8c45fSAndroid Build Coastguard Worker                     if (ext != nullptr) {
3029*38e8c45fSAndroid Build Coastguard Worker                         switch (MatchExtension(++ext)) {
3030*38e8c45fSAndroid Build Coastguard Worker                         case AID_MEDIA_AUDIO: audioSize += size; break;
3031*38e8c45fSAndroid Build Coastguard Worker                         case AID_MEDIA_VIDEO: videoSize += size; break;
3032*38e8c45fSAndroid Build Coastguard Worker                         case AID_MEDIA_IMAGE: imageSize += size; break;
3033*38e8c45fSAndroid Build Coastguard Worker                         }
3034*38e8c45fSAndroid Build Coastguard Worker                     }
3035*38e8c45fSAndroid Build Coastguard Worker                 }
3036*38e8c45fSAndroid Build Coastguard Worker                 [[fallthrough]]; // always count against total
3037*38e8c45fSAndroid Build Coastguard Worker             case FTS_D:
3038*38e8c45fSAndroid Build Coastguard Worker                 // Ignore data belonging to specific apps
3039*38e8c45fSAndroid Build Coastguard Worker                 p->fts_number = p->fts_parent->fts_number;
3040*38e8c45fSAndroid Build Coastguard Worker                 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
3041*38e8c45fSAndroid Build Coastguard Worker                     p->fts_number = 1;
3042*38e8c45fSAndroid Build Coastguard Worker                 }
3043*38e8c45fSAndroid Build Coastguard Worker                 [[fallthrough]]; // always count against total
3044*38e8c45fSAndroid Build Coastguard Worker             case FTS_DEFAULT:
3045*38e8c45fSAndroid Build Coastguard Worker             case FTS_SL:
3046*38e8c45fSAndroid Build Coastguard Worker             case FTS_SLNONE:
3047*38e8c45fSAndroid Build Coastguard Worker                 if (p->fts_parent->fts_number == 1) {
3048*38e8c45fSAndroid Build Coastguard Worker                     appSize += size;
3049*38e8c45fSAndroid Build Coastguard Worker                 }
3050*38e8c45fSAndroid Build Coastguard Worker                 totalSize += size;
3051*38e8c45fSAndroid Build Coastguard Worker                 break;
3052*38e8c45fSAndroid Build Coastguard Worker             }
3053*38e8c45fSAndroid Build Coastguard Worker         }
3054*38e8c45fSAndroid Build Coastguard Worker         fts_close(fts);
3055*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
3056*38e8c45fSAndroid Build Coastguard Worker 
3057*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_begin("obb");
3058*38e8c45fSAndroid Build Coastguard Worker         auto obbPath = StringPrintf("%s/Android/obb",
3059*38e8c45fSAndroid Build Coastguard Worker                 create_data_media_path(uuid_, userId).c_str());
3060*38e8c45fSAndroid Build Coastguard Worker         calculate_tree_size(obbPath, &obbSize);
3061*38e8c45fSAndroid Build Coastguard Worker         if (!(flags & FLAG_USE_QUOTA)) {
3062*38e8c45fSAndroid Build Coastguard Worker             totalSize -= obbSize;
3063*38e8c45fSAndroid Build Coastguard Worker         }
3064*38e8c45fSAndroid Build Coastguard Worker         atrace_pm_end();
3065*38e8c45fSAndroid Build Coastguard Worker     }
3066*38e8c45fSAndroid Build Coastguard Worker 
3067*38e8c45fSAndroid Build Coastguard Worker     std::vector<int64_t> ret;
3068*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(totalSize);
3069*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(audioSize);
3070*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(videoSize);
3071*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(imageSize);
3072*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(appSize);
3073*38e8c45fSAndroid Build Coastguard Worker     ret.push_back(obbSize);
3074*38e8c45fSAndroid Build Coastguard Worker #if MEASURE_DEBUG
3075*38e8c45fSAndroid Build Coastguard Worker     LOG(DEBUG) << "Final result " << toString(ret);
3076*38e8c45fSAndroid Build Coastguard Worker #endif
3077*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = ret;
3078*38e8c45fSAndroid Build Coastguard Worker     return ok();
3079*38e8c45fSAndroid Build Coastguard Worker }
3080*38e8c45fSAndroid Build Coastguard Worker 
getAppCrates(const std::optional<std::string> & uuid,const std::vector<std::string> & packageNames,int32_t userId,std::optional<std::vector<std::optional<CrateMetadata>>> * _aidl_return)3081*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::getAppCrates(
3082*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid,
3083*38e8c45fSAndroid Build Coastguard Worker         const std::vector<std::string>& packageNames, int32_t userId,
3084*38e8c45fSAndroid Build Coastguard Worker         std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
3085*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3086*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
3087*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3088*38e8c45fSAndroid Build Coastguard Worker     for (const auto& packageName : packageNames) {
3089*38e8c45fSAndroid Build Coastguard Worker         CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3090*38e8c45fSAndroid Build Coastguard Worker     }
3091*38e8c45fSAndroid Build Coastguard Worker #ifdef ENABLE_STORAGE_CRATES
3092*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
3093*38e8c45fSAndroid Build Coastguard Worker 
3094*38e8c45fSAndroid Build Coastguard Worker     auto retVector = std::vector<std::optional<CrateMetadata>>();
3095*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3096*38e8c45fSAndroid Build Coastguard Worker 
3097*38e8c45fSAndroid Build Coastguard Worker     std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3098*38e8c45fSAndroid Build Coastguard Worker             [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
3099*38e8c45fSAndroid Build Coastguard Worker         if (cratedFolder == nullptr) {
3100*38e8c45fSAndroid Build Coastguard Worker             return;
3101*38e8c45fSAndroid Build Coastguard Worker         }
3102*38e8c45fSAndroid Build Coastguard Worker         retVector.push_back(std::move(crateMetadata));
3103*38e8c45fSAndroid Build Coastguard Worker     };
3104*38e8c45fSAndroid Build Coastguard Worker 
3105*38e8c45fSAndroid Build Coastguard Worker     for (const auto& packageName : packageNames) {
3106*38e8c45fSAndroid Build Coastguard Worker #if CRATE_DEBUG
3107*38e8c45fSAndroid Build Coastguard Worker         LOG(DEBUG) << "packageName = " << packageName;
3108*38e8c45fSAndroid Build Coastguard Worker #endif
3109*38e8c45fSAndroid Build Coastguard Worker         auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageName);
3110*38e8c45fSAndroid Build Coastguard Worker         crateManager->traverseAllCrates(onCreateCrate);
3111*38e8c45fSAndroid Build Coastguard Worker     }
3112*38e8c45fSAndroid Build Coastguard Worker 
3113*38e8c45fSAndroid Build Coastguard Worker #if CRATE_DEBUG
3114*38e8c45fSAndroid Build Coastguard Worker     LOG(WARNING) << "retVector.size() =" << retVector.size();
3115*38e8c45fSAndroid Build Coastguard Worker     for (auto& item : retVector) {
3116*38e8c45fSAndroid Build Coastguard Worker         CrateManager::dump(*item);
3117*38e8c45fSAndroid Build Coastguard Worker     }
3118*38e8c45fSAndroid Build Coastguard Worker #endif
3119*38e8c45fSAndroid Build Coastguard Worker 
3120*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = std::move(retVector);
3121*38e8c45fSAndroid Build Coastguard Worker #else // ENABLE_STORAGE_CRATES
3122*38e8c45fSAndroid Build Coastguard Worker     _aidl_return->reset();
3123*38e8c45fSAndroid Build Coastguard Worker 
3124*38e8c45fSAndroid Build Coastguard Worker     /* prevent compile warning fail */
3125*38e8c45fSAndroid Build Coastguard Worker     if (userId < 0) {
3126*38e8c45fSAndroid Build Coastguard Worker         return error();
3127*38e8c45fSAndroid Build Coastguard Worker     }
3128*38e8c45fSAndroid Build Coastguard Worker #endif // ENABLE_STORAGE_CRATES
3129*38e8c45fSAndroid Build Coastguard Worker     return ok();
3130*38e8c45fSAndroid Build Coastguard Worker }
3131*38e8c45fSAndroid Build Coastguard Worker 
getUserCrates(const std::optional<std::string> & uuid,int32_t userId,std::optional<std::vector<std::optional<CrateMetadata>>> * _aidl_return)3132*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::getUserCrates(
3133*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, int32_t userId,
3134*38e8c45fSAndroid Build Coastguard Worker         std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
3135*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3136*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
3137*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3138*38e8c45fSAndroid Build Coastguard Worker #ifdef ENABLE_STORAGE_CRATES
3139*38e8c45fSAndroid Build Coastguard Worker     LOCK_USER();
3140*38e8c45fSAndroid Build Coastguard Worker 
3141*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3142*38e8c45fSAndroid Build Coastguard Worker     auto retVector = std::vector<std::optional<CrateMetadata>>();
3143*38e8c45fSAndroid Build Coastguard Worker 
3144*38e8c45fSAndroid Build Coastguard Worker     std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3145*38e8c45fSAndroid Build Coastguard Worker             [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
3146*38e8c45fSAndroid Build Coastguard Worker         if (cratedFolder == nullptr) {
3147*38e8c45fSAndroid Build Coastguard Worker             return;
3148*38e8c45fSAndroid Build Coastguard Worker         }
3149*38e8c45fSAndroid Build Coastguard Worker         retVector.push_back(std::move(crateMetadata));
3150*38e8c45fSAndroid Build Coastguard Worker     };
3151*38e8c45fSAndroid Build Coastguard Worker 
3152*38e8c45fSAndroid Build Coastguard Worker     std::function<void(FTSENT*)> onHandingPackage = [&](FTSENT* packageDir) -> void {
3153*38e8c45fSAndroid Build Coastguard Worker         auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageDir->fts_name);
3154*38e8c45fSAndroid Build Coastguard Worker         crateManager->traverseAllCrates(onCreateCrate);
3155*38e8c45fSAndroid Build Coastguard Worker     };
3156*38e8c45fSAndroid Build Coastguard Worker     CrateManager::traverseAllPackagesForUser(uuid, userId, onHandingPackage);
3157*38e8c45fSAndroid Build Coastguard Worker 
3158*38e8c45fSAndroid Build Coastguard Worker #if CRATE_DEBUG
3159*38e8c45fSAndroid Build Coastguard Worker     LOG(DEBUG) << "retVector.size() =" << retVector.size();
3160*38e8c45fSAndroid Build Coastguard Worker     for (auto& item : retVector) {
3161*38e8c45fSAndroid Build Coastguard Worker         CrateManager::dump(*item);
3162*38e8c45fSAndroid Build Coastguard Worker     }
3163*38e8c45fSAndroid Build Coastguard Worker #endif
3164*38e8c45fSAndroid Build Coastguard Worker 
3165*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = std::move(retVector);
3166*38e8c45fSAndroid Build Coastguard Worker #else // ENABLE_STORAGE_CRATES
3167*38e8c45fSAndroid Build Coastguard Worker     _aidl_return->reset();
3168*38e8c45fSAndroid Build Coastguard Worker 
3169*38e8c45fSAndroid Build Coastguard Worker     /* prevent compile warning fail */
3170*38e8c45fSAndroid Build Coastguard Worker     if (userId < 0) {
3171*38e8c45fSAndroid Build Coastguard Worker         return error();
3172*38e8c45fSAndroid Build Coastguard Worker     }
3173*38e8c45fSAndroid Build Coastguard Worker #endif // ENABLE_STORAGE_CRATES
3174*38e8c45fSAndroid Build Coastguard Worker     return ok();
3175*38e8c45fSAndroid Build Coastguard Worker }
3176*38e8c45fSAndroid Build Coastguard Worker 
setAppQuota(const std::optional<std::string> & uuid,int32_t userId,int32_t appId,int64_t cacheQuota)3177*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::setAppQuota(const std::optional<std::string>& uuid,
3178*38e8c45fSAndroid Build Coastguard Worker         int32_t userId, int32_t appId, int64_t cacheQuota) {
3179*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3180*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
3181*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3182*38e8c45fSAndroid Build Coastguard Worker     std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
3183*38e8c45fSAndroid Build Coastguard Worker 
3184*38e8c45fSAndroid Build Coastguard Worker     int32_t uid = multiuser_get_uid(userId, appId);
3185*38e8c45fSAndroid Build Coastguard Worker     mCacheQuotas[uid] = cacheQuota;
3186*38e8c45fSAndroid Build Coastguard Worker 
3187*38e8c45fSAndroid Build Coastguard Worker     return ok();
3188*38e8c45fSAndroid Build Coastguard Worker }
3189*38e8c45fSAndroid Build Coastguard Worker 
3190*38e8c45fSAndroid Build Coastguard Worker // Dumps the contents of a profile file, using pkgname's dex files for pretty
3191*38e8c45fSAndroid Build Coastguard Worker // printing the result.
dumpProfiles(int32_t uid,const std::string & packageName,const std::string & profileName,const std::string & codePath,bool dumpClassesAndMethods,bool * _aidl_return)3192*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
3193*38e8c45fSAndroid Build Coastguard Worker                                                    const std::string& profileName,
3194*38e8c45fSAndroid Build Coastguard Worker                                                    const std::string& codePath,
3195*38e8c45fSAndroid Build Coastguard Worker                                                    bool dumpClassesAndMethods, bool* _aidl_return) {
3196*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3197*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3198*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(codePath);
3199*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3200*38e8c45fSAndroid Build Coastguard Worker 
3201*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = dump_profiles(uid, packageName, profileName, codePath, dumpClassesAndMethods);
3202*38e8c45fSAndroid Build Coastguard Worker     return ok();
3203*38e8c45fSAndroid Build Coastguard Worker }
3204*38e8c45fSAndroid Build Coastguard Worker 
3205*38e8c45fSAndroid Build Coastguard Worker // Copy the contents of a system profile over the data profile.
copySystemProfile(const std::string & systemProfile,int32_t packageUid,const std::string & packageName,const std::string & profileName,bool * _aidl_return)3206*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
3207*38e8c45fSAndroid Build Coastguard Worker         int32_t packageUid, const std::string& packageName, const std::string& profileName,
3208*38e8c45fSAndroid Build Coastguard Worker         bool* _aidl_return) {
3209*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3210*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(systemProfile);
3211*38e8c45fSAndroid Build Coastguard Worker     if (!base::EndsWith(systemProfile, ".prof")) {
3212*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3213*38e8c45fSAndroid Build Coastguard Worker                          StringPrintf("System profile path %s does not end with .prof",
3214*38e8c45fSAndroid Build Coastguard Worker                                       systemProfile.c_str()));
3215*38e8c45fSAndroid Build Coastguard Worker     }
3216*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3217*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_FILE_NAME(profileName);
3218*38e8c45fSAndroid Build Coastguard Worker     if (!base::EndsWith(profileName, ".prof")) {
3219*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3220*38e8c45fSAndroid Build Coastguard Worker                          StringPrintf("Profile name %s does not end with .prof",
3221*38e8c45fSAndroid Build Coastguard Worker                                       profileName.c_str()));
3222*38e8c45fSAndroid Build Coastguard Worker     }
3223*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3224*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
3225*38e8c45fSAndroid Build Coastguard Worker     return ok();
3226*38e8c45fSAndroid Build Coastguard Worker }
3227*38e8c45fSAndroid Build Coastguard Worker 
3228*38e8c45fSAndroid Build Coastguard Worker // TODO: Consider returning error codes.
mergeProfiles(int32_t uid,const std::string & packageName,const std::string & profileName,int * _aidl_return)3229*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
3230*38e8c45fSAndroid Build Coastguard Worker         const std::string& profileName, int* _aidl_return) {
3231*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3232*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3233*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3234*38e8c45fSAndroid Build Coastguard Worker 
3235*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
3236*38e8c45fSAndroid Build Coastguard Worker     return ok();
3237*38e8c45fSAndroid Build Coastguard Worker }
3238*38e8c45fSAndroid Build Coastguard Worker 
createProfileSnapshot(int32_t appId,const std::string & packageName,const std::string & profileName,const std::string & classpath,bool * _aidl_return)3239*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
3240*38e8c45fSAndroid Build Coastguard Worker         const std::string& packageName, const std::string& profileName,
3241*38e8c45fSAndroid Build Coastguard Worker         const std::string& classpath, bool* _aidl_return) {
3242*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3243*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3244*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3245*38e8c45fSAndroid Build Coastguard Worker 
3246*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
3247*38e8c45fSAndroid Build Coastguard Worker     return ok();
3248*38e8c45fSAndroid Build Coastguard Worker }
3249*38e8c45fSAndroid Build Coastguard Worker 
destroyProfileSnapshot(const std::string & packageName,const std::string & profileName)3250*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
3251*38e8c45fSAndroid Build Coastguard Worker         const std::string& profileName) {
3252*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3253*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3254*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3255*38e8c45fSAndroid Build Coastguard Worker 
3256*38e8c45fSAndroid Build Coastguard Worker     std::string snapshot = create_snapshot_profile_path(packageName, profileName);
3257*38e8c45fSAndroid Build Coastguard Worker     if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
3258*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
3259*38e8c45fSAndroid Build Coastguard Worker     }
3260*38e8c45fSAndroid Build Coastguard Worker     return ok();
3261*38e8c45fSAndroid Build Coastguard Worker }
3262*38e8c45fSAndroid Build Coastguard Worker 
getCStr(const std::optional<std::string> & data,const char * default_value=nullptr)3263*38e8c45fSAndroid Build Coastguard Worker static const char* getCStr(const std::optional<std::string>& data,
3264*38e8c45fSAndroid Build Coastguard Worker         const char* default_value = nullptr) {
3265*38e8c45fSAndroid Build Coastguard Worker     return data ? data->c_str() : default_value;
3266*38e8c45fSAndroid Build Coastguard Worker }
dexopt(const std::string & apkPath,int32_t uid,const std::string & packageName,const std::string & instructionSet,int32_t dexoptNeeded,const std::optional<std::string> & outputPath,int32_t dexFlags,const std::string & compilerFilter,const std::optional<std::string> & uuid,const std::optional<std::string> & classLoaderContext,const std::optional<std::string> & seInfo,bool downgrade,int32_t targetSdkVersion,const std::optional<std::string> & profileName,const std::optional<std::string> & dexMetadataPath,const std::optional<std::string> & compilationReason,bool * aidl_return)3267*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::dexopt(
3268*38e8c45fSAndroid Build Coastguard Worker         const std::string& apkPath, int32_t uid, const std::string& packageName,
3269*38e8c45fSAndroid Build Coastguard Worker         const std::string& instructionSet, int32_t dexoptNeeded,
3270*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& outputPath, int32_t dexFlags,
3271*38e8c45fSAndroid Build Coastguard Worker         const std::string& compilerFilter, const std::optional<std::string>& uuid,
3272*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& classLoaderContext,
3273*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
3274*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& profileName,
3275*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& dexMetadataPath,
3276*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& compilationReason, bool* aidl_return) {
3277*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3278*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3279*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(apkPath);
3280*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3281*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(outputPath);
3282*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(dexMetadataPath);
3283*38e8c45fSAndroid Build Coastguard Worker     const auto userId = multiuser_get_user_id(uid);
3284*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
3285*38e8c45fSAndroid Build Coastguard Worker 
3286*38e8c45fSAndroid Build Coastguard Worker     const char* oat_dir = getCStr(outputPath);
3287*38e8c45fSAndroid Build Coastguard Worker     const char* instruction_set = instructionSet.c_str();
3288*38e8c45fSAndroid Build Coastguard Worker     if (oat_dir != nullptr && !createOatDir(packageName, oat_dir, instruction_set).isOk()) {
3289*38e8c45fSAndroid Build Coastguard Worker         // Can't create oat dir - let dexopt use cache dir.
3290*38e8c45fSAndroid Build Coastguard Worker         oat_dir = nullptr;
3291*38e8c45fSAndroid Build Coastguard Worker     }
3292*38e8c45fSAndroid Build Coastguard Worker 
3293*38e8c45fSAndroid Build Coastguard Worker     const char* apk_path = apkPath.c_str();
3294*38e8c45fSAndroid Build Coastguard Worker     const char* pkgname = packageName.c_str();
3295*38e8c45fSAndroid Build Coastguard Worker     const char* compiler_filter = compilerFilter.c_str();
3296*38e8c45fSAndroid Build Coastguard Worker     const char* volume_uuid = getCStr(uuid);
3297*38e8c45fSAndroid Build Coastguard Worker     const char* class_loader_context = getCStr(classLoaderContext);
3298*38e8c45fSAndroid Build Coastguard Worker     const char* se_info = getCStr(seInfo);
3299*38e8c45fSAndroid Build Coastguard Worker     const char* profile_name = getCStr(profileName);
3300*38e8c45fSAndroid Build Coastguard Worker     const char* dm_path = getCStr(dexMetadataPath);
3301*38e8c45fSAndroid Build Coastguard Worker     const char* compilation_reason = getCStr(compilationReason);
3302*38e8c45fSAndroid Build Coastguard Worker     std::string error_msg;
3303*38e8c45fSAndroid Build Coastguard Worker     bool completed = false; // not necessary but for compiler
3304*38e8c45fSAndroid Build Coastguard Worker     int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
3305*38e8c45fSAndroid Build Coastguard Worker             oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
3306*38e8c45fSAndroid Build Coastguard Worker             downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg,
3307*38e8c45fSAndroid Build Coastguard Worker             &completed);
3308*38e8c45fSAndroid Build Coastguard Worker     *aidl_return = completed;
3309*38e8c45fSAndroid Build Coastguard Worker     return res ? error(res, error_msg) : ok();
3310*38e8c45fSAndroid Build Coastguard Worker }
3311*38e8c45fSAndroid Build Coastguard Worker 
controlDexOptBlocking(bool block)3312*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::controlDexOptBlocking(bool block) {
3313*38e8c45fSAndroid Build Coastguard Worker     android::installd::control_dexopt_blocking(block);
3314*38e8c45fSAndroid Build Coastguard Worker     return ok();
3315*38e8c45fSAndroid Build Coastguard Worker }
3316*38e8c45fSAndroid Build Coastguard Worker 
linkNativeLibraryDirectory(const std::optional<std::string> & uuid,const std::string & packageName,const std::string & nativeLibPath32,int32_t userId)3317*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::linkNativeLibraryDirectory(
3318*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, const std::string& packageName,
3319*38e8c45fSAndroid Build Coastguard Worker         const std::string& nativeLibPath32, int32_t userId) {
3320*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3321*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3322*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3323*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(nativeLibPath32);
3324*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
3325*38e8c45fSAndroid Build Coastguard Worker 
3326*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3327*38e8c45fSAndroid Build Coastguard Worker     const char* pkgname = packageName.c_str();
3328*38e8c45fSAndroid Build Coastguard Worker     const char* asecLibDir = nativeLibPath32.c_str();
3329*38e8c45fSAndroid Build Coastguard Worker     struct stat s, libStat;
3330*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
3331*38e8c45fSAndroid Build Coastguard Worker 
3332*38e8c45fSAndroid Build Coastguard Worker     auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
3333*38e8c45fSAndroid Build Coastguard Worker     auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
3334*38e8c45fSAndroid Build Coastguard Worker 
3335*38e8c45fSAndroid Build Coastguard Worker     const char* pkgdir = _pkgdir.c_str();
3336*38e8c45fSAndroid Build Coastguard Worker     const char* libsymlink = _libsymlink.c_str();
3337*38e8c45fSAndroid Build Coastguard Worker 
3338*38e8c45fSAndroid Build Coastguard Worker     if (stat(pkgdir, &s) < 0) {
3339*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to stat " + _pkgdir);
3340*38e8c45fSAndroid Build Coastguard Worker     }
3341*38e8c45fSAndroid Build Coastguard Worker 
3342*38e8c45fSAndroid Build Coastguard Worker     char *con = nullptr;
3343*38e8c45fSAndroid Build Coastguard Worker     if (::lgetfilecon(pkgdir, &con) < 0) {
3344*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to lgetfilecon " + _pkgdir);
3345*38e8c45fSAndroid Build Coastguard Worker     }
3346*38e8c45fSAndroid Build Coastguard Worker 
3347*38e8c45fSAndroid Build Coastguard Worker     if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
3348*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to chown " + _pkgdir);
3349*38e8c45fSAndroid Build Coastguard Worker         goto out;
3350*38e8c45fSAndroid Build Coastguard Worker     }
3351*38e8c45fSAndroid Build Coastguard Worker 
3352*38e8c45fSAndroid Build Coastguard Worker     if (chmod(pkgdir, 0700) < 0) {
3353*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to chmod " + _pkgdir);
3354*38e8c45fSAndroid Build Coastguard Worker         goto out;
3355*38e8c45fSAndroid Build Coastguard Worker     }
3356*38e8c45fSAndroid Build Coastguard Worker 
3357*38e8c45fSAndroid Build Coastguard Worker     if (lstat(libsymlink, &libStat) < 0) {
3358*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENOENT) {
3359*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to stat " + _libsymlink);
3360*38e8c45fSAndroid Build Coastguard Worker             goto out;
3361*38e8c45fSAndroid Build Coastguard Worker         }
3362*38e8c45fSAndroid Build Coastguard Worker     } else {
3363*38e8c45fSAndroid Build Coastguard Worker         if (S_ISDIR(libStat.st_mode)) {
3364*38e8c45fSAndroid Build Coastguard Worker             if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
3365*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to delete " + _libsymlink);
3366*38e8c45fSAndroid Build Coastguard Worker                 goto out;
3367*38e8c45fSAndroid Build Coastguard Worker             }
3368*38e8c45fSAndroid Build Coastguard Worker         } else if (S_ISLNK(libStat.st_mode)) {
3369*38e8c45fSAndroid Build Coastguard Worker             if (unlink(libsymlink) < 0) {
3370*38e8c45fSAndroid Build Coastguard Worker                 res = error("Failed to unlink " + _libsymlink);
3371*38e8c45fSAndroid Build Coastguard Worker                 goto out;
3372*38e8c45fSAndroid Build Coastguard Worker             }
3373*38e8c45fSAndroid Build Coastguard Worker         }
3374*38e8c45fSAndroid Build Coastguard Worker     }
3375*38e8c45fSAndroid Build Coastguard Worker 
3376*38e8c45fSAndroid Build Coastguard Worker     if (symlink(asecLibDir, libsymlink) < 0) {
3377*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
3378*38e8c45fSAndroid Build Coastguard Worker         goto out;
3379*38e8c45fSAndroid Build Coastguard Worker     }
3380*38e8c45fSAndroid Build Coastguard Worker 
3381*38e8c45fSAndroid Build Coastguard Worker     if (lsetfilecon(libsymlink, con) < 0) {
3382*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to lsetfilecon " + _libsymlink);
3383*38e8c45fSAndroid Build Coastguard Worker         goto out;
3384*38e8c45fSAndroid Build Coastguard Worker     }
3385*38e8c45fSAndroid Build Coastguard Worker 
3386*38e8c45fSAndroid Build Coastguard Worker out:
3387*38e8c45fSAndroid Build Coastguard Worker     free(con);
3388*38e8c45fSAndroid Build Coastguard Worker     if (chmod(pkgdir, s.st_mode) < 0) {
3389*38e8c45fSAndroid Build Coastguard Worker         auto msg = "Failed to cleanup chmod " + _pkgdir;
3390*38e8c45fSAndroid Build Coastguard Worker         if (res.isOk()) {
3391*38e8c45fSAndroid Build Coastguard Worker             res = error(msg);
3392*38e8c45fSAndroid Build Coastguard Worker         } else {
3393*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << msg;
3394*38e8c45fSAndroid Build Coastguard Worker         }
3395*38e8c45fSAndroid Build Coastguard Worker     }
3396*38e8c45fSAndroid Build Coastguard Worker 
3397*38e8c45fSAndroid Build Coastguard Worker     if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
3398*38e8c45fSAndroid Build Coastguard Worker         auto msg = "Failed to cleanup chown " + _pkgdir;
3399*38e8c45fSAndroid Build Coastguard Worker         if (res.isOk()) {
3400*38e8c45fSAndroid Build Coastguard Worker             res = error(msg);
3401*38e8c45fSAndroid Build Coastguard Worker         } else {
3402*38e8c45fSAndroid Build Coastguard Worker             PLOG(ERROR) << msg;
3403*38e8c45fSAndroid Build Coastguard Worker         }
3404*38e8c45fSAndroid Build Coastguard Worker     }
3405*38e8c45fSAndroid Build Coastguard Worker 
3406*38e8c45fSAndroid Build Coastguard Worker     return res;
3407*38e8c45fSAndroid Build Coastguard Worker }
3408*38e8c45fSAndroid Build Coastguard Worker 
restoreconAppData(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags,int32_t appId,const std::string & seInfo)3409*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::restoreconAppData(const std::optional<std::string>& uuid,
3410*38e8c45fSAndroid Build Coastguard Worker         const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
3411*38e8c45fSAndroid Build Coastguard Worker         const std::string& seInfo) {
3412*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3413*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
3414*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3415*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3416*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
3417*38e8c45fSAndroid Build Coastguard Worker     return restoreconAppDataLocked(uuid, packageName, userId, flags, appId, seInfo);
3418*38e8c45fSAndroid Build Coastguard Worker }
3419*38e8c45fSAndroid Build Coastguard Worker 
restoreconAppDataLocked(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags,int32_t appId,const std::string & seInfo)3420*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::restoreconAppDataLocked(
3421*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3422*38e8c45fSAndroid Build Coastguard Worker         int32_t flags, int32_t appId, const std::string& seInfo) {
3423*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3424*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
3425*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3426*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3427*38e8c45fSAndroid Build Coastguard Worker 
3428*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
3429*38e8c45fSAndroid Build Coastguard Worker 
3430*38e8c45fSAndroid Build Coastguard Worker     // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
3431*38e8c45fSAndroid Build Coastguard Worker     unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
3432*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3433*38e8c45fSAndroid Build Coastguard Worker     const char* pkgName = packageName.c_str();
3434*38e8c45fSAndroid Build Coastguard Worker     const char* seinfo = seInfo.c_str();
3435*38e8c45fSAndroid Build Coastguard Worker 
3436*38e8c45fSAndroid Build Coastguard Worker     uid_t uid = multiuser_get_uid(userId, appId);
3437*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_CE) {
3438*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
3439*38e8c45fSAndroid Build Coastguard Worker         if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
3440*38e8c45fSAndroid Build Coastguard Worker             res = error("restorecon failed for " + path);
3441*38e8c45fSAndroid Build Coastguard Worker         }
3442*38e8c45fSAndroid Build Coastguard Worker     }
3443*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_DE) {
3444*38e8c45fSAndroid Build Coastguard Worker         auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
3445*38e8c45fSAndroid Build Coastguard Worker         if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
3446*38e8c45fSAndroid Build Coastguard Worker             res = error("restorecon failed for " + path);
3447*38e8c45fSAndroid Build Coastguard Worker         }
3448*38e8c45fSAndroid Build Coastguard Worker     }
3449*38e8c45fSAndroid Build Coastguard Worker     return res;
3450*38e8c45fSAndroid Build Coastguard Worker }
3451*38e8c45fSAndroid Build Coastguard Worker 
restoreconSdkDataLocked(const std::optional<std::string> & uuid,const std::string & packageName,int32_t userId,int32_t flags,int32_t appId,const std::string & seInfo)3452*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::restoreconSdkDataLocked(
3453*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3454*38e8c45fSAndroid Build Coastguard Worker         int32_t flags, int32_t appId, const std::string& seInfo) {
3455*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3456*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
3457*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3458*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3459*38e8c45fSAndroid Build Coastguard Worker 
3460*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
3461*38e8c45fSAndroid Build Coastguard Worker 
3462*38e8c45fSAndroid Build Coastguard Worker     // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
3463*38e8c45fSAndroid Build Coastguard Worker     unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
3464*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3465*38e8c45fSAndroid Build Coastguard Worker     const char* pkgName = packageName.c_str();
3466*38e8c45fSAndroid Build Coastguard Worker     const char* seinfo = seInfo.c_str();
3467*38e8c45fSAndroid Build Coastguard Worker 
3468*38e8c45fSAndroid Build Coastguard Worker     uid_t uid = multiuser_get_sdk_sandbox_uid(userId, appId);
3469*38e8c45fSAndroid Build Coastguard Worker     constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
3470*38e8c45fSAndroid Build Coastguard Worker     for (int currentFlag : storageFlags) {
3471*38e8c45fSAndroid Build Coastguard Worker         if ((flags & currentFlag) == 0) {
3472*38e8c45fSAndroid Build Coastguard Worker             continue;
3473*38e8c45fSAndroid Build Coastguard Worker         }
3474*38e8c45fSAndroid Build Coastguard Worker         const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
3475*38e8c45fSAndroid Build Coastguard Worker         const auto packagePath =
3476*38e8c45fSAndroid Build Coastguard Worker                 create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgName);
3477*38e8c45fSAndroid Build Coastguard Worker         if (access(packagePath.c_str(), F_OK) != 0) {
3478*38e8c45fSAndroid Build Coastguard Worker             LOG(INFO) << "Missing source " << packagePath;
3479*38e8c45fSAndroid Build Coastguard Worker             continue;
3480*38e8c45fSAndroid Build Coastguard Worker         }
3481*38e8c45fSAndroid Build Coastguard Worker         const auto subDirHandler = [&packagePath, &seinfo, &uid, &seflags,
3482*38e8c45fSAndroid Build Coastguard Worker                                     &res](const std::string& subDir) {
3483*38e8c45fSAndroid Build Coastguard Worker             const auto& fullpath = packagePath + "/" + subDir;
3484*38e8c45fSAndroid Build Coastguard Worker             if (selinux_android_restorecon_pkgdir(fullpath.c_str(), seinfo, uid, seflags) < 0) {
3485*38e8c45fSAndroid Build Coastguard Worker                 res = error("restorecon failed for " + fullpath);
3486*38e8c45fSAndroid Build Coastguard Worker             }
3487*38e8c45fSAndroid Build Coastguard Worker         };
3488*38e8c45fSAndroid Build Coastguard Worker         const auto ec = foreach_subdir(packagePath, subDirHandler);
3489*38e8c45fSAndroid Build Coastguard Worker         if (ec != 0) {
3490*38e8c45fSAndroid Build Coastguard Worker             res = error("Failed to restorecon for subdirs of " + packagePath);
3491*38e8c45fSAndroid Build Coastguard Worker         }
3492*38e8c45fSAndroid Build Coastguard Worker     }
3493*38e8c45fSAndroid Build Coastguard Worker     return res;
3494*38e8c45fSAndroid Build Coastguard Worker }
3495*38e8c45fSAndroid Build Coastguard Worker 
createOatDir(const std::string & packageName,const std::string & oatDir,const std::string & instructionSet)3496*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createOatDir(const std::string& packageName,
3497*38e8c45fSAndroid Build Coastguard Worker                                                    const std::string& oatDir,
3498*38e8c45fSAndroid Build Coastguard Worker                                                    const std::string& instructionSet) {
3499*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3500*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3501*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(oatDir);
3502*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3503*38e8c45fSAndroid Build Coastguard Worker 
3504*38e8c45fSAndroid Build Coastguard Worker     const char* oat_dir = oatDir.c_str();
3505*38e8c45fSAndroid Build Coastguard Worker     const char* instruction_set = instructionSet.c_str();
3506*38e8c45fSAndroid Build Coastguard Worker     char oat_instr_dir[PKG_PATH_MAX];
3507*38e8c45fSAndroid Build Coastguard Worker 
3508*38e8c45fSAndroid Build Coastguard Worker     if (validate_apk_path(oat_dir)) {
3509*38e8c45fSAndroid Build Coastguard Worker         return error("Invalid path " + oatDir);
3510*38e8c45fSAndroid Build Coastguard Worker     }
3511*38e8c45fSAndroid Build Coastguard Worker     if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
3512*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to prepare " + oatDir);
3513*38e8c45fSAndroid Build Coastguard Worker     }
3514*38e8c45fSAndroid Build Coastguard Worker     if (selinux_android_restorecon(oat_dir, 0)) {
3515*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to restorecon " + oatDir);
3516*38e8c45fSAndroid Build Coastguard Worker     }
3517*38e8c45fSAndroid Build Coastguard Worker     snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
3518*38e8c45fSAndroid Build Coastguard Worker     if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
3519*38e8c45fSAndroid Build Coastguard Worker         return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
3520*38e8c45fSAndroid Build Coastguard Worker     }
3521*38e8c45fSAndroid Build Coastguard Worker     return ok();
3522*38e8c45fSAndroid Build Coastguard Worker }
3523*38e8c45fSAndroid Build Coastguard Worker 
rmPackageDir(const std::string & packageName,const std::string & packageDir)3524*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::rmPackageDir(const std::string& packageName,
3525*38e8c45fSAndroid Build Coastguard Worker                                                    const std::string& packageDir) {
3526*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3527*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(packageDir);
3528*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3529*38e8c45fSAndroid Build Coastguard Worker 
3530*38e8c45fSAndroid Build Coastguard Worker     if (validate_apk_path(packageDir.c_str())) {
3531*38e8c45fSAndroid Build Coastguard Worker         return error("Invalid path " + packageDir);
3532*38e8c45fSAndroid Build Coastguard Worker     }
3533*38e8c45fSAndroid Build Coastguard Worker     if (rm_package_dir(packageDir) != 0) {
3534*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to delete " + packageDir);
3535*38e8c45fSAndroid Build Coastguard Worker     }
3536*38e8c45fSAndroid Build Coastguard Worker     return ok();
3537*38e8c45fSAndroid Build Coastguard Worker }
3538*38e8c45fSAndroid Build Coastguard Worker 
linkFile(const std::string & packageName,const std::string & relativePath,const std::string & fromBase,const std::string & toBase)3539*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::linkFile(const std::string& packageName,
3540*38e8c45fSAndroid Build Coastguard Worker                                                const std::string& relativePath,
3541*38e8c45fSAndroid Build Coastguard Worker                                                const std::string& fromBase,
3542*38e8c45fSAndroid Build Coastguard Worker                                                const std::string& toBase) {
3543*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3544*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3545*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(fromBase);
3546*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(toBase);
3547*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3548*38e8c45fSAndroid Build Coastguard Worker 
3549*38e8c45fSAndroid Build Coastguard Worker     const char* relative_path = relativePath.c_str();
3550*38e8c45fSAndroid Build Coastguard Worker     const char* from_base = fromBase.c_str();
3551*38e8c45fSAndroid Build Coastguard Worker     const char* to_base = toBase.c_str();
3552*38e8c45fSAndroid Build Coastguard Worker     char from_path[PKG_PATH_MAX];
3553*38e8c45fSAndroid Build Coastguard Worker     char to_path[PKG_PATH_MAX];
3554*38e8c45fSAndroid Build Coastguard Worker     snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
3555*38e8c45fSAndroid Build Coastguard Worker     snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
3556*38e8c45fSAndroid Build Coastguard Worker 
3557*38e8c45fSAndroid Build Coastguard Worker     if (validate_apk_path_subdirs(from_path)) {
3558*38e8c45fSAndroid Build Coastguard Worker         return error(StringPrintf("Invalid from path %s", from_path));
3559*38e8c45fSAndroid Build Coastguard Worker     }
3560*38e8c45fSAndroid Build Coastguard Worker 
3561*38e8c45fSAndroid Build Coastguard Worker     if (validate_apk_path_subdirs(to_path)) {
3562*38e8c45fSAndroid Build Coastguard Worker         return error(StringPrintf("Invalid to path %s", to_path));
3563*38e8c45fSAndroid Build Coastguard Worker     }
3564*38e8c45fSAndroid Build Coastguard Worker 
3565*38e8c45fSAndroid Build Coastguard Worker     if (link(from_path, to_path) < 0) {
3566*38e8c45fSAndroid Build Coastguard Worker         return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
3567*38e8c45fSAndroid Build Coastguard Worker     }
3568*38e8c45fSAndroid Build Coastguard Worker 
3569*38e8c45fSAndroid Build Coastguard Worker     return ok();
3570*38e8c45fSAndroid Build Coastguard Worker }
3571*38e8c45fSAndroid Build Coastguard Worker 
moveAb(const std::string & packageName,const std::string & apkPath,const std::string & instructionSet,const std::string & outputPath)3572*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::moveAb(const std::string& packageName,
3573*38e8c45fSAndroid Build Coastguard Worker                                              const std::string& apkPath,
3574*38e8c45fSAndroid Build Coastguard Worker                                              const std::string& instructionSet,
3575*38e8c45fSAndroid Build Coastguard Worker                                              const std::string& outputPath) {
3576*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3577*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3578*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(apkPath);
3579*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(outputPath);
3580*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3581*38e8c45fSAndroid Build Coastguard Worker 
3582*38e8c45fSAndroid Build Coastguard Worker     const char* apk_path = apkPath.c_str();
3583*38e8c45fSAndroid Build Coastguard Worker     const char* instruction_set = instructionSet.c_str();
3584*38e8c45fSAndroid Build Coastguard Worker     const char* oat_dir = outputPath.c_str();
3585*38e8c45fSAndroid Build Coastguard Worker 
3586*38e8c45fSAndroid Build Coastguard Worker     bool success = move_ab(apk_path, instruction_set, oat_dir);
3587*38e8c45fSAndroid Build Coastguard Worker     return success ? ok() : error();
3588*38e8c45fSAndroid Build Coastguard Worker }
3589*38e8c45fSAndroid Build Coastguard Worker 
deleteOdex(const std::string & packageName,const std::string & apkPath,const std::string & instructionSet,const std::optional<std::string> & outputPath,int64_t * _aidl_return)3590*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::deleteOdex(const std::string& packageName,
3591*38e8c45fSAndroid Build Coastguard Worker                                                  const std::string& apkPath,
3592*38e8c45fSAndroid Build Coastguard Worker                                                  const std::string& instructionSet,
3593*38e8c45fSAndroid Build Coastguard Worker                                                  const std::optional<std::string>& outputPath,
3594*38e8c45fSAndroid Build Coastguard Worker                                                  int64_t* _aidl_return) {
3595*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3596*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3597*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(apkPath);
3598*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(outputPath);
3599*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3600*38e8c45fSAndroid Build Coastguard Worker 
3601*38e8c45fSAndroid Build Coastguard Worker     const char* apk_path = apkPath.c_str();
3602*38e8c45fSAndroid Build Coastguard Worker     const char* instruction_set = instructionSet.c_str();
3603*38e8c45fSAndroid Build Coastguard Worker     const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
3604*38e8c45fSAndroid Build Coastguard Worker 
3605*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = delete_odex(apk_path, instruction_set, oat_dir);
3606*38e8c45fSAndroid Build Coastguard Worker     return *_aidl_return == -1 ? error() : ok();
3607*38e8c45fSAndroid Build Coastguard Worker }
3608*38e8c45fSAndroid Build Coastguard Worker 
reconcileSecondaryDexFile(const std::string & dexPath,const std::string & packageName,int32_t uid,const std::vector<std::string> & isas,const std::optional<std::string> & volumeUuid,int32_t storage_flag,bool * _aidl_return)3609*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::reconcileSecondaryDexFile(
3610*38e8c45fSAndroid Build Coastguard Worker         const std::string& dexPath, const std::string& packageName, int32_t uid,
3611*38e8c45fSAndroid Build Coastguard Worker         const std::vector<std::string>& isas, const std::optional<std::string>& volumeUuid,
3612*38e8c45fSAndroid Build Coastguard Worker         int32_t storage_flag, bool* _aidl_return) {
3613*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3614*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(volumeUuid);
3615*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3616*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(dexPath);
3617*38e8c45fSAndroid Build Coastguard Worker     const auto userId = multiuser_get_user_id(uid);
3618*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
3619*38e8c45fSAndroid Build Coastguard Worker 
3620*38e8c45fSAndroid Build Coastguard Worker     bool result = android::installd::reconcile_secondary_dex_file(
3621*38e8c45fSAndroid Build Coastguard Worker             dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
3622*38e8c45fSAndroid Build Coastguard Worker     return result ? ok() : error();
3623*38e8c45fSAndroid Build Coastguard Worker }
3624*38e8c45fSAndroid Build Coastguard Worker 
hashSecondaryDexFile(const std::string & dexPath,const std::string & packageName,int32_t uid,const std::optional<std::string> & volumeUuid,int32_t storageFlag,std::vector<uint8_t> * _aidl_return)3625*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::hashSecondaryDexFile(
3626*38e8c45fSAndroid Build Coastguard Worker         const std::string& dexPath, const std::string& packageName, int32_t uid,
3627*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& volumeUuid, int32_t storageFlag,
3628*38e8c45fSAndroid Build Coastguard Worker         std::vector<uint8_t>* _aidl_return) {
3629*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3630*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(volumeUuid);
3631*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3632*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(dexPath);
3633*38e8c45fSAndroid Build Coastguard Worker 
3634*38e8c45fSAndroid Build Coastguard Worker     // mLock is not taken here since we will never modify the file system.
3635*38e8c45fSAndroid Build Coastguard Worker     // If a file is modified just as we are reading it this may result in an
3636*38e8c45fSAndroid Build Coastguard Worker     // anomalous hash, but that's ok.
3637*38e8c45fSAndroid Build Coastguard Worker     bool result = android::installd::hash_secondary_dex_file(
3638*38e8c45fSAndroid Build Coastguard Worker         dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
3639*38e8c45fSAndroid Build Coastguard Worker     return result ? ok() : error();
3640*38e8c45fSAndroid Build Coastguard Worker }
3641*38e8c45fSAndroid Build Coastguard Worker /**
3642*38e8c45fSAndroid Build Coastguard Worker  * Returns true if ioctl feature (F2FS_IOC_FS{GET,SET}XATTR) is supported as
3643*38e8c45fSAndroid Build Coastguard Worker  * these were introduced in Linux 4.14, so kernel versions before that will fail
3644*38e8c45fSAndroid Build Coastguard Worker  * while setting project id attributes. Only when these features are enabled,
3645*38e8c45fSAndroid Build Coastguard Worker  * storage calculation using project_id is enabled
3646*38e8c45fSAndroid Build Coastguard Worker  */
check_if_ioctl_feature_is_supported()3647*38e8c45fSAndroid Build Coastguard Worker bool check_if_ioctl_feature_is_supported() {
3648*38e8c45fSAndroid Build Coastguard Worker     bool result = false;
3649*38e8c45fSAndroid Build Coastguard Worker     auto temp_path = StringPrintf("%smisc/installd/ioctl_check", android_data_dir.c_str());
3650*38e8c45fSAndroid Build Coastguard Worker     if (access(temp_path.c_str(), F_OK) != 0) {
3651*38e8c45fSAndroid Build Coastguard Worker         int fd = open(temp_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644);
3652*38e8c45fSAndroid Build Coastguard Worker         result = set_quota_project_id(temp_path, 0, false) == 0;
3653*38e8c45fSAndroid Build Coastguard Worker         close(fd);
3654*38e8c45fSAndroid Build Coastguard Worker         // delete the temp file
3655*38e8c45fSAndroid Build Coastguard Worker         remove(temp_path.c_str());
3656*38e8c45fSAndroid Build Coastguard Worker     }
3657*38e8c45fSAndroid Build Coastguard Worker     return result;
3658*38e8c45fSAndroid Build Coastguard Worker }
3659*38e8c45fSAndroid Build Coastguard Worker 
setFirstBoot()3660*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::setFirstBoot() {
3661*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3662*38e8c45fSAndroid Build Coastguard Worker     std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3663*38e8c45fSAndroid Build Coastguard Worker     std::string uuid;
3664*38e8c45fSAndroid Build Coastguard Worker     if (GetOccupiedSpaceForProjectId(uuid, 0) != -1 && check_if_ioctl_feature_is_supported()) {
3665*38e8c45fSAndroid Build Coastguard Worker         auto first_boot_path =
3666*38e8c45fSAndroid Build Coastguard Worker                 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
3667*38e8c45fSAndroid Build Coastguard Worker         if (access(first_boot_path.c_str(), F_OK) != 0) {
3668*38e8c45fSAndroid Build Coastguard Worker             close(open(first_boot_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644));
3669*38e8c45fSAndroid Build Coastguard Worker         }
3670*38e8c45fSAndroid Build Coastguard Worker     }
3671*38e8c45fSAndroid Build Coastguard Worker     return ok();
3672*38e8c45fSAndroid Build Coastguard Worker }
3673*38e8c45fSAndroid Build Coastguard Worker 
invalidateMounts()3674*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::invalidateMounts() {
3675*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3676*38e8c45fSAndroid Build Coastguard Worker     std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3677*38e8c45fSAndroid Build Coastguard Worker 
3678*38e8c45fSAndroid Build Coastguard Worker     mStorageMounts.clear();
3679*38e8c45fSAndroid Build Coastguard Worker 
3680*38e8c45fSAndroid Build Coastguard Worker #if !BYPASS_QUOTA
3681*38e8c45fSAndroid Build Coastguard Worker     if (!InvalidateQuotaMounts()) {
3682*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to read mounts");
3683*38e8c45fSAndroid Build Coastguard Worker     }
3684*38e8c45fSAndroid Build Coastguard Worker #endif
3685*38e8c45fSAndroid Build Coastguard Worker 
3686*38e8c45fSAndroid Build Coastguard Worker     std::ifstream in("/proc/mounts");
3687*38e8c45fSAndroid Build Coastguard Worker     if (!in.is_open()) {
3688*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to read mounts");
3689*38e8c45fSAndroid Build Coastguard Worker     }
3690*38e8c45fSAndroid Build Coastguard Worker 
3691*38e8c45fSAndroid Build Coastguard Worker     std::string source;
3692*38e8c45fSAndroid Build Coastguard Worker     std::string target;
3693*38e8c45fSAndroid Build Coastguard Worker     std::string ignored;
3694*38e8c45fSAndroid Build Coastguard Worker     while (!in.eof()) {
3695*38e8c45fSAndroid Build Coastguard Worker         std::getline(in, source, ' ');
3696*38e8c45fSAndroid Build Coastguard Worker         std::getline(in, target, ' ');
3697*38e8c45fSAndroid Build Coastguard Worker         std::getline(in, ignored);
3698*38e8c45fSAndroid Build Coastguard Worker 
3699*38e8c45fSAndroid Build Coastguard Worker         if (android::base::GetBoolProperty(kFuseProp, false)) {
3700*38e8c45fSAndroid Build Coastguard Worker             if (target.find(kMntFuse) == 0) {
3701*38e8c45fSAndroid Build Coastguard Worker                 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3702*38e8c45fSAndroid Build Coastguard Worker                 mStorageMounts[source] = target;
3703*38e8c45fSAndroid Build Coastguard Worker             }
3704*38e8c45fSAndroid Build Coastguard Worker         } else {
3705*38e8c45fSAndroid Build Coastguard Worker #if !BYPASS_SDCARDFS
3706*38e8c45fSAndroid Build Coastguard Worker             if (target.find(kMntSdcardfs) == 0) {
3707*38e8c45fSAndroid Build Coastguard Worker                 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3708*38e8c45fSAndroid Build Coastguard Worker                 mStorageMounts[source] = target;
3709*38e8c45fSAndroid Build Coastguard Worker             }
3710*38e8c45fSAndroid Build Coastguard Worker #endif
3711*38e8c45fSAndroid Build Coastguard Worker         }
3712*38e8c45fSAndroid Build Coastguard Worker     }
3713*38e8c45fSAndroid Build Coastguard Worker     return ok();
3714*38e8c45fSAndroid Build Coastguard Worker }
3715*38e8c45fSAndroid Build Coastguard Worker 
3716*38e8c45fSAndroid Build Coastguard Worker // Mount volume's CE and DE storage to mirror
tryMountDataMirror(const std::optional<std::string> & uuid)3717*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::tryMountDataMirror(
3718*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid) {
3719*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3720*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3721*38e8c45fSAndroid Build Coastguard Worker     if (!sAppDataIsolationEnabled) {
3722*38e8c45fSAndroid Build Coastguard Worker         return ok();
3723*38e8c45fSAndroid Build Coastguard Worker     }
3724*38e8c45fSAndroid Build Coastguard Worker     if (!uuid) {
3725*38e8c45fSAndroid Build Coastguard Worker         return error("Should not happen, mounting uuid == null");
3726*38e8c45fSAndroid Build Coastguard Worker     }
3727*38e8c45fSAndroid Build Coastguard Worker 
3728*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid->c_str();
3729*38e8c45fSAndroid Build Coastguard Worker 
3730*38e8c45fSAndroid Build Coastguard Worker     std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3731*38e8c45fSAndroid Build Coastguard Worker 
3732*38e8c45fSAndroid Build Coastguard Worker     std::string mirrorVolCePath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
3733*38e8c45fSAndroid Build Coastguard Worker     if (fs_prepare_dir(mirrorVolCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
3734*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to create CE data mirror");
3735*38e8c45fSAndroid Build Coastguard Worker     }
3736*38e8c45fSAndroid Build Coastguard Worker 
3737*38e8c45fSAndroid Build Coastguard Worker     std::string mirrorVolDePath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
3738*38e8c45fSAndroid Build Coastguard Worker     if (fs_prepare_dir(mirrorVolDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
3739*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to create DE data mirror");
3740*38e8c45fSAndroid Build Coastguard Worker     }
3741*38e8c45fSAndroid Build Coastguard Worker 
3742*38e8c45fSAndroid Build Coastguard Worker     std::string mirrorVolMiscCePath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
3743*38e8c45fSAndroid Build Coastguard Worker     if (fs_prepare_dir(mirrorVolMiscCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
3744*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to create CE misc mirror");
3745*38e8c45fSAndroid Build Coastguard Worker     }
3746*38e8c45fSAndroid Build Coastguard Worker 
3747*38e8c45fSAndroid Build Coastguard Worker     std::string mirrorVolMiscDePath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
3748*38e8c45fSAndroid Build Coastguard Worker     if (fs_prepare_dir(mirrorVolMiscDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
3749*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to create DE misc mirror");
3750*38e8c45fSAndroid Build Coastguard Worker     }
3751*38e8c45fSAndroid Build Coastguard Worker 
3752*38e8c45fSAndroid Build Coastguard Worker     auto cePath = StringPrintf("%s/user", create_data_path(uuid_).c_str());
3753*38e8c45fSAndroid Build Coastguard Worker     auto dePath = StringPrintf("%s/user_de", create_data_path(uuid_).c_str());
3754*38e8c45fSAndroid Build Coastguard Worker     auto miscCePath = StringPrintf("%s/misc_ce", create_data_path(uuid_).c_str());
3755*38e8c45fSAndroid Build Coastguard Worker     auto miscDePath = StringPrintf("%s/misc_de", create_data_path(uuid_).c_str());
3756*38e8c45fSAndroid Build Coastguard Worker 
3757*38e8c45fSAndroid Build Coastguard Worker     if (access(cePath.c_str(), F_OK) != 0) {
3758*38e8c45fSAndroid Build Coastguard Worker         return error("Cannot access CE path: " + cePath);
3759*38e8c45fSAndroid Build Coastguard Worker     }
3760*38e8c45fSAndroid Build Coastguard Worker     if (access(dePath.c_str(), F_OK) != 0) {
3761*38e8c45fSAndroid Build Coastguard Worker         return error("Cannot access DE path: " + dePath);
3762*38e8c45fSAndroid Build Coastguard Worker     }
3763*38e8c45fSAndroid Build Coastguard Worker     if (access(miscCePath.c_str(), F_OK) != 0) {
3764*38e8c45fSAndroid Build Coastguard Worker         return error("Cannot access misc CE path: " + cePath);
3765*38e8c45fSAndroid Build Coastguard Worker     }
3766*38e8c45fSAndroid Build Coastguard Worker     if (access(miscDePath.c_str(), F_OK) != 0) {
3767*38e8c45fSAndroid Build Coastguard Worker         return error("Cannot access misc DE path: " + dePath);
3768*38e8c45fSAndroid Build Coastguard Worker     }
3769*38e8c45fSAndroid Build Coastguard Worker 
3770*38e8c45fSAndroid Build Coastguard Worker     struct stat ceStat, mirrorCeStat;
3771*38e8c45fSAndroid Build Coastguard Worker     if (stat(cePath.c_str(), &ceStat) != 0) {
3772*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to stat " + cePath);
3773*38e8c45fSAndroid Build Coastguard Worker     }
3774*38e8c45fSAndroid Build Coastguard Worker     if (stat(mirrorVolCePath.c_str(), &mirrorCeStat) != 0) {
3775*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to stat " + mirrorVolCePath);
3776*38e8c45fSAndroid Build Coastguard Worker     }
3777*38e8c45fSAndroid Build Coastguard Worker 
3778*38e8c45fSAndroid Build Coastguard Worker     if (mirrorCeStat.st_ino == ceStat.st_ino && mirrorCeStat.st_dev == ceStat.st_dev) {
3779*38e8c45fSAndroid Build Coastguard Worker         // As it's being called by prepareUserStorage, it can be called multiple times.
3780*38e8c45fSAndroid Build Coastguard Worker         // Hence, we if we mount it already, we should skip it.
3781*38e8c45fSAndroid Build Coastguard Worker         LOG(INFO) << "CE dir is mounted already: " + cePath;
3782*38e8c45fSAndroid Build Coastguard Worker         return ok();
3783*38e8c45fSAndroid Build Coastguard Worker     }
3784*38e8c45fSAndroid Build Coastguard Worker 
3785*38e8c45fSAndroid Build Coastguard Worker     // Mount CE mirror
3786*38e8c45fSAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(mount(cePath.c_str(), mirrorVolCePath.c_str(), NULL,
3787*38e8c45fSAndroid Build Coastguard Worker             MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3788*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to mount " + mirrorVolCePath);
3789*38e8c45fSAndroid Build Coastguard Worker     }
3790*38e8c45fSAndroid Build Coastguard Worker 
3791*38e8c45fSAndroid Build Coastguard Worker     // Mount DE mirror
3792*38e8c45fSAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(mount(dePath.c_str(), mirrorVolDePath.c_str(), NULL,
3793*38e8c45fSAndroid Build Coastguard Worker             MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3794*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to mount " + mirrorVolDePath);
3795*38e8c45fSAndroid Build Coastguard Worker     }
3796*38e8c45fSAndroid Build Coastguard Worker 
3797*38e8c45fSAndroid Build Coastguard Worker     // Mount misc CE mirror
3798*38e8c45fSAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(mount(miscCePath.c_str(), mirrorVolMiscCePath.c_str(), NULL,
3799*38e8c45fSAndroid Build Coastguard Worker                                  MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3800*38e8c45fSAndroid Build Coastguard Worker                                  nullptr)) == -1) {
3801*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to mount " + mirrorVolMiscCePath);
3802*38e8c45fSAndroid Build Coastguard Worker     }
3803*38e8c45fSAndroid Build Coastguard Worker 
3804*38e8c45fSAndroid Build Coastguard Worker     // Mount misc DE mirror
3805*38e8c45fSAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(mount(miscDePath.c_str(), mirrorVolMiscDePath.c_str(), NULL,
3806*38e8c45fSAndroid Build Coastguard Worker                                  MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3807*38e8c45fSAndroid Build Coastguard Worker                                  nullptr)) == -1) {
3808*38e8c45fSAndroid Build Coastguard Worker         return error("Failed to mount " + mirrorVolMiscDePath);
3809*38e8c45fSAndroid Build Coastguard Worker     }
3810*38e8c45fSAndroid Build Coastguard Worker 
3811*38e8c45fSAndroid Build Coastguard Worker     return ok();
3812*38e8c45fSAndroid Build Coastguard Worker }
3813*38e8c45fSAndroid Build Coastguard Worker 
3814*38e8c45fSAndroid Build Coastguard Worker // Unmount volume's CE and DE storage from mirror
onPrivateVolumeRemoved(const std::optional<std::string> & uuid)3815*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::onPrivateVolumeRemoved(
3816*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid) {
3817*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3818*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_UUID(uuid);
3819*38e8c45fSAndroid Build Coastguard Worker     if (!sAppDataIsolationEnabled) {
3820*38e8c45fSAndroid Build Coastguard Worker         return ok();
3821*38e8c45fSAndroid Build Coastguard Worker     }
3822*38e8c45fSAndroid Build Coastguard Worker     if (!uuid) {
3823*38e8c45fSAndroid Build Coastguard Worker         // It happens when private volume failed to mount.
3824*38e8c45fSAndroid Build Coastguard Worker         LOG(INFO) << "Ignore unmount uuid=null";
3825*38e8c45fSAndroid Build Coastguard Worker         return ok();
3826*38e8c45fSAndroid Build Coastguard Worker     }
3827*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid->c_str();
3828*38e8c45fSAndroid Build Coastguard Worker 
3829*38e8c45fSAndroid Build Coastguard Worker     binder::Status res = ok();
3830*38e8c45fSAndroid Build Coastguard Worker 
3831*38e8c45fSAndroid Build Coastguard Worker     std::string mirrorCeVolPath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
3832*38e8c45fSAndroid Build Coastguard Worker     std::string mirrorDeVolPath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
3833*38e8c45fSAndroid Build Coastguard Worker     std::string mirrorMiscCeVolPath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
3834*38e8c45fSAndroid Build Coastguard Worker     std::string mirrorMiscDeVolPath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
3835*38e8c45fSAndroid Build Coastguard Worker 
3836*38e8c45fSAndroid Build Coastguard Worker     std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3837*38e8c45fSAndroid Build Coastguard Worker 
3838*38e8c45fSAndroid Build Coastguard Worker     // Unmount CE storage
3839*38e8c45fSAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(umount(mirrorCeVolPath.c_str())) != 0) {
3840*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENOENT) {
3841*38e8c45fSAndroid Build Coastguard Worker             res = error(StringPrintf("Failed to umount %s %s", mirrorCeVolPath.c_str(),
3842*38e8c45fSAndroid Build Coastguard Worker                                 strerror(errno)));
3843*38e8c45fSAndroid Build Coastguard Worker         }
3844*38e8c45fSAndroid Build Coastguard Worker     }
3845*38e8c45fSAndroid Build Coastguard Worker     if (delete_dir_contents_and_dir(mirrorCeVolPath, true) != 0) {
3846*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to delete " + mirrorCeVolPath);
3847*38e8c45fSAndroid Build Coastguard Worker     }
3848*38e8c45fSAndroid Build Coastguard Worker 
3849*38e8c45fSAndroid Build Coastguard Worker     // Unmount DE storage
3850*38e8c45fSAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(umount(mirrorDeVolPath.c_str())) != 0) {
3851*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENOENT) {
3852*38e8c45fSAndroid Build Coastguard Worker             res = error(StringPrintf("Failed to umount %s %s", mirrorDeVolPath.c_str(),
3853*38e8c45fSAndroid Build Coastguard Worker                                 strerror(errno)));
3854*38e8c45fSAndroid Build Coastguard Worker         }
3855*38e8c45fSAndroid Build Coastguard Worker     }
3856*38e8c45fSAndroid Build Coastguard Worker     if (delete_dir_contents_and_dir(mirrorDeVolPath, true) != 0) {
3857*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to delete " + mirrorDeVolPath);
3858*38e8c45fSAndroid Build Coastguard Worker     }
3859*38e8c45fSAndroid Build Coastguard Worker 
3860*38e8c45fSAndroid Build Coastguard Worker     // Unmount misc CE storage
3861*38e8c45fSAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(umount(mirrorMiscCeVolPath.c_str())) != 0) {
3862*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENOENT) {
3863*38e8c45fSAndroid Build Coastguard Worker             res = error(StringPrintf("Failed to umount %s %s", mirrorMiscCeVolPath.c_str(),
3864*38e8c45fSAndroid Build Coastguard Worker                                      strerror(errno)));
3865*38e8c45fSAndroid Build Coastguard Worker         }
3866*38e8c45fSAndroid Build Coastguard Worker     }
3867*38e8c45fSAndroid Build Coastguard Worker     if (delete_dir_contents_and_dir(mirrorMiscCeVolPath, true) != 0) {
3868*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to delete " + mirrorMiscCeVolPath);
3869*38e8c45fSAndroid Build Coastguard Worker     }
3870*38e8c45fSAndroid Build Coastguard Worker 
3871*38e8c45fSAndroid Build Coastguard Worker     // Unmount misc DE storage
3872*38e8c45fSAndroid Build Coastguard Worker     if (TEMP_FAILURE_RETRY(umount(mirrorMiscDeVolPath.c_str())) != 0) {
3873*38e8c45fSAndroid Build Coastguard Worker         if (errno != ENOENT) {
3874*38e8c45fSAndroid Build Coastguard Worker             res = error(StringPrintf("Failed to umount %s %s", mirrorMiscDeVolPath.c_str(),
3875*38e8c45fSAndroid Build Coastguard Worker                                      strerror(errno)));
3876*38e8c45fSAndroid Build Coastguard Worker         }
3877*38e8c45fSAndroid Build Coastguard Worker     }
3878*38e8c45fSAndroid Build Coastguard Worker     if (delete_dir_contents_and_dir(mirrorMiscDeVolPath, true) != 0) {
3879*38e8c45fSAndroid Build Coastguard Worker         res = error("Failed to delete " + mirrorMiscDeVolPath);
3880*38e8c45fSAndroid Build Coastguard Worker     }
3881*38e8c45fSAndroid Build Coastguard Worker 
3882*38e8c45fSAndroid Build Coastguard Worker     return res;
3883*38e8c45fSAndroid Build Coastguard Worker }
3884*38e8c45fSAndroid Build Coastguard Worker 
findDataMediaPath(const std::optional<std::string> & uuid,userid_t userid)3885*38e8c45fSAndroid Build Coastguard Worker std::string InstalldNativeService::findDataMediaPath(
3886*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, userid_t userid) {
3887*38e8c45fSAndroid Build Coastguard Worker     std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3888*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3889*38e8c45fSAndroid Build Coastguard Worker     auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
3890*38e8c45fSAndroid Build Coastguard Worker     auto resolved = mStorageMounts[path];
3891*38e8c45fSAndroid Build Coastguard Worker     if (resolved.empty()) {
3892*38e8c45fSAndroid Build Coastguard Worker         LOG(WARNING) << "Failed to find storage mount for " << path;
3893*38e8c45fSAndroid Build Coastguard Worker         resolved = path;
3894*38e8c45fSAndroid Build Coastguard Worker     }
3895*38e8c45fSAndroid Build Coastguard Worker     return StringPrintf("%s/%u", resolved.c_str(), userid);
3896*38e8c45fSAndroid Build Coastguard Worker }
3897*38e8c45fSAndroid Build Coastguard Worker 
isQuotaSupported(const std::optional<std::string> & uuid,bool * _aidl_return)3898*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::isQuotaSupported(
3899*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, bool* _aidl_return) {
3900*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = IsQuotaSupported(uuid.value_or(""));
3901*38e8c45fSAndroid Build Coastguard Worker     return ok();
3902*38e8c45fSAndroid Build Coastguard Worker }
3903*38e8c45fSAndroid Build Coastguard Worker 
prepareAppProfile(const std::string & packageName,int32_t userId,int32_t appId,const std::string & profileName,const std::string & codePath,const std::optional<std::string> & dexMetadata,bool * _aidl_return)3904*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
3905*38e8c45fSAndroid Build Coastguard Worker         int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
3906*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& dexMetadata, bool* _aidl_return) {
3907*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3908*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER_OR_NULL(userId);
3909*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3910*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(codePath);
3911*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE_USER();
3912*38e8c45fSAndroid Build Coastguard Worker 
3913*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
3914*38e8c45fSAndroid Build Coastguard Worker         dexMetadata);
3915*38e8c45fSAndroid Build Coastguard Worker     return ok();
3916*38e8c45fSAndroid Build Coastguard Worker }
3917*38e8c45fSAndroid Build Coastguard Worker 
migrateLegacyObbData()3918*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::migrateLegacyObbData() {
3919*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3920*38e8c45fSAndroid Build Coastguard Worker     // NOTE: The lint warning doesn't apply to the use of system(3) with
3921*38e8c45fSAndroid Build Coastguard Worker     // absolute parse and no command line arguments.
3922*38e8c45fSAndroid Build Coastguard Worker     if (system("/system/bin/migrate_legacy_obb_data") != 0) { // NOLINT(cert-env33-c)
3923*38e8c45fSAndroid Build Coastguard Worker         LOG(ERROR) << "Unable to migrate legacy obb data";
3924*38e8c45fSAndroid Build Coastguard Worker     }
3925*38e8c45fSAndroid Build Coastguard Worker 
3926*38e8c45fSAndroid Build Coastguard Worker     return ok();
3927*38e8c45fSAndroid Build Coastguard Worker }
3928*38e8c45fSAndroid Build Coastguard Worker 
cleanupInvalidPackageDirs(const std::optional<std::string> & uuid,int32_t userId,int32_t flags)3929*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::cleanupInvalidPackageDirs(
3930*38e8c45fSAndroid Build Coastguard Worker         const std::optional<std::string>& uuid, int32_t userId, int32_t flags) {
3931*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(userId);
3932*38e8c45fSAndroid Build Coastguard Worker     const char* uuid_cstr = uuid ? uuid->c_str() : nullptr;
3933*38e8c45fSAndroid Build Coastguard Worker 
3934*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_CE) {
3935*38e8c45fSAndroid Build Coastguard Worker         auto ce_path = create_data_user_ce_path(uuid_cstr, userId);
3936*38e8c45fSAndroid Build Coastguard Worker         cleanup_invalid_package_dirs_under_path(ce_path);
3937*38e8c45fSAndroid Build Coastguard Worker         auto sdksandbox_ce_path =
3938*38e8c45fSAndroid Build Coastguard Worker                 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/true, userId);
3939*38e8c45fSAndroid Build Coastguard Worker         cleanup_invalid_package_dirs_under_path(sdksandbox_ce_path);
3940*38e8c45fSAndroid Build Coastguard Worker     }
3941*38e8c45fSAndroid Build Coastguard Worker 
3942*38e8c45fSAndroid Build Coastguard Worker     if (flags & FLAG_STORAGE_DE) {
3943*38e8c45fSAndroid Build Coastguard Worker         auto de_path = create_data_user_de_path(uuid_cstr, userId);
3944*38e8c45fSAndroid Build Coastguard Worker         cleanup_invalid_package_dirs_under_path(de_path);
3945*38e8c45fSAndroid Build Coastguard Worker         auto sdksandbox_de_path =
3946*38e8c45fSAndroid Build Coastguard Worker                 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/false, userId);
3947*38e8c45fSAndroid Build Coastguard Worker         cleanup_invalid_package_dirs_under_path(sdksandbox_de_path);
3948*38e8c45fSAndroid Build Coastguard Worker     }
3949*38e8c45fSAndroid Build Coastguard Worker 
3950*38e8c45fSAndroid Build Coastguard Worker     return ok();
3951*38e8c45fSAndroid Build Coastguard Worker }
3952*38e8c45fSAndroid Build Coastguard Worker 
getOdexVisibility(const std::string & packageName,const std::string & apkPath,const std::string & instructionSet,const std::optional<std::string> & outputPath,int32_t * _aidl_return)3953*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::getOdexVisibility(
3954*38e8c45fSAndroid Build Coastguard Worker         const std::string& packageName, const std::string& apkPath,
3955*38e8c45fSAndroid Build Coastguard Worker         const std::string& instructionSet, const std::optional<std::string>& outputPath,
3956*38e8c45fSAndroid Build Coastguard Worker         int32_t* _aidl_return) {
3957*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
3958*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3959*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(apkPath);
3960*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(outputPath);
3961*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
3962*38e8c45fSAndroid Build Coastguard Worker 
3963*38e8c45fSAndroid Build Coastguard Worker     const char* apk_path = apkPath.c_str();
3964*38e8c45fSAndroid Build Coastguard Worker     const char* instruction_set = instructionSet.c_str();
3965*38e8c45fSAndroid Build Coastguard Worker     const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
3966*38e8c45fSAndroid Build Coastguard Worker 
3967*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = get_odex_visibility(apk_path, instruction_set, oat_dir);
3968*38e8c45fSAndroid Build Coastguard Worker     return *_aidl_return == -1 ? error() : ok();
3969*38e8c45fSAndroid Build Coastguard Worker }
3970*38e8c45fSAndroid Build Coastguard Worker 
3971*38e8c45fSAndroid Build Coastguard Worker // Creates an auth token to be used in enableFsverity. This token is really to store a proof that
3972*38e8c45fSAndroid Build Coastguard Worker // the caller can write to a file, represented by the authFd. Effectively, system_server as the
3973*38e8c45fSAndroid Build Coastguard Worker // attacker-in-the-middle cannot enable fs-verity on arbitrary app files. If the FD is not writable,
3974*38e8c45fSAndroid Build Coastguard Worker // return null.
3975*38e8c45fSAndroid Build Coastguard Worker //
3976*38e8c45fSAndroid Build Coastguard Worker // app process uid is passed for additional ownership check, such that one app can not be
3977*38e8c45fSAndroid Build Coastguard Worker // authenticated for another app's file. These parameters are assumed trusted for this purpose of
3978*38e8c45fSAndroid Build Coastguard Worker // consistency check.
3979*38e8c45fSAndroid Build Coastguard Worker //
3980*38e8c45fSAndroid Build Coastguard Worker // Notably, creating the token allows us to manage the writable FD easily during enableFsverity.
3981*38e8c45fSAndroid Build Coastguard Worker // Since enabling fs-verity to a file requires no outstanding writable FD, passing the authFd to the
3982*38e8c45fSAndroid Build Coastguard Worker // server allows the server to hold the only reference (as long as the client app doesn't).
createFsveritySetupAuthToken(const ParcelFileDescriptor & authFd,int32_t uid,sp<IFsveritySetupAuthToken> * _aidl_return)3983*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::createFsveritySetupAuthToken(
3984*38e8c45fSAndroid Build Coastguard Worker         const ParcelFileDescriptor& authFd, int32_t uid,
3985*38e8c45fSAndroid Build Coastguard Worker         sp<IFsveritySetupAuthToken>* _aidl_return) {
3986*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_APP_ID(multiuser_get_app_id(uid));
3987*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_VALID_USER(multiuser_get_user_id(uid));
3988*38e8c45fSAndroid Build Coastguard Worker 
3989*38e8c45fSAndroid Build Coastguard Worker     auto token = sp<FsveritySetupAuthToken>::make();
3990*38e8c45fSAndroid Build Coastguard Worker     binder::Status status = token->authenticate(authFd, uid);
3991*38e8c45fSAndroid Build Coastguard Worker     if (!status.isOk()) {
3992*38e8c45fSAndroid Build Coastguard Worker         return status;
3993*38e8c45fSAndroid Build Coastguard Worker     }
3994*38e8c45fSAndroid Build Coastguard Worker     *_aidl_return = token;
3995*38e8c45fSAndroid Build Coastguard Worker     return ok();
3996*38e8c45fSAndroid Build Coastguard Worker }
3997*38e8c45fSAndroid Build Coastguard Worker 
3998*38e8c45fSAndroid Build Coastguard Worker // Enables fs-verity for filePath, which must be an absolute path and the same inode as in the auth
3999*38e8c45fSAndroid Build Coastguard Worker // token previously returned from createFsveritySetupAuthToken, and owned by the app uid. As
4000*38e8c45fSAndroid Build Coastguard Worker // installd is more privileged than its client / system server, we attempt to limit what a
4001*38e8c45fSAndroid Build Coastguard Worker // (compromised) client can do.
4002*38e8c45fSAndroid Build Coastguard Worker //
4003*38e8c45fSAndroid Build Coastguard Worker // The reason for this app request to go through installd is to avoid exposing a risky area (PKCS#7
4004*38e8c45fSAndroid Build Coastguard Worker // signature verification) in the kernel to the app as an attack surface (it can't be system server
4005*38e8c45fSAndroid Build Coastguard Worker // because it can't override DAC and manipulate app files). Note that we should be able to drop
4006*38e8c45fSAndroid Build Coastguard Worker // these hops and simply the app calls the ioctl, once all upgrading devices run with a kernel
4007*38e8c45fSAndroid Build Coastguard Worker // without fs-verity built-in signature (https://r.android.com/2650402).
enableFsverity(const sp<IFsveritySetupAuthToken> & authToken,const std::string & filePath,const std::string & packageName,int32_t * _aidl_return)4008*38e8c45fSAndroid Build Coastguard Worker binder::Status InstalldNativeService::enableFsverity(const sp<IFsveritySetupAuthToken>& authToken,
4009*38e8c45fSAndroid Build Coastguard Worker                                                      const std::string& filePath,
4010*38e8c45fSAndroid Build Coastguard Worker                                                      const std::string& packageName,
4011*38e8c45fSAndroid Build Coastguard Worker                                                      int32_t* _aidl_return) {
4012*38e8c45fSAndroid Build Coastguard Worker     ENFORCE_UID(AID_SYSTEM);
4013*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PATH(filePath);
4014*38e8c45fSAndroid Build Coastguard Worker     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
4015*38e8c45fSAndroid Build Coastguard Worker     LOCK_PACKAGE();
4016*38e8c45fSAndroid Build Coastguard Worker     if (authToken == nullptr) {
4017*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Received a null auth token");
4018*38e8c45fSAndroid Build Coastguard Worker     }
4019*38e8c45fSAndroid Build Coastguard Worker 
4020*38e8c45fSAndroid Build Coastguard Worker     // Authenticate to check the targeting file is the same inode as the authFd. With O_PATH, we
4021*38e8c45fSAndroid Build Coastguard Worker     // prevent a malicious client from blocking installd by providing a path to FIFO. After the
4022*38e8c45fSAndroid Build Coastguard Worker     // authentication, the actual open is safe.
4023*38e8c45fSAndroid Build Coastguard Worker     sp<IBinder> authTokenBinder = IInterface::asBinder(authToken)->localBinder();
4024*38e8c45fSAndroid Build Coastguard Worker     if (authTokenBinder == nullptr) {
4025*38e8c45fSAndroid Build Coastguard Worker         return exception(binder::Status::EX_SECURITY, "Received a non-local auth token");
4026*38e8c45fSAndroid Build Coastguard Worker     }
4027*38e8c45fSAndroid Build Coastguard Worker     unique_fd pathFd(open(filePath.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_PATH));
4028*38e8c45fSAndroid Build Coastguard Worker     // Returns a constant errno to avoid one app probing file existence of the others, before the
4029*38e8c45fSAndroid Build Coastguard Worker     // authentication is done.
4030*38e8c45fSAndroid Build Coastguard Worker     const int kFixedErrno = EPERM;
4031*38e8c45fSAndroid Build Coastguard Worker     if (pathFd.get() < 0) {
4032*38e8c45fSAndroid Build Coastguard Worker         PLOG(DEBUG) << "Failed to open the path";
4033*38e8c45fSAndroid Build Coastguard Worker         *_aidl_return = kFixedErrno;
4034*38e8c45fSAndroid Build Coastguard Worker         return ok();
4035*38e8c45fSAndroid Build Coastguard Worker     }
4036*38e8c45fSAndroid Build Coastguard Worker     std::string procFdPath(StringPrintf("/proc/self/fd/%d", pathFd.get()));
4037*38e8c45fSAndroid Build Coastguard Worker     struct stat stFromPath;
4038*38e8c45fSAndroid Build Coastguard Worker     if (stat(procFdPath.c_str(), &stFromPath) < 0) {
4039*38e8c45fSAndroid Build Coastguard Worker         PLOG(DEBUG) << "Failed to stat proc fd " << pathFd.get() << " -> " << filePath;
4040*38e8c45fSAndroid Build Coastguard Worker         *_aidl_return = kFixedErrno;
4041*38e8c45fSAndroid Build Coastguard Worker         return ok();
4042*38e8c45fSAndroid Build Coastguard Worker     }
4043*38e8c45fSAndroid Build Coastguard Worker     auto authTokenInstance = sp<FsveritySetupAuthToken>::cast(authTokenBinder);
4044*38e8c45fSAndroid Build Coastguard Worker     if (!authTokenInstance->isSameStat(stFromPath)) {
4045*38e8c45fSAndroid Build Coastguard Worker         LOG(DEBUG) << "FD authentication failed";
4046*38e8c45fSAndroid Build Coastguard Worker         *_aidl_return = kFixedErrno;
4047*38e8c45fSAndroid Build Coastguard Worker         return ok();
4048*38e8c45fSAndroid Build Coastguard Worker     }
4049*38e8c45fSAndroid Build Coastguard Worker 
4050*38e8c45fSAndroid Build Coastguard Worker     unique_fd rfd(open(procFdPath.c_str(), O_RDONLY | O_CLOEXEC));
4051*38e8c45fSAndroid Build Coastguard Worker     fsverity_enable_arg arg = {};
4052*38e8c45fSAndroid Build Coastguard Worker     arg.version = 1;
4053*38e8c45fSAndroid Build Coastguard Worker     arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
4054*38e8c45fSAndroid Build Coastguard Worker     arg.block_size = 4096;
4055*38e8c45fSAndroid Build Coastguard Worker     if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, &arg) < 0) {
4056*38e8c45fSAndroid Build Coastguard Worker         *_aidl_return = errno;
4057*38e8c45fSAndroid Build Coastguard Worker     } else {
4058*38e8c45fSAndroid Build Coastguard Worker         *_aidl_return = 0;
4059*38e8c45fSAndroid Build Coastguard Worker     }
4060*38e8c45fSAndroid Build Coastguard Worker     return ok();
4061*38e8c45fSAndroid Build Coastguard Worker }
4062*38e8c45fSAndroid Build Coastguard Worker 
4063*38e8c45fSAndroid Build Coastguard Worker }  // namespace installd
4064*38e8c45fSAndroid Build Coastguard Worker }  // namespace android
4065