blob: 74ad1841a5d2361b1f3511bf35e15803070b3a01 [file] [log] [blame]
Mike Lockwood94afecf2012-10-24 10:45:23 -07001/*
2** Copyright 2008, The Android Open Source Project
3**
Dave Allisond9370732014-01-30 14:19:23 -08004** Licensed under the Apache License, Version 2.0 (the "License");
5** you may not use this file except in compliance with the License.
6** You may obtain a copy of the License at
Mike Lockwood94afecf2012-10-24 10:45:23 -07007**
Dave Allisond9370732014-01-30 14:19:23 -08008** http://www.apache.org/licenses/LICENSE-2.0
Mike Lockwood94afecf2012-10-24 10:45:23 -07009**
Dave Allisond9370732014-01-30 14:19:23 -080010** Unless required by applicable law or agreed to in writing, software
11** distributed under the License is distributed on an "AS IS" BASIS,
12** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13** See the License for the specific language governing permissions and
Mike Lockwood94afecf2012-10-24 10:45:23 -070014** limitations under the License.
15*/
16
Andreas Gampe02d0de52015-11-11 20:43:16 -080017#include "utils.h"
Mike Lockwood94afecf2012-10-24 10:45:23 -070018
Andreas Gampe02d0de52015-11-11 20:43:16 -080019#include <errno.h>
20#include <fcntl.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070021#include <fts.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080022#include <stdlib.h>
23#include <sys/stat.h>
24#include <sys/wait.h>
Jeff Sharkey9a998f42016-07-14 18:16:22 -060025#include <sys/xattr.h>
Jeff Sharkeyed909ae2017-03-22 21:27:40 -060026#include <sys/statvfs.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080027
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080028#include <android-base/logging.h>
Calin Juravlecfcd6aa2018-01-18 20:23:17 -080029#include <android-base/strings.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080030#include <android-base/stringprintf.h>
Calin Juravlee61189e2018-01-23 19:54:11 -080031#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080032#include <cutils/fs.h>
Jeff Sharkey871a8f22017-02-21 18:30:28 -070033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include <private/android_filesystem_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070036
Andreas Gampe02d0de52015-11-11 20:43:16 -080037#include "globals.h" // extern variables.
38
39#ifndef LOG_TAG
40#define LOG_TAG "installd"
41#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060042
Jeff Sharkey9a998f42016-07-14 18:16:22 -060043#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070044
Calin Juravlee61189e2018-01-23 19:54:11 -080045using android::base::EndsWith;
Mathieu Chartier89883e32018-11-01 11:39:00 -070046using android::base::Fdopendir;
Jeff Sharkeyc03de092015-04-07 18:14:05 -070047using android::base::StringPrintf;
Calin Juravlee61189e2018-01-23 19:54:11 -080048using android::base::unique_fd;
Mike Lockwood94afecf2012-10-24 10:45:23 -070049
Andreas Gampe02d0de52015-11-11 20:43:16 -080050namespace android {
51namespace installd {
52
Jeff Sharkeyc03de092015-04-07 18:14:05 -070053/**
54 * Check that given string is valid filename, and that it attempts no
55 * parent or child directory traversal.
56 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070057bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070058 if (name.empty() || (name == ".") || (name == "..")
59 || (name.find('/') != std::string::npos)) {
60 return false;
61 } else {
62 return true;
63 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070064}
65
Calin Juravle6a1648e2016-02-01 12:12:16 +000066static void check_package_name(const char* package_name) {
67 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070068 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000069}
70
Mike Lockwood94afecf2012-10-24 10:45:23 -070071/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -070072 * Create the path name where package app contents should be stored for
73 * the given volume UUID and package name. An empty UUID is assumed to
74 * be internal storage.
75 */
76std::string create_data_app_package_path(const char* volume_uuid,
77 const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000078 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070079 return StringPrintf("%s/%s",
80 create_data_app_path(volume_uuid).c_str(), package_name);
81}
82
83/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070084 * Create the path name where package data should be stored for the given
85 * volume UUID, package name, and user ID. An empty UUID is assumed to be
86 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070087 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -060088std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -070089 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000090 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070091 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -060092 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
93}
94
Calin Juravle7d765462017-09-04 15:57:10 -070095/**
96 * Create the path name where package data should be stored for the given
97 * volume UUID, package name, and user ID. An empty UUID is assumed to be
98 * internal storage.
99 * Compared to create_data_user_ce_package_path this method always return the
100 * ".../user/..." directory.
101 */
102std::string create_data_user_ce_package_path_as_user_link(
103 const char* volume_uuid, userid_t userid, const char* package_name) {
104 check_package_name(package_name);
105 std::string data(create_data_path(volume_uuid));
106 return StringPrintf("%s/user/%u/%s", data.c_str(), userid, package_name);
107}
108
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600109std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
110 const char* package_name, ino_t ce_data_inode) {
111 // For testing purposes, rely on the inode when defined; this could be
112 // optimized to use access() in the future.
113 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
114 if (ce_data_inode != 0) {
115 auto user_path = create_data_user_ce_path(volume_uuid, user);
116 DIR* dir = opendir(user_path.c_str());
117 if (dir == nullptr) {
118 PLOG(ERROR) << "Failed to opendir " << user_path;
119 return fallback;
120 }
121
122 struct dirent* ent;
123 while ((ent = readdir(dir))) {
124 if (ent->d_ino == ce_data_inode) {
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600125 auto resolved = StringPrintf("%s/%s", user_path.c_str(), ent->d_name);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600126#if DEBUG_XATTRS
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600127 if (resolved != fallback) {
128 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
129 << " instead of " << fallback;
130 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600131#endif
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600132 closedir(dir);
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600133 return resolved;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600134 }
135 }
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600136 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600137 closedir(dir);
138 return fallback;
139 } else {
140 return fallback;
141 }
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700142}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700143
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800144std::string create_data_user_de_package_path(const char* volume_uuid,
145 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000146 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800147 return StringPrintf("%s/%s",
148 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
149}
150
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700151std::string create_data_path(const char* volume_uuid) {
152 if (volume_uuid == nullptr) {
153 return "/data";
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700154 } else if (!strcmp(volume_uuid, "TEST")) {
155 CHECK(property_get_bool("ro.debuggable", false));
156 return "/data/local/tmp";
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700157 } else {
158 CHECK(is_valid_filename(volume_uuid));
159 return StringPrintf("/mnt/expand/%s", volume_uuid);
160 }
161}
162
Mike Lockwood94afecf2012-10-24 10:45:23 -0700163/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700164 * Create the path name for app data.
165 */
166std::string create_data_app_path(const char* volume_uuid) {
167 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
168}
169
170/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700171 * Create the path name for user data for a certain userid.
cjbao75d4e572017-04-12 00:12:24 +0800172 * Keep same implementation as vold to minimize path walking overhead
Mike Lockwood94afecf2012-10-24 10:45:23 -0700173 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600174std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700175 std::string data(create_data_path(volume_uuid));
cjbao75d4e572017-04-12 00:12:24 +0800176 if (volume_uuid == nullptr && userid == 0) {
177 std::string legacy = StringPrintf("%s/data", data.c_str());
178 struct stat sb;
179 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
180 /* /data/data is dir, return /data/data for legacy system */
181 return legacy;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700182 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700183 }
cjbao75d4e572017-04-12 00:12:24 +0800184 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700185}
186
187/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800188 * Create the path name for device encrypted user data for a certain userid.
189 */
190std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
191 std::string data(create_data_path(volume_uuid));
192 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
193}
194
195/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700196 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700197 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700198std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
199 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700200}
201
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700202std::string create_data_media_obb_path(const char* volume_uuid, const char* package_name) {
203 return StringPrintf("%s/media/obb/%s", create_data_path(volume_uuid).c_str(), package_name);
204}
205
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700206std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
207 const char* data_type, const char* package_name) {
208 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
209 data_type, package_name);
210}
211
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600212std::string create_data_misc_legacy_path(userid_t userid) {
213 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
214}
215
Calin Juravle114f0812017-03-08 19:05:07 -0800216std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600217 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000218}
219
Calin Juravle114f0812017-03-08 19:05:07 -0800220std::string create_primary_current_profile_package_dir_path(userid_t user,
221 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800222 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800223 return StringPrintf("%s/%s",
224 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700225}
226
Calin Juravle114f0812017-03-08 19:05:07 -0800227std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600228 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000229}
230
Calin Juravle114f0812017-03-08 19:05:07 -0800231std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800232 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600233 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000234}
235
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700236std::string create_data_dalvik_cache_path() {
237 return "/data/dalvik-cache";
238}
239
Calin Juravle114f0812017-03-08 19:05:07 -0800240// Keep profile paths in sync with ActivityThread and LoadedApk.
241const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700242const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800243const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700244
Calin Juravle3760ad32017-07-27 16:31:55 -0700245// Gets the parent directory and the file name for the given secondary dex path.
246// Returns true on success, false on failure (if the dex_path does not have the expected
247// structure).
248static bool get_secondary_dex_location(const std::string& dex_path,
249 std::string* out_dir_name, std::string* out_file_name) {
250 size_t dirIndex = dex_path.rfind('/');
251 if (dirIndex == std::string::npos) {
252 return false;
253 }
254 if (dirIndex == dex_path.size() - 1) {
255 return false;
256 }
257 *out_dir_name = dex_path.substr(0, dirIndex);
258 *out_file_name = dex_path.substr(dirIndex + 1);
259
260 return true;
261}
262
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800263std::string create_current_profile_path(userid_t user, const std::string& package_name,
264 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800265 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700266 // Secondary dex current profiles are stored next to the dex files under the oat folder.
267 std::string dex_dir;
268 std::string dex_name;
269 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
270 << "Unexpected dir structure for secondary dex " << location;
271 return StringPrintf("%s/oat/%s%s%s",
272 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
273 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800274 } else {
275 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800276 std::string profile_dir = create_primary_current_profile_package_dir_path(
277 user, package_name);
278 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800279 }
280}
281
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800282std::string create_reference_profile_path(const std::string& package_name,
283 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800284 if (is_secondary_dex) {
285 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700286 std::string dex_dir;
287 std::string dex_name;
288 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800289 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800290 return StringPrintf("%s/oat/%s%s",
291 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
292 } else {
293 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800294 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
295 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800296 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700297}
298
Calin Juravle29591732017-11-20 17:46:19 -0800299std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800300 const std::string& profile_name) {
301 std::string ref_profile = create_reference_profile_path(package, profile_name,
302 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800303 return ref_profile + SNAPSHOT_PROFILE_EXT;
304}
305
Jeff Sharkeye3637242015-04-08 20:56:42 -0700306std::vector<userid_t> get_known_users(const char* volume_uuid) {
307 std::vector<userid_t> users;
308
309 // We always have an owner
310 users.push_back(0);
311
312 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
313 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700314 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700315 // Unable to discover other users, but at least return owner
316 PLOG(ERROR) << "Failed to opendir " << path;
317 return users;
318 }
319
320 struct dirent* ent;
321 while ((ent = readdir(dir))) {
322 if (ent->d_type != DT_DIR) {
323 continue;
324 }
325
326 char* end;
327 userid_t user = strtol(ent->d_name, &end, 10);
328 if (*end == '\0' && user != 0) {
329 LOG(DEBUG) << "Found valid user " << user;
330 users.push_back(user);
331 }
332 }
333 closedir(dir);
334
335 return users;
336}
337
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700338int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700339 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700340 FTS *fts;
341 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700342 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700343 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700344 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700345 if (errno != ENOENT) {
346 PLOG(ERROR) << "Failed to fts_open " << path;
347 }
348 return -1;
349 }
Yi Kong954cf642018-07-17 16:16:24 -0700350 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700351 switch (p->fts_info) {
352 case FTS_D:
353 case FTS_DEFAULT:
354 case FTS_F:
355 case FTS_SL:
356 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700357 int32_t uid = p->fts_statp->st_uid;
358 int32_t gid = p->fts_statp->st_gid;
359 int32_t user_uid = multiuser_get_app_id(uid);
360 int32_t user_gid = multiuser_get_app_id(gid);
361 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
362 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
363 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
364 // Don't traverse inside or measure
365 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700366 break;
367 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700368 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700369 break;
370 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700371 if (exclude_gid != -1 && gid == exclude_gid) {
372 break;
373 }
374 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700375 break;
376 }
377 }
378 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700379#if MEASURE_DEBUG
380 if ((include_gid == -1) && (exclude_gid == -1)) {
381 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
382 } else {
383 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
384 << " exclude " << exclude_gid;
385 }
386#endif
387 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700388 return 0;
389}
390
Mike Lockwood94afecf2012-10-24 10:45:23 -0700391/**
392 * Checks whether the package name is valid. Returns -1 on error and
393 * 0 on success.
394 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700395bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700396 // This logic is borrowed from PackageParser.java
397 bool hasSep = false;
398 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700399
Jeff Sharkey367ace22017-03-07 22:12:03 -0700400 auto it = packageName.begin();
401 for (; it != packageName.end() && *it != '-'; it++) {
402 char c = *it;
403 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
404 front = false;
405 continue;
406 }
407 if (!front) {
408 if ((c >= '0' && c <= '9') || c == '_') {
409 continue;
410 }
411 }
412 if (c == '.') {
413 hasSep = true;
414 front = true;
415 continue;
416 }
417 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700418 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700419 }
420
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700421 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700422 LOG(WARNING) << "Missing separator in " << packageName;
423 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700424 }
425
Jeff Sharkey367ace22017-03-07 22:12:03 -0700426 for (; it != packageName.end(); it++) {
427 char c = *it;
428 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
429 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
430 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
431 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700432 }
433
Jeff Sharkey423e7462016-12-09 18:18:43 -0700434 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700435}
436
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100437static int _delete_dir_contents(DIR *d,
438 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700439{
440 int result = 0;
441 struct dirent *de;
442 int dfd;
443
444 dfd = dirfd(d);
445
446 if (dfd < 0) return -1;
447
448 while ((de = readdir(d))) {
449 const char *name = de->d_name;
450
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100451 /* check using the exclusion predicate, if provided */
452 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
453 continue;
454 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700455
456 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700457 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700458 DIR *subdir;
459
460 /* always skip "." and ".." */
461 if (name[0] == '.') {
462 if (name[1] == 0) continue;
463 if ((name[1] == '.') && (name[2] == 0)) continue;
464 }
465
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700466 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700467 if (subfd < 0) {
468 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
469 result = -1;
470 continue;
471 }
472 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700473 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700474 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
475 close(subfd);
476 result = -1;
477 continue;
478 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100479 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700480 result = -1;
481 }
482 closedir(subdir);
483 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
484 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
485 result = -1;
486 }
487 } else {
488 if (unlinkat(dfd, name, 0) < 0) {
489 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
490 result = -1;
491 }
492 }
493 }
494
495 return result;
496}
497
Calin Juravleb06f98a2016-03-28 15:11:01 +0100498int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700499 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700500}
501
Calin Juravleb06f98a2016-03-28 15:11:01 +0100502int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700503 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700504}
505
Mike Lockwood94afecf2012-10-24 10:45:23 -0700506int delete_dir_contents(const char *pathname,
507 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100508 int (*exclusion_predicate)(const char*, const int),
509 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700510{
511 int res = 0;
512 DIR *d;
513
514 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700515 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100516 if (ignore_if_missing && (errno == ENOENT)) {
517 return 0;
518 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700519 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
520 return -errno;
521 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100522 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700523 closedir(d);
524 if (also_delete_dir) {
525 if (rmdir(pathname)) {
526 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
527 res = -1;
528 }
529 }
530 return res;
531}
532
533int delete_dir_contents_fd(int dfd, const char *name)
534{
535 int fd, res;
536 DIR *d;
537
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700538 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700539 if (fd < 0) {
540 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
541 return -1;
542 }
543 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700544 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700545 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
546 close(fd);
547 return -1;
548 }
Yi Kong954cf642018-07-17 16:16:24 -0700549 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700550 closedir(d);
551 return res;
552}
553
Robin Lee60fd3fe2014-10-07 16:55:02 +0100554static int _copy_owner_permissions(int srcfd, int dstfd)
555{
556 struct stat st;
557 if (fstat(srcfd, &st) != 0) {
558 return -1;
559 }
560 if (fchmod(dstfd, st.st_mode) != 0) {
561 return -1;
562 }
563 return 0;
564}
565
566static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
567{
568 int result = 0;
569 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
570 ALOGE("_copy_dir_files failed to copy dir permissions\n");
571 }
572 if (fchown(ddfd, owner, group) != 0) {
573 ALOGE("_copy_dir_files failed to change dir owner\n");
574 }
575
576 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700577 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100578 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
579 return -1;
580 }
581 struct dirent *de;
582 while ((de = readdir(ds))) {
583 if (de->d_type != DT_REG) {
584 continue;
585 }
586
587 const char *name = de->d_name;
588 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
589 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
590 if (fsfd == -1 || fdfd == -1) {
591 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
592 } else {
593 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
594 ALOGE("Failed to change file permissions\n");
595 }
596 if (fchown(fdfd, owner, group) != 0) {
597 ALOGE("Failed to change file owner\n");
598 }
599
600 char buf[8192];
601 ssize_t size;
602 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
603 write(fdfd, buf, size);
604 }
605 if (size < 0) {
606 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
607 result = -1;
608 }
609 }
610 close(fdfd);
611 close(fsfd);
612 }
613
614 return result;
615}
616
617int copy_dir_files(const char *srcname,
618 const char *dstname,
619 uid_t owner,
620 uid_t group)
621{
622 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700623 DIR *ds = nullptr;
624 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100625
626 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700627 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100628 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
629 return -errno;
630 }
631
632 mkdir(dstname, 0600);
633 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700634 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100635 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
636 closedir(ds);
637 return -errno;
638 }
639
640 int sdfd = dirfd(ds);
641 int ddfd = dirfd(dd);
642 if (sdfd != -1 && ddfd != -1) {
643 res = _copy_dir_files(sdfd, ddfd, owner, group);
644 } else {
645 res = -errno;
646 }
647 closedir(dd);
648 closedir(ds);
649 return res;
650}
651
Jeff Sharkeya836c472017-04-02 23:29:30 -0600652int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600653 struct statvfs sfs;
654 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600655 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700656 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600657 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700658 return -1;
659 }
660}
661
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600662int get_path_inode(const std::string& path, ino_t *inode) {
663 struct stat buf;
664 memset(&buf, 0, sizeof(buf));
665 if (stat(path.c_str(), &buf) != 0) {
666 PLOG(WARNING) << "Failed to stat " << path;
667 return -1;
668 } else {
669 *inode = buf.st_ino;
670 return 0;
671 }
672}
673
674/**
675 * Write the inode of a specific child file into the given xattr on the
676 * parent directory. This allows you to find the child later, even if its
677 * name is encrypted.
678 */
679int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
680 ino_t inode = 0;
681 uint64_t inode_raw = 0;
682 auto path = StringPrintf("%s/%s", parent.c_str(), name);
683
684 if (get_path_inode(path, &inode) != 0) {
685 // Path probably doesn't exist yet; ignore
686 return 0;
687 }
688
689 // Check to see if already set correctly
690 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
691 if (inode_raw == inode) {
692 // Already set correctly; skip writing
693 return 0;
694 } else {
695 PLOG(WARNING) << "Mismatched inode value; found " << inode
696 << " on disk but marked value was " << inode_raw << "; overwriting";
697 }
698 }
699
700 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600701 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600702 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
703 return -1;
704 } else {
705 return 0;
706 }
707}
708
709/**
710 * Read the inode of a specific child file from the given xattr on the
711 * parent directory. Returns a currently valid path for that child, which
712 * might have an encrypted name.
713 */
714std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
715 ino_t inode = 0;
716 uint64_t inode_raw = 0;
717 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
718
719 // Lookup the inode value written earlier
720 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
721 inode = inode_raw;
722 }
723
724 // For testing purposes, rely on the inode when defined; this could be
725 // optimized to use access() in the future.
726 if (inode != 0) {
727 DIR* dir = opendir(parent.c_str());
728 if (dir == nullptr) {
729 PLOG(ERROR) << "Failed to opendir " << parent;
730 return fallback;
731 }
732
733 struct dirent* ent;
734 while ((ent = readdir(dir))) {
735 if (ent->d_ino == inode) {
736 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
737#if DEBUG_XATTRS
738 if (resolved != fallback) {
739 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
740 << " instead of " << fallback;
741 }
742#endif
743 closedir(dir);
744 return resolved;
745 }
746 }
747 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
748 closedir(dir);
749 return fallback;
750 } else {
751 return fallback;
752 }
753}
754
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900755void remove_path_xattr(const std::string& path, const char* inode_xattr) {
756 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
757 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
758 }
759}
760
Mike Lockwood94afecf2012-10-24 10:45:23 -0700761/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100762 * Validate that the path is valid in the context of the provided directory.
763 * The path is allowed to have at most one subdirectory and no indirections
764 * to top level directories (i.e. have "..").
765 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600766static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
767 // Argument sanity checking
768 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
769 || dir.find("..") != std::string::npos) {
770 LOG(ERROR) << "Invalid directory " << dir;
771 return -1;
772 }
773 if (path.find("..") != std::string::npos) {
774 LOG(ERROR) << "Invalid path " << path;
775 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100776 }
777
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600778 if (path.compare(0, dir.size(), dir) != 0) {
779 // Common case, path isn't under directory
780 return -1;
781 }
782
783 // Count number of subdirectories
784 auto pos = path.find('/', dir.size());
785 int count = 0;
786 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600787 auto next = path.find('/', pos + 1);
788 if (next > pos + 1) {
789 count++;
790 }
791 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600792 }
793
794 if (count > maxSubdirs) {
795 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100796 return -1;
797 }
798
799 return 0;
800}
801
802/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700803 * Checks whether a path points to a system app (.apk file). Returns 0
804 * if it is a system app or -1 if it is not.
805 */
806int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600807 std::string path_ = path;
808 for (const auto& dir : android_system_dirs) {
809 if (validate_path(dir, path, 1) == 0) {
810 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700811 }
812 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700813 return -1;
814}
815
Calin Juravle114f0812017-03-08 19:05:07 -0800816bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -0700817 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -0800818 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
819
Calin Juravle3760ad32017-07-27 16:31:55 -0700820 // Empty paths are not allowed.
821 if (dex_path.empty()) { return false; }
822 // First character should always be '/'. No relative paths.
823 if (dex_path[0] != '/') { return false; }
824 // The last character should not be '/'.
825 if (dex_path[dex_path.size() - 1] == '/') { return false; }
826 // There should be no '.' after the directory marker.
827 if (dex_path.find("/.") != std::string::npos) { return false; }
828 // The path should be at most PKG_PATH_MAX long.
829 if (dex_path.size() > PKG_PATH_MAX) { return false; }
830
Calin Juravle7d765462017-09-04 15:57:10 -0700831 // The dex_path should be under the app data directory.
832 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -0700833 ? create_data_user_ce_package_path(
834 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
835 : create_data_user_de_package_path(
836 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -0700837
Calin Juravle7d765462017-09-04 15:57:10 -0700838 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
839 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
840 // If that's the case, attempt to validate against the user data link.
841 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
842 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
843 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
844 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -0700845 return false;
846 }
Calin Juravle42451c02017-01-17 14:43:25 -0800847 }
Calin Juravle3760ad32017-07-27 16:31:55 -0700848
849 // If we got here we have a valid path.
850 return true;
Calin Juravle42451c02017-01-17 14:43:25 -0800851}
852
Mike Lockwood94afecf2012-10-24 10:45:23 -0700853/**
Narayan Kamathd845c962015-06-04 13:20:27 +0100854 * Check whether path points to a valid path for an APK file. The path must
855 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
856 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
857 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700858 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600859static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
860 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600861 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600862 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600863 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600864 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600865 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600866 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600867 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600868 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
869 // Rewrite the path as if it were on internal storage, and test that
870 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
871 if (end != std::string::npos) {
872 auto modified = path;
873 modified.replace(0, end + 1, android_data_dir);
874 return validate_apk_path_internal(modified, maxSubdirs);
875 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700876 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600877 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700878}
879
Narayan Kamathd845c962015-06-04 13:20:27 +0100880int validate_apk_path(const char* path) {
881 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
882}
883
884int validate_apk_path_subdirs(const char* path) {
885 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
886}
887
Robin Lee095c7632014-04-25 15:05:19 +0100888int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +0100889 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +0100890 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
891 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +0100892
893 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600894 auto path = create_data_misc_legacy_path(userid);
895 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +0100896}
Andreas Gampe02d0de52015-11-11 20:43:16 -0800897
898int wait_child(pid_t pid)
899{
900 int status;
901 pid_t got_pid;
902
903 while (1) {
904 got_pid = waitpid(pid, &status, 0);
905 if (got_pid == -1 && errno == EINTR) {
906 printf("waitpid interrupted, retrying\n");
907 } else {
908 break;
909 }
910 }
911 if (got_pid != pid) {
912 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
913 (int) pid, (int) got_pid, strerror(errno));
914 return 1;
915 }
916
917 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
918 return 0;
919 } else {
920 return status; /* always nonzero */
921 }
922}
923
Calin Juravle42451c02017-01-17 14:43:25 -0800924/**
925 * Prepare an app cache directory, which offers to fix-up the GID and
926 * directory mode flags during a platform upgrade.
927 * The app cache directory path will be 'parent'/'name'.
928 */
929int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
930 uid_t uid, gid_t gid) {
931 auto path = StringPrintf("%s/%s", parent.c_str(), name);
932 struct stat st;
933 if (stat(path.c_str(), &st) != 0) {
934 if (errno == ENOENT) {
935 // This is fine, just create it
936 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
937 PLOG(ERROR) << "Failed to prepare " << path;
938 return -1;
939 } else {
940 return 0;
941 }
942 } else {
943 PLOG(ERROR) << "Failed to stat " << path;
944 return -1;
945 }
946 }
947
948 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
949 if (st.st_uid != uid) {
950 // Mismatched UID is real trouble; we can't recover
951 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
952 << " but expected " << uid;
953 return -1;
954 } else if (st.st_gid == gid && actual_mode == target_mode) {
955 // Everything looks good!
956 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600957 } else {
958 // Mismatched GID/mode is recoverable; fall through to update
959 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -0700960 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -0800961 }
962
963 // Directory is owned correctly, but GID or mode mismatch means it's
964 // probably a platform upgrade so we need to fix them
965 FTS *fts;
966 FTSENT *p;
967 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700968 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -0800969 PLOG(ERROR) << "Failed to fts_open " << path;
970 return -1;
971 }
Yi Kong954cf642018-07-17 16:16:24 -0700972 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -0800973 switch (p->fts_info) {
974 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600975 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800976 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
977 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -0700978 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -0800979 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600980 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800981 PLOG(WARNING) << "Failed to chown " << p->fts_path;
982 }
983 break;
984 case FTS_SL:
985 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600986 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800987 PLOG(WARNING) << "Failed to chown " << p->fts_path;
988 }
989 break;
990 }
991 }
992 fts_close(fts);
993 return 0;
994}
995
Calin Juravlee61189e2018-01-23 19:54:11 -0800996// Collect all non empty profiles from the given directory and puts then into profile_paths.
997// The profiles are identified based on PROFILE_EXT extension.
998// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
999// It returns true if there were no errors at all, and false otherwise.
1000static bool collect_profiles(DIR* d,
1001 const std::string& current_path,
1002 std::vector<std::string>* profiles_paths) {
1003 int32_t dir_fd = dirfd(d);
1004 if (dir_fd < 0) {
1005 return false;
1006 }
1007
1008 bool result = true;
1009 struct dirent* dir_entry;
1010 while ((dir_entry = readdir(d))) {
1011 std::string name = dir_entry->d_name;
1012 std::string local_path = current_path + "/" + name;
1013
1014 if (dir_entry->d_type == DT_REG) {
1015 // Check if this is a non empty profile file.
1016 if (EndsWith(name, PROFILE_EXT)) {
1017 struct stat st;
1018 if (stat(local_path.c_str(), &st) != 0) {
1019 PLOG(WARNING) << "Cannot stat local path " << local_path;
1020 result = false;
1021 continue;
1022 } else if (st.st_size > 0) {
1023 profiles_paths->push_back(local_path);
1024 }
1025 }
1026 } else if (dir_entry->d_type == DT_DIR) {
1027 // always skip "." and ".."
1028 if (name == "." || name == "..") {
1029 continue;
1030 }
1031
1032 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1033 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1034 if (subdir_fd < 0) {
1035 PLOG(WARNING) << "Could not open dir path " << local_path;
1036 result = false;
1037 continue;
1038 }
1039
Mathieu Chartier89883e32018-11-01 11:39:00 -07001040 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001041 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001042 PLOG(WARNING) << "Could not open dir path " << local_path;
1043 result = false;
1044 continue;
1045 }
1046 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1047 result = result && new_result;
1048 if (closedir(subdir) != 0) {
1049 PLOG(WARNING) << "Could not close dir path " << local_path;
1050 }
1051 }
1052 }
1053
1054 return result;
1055}
1056
1057bool collect_profiles(std::vector<std::string>* profiles_paths) {
1058 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001059 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001060 return false;
1061 } else {
1062 return collect_profiles(d, android_profiles_dir, profiles_paths);
1063 }
1064}
1065
Andreas Gampe02d0de52015-11-11 20:43:16 -08001066} // namespace installd
1067} // namespace android