• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 ** Copyright 2008, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 **     http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16 
17 #include "utils.h"
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <fts.h>
22 #include <poll.h>
23 #include <stdlib.h>
24 #include <sys/capability.h>
25 #include <sys/pidfd.h>
26 #include <sys/stat.h>
27 #include <sys/statvfs.h>
28 #include <sys/wait.h>
29 #include <sys/xattr.h>
30 #include <unistd.h>
31 #include <uuid/uuid.h>
32 
33 #include <android-base/file.h>
34 #include <android-base/logging.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <android-base/unique_fd.h>
38 #include <cutils/fs.h>
39 #include <cutils/properties.h>
40 #include <linux/fs.h>
41 #include <log/log.h>
42 #include <private/android_filesystem_config.h>
43 #include <private/android_projectid_config.h>
44 
45 #include "dexopt_return_codes.h"
46 #include "globals.h"  // extern variables.
47 #include "QuotaUtils.h"
48 
49 #ifndef LOG_TAG
50 #define LOG_TAG "installd"
51 #endif
52 
53 #define DEBUG_XATTRS 0
54 
55 using android::base::Dirname;
56 using android::base::EndsWith;
57 using android::base::Fdopendir;
58 using android::base::StringPrintf;
59 using android::base::unique_fd;
60 
61 namespace android {
62 namespace installd {
63 
64 using namespace std::literals;
65 
66 static constexpr auto deletedSuffix = "==deleted=="sv;
67 
68 /**
69  * Check that given string is valid filename, and that it attempts no
70  * parent or child directory traversal.
71  */
is_valid_filename(const std::string & name)72 bool is_valid_filename(const std::string& name) {
73     if (name.empty() || (name == ".") || (name == "..")
74             || (name.find('/') != std::string::npos)) {
75         return false;
76     } else {
77         return true;
78     }
79 }
80 
check_package_name(const char * package_name)81 static void check_package_name(const char* package_name) {
82     CHECK(is_valid_filename(package_name));
83     CHECK(is_valid_package_name(package_name));
84 }
85 
resolve_ce_path_by_inode_or_fallback(const std::string & root_path,ino_t ce_data_inode,const std::string & fallback)86 static std::string resolve_ce_path_by_inode_or_fallback(const std::string& root_path,
87         ino_t ce_data_inode, const std::string& fallback) {
88     if (ce_data_inode != 0) {
89         DIR* dir = opendir(root_path.c_str());
90         if (dir == nullptr) {
91             PLOG(ERROR) << "Failed to opendir " << root_path;
92             return fallback;
93         }
94 
95         struct dirent* ent;
96         while ((ent = readdir(dir))) {
97             if (ent->d_ino == ce_data_inode) {
98                 auto resolved = StringPrintf("%s/%s", root_path.c_str(), ent->d_name);
99                 if (resolved != fallback) {
100                     LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
101                             << " instead of " << fallback;
102                 }
103                 closedir(dir);
104                 return resolved;
105             }
106         }
107         LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
108         closedir(dir);
109         return fallback;
110     } else {
111         return fallback;
112     }
113 }
114 
115 /**
116  * Create the path name where package data should be stored for the given
117  * volume UUID, package name, and user ID. An empty UUID is assumed to be
118  * internal storage.
119  */
create_data_user_ce_package_path(const char * volume_uuid,userid_t user,const char * package_name)120 std::string create_data_user_ce_package_path(const char* volume_uuid,
121         userid_t user, const char* package_name) {
122     check_package_name(package_name);
123     return StringPrintf("%s/%s",
124             create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
125 }
126 
127 /**
128  * Create the path name where package data should be stored for the given
129  * volume UUID, package name, and user ID. An empty UUID is assumed to be
130  * internal storage.
131  * Compared to create_data_user_ce_package_path this method always return the
132  * ".../user/..." directory.
133  */
create_data_user_ce_package_path_as_user_link(const char * volume_uuid,userid_t userid,const char * package_name)134 std::string create_data_user_ce_package_path_as_user_link(
135         const char* volume_uuid, userid_t userid, const char* package_name) {
136     check_package_name(package_name);
137     std::string data(create_data_path(volume_uuid));
138     return StringPrintf("%s/user/%u/%s", data.c_str(), userid, package_name);
139 }
140 
create_data_user_ce_package_path(const char * volume_uuid,userid_t user,const char * package_name,ino_t ce_data_inode)141 std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
142         const char* package_name, ino_t ce_data_inode) {
143     // For testing purposes, rely on the inode when defined; this could be
144     // optimized to use access() in the future.
145     auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
146     auto user_path = create_data_user_ce_path(volume_uuid, user);
147     return resolve_ce_path_by_inode_or_fallback(user_path, ce_data_inode, fallback);
148 }
149 
create_data_user_de_package_path(const char * volume_uuid,userid_t user,const char * package_name)150 std::string create_data_user_de_package_path(const char* volume_uuid,
151         userid_t user, const char* package_name) {
152     check_package_name(package_name);
153     return StringPrintf("%s/%s",
154             create_data_user_de_path(volume_uuid, user).c_str(), package_name);
155 }
156 
create_data_path(const char * volume_uuid)157 std::string create_data_path(const char* volume_uuid) {
158     if (volume_uuid == nullptr) {
159         return "/data";
160     } else if (!strcmp(volume_uuid, "TEST")) {
161         CHECK(property_get_bool("ro.debuggable", false));
162         return "/data/local/tmp";
163     } else {
164         CHECK(is_valid_filename(volume_uuid));
165         return StringPrintf("/mnt/expand/%s", volume_uuid);
166     }
167 }
168 
169 /**
170  * Create the path name for app data.
171  */
create_data_app_path(const char * volume_uuid)172 std::string create_data_app_path(const char* volume_uuid) {
173     return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
174 }
175 
176 /**
177  * Create the path name for user data for a certain userid.
178  * Keep same implementation as vold to minimize path walking overhead
179  */
create_data_user_ce_path(const char * volume_uuid,userid_t userid)180 std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
181     std::string data(create_data_path(volume_uuid));
182     if (volume_uuid == nullptr && userid == 0) {
183         std::string legacy = StringPrintf("%s/data", data.c_str());
184         struct stat sb;
185         if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
186             /* /data/data is dir, return /data/data for legacy system */
187             return legacy;
188         }
189     }
190     return StringPrintf("%s/user/%u", data.c_str(), userid);
191 }
192 
193 /**
194  * Create the path name for device encrypted user data for a certain userid.
195  */
create_data_user_de_path(const char * volume_uuid,userid_t userid)196 std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
197     std::string data(create_data_path(volume_uuid));
198     return StringPrintf("%s/user_de/%u", data.c_str(), userid);
199 }
200 
201 /**
202  * Create the path name where sdk_sandbox data for all apps will be stored.
203  * E.g. /data/misc_ce/0/sdksandbox
204  */
create_data_misc_sdk_sandbox_path(const char * uuid,bool isCeData,userid_t user)205 std::string create_data_misc_sdk_sandbox_path(const char* uuid, bool isCeData, userid_t user) {
206     std::string data(create_data_path(uuid));
207     if (isCeData) {
208         return StringPrintf("%s/misc_ce/%d/sdksandbox", data.c_str(), user);
209     } else {
210         return StringPrintf("%s/misc_de/%d/sdksandbox", data.c_str(), user);
211     }
212 }
213 
214 /**
215  * Create the path name where code data for all codes in a particular app will be stored.
216  * E.g. /data/misc_ce/0/sdksandbox/<package-name>
217  */
create_data_misc_sdk_sandbox_package_path(const char * volume_uuid,bool isCeData,userid_t user,const char * package_name)218 std::string create_data_misc_sdk_sandbox_package_path(const char* volume_uuid, bool isCeData,
219                                                       userid_t user, const char* package_name) {
220     check_package_name(package_name);
221     return StringPrintf("%s/%s",
222                         create_data_misc_sdk_sandbox_path(volume_uuid, isCeData, user).c_str(),
223                         package_name);
224 }
225 
226 /**
227  * Create the path name where sdk data for a particular sdk will be stored.
228  * E.g. /data/misc_ce/0/sdksandbox/<package-name>/com.foo@randomstrings
229  */
create_data_misc_sdk_sandbox_sdk_path(const char * volume_uuid,bool isCeData,userid_t user,const char * package_name,const char * sub_dir_name)230 std::string create_data_misc_sdk_sandbox_sdk_path(const char* volume_uuid, bool isCeData,
231                                                   userid_t user, const char* package_name,
232                                                   const char* sub_dir_name) {
233     return StringPrintf("%s/%s",
234                         create_data_misc_sdk_sandbox_package_path(volume_uuid, isCeData, user,
235                                                                   package_name)
236                                 .c_str(),
237                         sub_dir_name);
238 }
239 
create_data_misc_ce_rollback_base_path(const char * volume_uuid,userid_t user)240 std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
241     return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
242 }
243 
create_data_misc_de_rollback_base_path(const char * volume_uuid,userid_t user)244 std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
245     return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
246 }
247 
create_data_misc_ce_rollback_path(const char * volume_uuid,userid_t user,int32_t snapshot_id)248 std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
249         int32_t snapshot_id) {
250     return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
251           snapshot_id);
252 }
253 
create_data_misc_de_rollback_path(const char * volume_uuid,userid_t user,int32_t snapshot_id)254 std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
255         int32_t snapshot_id) {
256     return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
257           snapshot_id);
258 }
259 
create_data_misc_ce_rollback_package_path(const char * volume_uuid,userid_t user,int32_t snapshot_id,const char * package_name)260 std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
261         userid_t user, int32_t snapshot_id, const char* package_name) {
262     return StringPrintf("%s/%s",
263            create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
264 }
265 
create_data_misc_ce_rollback_package_path(const char * volume_uuid,userid_t user,int32_t snapshot_id,const char * package_name,ino_t ce_rollback_inode)266 std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
267         userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
268     auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
269             package_name);
270     auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
271     return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
272 }
273 
create_data_misc_de_rollback_package_path(const char * volume_uuid,userid_t user,int32_t snapshot_id,const char * package_name)274 std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
275         userid_t user, int32_t snapshot_id, const char* package_name) {
276     return StringPrintf("%s/%s",
277            create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
278 }
279 
280 /**
281  * Create the path name for media for a certain userid.
282  */
create_data_media_path(const char * volume_uuid,userid_t userid)283 std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
284     return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
285 }
286 
create_data_media_package_path(const char * volume_uuid,userid_t userid,const char * data_type,const char * package_name)287 std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
288         const char* data_type, const char* package_name) {
289     return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
290             data_type, package_name);
291 }
292 
create_data_misc_legacy_path(userid_t userid)293 std::string create_data_misc_legacy_path(userid_t userid) {
294     return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
295 }
296 
create_primary_cur_profile_dir_path(userid_t userid)297 std::string create_primary_cur_profile_dir_path(userid_t userid) {
298     return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
299 }
300 
create_primary_current_profile_package_dir_path(userid_t user,const std::string & package_name)301 std::string create_primary_current_profile_package_dir_path(userid_t user,
302         const std::string& package_name) {
303     check_package_name(package_name.c_str());
304     return StringPrintf("%s/%s",
305             create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
306 }
307 
create_primary_ref_profile_dir_path()308 std::string create_primary_ref_profile_dir_path() {
309     return StringPrintf("%s/ref", android_profiles_dir.c_str());
310 }
311 
create_primary_reference_profile_package_dir_path(const std::string & package_name)312 std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
313     check_package_name(package_name.c_str());
314     return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
315 }
316 
create_data_dalvik_cache_path()317 std::string create_data_dalvik_cache_path() {
318     return "/data/dalvik-cache";
319 }
320 
create_system_user_ce_path(userid_t userId)321 std::string create_system_user_ce_path(userid_t userId) {
322     return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
323 }
324 
create_system_user_ce_package_path(userid_t userId,const char * package_name)325 std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
326     check_package_name(package_name);
327     return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
328 }
329 
330 // Keep profile paths in sync with ActivityThread and LoadedApk.
331 const std::string PROFILE_EXT = ".prof";
332 const std::string CURRENT_PROFILE_EXT = ".cur";
333 const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
334 
335 // Gets the parent directory and the file name for the given secondary dex path.
336 // Returns true on success, false on failure (if the dex_path does not have the expected
337 // structure).
get_secondary_dex_location(const std::string & dex_path,std::string * out_dir_name,std::string * out_file_name)338 static bool get_secondary_dex_location(const std::string& dex_path,
339         std::string* out_dir_name, std::string* out_file_name) {
340    size_t dirIndex = dex_path.rfind('/');
341    if (dirIndex == std::string::npos) {
342         return false;
343    }
344    if (dirIndex == dex_path.size() - 1) {
345         return false;
346    }
347    *out_dir_name = dex_path.substr(0, dirIndex);
348    *out_file_name = dex_path.substr(dirIndex + 1);
349 
350    return true;
351 }
352 
create_current_profile_path(userid_t user,const std::string & package_name,const std::string & location,bool is_secondary_dex)353 std::string create_current_profile_path(userid_t user, const std::string& package_name,
354         const std::string& location, bool is_secondary_dex) {
355     if (is_secondary_dex) {
356         // Secondary dex current profiles are stored next to the dex files under the oat folder.
357         std::string dex_dir;
358         std::string dex_name;
359         CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
360                 << "Unexpected dir structure for secondary dex " << location;
361         return StringPrintf("%s/oat/%s%s%s",
362                 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
363                 PROFILE_EXT.c_str());
364     } else {
365         // Profiles for primary apks are under /data/misc/profiles/cur.
366         std::string profile_dir = create_primary_current_profile_package_dir_path(
367                 user, package_name);
368         return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
369     }
370 }
371 
create_reference_profile_path(const std::string & package_name,const std::string & location,bool is_secondary_dex)372 std::string create_reference_profile_path(const std::string& package_name,
373         const std::string& location, bool is_secondary_dex) {
374     if (is_secondary_dex) {
375         // Secondary dex reference profiles are stored next to the dex files under the oat folder.
376         std::string dex_dir;
377         std::string dex_name;
378         CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
379                 << "Unexpected dir structure for secondary dex " << location;
380         return StringPrintf("%s/oat/%s%s",
381                 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
382     } else {
383         // Reference profiles for primary apks are stored in /data/misc/profile/ref.
384         std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
385         return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
386     }
387 }
388 
create_snapshot_profile_path(const std::string & package,const std::string & profile_name)389 std::string create_snapshot_profile_path(const std::string& package,
390         const std::string& profile_name) {
391     std::string ref_profile = create_reference_profile_path(package, profile_name,
392             /*is_secondary_dex*/ false);
393     return ref_profile + SNAPSHOT_PROFILE_EXT;
394 }
395 
get_known_users(const char * volume_uuid)396 std::vector<userid_t> get_known_users(const char* volume_uuid) {
397     std::vector<userid_t> users;
398 
399     // We always have an owner
400     users.push_back(0);
401 
402     std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
403     DIR* dir = opendir(path.c_str());
404     if (dir == nullptr) {
405         // Unable to discover other users, but at least return owner
406         PLOG(ERROR) << "Failed to opendir " << path;
407         return users;
408     }
409 
410     struct dirent* ent;
411     while ((ent = readdir(dir))) {
412         if (ent->d_type != DT_DIR) {
413             continue;
414         }
415 
416         char* end;
417         userid_t user = strtol(ent->d_name, &end, 10);
418         if (*end == '\0' && user != 0) {
419             LOG(DEBUG) << "Found valid user " << user;
420             users.push_back(user);
421         }
422     }
423     closedir(dir);
424 
425     return users;
426 }
427 
get_project_id(uid_t uid,long start_project_id_range)428 long get_project_id(uid_t uid, long start_project_id_range) {
429     return uid - AID_APP_START + start_project_id_range;
430 }
431 
set_quota_project_id(const std::string & path,long project_id,bool set_inherit)432 int set_quota_project_id(const std::string& path, long project_id, bool set_inherit) {
433     struct fsxattr fsx;
434     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
435     if (fd == -1) {
436         PLOG(ERROR) << "Failed to open " << path << " to set project id.";
437         return -1;
438     }
439 
440     if (ioctl(fd, FS_IOC_FSGETXATTR, &fsx) == -1) {
441         PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
442         return -1;
443     }
444 
445     fsx.fsx_projid = project_id;
446     if (ioctl(fd, FS_IOC_FSSETXATTR, &fsx) == -1) {
447         PLOG(ERROR) << "Failed to set project id on " << path;
448         return -1;
449     }
450     if (set_inherit) {
451         unsigned int flags;
452         if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1) {
453             PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
454             return -1;
455         }
456 
457         flags |= FS_PROJINHERIT_FL;
458 
459         if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == -1) {
460             PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
461             return -1;
462         }
463     }
464     return 0;
465 }
466 
calculate_tree_size(const std::string & path,int64_t * size,int32_t include_gid,int32_t exclude_gid,bool exclude_apps)467 int calculate_tree_size(const std::string& path, int64_t* size,
468         int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
469     FTS *fts;
470     FTSENT *p;
471     int64_t matchedSize = 0;
472     char *argv[] = { (char*) path.c_str(), nullptr };
473     if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
474         if (errno != ENOENT) {
475             PLOG(ERROR) << "Failed to fts_open " << path;
476         }
477         return -1;
478     }
479     while ((p = fts_read(fts)) != nullptr) {
480         switch (p->fts_info) {
481         case FTS_D:
482         case FTS_DEFAULT:
483         case FTS_F:
484         case FTS_SL:
485         case FTS_SLNONE:
486             int32_t uid = p->fts_statp->st_uid;
487             int32_t gid = p->fts_statp->st_gid;
488             int32_t user_uid = multiuser_get_app_id(uid);
489             int32_t user_gid = multiuser_get_app_id(gid);
490             if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
491                     || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
492                     || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
493                 // Don't traverse inside or measure
494                 fts_set(fts, p, FTS_SKIP);
495                 break;
496             }
497             if (include_gid != -1 && gid != include_gid) {
498                 break;
499             }
500             if (exclude_gid != -1 && gid == exclude_gid) {
501                 break;
502             }
503             matchedSize += (p->fts_statp->st_blocks * 512);
504             break;
505         }
506     }
507     fts_close(fts);
508 #if MEASURE_DEBUG
509     if ((include_gid == -1) && (exclude_gid == -1)) {
510         LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
511     } else {
512         LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
513                 << " exclude " << exclude_gid;
514     }
515 #endif
516     *size += matchedSize;
517     return 0;
518 }
519 
520 /**
521  * Checks whether the package name is valid. Returns -1 on error and
522  * 0 on success.
523  */
is_valid_package_name(const std::string & packageName)524 bool is_valid_package_name(const std::string& packageName) {
525     // This logic is borrowed from PackageParser.java
526     bool front = true;
527 
528     auto it = packageName.begin();
529     for (; it != packageName.end() && *it != '-'; it++) {
530         char c = *it;
531         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
532             front = false;
533             continue;
534         }
535         if (!front) {
536             if ((c >= '0' && c <= '9') || c == '_') {
537                 continue;
538             }
539         }
540         if (c == '.') {
541             front = true;
542             continue;
543         }
544         LOG(WARNING) << "Bad package character " << c << " in " << packageName;
545         return false;
546     }
547 
548     if (front) {
549         LOG(WARNING) << "Missing separator in " << packageName;
550         return false;
551     }
552 
553     for (; it != packageName.end(); it++) {
554         char c = *it;
555         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
556         if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
557         LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
558         return false;
559     }
560 
561     return true;
562 }
563 
_delete_dir_contents(DIR * d,int (* exclusion_predicate)(const char * name,const int is_dir))564 static int _delete_dir_contents(DIR *d,
565                                 int (*exclusion_predicate)(const char *name, const int is_dir))
566 {
567     int result = 0;
568     struct dirent *de;
569     int dfd;
570 
571     dfd = dirfd(d);
572 
573     if (dfd < 0) return -1;
574 
575     while ((de = readdir(d))) {
576         const char *name = de->d_name;
577 
578             /* check using the exclusion predicate, if provided */
579         if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
580             continue;
581         }
582 
583         if (de->d_type == DT_DIR) {
584             int subfd;
585             DIR *subdir;
586 
587                 /* always skip "." and ".." */
588             if (name[0] == '.') {
589                 if (name[1] == 0) continue;
590                 if ((name[1] == '.') && (name[2] == 0)) continue;
591             }
592 
593             subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
594             if (subfd < 0) {
595                 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
596                 result = -1;
597                 continue;
598             }
599             subdir = fdopendir(subfd);
600             if (subdir == nullptr) {
601                 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
602                 close(subfd);
603                 result = -1;
604                 continue;
605             }
606             if (_delete_dir_contents(subdir, exclusion_predicate)) {
607                 result = -1;
608             }
609             closedir(subdir);
610             if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
611                 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
612                 result = -1;
613             }
614         } else {
615             if (unlinkat(dfd, name, 0) < 0) {
616                 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
617                 result = -1;
618             }
619         }
620     }
621 
622     return result;
623 }
624 
create_dir_if_needed(const std::string & pathname,mode_t perms)625 int create_dir_if_needed(const std::string& pathname, mode_t perms) {
626     struct stat st;
627 
628     int rc;
629     if ((rc = stat(pathname.c_str(), &st)) != 0) {
630         if (errno == ENOENT) {
631             return mkdir(pathname.c_str(), perms);
632         } else {
633             return rc;
634         }
635     } else if (!S_ISDIR(st.st_mode)) {
636         LOG(DEBUG) << pathname << " is not a folder";
637         return -1;
638     }
639 
640     mode_t actual_perms = st.st_mode & ALLPERMS;
641     if (actual_perms != perms) {
642         LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
643         return -1;
644     }
645 
646     return 0;
647 }
648 
delete_dir_contents(const std::string & pathname,bool ignore_if_missing)649 int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
650     return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
651 }
652 
delete_dir_contents_and_dir(const std::string & pathname,bool ignore_if_missing)653 int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
654     return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
655 }
656 
delete_dir_contents(const char * pathname,int also_delete_dir,int (* exclusion_predicate)(const char *,const int),bool ignore_if_missing)657 int delete_dir_contents(const char *pathname,
658                         int also_delete_dir,
659                         int (*exclusion_predicate)(const char*, const int),
660                         bool ignore_if_missing)
661 {
662     int res = 0;
663     DIR *d;
664 
665     d = opendir(pathname);
666     if (d == nullptr) {
667         if (ignore_if_missing && (errno == ENOENT)) {
668             return 0;
669         }
670         ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
671         return -errno;
672     }
673     res = _delete_dir_contents(d, exclusion_predicate);
674     closedir(d);
675     if (also_delete_dir) {
676         if (rmdir(pathname)) {
677             ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
678             res = -1;
679         }
680     }
681     return res;
682 }
683 
make_unique_name(std::string_view suffix)684 static std::string make_unique_name(std::string_view suffix) {
685     static constexpr auto uuidStringSize = 36;
686 
687     uuid_t guid;
688     uuid_generate(guid);
689 
690     std::string name;
691     const auto suffixSize = suffix.size();
692     name.reserve(uuidStringSize + suffixSize);
693 
694     name.resize(uuidStringSize);
695     uuid_unparse(guid, name.data());
696     name.append(suffix);
697 
698     return name;
699 }
700 
rename_delete_dir_contents(const std::string & pathname,int (* exclusion_predicate)(const char *,const int),bool ignore_if_missing)701 static int rename_delete_dir_contents(const std::string& pathname,
702                                       int (*exclusion_predicate)(const char*, const int),
703                                       bool ignore_if_missing) {
704     auto temp_dir_name = make_unique_name(deletedSuffix);
705     auto temp_dir_path =
706             base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
707 
708     auto dir_to_delete = temp_dir_path.c_str();
709     if (::rename(pathname.c_str(), dir_to_delete)) {
710         if (ignore_if_missing && (errno == ENOENT)) {
711             return 0;
712         }
713         ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), dir_to_delete, strerror(errno));
714         dir_to_delete = pathname.c_str();
715     }
716 
717     return delete_dir_contents(dir_to_delete, 1, exclusion_predicate, ignore_if_missing);
718 }
719 
is_renamed_deleted_dir(const std::string & path)720 bool is_renamed_deleted_dir(const std::string& path) {
721     if (path.size() < deletedSuffix.size()) {
722         return false;
723     }
724     std::string_view pathSuffix{path.c_str() + path.size() - deletedSuffix.size()};
725     return pathSuffix == deletedSuffix;
726 }
727 
rename_delete_dir_contents_and_dir(const std::string & pathname,bool ignore_if_missing)728 int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
729     return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
730 }
731 
open_dir(const char * dir)732 static auto open_dir(const char* dir) {
733     struct DirCloser {
734         void operator()(DIR* d) const noexcept { ::closedir(d); }
735     };
736     return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
737 }
738 
739 // Collects filename of subdirectories of given directory and passes it to the function
foreach_subdir(const std::string & pathname,const std::function<void (const std::string &)> fn)740 int foreach_subdir(const std::string& pathname, const std::function<void(const std::string&)> fn) {
741     auto dir = open_dir(pathname.c_str());
742     if (!dir) return -1;
743 
744     int dfd = dirfd(dir.get());
745     if (dfd < 0) {
746         ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
747         return -1;
748     }
749 
750     struct dirent* de;
751     while ((de = readdir(dir.get()))) {
752         if (de->d_type != DT_DIR) {
753             continue;
754         }
755 
756         std::string name{de->d_name};
757         // always skip "." and ".."
758         if (name == "." || name == "..") {
759             continue;
760         }
761         fn(name);
762     }
763 
764     return 0;
765 }
766 
cleanup_invalid_package_dirs_under_path(const std::string & pathname)767 void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
768     auto dir = open_dir(pathname.c_str());
769     if (!dir) {
770         return;
771     }
772     int dfd = dirfd(dir.get());
773     if (dfd < 0) {
774         ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
775         return;
776     }
777 
778     struct dirent* de;
779     while ((de = readdir(dir.get()))) {
780         if (de->d_type != DT_DIR) {
781             continue;
782         }
783 
784         std::string name{de->d_name};
785         // always skip "." and ".."
786         if (name == "." || name == "..") {
787             continue;
788         }
789 
790         if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
791             !is_valid_package_name(name)) {
792             ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
793             // Deleting the content.
794             delete_dir_contents_fd(dfd, name.c_str());
795             // Deleting the directory
796             if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
797                 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
798             }
799         }
800     }
801 }
802 
delete_dir_contents_fd(int dfd,const char * name)803 int delete_dir_contents_fd(int dfd, const char *name)
804 {
805     int fd, res;
806     DIR *d;
807 
808     fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
809     if (fd < 0) {
810         ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
811         return -1;
812     }
813     d = fdopendir(fd);
814     if (d == nullptr) {
815         ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
816         close(fd);
817         return -1;
818     }
819     res = _delete_dir_contents(d, nullptr);
820     closedir(d);
821     return res;
822 }
823 
_copy_owner_permissions(int srcfd,int dstfd)824 static int _copy_owner_permissions(int srcfd, int dstfd)
825 {
826     struct stat st;
827     if (fstat(srcfd, &st) != 0) {
828         return -1;
829     }
830     if (fchmod(dstfd, st.st_mode) != 0) {
831         return -1;
832     }
833     return 0;
834 }
835 
_copy_dir_files(int sdfd,int ddfd,uid_t owner,gid_t group)836 static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
837 {
838     int result = 0;
839     if (_copy_owner_permissions(sdfd, ddfd) != 0) {
840         ALOGE("_copy_dir_files failed to copy dir permissions\n");
841     }
842     if (fchown(ddfd, owner, group) != 0) {
843         ALOGE("_copy_dir_files failed to change dir owner\n");
844     }
845 
846     DIR *ds = fdopendir(sdfd);
847     if (ds == nullptr) {
848         ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
849         return -1;
850     }
851     struct dirent *de;
852     while ((de = readdir(ds))) {
853         if (de->d_type != DT_REG) {
854             continue;
855         }
856 
857         const char *name = de->d_name;
858         int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
859         int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
860         if (fsfd == -1 || fdfd == -1) {
861             ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
862         } else {
863             if (_copy_owner_permissions(fsfd, fdfd) != 0) {
864                 ALOGE("Failed to change file permissions\n");
865             }
866             if (fchown(fdfd, owner, group) != 0) {
867                 ALOGE("Failed to change file owner\n");
868             }
869 
870             char buf[8192];
871             ssize_t size;
872             while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
873                 write(fdfd, buf, size);
874             }
875             if (size < 0) {
876                 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
877                 result = -1;
878             }
879         }
880         close(fdfd);
881         close(fsfd);
882     }
883 
884     return result;
885 }
886 
copy_dir_files(const char * srcname,const char * dstname,uid_t owner,uid_t group)887 int copy_dir_files(const char *srcname,
888                    const char *dstname,
889                    uid_t owner,
890                    uid_t group)
891 {
892     int res = 0;
893     DIR *ds = nullptr;
894     DIR *dd = nullptr;
895 
896     ds = opendir(srcname);
897     if (ds == nullptr) {
898         ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
899         return -errno;
900     }
901 
902     mkdir(dstname, 0600);
903     dd = opendir(dstname);
904     if (dd == nullptr) {
905         ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
906         closedir(ds);
907         return -errno;
908     }
909 
910     int sdfd = dirfd(ds);
911     int ddfd = dirfd(dd);
912     if (sdfd != -1 && ddfd != -1) {
913         res = _copy_dir_files(sdfd, ddfd, owner, group);
914     } else {
915         res = -errno;
916     }
917     closedir(dd);
918     closedir(ds);
919     return res;
920 }
921 
data_disk_free(const std::string & data_path)922 int64_t data_disk_free(const std::string& data_path) {
923     struct statvfs sfs;
924     if (statvfs(data_path.c_str(), &sfs) == 0) {
925         return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
926     } else {
927         PLOG(ERROR) << "Couldn't statvfs " << data_path;
928         return -1;
929     }
930 }
931 
get_path_inode(const std::string & path,ino_t * inode)932 int get_path_inode(const std::string& path, ino_t *inode) {
933     struct stat buf;
934     memset(&buf, 0, sizeof(buf));
935     if (stat(path.c_str(), &buf) != 0) {
936         PLOG(WARNING) << "Failed to stat " << path;
937         return -1;
938     } else {
939         *inode = buf.st_ino;
940         return 0;
941     }
942 }
943 
944 /**
945  * Write the inode of a specific child file into the given xattr on the
946  * parent directory. This allows you to find the child later, even if its
947  * name is encrypted.
948  */
write_path_inode(const std::string & parent,const char * name,const char * inode_xattr)949 int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
950     ino_t inode = 0;
951     uint64_t inode_raw = 0;
952     auto path = StringPrintf("%s/%s", parent.c_str(), name);
953 
954     if (get_path_inode(path, &inode) != 0) {
955         // Path probably doesn't exist yet; ignore
956         return 0;
957     }
958 
959     // Check to see if already set correctly
960     if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
961         if (inode_raw == inode) {
962             // Already set correctly; skip writing
963             return 0;
964         } else {
965             PLOG(WARNING) << "Mismatched inode value; found " << inode
966                     << " on disk but marked value was " << inode_raw << "; overwriting";
967         }
968     }
969 
970     inode_raw = inode;
971     if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
972         PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
973         return -1;
974     } else {
975         return 0;
976     }
977 }
978 
979 /**
980  * Read the inode of a specific child file from the given xattr on the
981  * parent directory. Returns a currently valid path for that child, which
982  * might have an encrypted name.
983  */
read_path_inode(const std::string & parent,const char * name,const char * inode_xattr)984 std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
985     ino_t inode = 0;
986     uint64_t inode_raw = 0;
987     auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
988 
989     // Lookup the inode value written earlier
990     if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
991         inode = inode_raw;
992     }
993 
994     // For testing purposes, rely on the inode when defined; this could be
995     // optimized to use access() in the future.
996     if (inode != 0) {
997         DIR* dir = opendir(parent.c_str());
998         if (dir == nullptr) {
999             PLOG(ERROR) << "Failed to opendir " << parent;
1000             return fallback;
1001         }
1002 
1003         struct dirent* ent;
1004         while ((ent = readdir(dir))) {
1005             if (ent->d_ino == inode) {
1006                 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
1007 #if DEBUG_XATTRS
1008                 if (resolved != fallback) {
1009                     LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
1010                             << " instead of " << fallback;
1011                 }
1012 #endif
1013                 closedir(dir);
1014                 return resolved;
1015             }
1016         }
1017         LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
1018         closedir(dir);
1019         return fallback;
1020     } else {
1021         return fallback;
1022     }
1023 }
1024 
remove_path_xattr(const std::string & path,const char * inode_xattr)1025 void remove_path_xattr(const std::string& path, const char* inode_xattr) {
1026     if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
1027         PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
1028     }
1029 }
1030 
1031 /**
1032  * Validate that the path is valid in the context of the provided directory.
1033  * The path is allowed to have at most one subdirectory and no indirections
1034  * to top level directories (i.e. have "..").
1035  */
validate_path(const std::string & dir,const std::string & path,int maxSubdirs)1036 static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
1037     // Argument check
1038     if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
1039             || dir.find("..") != std::string::npos) {
1040         LOG(ERROR) << "Invalid directory " << dir;
1041         return -1;
1042     }
1043     if (path.find("..") != std::string::npos) {
1044         LOG(ERROR) << "Invalid path " << path;
1045         return -1;
1046     }
1047 
1048     if (path.compare(0, dir.size(), dir) != 0) {
1049         // Common case, path isn't under directory
1050         return -1;
1051     }
1052 
1053     // Count number of subdirectories
1054     auto pos = path.find('/', dir.size());
1055     int count = 0;
1056     while (pos != std::string::npos) {
1057         auto next = path.find('/', pos + 1);
1058         if (next > pos + 1) {
1059             count++;
1060         }
1061         pos = next;
1062     }
1063 
1064     if (count > maxSubdirs) {
1065         LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
1066         return -1;
1067     }
1068 
1069     return 0;
1070 }
1071 
1072 /**
1073  * Checks whether a path points to a system app (.apk file). Returns 0
1074  * if it is a system app or -1 if it is not.
1075  */
validate_system_app_path(const char * path)1076 int validate_system_app_path(const char* path) {
1077     std::string path_ = path;
1078     for (const auto& dir : android_system_dirs) {
1079         if (validate_path(dir, path, 1) == 0) {
1080             return 0;
1081         }
1082     }
1083     return -1;
1084 }
1085 
validate_secondary_dex_path(const std::string & pkgname,const std::string & dex_path,const char * volume_uuid,int uid,int storage_flag)1086 bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
1087         const char* volume_uuid, int uid, int storage_flag) {
1088     CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1089 
1090     // Empty paths are not allowed.
1091     if (dex_path.empty()) { return false; }
1092     // First character should always be '/'. No relative paths.
1093     if (dex_path[0] != '/') { return false; }
1094     // The last character should not be '/'.
1095     if (dex_path[dex_path.size() - 1] == '/') { return false; }
1096     // There should be no '.' after the directory marker.
1097     if (dex_path.find("/.") != std::string::npos) { return false; }
1098     // The path should be at most PKG_PATH_MAX long.
1099     if (dex_path.size() > PKG_PATH_MAX) { return false; }
1100 
1101     // The dex_path should be under the app data directory.
1102     std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
1103             ? create_data_user_ce_package_path(
1104                     volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1105             : create_data_user_de_package_path(
1106                     volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1107 
1108     if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1109         // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1110         // If that's the case, attempt to validate against the user data link.
1111         std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1112                 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1113         if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1114                 app_private_dir_symlink.size()) != 0) {
1115             return false;
1116         }
1117     }
1118 
1119     // If we got here we have a valid path.
1120     return true;
1121 }
1122 
1123 /**
1124  * Check whether path points to a valid path for an APK file. The path must
1125  * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1126  * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1127  * is encountered.
1128  */
validate_apk_path_internal(const std::string & path,int maxSubdirs)1129 static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1130     if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
1131         return 0;
1132     } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1133         return 0;
1134     } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
1135         return 0;
1136     } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
1137         return 0;
1138     } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
1139         return 0;
1140     } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1141         // Rewrite the path as if it were on internal storage, and test that
1142         size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1143         if (end != std::string::npos) {
1144             auto modified = path;
1145             modified.replace(0, end + 1, android_data_dir);
1146             return validate_apk_path_internal(modified, maxSubdirs);
1147         }
1148     }
1149     return -1;
1150 }
1151 
validate_apk_path(const char * path)1152 int validate_apk_path(const char* path) {
1153     return validate_apk_path_internal(path, 2 /* maxSubdirs */);
1154 }
1155 
validate_apk_path_subdirs(const char * path)1156 int validate_apk_path_subdirs(const char* path) {
1157     return validate_apk_path_internal(path, 4 /* maxSubdirs */);
1158 }
1159 
ensure_config_user_dirs(userid_t userid)1160 int ensure_config_user_dirs(userid_t userid) {
1161     // writable by system, readable by any app within the same user
1162     const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1163     const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
1164 
1165     // Ensure /data/misc/user/<userid> exists
1166     auto path = create_data_misc_legacy_path(userid);
1167     return fs_prepare_dir(path.c_str(), 0750, uid, gid);
1168 }
1169 
wait_child(pid_t pid)1170 static int wait_child(pid_t pid) {
1171     int status;
1172     pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, /*options=*/0));
1173 
1174     if (got_pid != pid) {
1175         PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
1176         return W_EXITCODE(/*exit_code=*/255, /*signal_number=*/0);
1177     }
1178 
1179     return status;
1180 }
1181 
wait_child_with_timeout(pid_t pid,int timeout_ms)1182 int wait_child_with_timeout(pid_t pid, int timeout_ms) {
1183     int pidfd = pidfd_open(pid, /*flags=*/0);
1184     if (pidfd < 0) {
1185         PLOG(ERROR) << "pidfd_open failed for pid " << pid
1186                     << ", waiting for child process without timeout";
1187         return wait_child(pid);
1188     }
1189 
1190     struct pollfd pfd;
1191     pfd.fd = pidfd;
1192     pfd.events = POLLIN;
1193     int poll_ret = TEMP_FAILURE_RETRY(poll(&pfd, /*nfds=*/1, timeout_ms));
1194 
1195     close(pidfd);
1196 
1197     if (poll_ret < 0) {
1198         PLOG(ERROR) << "poll failed for pid " << pid;
1199         kill(pid, SIGKILL);
1200         return wait_child(pid);
1201     }
1202     if (poll_ret == 0) {
1203         LOG(WARNING) << "Child process " << pid << " timed out after " << timeout_ms
1204                      << "ms. Killing it";
1205         kill(pid, SIGKILL);
1206         return wait_child(pid);
1207     }
1208     return wait_child(pid);
1209 }
1210 
1211 /**
1212  * Prepare an app cache directory, which offers to fix-up the GID and
1213  * directory mode flags during a platform upgrade.
1214  * The app cache directory path will be 'parent'/'name'.
1215  */
prepare_app_cache_dir(const std::string & parent,const char * name,mode_t target_mode,uid_t uid,gid_t gid)1216 int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1217         uid_t uid, gid_t gid) {
1218     auto path = StringPrintf("%s/%s", parent.c_str(), name);
1219     struct stat st;
1220     if (stat(path.c_str(), &st) != 0) {
1221         if (errno == ENOENT) {
1222             // This is fine, just create it
1223             if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1224                 PLOG(ERROR) << "Failed to prepare " << path;
1225                 return -1;
1226             } else {
1227                 return 0;
1228             }
1229         } else {
1230             PLOG(ERROR) << "Failed to stat " << path;
1231             return -1;
1232         }
1233     }
1234 
1235     mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1236     if (st.st_uid != uid) {
1237         // Mismatched UID is real trouble; we can't recover
1238         LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1239                 << " but expected " << uid;
1240         return -1;
1241     } else if (st.st_gid == gid && actual_mode == target_mode) {
1242         // Everything looks good!
1243         return 0;
1244     } else {
1245         // Mismatched GID/mode is recoverable; fall through to update
1246         LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
1247                 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
1248     }
1249 
1250     // Directory is owned correctly, but GID or mode mismatch means it's
1251     // probably a platform upgrade so we need to fix them
1252     FTS *fts;
1253     FTSENT *p;
1254     char *argv[] = { (char*) path.c_str(), nullptr };
1255     if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
1256         PLOG(ERROR) << "Failed to fts_open " << path;
1257         return -1;
1258     }
1259     while ((p = fts_read(fts)) != nullptr) {
1260         switch (p->fts_info) {
1261         case FTS_DP:
1262             if (chmod(p->fts_path, target_mode) != 0) {
1263                 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1264             }
1265             [[fallthrough]]; // to also set GID
1266         case FTS_F:
1267             if (chown(p->fts_path, -1, gid) != 0) {
1268                 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1269             }
1270             break;
1271         case FTS_SL:
1272         case FTS_SLNONE:
1273             if (lchown(p->fts_path, -1, gid) != 0) {
1274                 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1275             }
1276             break;
1277         }
1278     }
1279     fts_close(fts);
1280     return 0;
1281 }
1282 
1283 static const char* kProcFilesystems = "/proc/filesystems";
supports_sdcardfs()1284 bool supports_sdcardfs() {
1285     if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1286         return false;
1287     std::string supported;
1288     if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1289         PLOG(ERROR) << "Failed to read supported filesystems";
1290         return false;
1291     }
1292     return supported.find("sdcardfs\n") != std::string::npos;
1293 }
1294 
get_occupied_app_space_external(const std::string & uuid,int32_t userId,int32_t appId)1295 int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1296     static const bool supportsSdcardFs = supports_sdcardfs();
1297 
1298     if (supportsSdcardFs) {
1299         int extGid = multiuser_get_ext_gid(userId, appId);
1300 
1301         if (extGid == -1) {
1302             return -1;
1303         }
1304 
1305         return GetOccupiedSpaceForGid(uuid, extGid);
1306     } else {
1307         uid_t uid = multiuser_get_uid(userId, appId);
1308         long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1309         return GetOccupiedSpaceForProjectId(uuid, projectId);
1310     }
1311 }
get_occupied_app_cache_space_external(const std::string & uuid,int32_t userId,int32_t appId)1312 int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1313     static const bool supportsSdcardFs = supports_sdcardfs();
1314 
1315     if (supportsSdcardFs) {
1316         int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1317 
1318         if (extCacheGid == -1) {
1319             return -1;
1320         }
1321 
1322         return GetOccupiedSpaceForGid(uuid, extCacheGid);
1323     } else {
1324         uid_t uid = multiuser_get_uid(userId, appId);
1325         long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1326         return GetOccupiedSpaceForProjectId(uuid, projectId);
1327     }
1328 }
1329 
1330 // Collect all non empty profiles from the given directory and puts then into profile_paths.
1331 // The profiles are identified based on PROFILE_EXT extension.
1332 // If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1333 // It returns true if there were no errors at all, and false otherwise.
collect_profiles(DIR * d,const std::string & current_path,std::vector<std::string> * profiles_paths)1334 static bool collect_profiles(DIR* d,
1335                              const std::string& current_path,
1336                              std::vector<std::string>* profiles_paths) {
1337     int32_t dir_fd = dirfd(d);
1338     if (dir_fd < 0) {
1339         return false;
1340     }
1341 
1342     bool result = true;
1343     struct dirent* dir_entry;
1344     while ((dir_entry = readdir(d))) {
1345         std::string name = dir_entry->d_name;
1346         std::string local_path = current_path + "/" + name;
1347 
1348         if (dir_entry->d_type == DT_REG) {
1349             // Check if this is a non empty profile file.
1350             if (EndsWith(name, PROFILE_EXT)) {
1351                 struct stat st;
1352                 if (stat(local_path.c_str(), &st) != 0) {
1353                     PLOG(WARNING) << "Cannot stat local path " << local_path;
1354                     result = false;
1355                     continue;
1356                 } else if (st.st_size > 0) {
1357                     profiles_paths->push_back(local_path);
1358                 }
1359             }
1360         } else if (dir_entry->d_type == DT_DIR) {
1361             // always skip "." and ".."
1362             if (name == "." || name == "..") {
1363                 continue;
1364             }
1365 
1366             unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1367                     O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1368             if (subdir_fd < 0) {
1369                 PLOG(WARNING) << "Could not open dir path " << local_path;
1370                 result = false;
1371                 continue;
1372             }
1373 
1374             DIR* subdir = Fdopendir(std::move(subdir_fd));
1375             if (subdir == nullptr) {
1376                 PLOG(WARNING) << "Could not open dir path " << local_path;
1377                 result = false;
1378                 continue;
1379             }
1380             bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1381             result = result && new_result;
1382             if (closedir(subdir) != 0) {
1383                 PLOG(WARNING) << "Could not close dir path " << local_path;
1384             }
1385         }
1386     }
1387 
1388     return result;
1389 }
1390 
collect_profiles(std::vector<std::string> * profiles_paths)1391 bool collect_profiles(std::vector<std::string>* profiles_paths) {
1392     DIR* d = opendir(android_profiles_dir.c_str());
1393     if (d == nullptr) {
1394         return false;
1395     } else {
1396         return collect_profiles(d, android_profiles_dir, profiles_paths);
1397     }
1398 }
1399 
drop_capabilities(uid_t uid)1400 void drop_capabilities(uid_t uid) {
1401     if (setgid(uid) != 0) {
1402         PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1403         exit(DexoptReturnCodes::kSetGid);
1404     }
1405     if (setuid(uid) != 0) {
1406         PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1407         exit(DexoptReturnCodes::kSetUid);
1408     }
1409     // drop capabilities
1410     struct __user_cap_header_struct capheader;
1411     struct __user_cap_data_struct capdata[2];
1412     memset(&capheader, 0, sizeof(capheader));
1413     memset(&capdata, 0, sizeof(capdata));
1414     capheader.version = _LINUX_CAPABILITY_VERSION_3;
1415     if (capset(&capheader, &capdata[0]) < 0) {
1416         PLOG(ERROR) << "capset failed";
1417         exit(DexoptReturnCodes::kCapSet);
1418     }
1419 }
1420 
remove_file_at_fd(int fd,std::string * path)1421 bool remove_file_at_fd(int fd, /*out*/ std::string* path) {
1422     char path_buffer[PATH_MAX + 1];
1423     std::string proc_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
1424     ssize_t len = readlink(proc_path.c_str(), path_buffer, PATH_MAX);
1425     if (len < 0) {
1426         PLOG(WARNING) << "Could not remove file at fd " << fd << ": Failed to get file path";
1427         return false;
1428     }
1429     path_buffer[len] = '\0';
1430     if (path != nullptr) {
1431         *path = path_buffer;
1432     }
1433     if (unlink(path_buffer) != 0) {
1434         if (errno == ENOENT) {
1435             return true;
1436         }
1437         PLOG(WARNING) << "Could not remove file at path " << path_buffer;
1438         return false;
1439     }
1440     return true;
1441 }
1442 
1443 }  // namespace installd
1444 }  // namespace android
1445