• 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 hasSep = false;
527     bool front = true;
528 
529     auto it = packageName.begin();
530     for (; it != packageName.end() && *it != '-'; it++) {
531         char c = *it;
532         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
533             front = false;
534             continue;
535         }
536         if (!front) {
537             if ((c >= '0' && c <= '9') || c == '_') {
538                 continue;
539             }
540         }
541         if (c == '.') {
542             hasSep = true;
543             front = true;
544             continue;
545         }
546         LOG(WARNING) << "Bad package character " << c << " in " << packageName;
547         return false;
548     }
549 
550     if (front) {
551         LOG(WARNING) << "Missing separator in " << packageName;
552         return false;
553     }
554 
555     for (; it != packageName.end(); it++) {
556         char c = *it;
557         if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
558         if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
559         LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
560         return false;
561     }
562 
563     return true;
564 }
565 
_delete_dir_contents(DIR * d,int (* exclusion_predicate)(const char * name,const int is_dir))566 static int _delete_dir_contents(DIR *d,
567                                 int (*exclusion_predicate)(const char *name, const int is_dir))
568 {
569     int result = 0;
570     struct dirent *de;
571     int dfd;
572 
573     dfd = dirfd(d);
574 
575     if (dfd < 0) return -1;
576 
577     while ((de = readdir(d))) {
578         const char *name = de->d_name;
579 
580             /* check using the exclusion predicate, if provided */
581         if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
582             continue;
583         }
584 
585         if (de->d_type == DT_DIR) {
586             int subfd;
587             DIR *subdir;
588 
589                 /* always skip "." and ".." */
590             if (name[0] == '.') {
591                 if (name[1] == 0) continue;
592                 if ((name[1] == '.') && (name[2] == 0)) continue;
593             }
594 
595             subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
596             if (subfd < 0) {
597                 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
598                 result = -1;
599                 continue;
600             }
601             subdir = fdopendir(subfd);
602             if (subdir == nullptr) {
603                 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
604                 close(subfd);
605                 result = -1;
606                 continue;
607             }
608             if (_delete_dir_contents(subdir, exclusion_predicate)) {
609                 result = -1;
610             }
611             closedir(subdir);
612             if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
613                 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
614                 result = -1;
615             }
616         } else {
617             if (unlinkat(dfd, name, 0) < 0) {
618                 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
619                 result = -1;
620             }
621         }
622     }
623 
624     return result;
625 }
626 
create_dir_if_needed(const std::string & pathname,mode_t perms)627 int create_dir_if_needed(const std::string& pathname, mode_t perms) {
628     struct stat st;
629 
630     int rc;
631     if ((rc = stat(pathname.c_str(), &st)) != 0) {
632         if (errno == ENOENT) {
633             return mkdir(pathname.c_str(), perms);
634         } else {
635             return rc;
636         }
637     } else if (!S_ISDIR(st.st_mode)) {
638         LOG(DEBUG) << pathname << " is not a folder";
639         return -1;
640     }
641 
642     mode_t actual_perms = st.st_mode & ALLPERMS;
643     if (actual_perms != perms) {
644         LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
645         return -1;
646     }
647 
648     return 0;
649 }
650 
delete_dir_contents(const std::string & pathname,bool ignore_if_missing)651 int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
652     return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
653 }
654 
delete_dir_contents_and_dir(const std::string & pathname,bool ignore_if_missing)655 int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
656     return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
657 }
658 
delete_dir_contents(const char * pathname,int also_delete_dir,int (* exclusion_predicate)(const char *,const int),bool ignore_if_missing)659 int delete_dir_contents(const char *pathname,
660                         int also_delete_dir,
661                         int (*exclusion_predicate)(const char*, const int),
662                         bool ignore_if_missing)
663 {
664     int res = 0;
665     DIR *d;
666 
667     d = opendir(pathname);
668     if (d == nullptr) {
669         if (ignore_if_missing && (errno == ENOENT)) {
670             return 0;
671         }
672         ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
673         return -errno;
674     }
675     res = _delete_dir_contents(d, exclusion_predicate);
676     closedir(d);
677     if (also_delete_dir) {
678         if (rmdir(pathname)) {
679             ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
680             res = -1;
681         }
682     }
683     return res;
684 }
685 
make_unique_name(std::string_view suffix)686 static std::string make_unique_name(std::string_view suffix) {
687     static constexpr auto uuidStringSize = 36;
688 
689     uuid_t guid;
690     uuid_generate(guid);
691 
692     std::string name;
693     const auto suffixSize = suffix.size();
694     name.reserve(uuidStringSize + suffixSize);
695 
696     name.resize(uuidStringSize);
697     uuid_unparse(guid, name.data());
698     name.append(suffix);
699 
700     return name;
701 }
702 
rename_delete_dir_contents(const std::string & pathname,int (* exclusion_predicate)(const char *,const int),bool ignore_if_missing)703 static int rename_delete_dir_contents(const std::string& pathname,
704                                       int (*exclusion_predicate)(const char*, const int),
705                                       bool ignore_if_missing) {
706     auto temp_dir_name = make_unique_name(deletedSuffix);
707     auto temp_dir_path =
708             base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
709 
710     auto dir_to_delete = temp_dir_path.c_str();
711     if (::rename(pathname.c_str(), dir_to_delete)) {
712         if (ignore_if_missing && (errno == ENOENT)) {
713             return 0;
714         }
715         ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), dir_to_delete, strerror(errno));
716         dir_to_delete = pathname.c_str();
717     }
718 
719     return delete_dir_contents(dir_to_delete, 1, exclusion_predicate, ignore_if_missing);
720 }
721 
is_renamed_deleted_dir(const std::string & path)722 bool is_renamed_deleted_dir(const std::string& path) {
723     if (path.size() < deletedSuffix.size()) {
724         return false;
725     }
726     std::string_view pathSuffix{path.c_str() + path.size() - deletedSuffix.size()};
727     return pathSuffix == deletedSuffix;
728 }
729 
rename_delete_dir_contents_and_dir(const std::string & pathname,bool ignore_if_missing)730 int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
731     return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
732 }
733 
open_dir(const char * dir)734 static auto open_dir(const char* dir) {
735     struct DirCloser {
736         void operator()(DIR* d) const noexcept { ::closedir(d); }
737     };
738     return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
739 }
740 
741 // 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)742 int foreach_subdir(const std::string& pathname, const std::function<void(const std::string&)> fn) {
743     auto dir = open_dir(pathname.c_str());
744     if (!dir) return -1;
745 
746     int dfd = dirfd(dir.get());
747     if (dfd < 0) {
748         ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
749         return -1;
750     }
751 
752     struct dirent* de;
753     while ((de = readdir(dir.get()))) {
754         if (de->d_type != DT_DIR) {
755             continue;
756         }
757 
758         std::string name{de->d_name};
759         // always skip "." and ".."
760         if (name == "." || name == "..") {
761             continue;
762         }
763         fn(name);
764     }
765 
766     return 0;
767 }
768 
cleanup_invalid_package_dirs_under_path(const std::string & pathname)769 void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
770     auto dir = open_dir(pathname.c_str());
771     if (!dir) {
772         return;
773     }
774     int dfd = dirfd(dir.get());
775     if (dfd < 0) {
776         ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
777         return;
778     }
779 
780     struct dirent* de;
781     while ((de = readdir(dir.get()))) {
782         if (de->d_type != DT_DIR) {
783             continue;
784         }
785 
786         std::string name{de->d_name};
787         // always skip "." and ".."
788         if (name == "." || name == "..") {
789             continue;
790         }
791 
792         if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
793             !is_valid_package_name(name)) {
794             ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
795             // Deleting the content.
796             delete_dir_contents_fd(dfd, name.c_str());
797             // Deleting the directory
798             if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
799                 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
800             }
801         }
802     }
803 }
804 
delete_dir_contents_fd(int dfd,const char * name)805 int delete_dir_contents_fd(int dfd, const char *name)
806 {
807     int fd, res;
808     DIR *d;
809 
810     fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
811     if (fd < 0) {
812         ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
813         return -1;
814     }
815     d = fdopendir(fd);
816     if (d == nullptr) {
817         ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
818         close(fd);
819         return -1;
820     }
821     res = _delete_dir_contents(d, nullptr);
822     closedir(d);
823     return res;
824 }
825 
_copy_owner_permissions(int srcfd,int dstfd)826 static int _copy_owner_permissions(int srcfd, int dstfd)
827 {
828     struct stat st;
829     if (fstat(srcfd, &st) != 0) {
830         return -1;
831     }
832     if (fchmod(dstfd, st.st_mode) != 0) {
833         return -1;
834     }
835     return 0;
836 }
837 
_copy_dir_files(int sdfd,int ddfd,uid_t owner,gid_t group)838 static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
839 {
840     int result = 0;
841     if (_copy_owner_permissions(sdfd, ddfd) != 0) {
842         ALOGE("_copy_dir_files failed to copy dir permissions\n");
843     }
844     if (fchown(ddfd, owner, group) != 0) {
845         ALOGE("_copy_dir_files failed to change dir owner\n");
846     }
847 
848     DIR *ds = fdopendir(sdfd);
849     if (ds == nullptr) {
850         ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
851         return -1;
852     }
853     struct dirent *de;
854     while ((de = readdir(ds))) {
855         if (de->d_type != DT_REG) {
856             continue;
857         }
858 
859         const char *name = de->d_name;
860         int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
861         int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
862         if (fsfd == -1 || fdfd == -1) {
863             ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
864         } else {
865             if (_copy_owner_permissions(fsfd, fdfd) != 0) {
866                 ALOGE("Failed to change file permissions\n");
867             }
868             if (fchown(fdfd, owner, group) != 0) {
869                 ALOGE("Failed to change file owner\n");
870             }
871 
872             char buf[8192];
873             ssize_t size;
874             while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
875                 write(fdfd, buf, size);
876             }
877             if (size < 0) {
878                 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
879                 result = -1;
880             }
881         }
882         close(fdfd);
883         close(fsfd);
884     }
885 
886     return result;
887 }
888 
copy_dir_files(const char * srcname,const char * dstname,uid_t owner,uid_t group)889 int copy_dir_files(const char *srcname,
890                    const char *dstname,
891                    uid_t owner,
892                    uid_t group)
893 {
894     int res = 0;
895     DIR *ds = nullptr;
896     DIR *dd = nullptr;
897 
898     ds = opendir(srcname);
899     if (ds == nullptr) {
900         ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
901         return -errno;
902     }
903 
904     mkdir(dstname, 0600);
905     dd = opendir(dstname);
906     if (dd == nullptr) {
907         ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
908         closedir(ds);
909         return -errno;
910     }
911 
912     int sdfd = dirfd(ds);
913     int ddfd = dirfd(dd);
914     if (sdfd != -1 && ddfd != -1) {
915         res = _copy_dir_files(sdfd, ddfd, owner, group);
916     } else {
917         res = -errno;
918     }
919     closedir(dd);
920     closedir(ds);
921     return res;
922 }
923 
data_disk_free(const std::string & data_path)924 int64_t data_disk_free(const std::string& data_path) {
925     struct statvfs sfs;
926     if (statvfs(data_path.c_str(), &sfs) == 0) {
927         return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
928     } else {
929         PLOG(ERROR) << "Couldn't statvfs " << data_path;
930         return -1;
931     }
932 }
933 
get_path_inode(const std::string & path,ino_t * inode)934 int get_path_inode(const std::string& path, ino_t *inode) {
935     struct stat buf;
936     memset(&buf, 0, sizeof(buf));
937     if (stat(path.c_str(), &buf) != 0) {
938         PLOG(WARNING) << "Failed to stat " << path;
939         return -1;
940     } else {
941         *inode = buf.st_ino;
942         return 0;
943     }
944 }
945 
946 /**
947  * Write the inode of a specific child file into the given xattr on the
948  * parent directory. This allows you to find the child later, even if its
949  * name is encrypted.
950  */
write_path_inode(const std::string & parent,const char * name,const char * inode_xattr)951 int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
952     ino_t inode = 0;
953     uint64_t inode_raw = 0;
954     auto path = StringPrintf("%s/%s", parent.c_str(), name);
955 
956     if (get_path_inode(path, &inode) != 0) {
957         // Path probably doesn't exist yet; ignore
958         return 0;
959     }
960 
961     // Check to see if already set correctly
962     if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
963         if (inode_raw == inode) {
964             // Already set correctly; skip writing
965             return 0;
966         } else {
967             PLOG(WARNING) << "Mismatched inode value; found " << inode
968                     << " on disk but marked value was " << inode_raw << "; overwriting";
969         }
970     }
971 
972     inode_raw = inode;
973     if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
974         PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
975         return -1;
976     } else {
977         return 0;
978     }
979 }
980 
981 /**
982  * Read the inode of a specific child file from the given xattr on the
983  * parent directory. Returns a currently valid path for that child, which
984  * might have an encrypted name.
985  */
read_path_inode(const std::string & parent,const char * name,const char * inode_xattr)986 std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
987     ino_t inode = 0;
988     uint64_t inode_raw = 0;
989     auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
990 
991     // Lookup the inode value written earlier
992     if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
993         inode = inode_raw;
994     }
995 
996     // For testing purposes, rely on the inode when defined; this could be
997     // optimized to use access() in the future.
998     if (inode != 0) {
999         DIR* dir = opendir(parent.c_str());
1000         if (dir == nullptr) {
1001             PLOG(ERROR) << "Failed to opendir " << parent;
1002             return fallback;
1003         }
1004 
1005         struct dirent* ent;
1006         while ((ent = readdir(dir))) {
1007             if (ent->d_ino == inode) {
1008                 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
1009 #if DEBUG_XATTRS
1010                 if (resolved != fallback) {
1011                     LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
1012                             << " instead of " << fallback;
1013                 }
1014 #endif
1015                 closedir(dir);
1016                 return resolved;
1017             }
1018         }
1019         LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
1020         closedir(dir);
1021         return fallback;
1022     } else {
1023         return fallback;
1024     }
1025 }
1026 
remove_path_xattr(const std::string & path,const char * inode_xattr)1027 void remove_path_xattr(const std::string& path, const char* inode_xattr) {
1028     if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
1029         PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
1030     }
1031 }
1032 
1033 /**
1034  * Validate that the path is valid in the context of the provided directory.
1035  * The path is allowed to have at most one subdirectory and no indirections
1036  * to top level directories (i.e. have "..").
1037  */
validate_path(const std::string & dir,const std::string & path,int maxSubdirs)1038 static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
1039     // Argument check
1040     if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
1041             || dir.find("..") != std::string::npos) {
1042         LOG(ERROR) << "Invalid directory " << dir;
1043         return -1;
1044     }
1045     if (path.find("..") != std::string::npos) {
1046         LOG(ERROR) << "Invalid path " << path;
1047         return -1;
1048     }
1049 
1050     if (path.compare(0, dir.size(), dir) != 0) {
1051         // Common case, path isn't under directory
1052         return -1;
1053     }
1054 
1055     // Count number of subdirectories
1056     auto pos = path.find('/', dir.size());
1057     int count = 0;
1058     while (pos != std::string::npos) {
1059         auto next = path.find('/', pos + 1);
1060         if (next > pos + 1) {
1061             count++;
1062         }
1063         pos = next;
1064     }
1065 
1066     if (count > maxSubdirs) {
1067         LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
1068         return -1;
1069     }
1070 
1071     return 0;
1072 }
1073 
1074 /**
1075  * Checks whether a path points to a system app (.apk file). Returns 0
1076  * if it is a system app or -1 if it is not.
1077  */
validate_system_app_path(const char * path)1078 int validate_system_app_path(const char* path) {
1079     std::string path_ = path;
1080     for (const auto& dir : android_system_dirs) {
1081         if (validate_path(dir, path, 1) == 0) {
1082             return 0;
1083         }
1084     }
1085     return -1;
1086 }
1087 
validate_secondary_dex_path(const std::string & pkgname,const std::string & dex_path,const char * volume_uuid,int uid,int storage_flag)1088 bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
1089         const char* volume_uuid, int uid, int storage_flag) {
1090     CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1091 
1092     // Empty paths are not allowed.
1093     if (dex_path.empty()) { return false; }
1094     // First character should always be '/'. No relative paths.
1095     if (dex_path[0] != '/') { return false; }
1096     // The last character should not be '/'.
1097     if (dex_path[dex_path.size() - 1] == '/') { return false; }
1098     // There should be no '.' after the directory marker.
1099     if (dex_path.find("/.") != std::string::npos) { return false; }
1100     // The path should be at most PKG_PATH_MAX long.
1101     if (dex_path.size() > PKG_PATH_MAX) { return false; }
1102 
1103     // The dex_path should be under the app data directory.
1104     std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
1105             ? create_data_user_ce_package_path(
1106                     volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1107             : create_data_user_de_package_path(
1108                     volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1109 
1110     if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1111         // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1112         // If that's the case, attempt to validate against the user data link.
1113         std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1114                 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1115         if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1116                 app_private_dir_symlink.size()) != 0) {
1117             return false;
1118         }
1119     }
1120 
1121     // If we got here we have a valid path.
1122     return true;
1123 }
1124 
1125 /**
1126  * Check whether path points to a valid path for an APK file. The path must
1127  * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1128  * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1129  * is encountered.
1130  */
validate_apk_path_internal(const std::string & path,int maxSubdirs)1131 static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1132     if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
1133         return 0;
1134     } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1135         return 0;
1136     } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
1137         return 0;
1138     } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
1139         return 0;
1140     } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
1141         return 0;
1142     } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1143         // Rewrite the path as if it were on internal storage, and test that
1144         size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1145         if (end != std::string::npos) {
1146             auto modified = path;
1147             modified.replace(0, end + 1, android_data_dir);
1148             return validate_apk_path_internal(modified, maxSubdirs);
1149         }
1150     }
1151     return -1;
1152 }
1153 
validate_apk_path(const char * path)1154 int validate_apk_path(const char* path) {
1155     return validate_apk_path_internal(path, 2 /* maxSubdirs */);
1156 }
1157 
validate_apk_path_subdirs(const char * path)1158 int validate_apk_path_subdirs(const char* path) {
1159     return validate_apk_path_internal(path, 4 /* maxSubdirs */);
1160 }
1161 
ensure_config_user_dirs(userid_t userid)1162 int ensure_config_user_dirs(userid_t userid) {
1163     // writable by system, readable by any app within the same user
1164     const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1165     const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
1166 
1167     // Ensure /data/misc/user/<userid> exists
1168     auto path = create_data_misc_legacy_path(userid);
1169     return fs_prepare_dir(path.c_str(), 0750, uid, gid);
1170 }
1171 
wait_child(pid_t pid)1172 static int wait_child(pid_t pid) {
1173     int status;
1174     pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, /*options=*/0));
1175 
1176     if (got_pid != pid) {
1177         PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
1178         return W_EXITCODE(/*exit_code=*/255, /*signal_number=*/0);
1179     }
1180 
1181     return status;
1182 }
1183 
wait_child_with_timeout(pid_t pid,int timeout_ms)1184 int wait_child_with_timeout(pid_t pid, int timeout_ms) {
1185     int pidfd = pidfd_open(pid, /*flags=*/0);
1186     if (pidfd < 0) {
1187         PLOG(ERROR) << "pidfd_open failed for pid " << pid
1188                     << ", waiting for child process without timeout";
1189         return wait_child(pid);
1190     }
1191 
1192     struct pollfd pfd;
1193     pfd.fd = pidfd;
1194     pfd.events = POLLIN;
1195     int poll_ret = TEMP_FAILURE_RETRY(poll(&pfd, /*nfds=*/1, timeout_ms));
1196 
1197     close(pidfd);
1198 
1199     if (poll_ret < 0) {
1200         PLOG(ERROR) << "poll failed for pid " << pid;
1201         kill(pid, SIGKILL);
1202         return wait_child(pid);
1203     }
1204     if (poll_ret == 0) {
1205         LOG(WARNING) << "Child process " << pid << " timed out after " << timeout_ms
1206                      << "ms. Killing it";
1207         kill(pid, SIGKILL);
1208         return wait_child(pid);
1209     }
1210     return wait_child(pid);
1211 }
1212 
1213 /**
1214  * Prepare an app cache directory, which offers to fix-up the GID and
1215  * directory mode flags during a platform upgrade.
1216  * The app cache directory path will be 'parent'/'name'.
1217  */
prepare_app_cache_dir(const std::string & parent,const char * name,mode_t target_mode,uid_t uid,gid_t gid)1218 int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1219         uid_t uid, gid_t gid) {
1220     auto path = StringPrintf("%s/%s", parent.c_str(), name);
1221     struct stat st;
1222     if (stat(path.c_str(), &st) != 0) {
1223         if (errno == ENOENT) {
1224             // This is fine, just create it
1225             if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1226                 PLOG(ERROR) << "Failed to prepare " << path;
1227                 return -1;
1228             } else {
1229                 return 0;
1230             }
1231         } else {
1232             PLOG(ERROR) << "Failed to stat " << path;
1233             return -1;
1234         }
1235     }
1236 
1237     mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1238     if (st.st_uid != uid) {
1239         // Mismatched UID is real trouble; we can't recover
1240         LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1241                 << " but expected " << uid;
1242         return -1;
1243     } else if (st.st_gid == gid && actual_mode == target_mode) {
1244         // Everything looks good!
1245         return 0;
1246     } else {
1247         // Mismatched GID/mode is recoverable; fall through to update
1248         LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
1249                 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
1250     }
1251 
1252     // Directory is owned correctly, but GID or mode mismatch means it's
1253     // probably a platform upgrade so we need to fix them
1254     FTS *fts;
1255     FTSENT *p;
1256     char *argv[] = { (char*) path.c_str(), nullptr };
1257     if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
1258         PLOG(ERROR) << "Failed to fts_open " << path;
1259         return -1;
1260     }
1261     while ((p = fts_read(fts)) != nullptr) {
1262         switch (p->fts_info) {
1263         case FTS_DP:
1264             if (chmod(p->fts_path, target_mode) != 0) {
1265                 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1266             }
1267             [[fallthrough]]; // to also set GID
1268         case FTS_F:
1269             if (chown(p->fts_path, -1, gid) != 0) {
1270                 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1271             }
1272             break;
1273         case FTS_SL:
1274         case FTS_SLNONE:
1275             if (lchown(p->fts_path, -1, gid) != 0) {
1276                 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1277             }
1278             break;
1279         }
1280     }
1281     fts_close(fts);
1282     return 0;
1283 }
1284 
1285 static const char* kProcFilesystems = "/proc/filesystems";
supports_sdcardfs()1286 bool supports_sdcardfs() {
1287     if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1288         return false;
1289     std::string supported;
1290     if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1291         PLOG(ERROR) << "Failed to read supported filesystems";
1292         return false;
1293     }
1294     return supported.find("sdcardfs\n") != std::string::npos;
1295 }
1296 
get_occupied_app_space_external(const std::string & uuid,int32_t userId,int32_t appId)1297 int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1298     static const bool supportsSdcardFs = supports_sdcardfs();
1299 
1300     if (supportsSdcardFs) {
1301         int extGid = multiuser_get_ext_gid(userId, appId);
1302 
1303         if (extGid == -1) {
1304             return -1;
1305         }
1306 
1307         return GetOccupiedSpaceForGid(uuid, extGid);
1308     } else {
1309         uid_t uid = multiuser_get_uid(userId, appId);
1310         long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1311         return GetOccupiedSpaceForProjectId(uuid, projectId);
1312     }
1313 }
get_occupied_app_cache_space_external(const std::string & uuid,int32_t userId,int32_t appId)1314 int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1315     static const bool supportsSdcardFs = supports_sdcardfs();
1316 
1317     if (supportsSdcardFs) {
1318         int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1319 
1320         if (extCacheGid == -1) {
1321             return -1;
1322         }
1323 
1324         return GetOccupiedSpaceForGid(uuid, extCacheGid);
1325     } else {
1326         uid_t uid = multiuser_get_uid(userId, appId);
1327         long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1328         return GetOccupiedSpaceForProjectId(uuid, projectId);
1329     }
1330 }
1331 
1332 // Collect all non empty profiles from the given directory and puts then into profile_paths.
1333 // The profiles are identified based on PROFILE_EXT extension.
1334 // If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1335 // 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)1336 static bool collect_profiles(DIR* d,
1337                              const std::string& current_path,
1338                              std::vector<std::string>* profiles_paths) {
1339     int32_t dir_fd = dirfd(d);
1340     if (dir_fd < 0) {
1341         return false;
1342     }
1343 
1344     bool result = true;
1345     struct dirent* dir_entry;
1346     while ((dir_entry = readdir(d))) {
1347         std::string name = dir_entry->d_name;
1348         std::string local_path = current_path + "/" + name;
1349 
1350         if (dir_entry->d_type == DT_REG) {
1351             // Check if this is a non empty profile file.
1352             if (EndsWith(name, PROFILE_EXT)) {
1353                 struct stat st;
1354                 if (stat(local_path.c_str(), &st) != 0) {
1355                     PLOG(WARNING) << "Cannot stat local path " << local_path;
1356                     result = false;
1357                     continue;
1358                 } else if (st.st_size > 0) {
1359                     profiles_paths->push_back(local_path);
1360                 }
1361             }
1362         } else if (dir_entry->d_type == DT_DIR) {
1363             // always skip "." and ".."
1364             if (name == "." || name == "..") {
1365                 continue;
1366             }
1367 
1368             unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1369                     O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1370             if (subdir_fd < 0) {
1371                 PLOG(WARNING) << "Could not open dir path " << local_path;
1372                 result = false;
1373                 continue;
1374             }
1375 
1376             DIR* subdir = Fdopendir(std::move(subdir_fd));
1377             if (subdir == nullptr) {
1378                 PLOG(WARNING) << "Could not open dir path " << local_path;
1379                 result = false;
1380                 continue;
1381             }
1382             bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1383             result = result && new_result;
1384             if (closedir(subdir) != 0) {
1385                 PLOG(WARNING) << "Could not close dir path " << local_path;
1386             }
1387         }
1388     }
1389 
1390     return result;
1391 }
1392 
collect_profiles(std::vector<std::string> * profiles_paths)1393 bool collect_profiles(std::vector<std::string>* profiles_paths) {
1394     DIR* d = opendir(android_profiles_dir.c_str());
1395     if (d == nullptr) {
1396         return false;
1397     } else {
1398         return collect_profiles(d, android_profiles_dir, profiles_paths);
1399     }
1400 }
1401 
drop_capabilities(uid_t uid)1402 void drop_capabilities(uid_t uid) {
1403     if (setgid(uid) != 0) {
1404         PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1405         exit(DexoptReturnCodes::kSetGid);
1406     }
1407     if (setuid(uid) != 0) {
1408         PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1409         exit(DexoptReturnCodes::kSetUid);
1410     }
1411     // drop capabilities
1412     struct __user_cap_header_struct capheader;
1413     struct __user_cap_data_struct capdata[2];
1414     memset(&capheader, 0, sizeof(capheader));
1415     memset(&capdata, 0, sizeof(capdata));
1416     capheader.version = _LINUX_CAPABILITY_VERSION_3;
1417     if (capset(&capheader, &capdata[0]) < 0) {
1418         PLOG(ERROR) << "capset failed";
1419         exit(DexoptReturnCodes::kCapSet);
1420     }
1421 }
1422 
remove_file_at_fd(int fd,std::string * path)1423 bool remove_file_at_fd(int fd, /*out*/ std::string* path) {
1424     char path_buffer[PATH_MAX + 1];
1425     std::string proc_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
1426     ssize_t len = readlink(proc_path.c_str(), path_buffer, PATH_MAX);
1427     if (len < 0) {
1428         PLOG(WARNING) << "Could not remove file at fd " << fd << ": Failed to get file path";
1429         return false;
1430     }
1431     path_buffer[len] = '\0';
1432     if (path != nullptr) {
1433         *path = path_buffer;
1434     }
1435     if (unlink(path_buffer) != 0) {
1436         if (errno == ENOENT) {
1437             return true;
1438         }
1439         PLOG(WARNING) << "Could not remove file at path " << path_buffer;
1440         return false;
1441     }
1442     return true;
1443 }
1444 
1445 }  // namespace installd
1446 }  // namespace android
1447