blob: c21fae5e83f8f1e0793d1e77460ac874c9d51065 [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>
Andreas Gampe02d0de52015-11-11 20:43:16 -080029#include <android-base/stringprintf.h>
30#include <cutils/fs.h>
Jeff Sharkey871a8f22017-02-21 18:30:28 -070031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080033#include <private/android_filesystem_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070034
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include "globals.h" // extern variables.
36
37#ifndef LOG_TAG
38#define LOG_TAG "installd"
39#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060040
Jeff Sharkey9a998f42016-07-14 18:16:22 -060041#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070042
Jeff Sharkeyc03de092015-04-07 18:14:05 -070043using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070044
Andreas Gampe02d0de52015-11-11 20:43:16 -080045namespace android {
46namespace installd {
47
Jeff Sharkeyc03de092015-04-07 18:14:05 -070048/**
49 * Check that given string is valid filename, and that it attempts no
50 * parent or child directory traversal.
51 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070052bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070053 if (name.empty() || (name == ".") || (name == "..")
54 || (name.find('/') != std::string::npos)) {
55 return false;
56 } else {
57 return true;
58 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070059}
60
Calin Juravle6a1648e2016-02-01 12:12:16 +000061static void check_package_name(const char* package_name) {
62 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070063 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000064}
65
Mike Lockwood94afecf2012-10-24 10:45:23 -070066/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -070067 * Create the path name where package app contents should be stored for
68 * the given volume UUID and package name. An empty UUID is assumed to
69 * be internal storage.
70 */
71std::string create_data_app_package_path(const char* volume_uuid,
72 const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000073 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070074 return StringPrintf("%s/%s",
75 create_data_app_path(volume_uuid).c_str(), package_name);
76}
77
78/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070079 * Create the path name where package data should be stored for the given
80 * volume UUID, package name, and user ID. An empty UUID is assumed to be
81 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070082 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -060083std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -070084 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000085 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070086 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -060087 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
88}
89
90std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
91 const char* package_name, ino_t ce_data_inode) {
92 // For testing purposes, rely on the inode when defined; this could be
93 // optimized to use access() in the future.
94 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
95 if (ce_data_inode != 0) {
96 auto user_path = create_data_user_ce_path(volume_uuid, user);
97 DIR* dir = opendir(user_path.c_str());
98 if (dir == nullptr) {
99 PLOG(ERROR) << "Failed to opendir " << user_path;
100 return fallback;
101 }
102
103 struct dirent* ent;
104 while ((ent = readdir(dir))) {
105 if (ent->d_ino == ce_data_inode) {
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600106 auto resolved = StringPrintf("%s/%s", user_path.c_str(), ent->d_name);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600107#if DEBUG_XATTRS
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600108 if (resolved != fallback) {
109 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
110 << " instead of " << fallback;
111 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600112#endif
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600113 closedir(dir);
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600114 return resolved;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600115 }
116 }
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600117 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600118 closedir(dir);
119 return fallback;
120 } else {
121 return fallback;
122 }
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700123}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700124
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800125std::string create_data_user_de_package_path(const char* volume_uuid,
126 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000127 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800128 return StringPrintf("%s/%s",
129 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
130}
131
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700132std::string create_data_path(const char* volume_uuid) {
133 if (volume_uuid == nullptr) {
134 return "/data";
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700135 } else if (!strcmp(volume_uuid, "TEST")) {
136 CHECK(property_get_bool("ro.debuggable", false));
137 return "/data/local/tmp";
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700138 } else {
139 CHECK(is_valid_filename(volume_uuid));
140 return StringPrintf("/mnt/expand/%s", volume_uuid);
141 }
142}
143
Mike Lockwood94afecf2012-10-24 10:45:23 -0700144/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700145 * Create the path name for app data.
146 */
147std::string create_data_app_path(const char* volume_uuid) {
148 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
149}
150
151/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700152 * Create the path name for user data for a certain userid.
cjbao75d4e572017-04-12 00:12:24 +0800153 * Keep same implementation as vold to minimize path walking overhead
Mike Lockwood94afecf2012-10-24 10:45:23 -0700154 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600155std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700156 std::string data(create_data_path(volume_uuid));
cjbao75d4e572017-04-12 00:12:24 +0800157 if (volume_uuid == nullptr && userid == 0) {
158 std::string legacy = StringPrintf("%s/data", data.c_str());
159 struct stat sb;
160 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
161 /* /data/data is dir, return /data/data for legacy system */
162 return legacy;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700163 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700164 }
cjbao75d4e572017-04-12 00:12:24 +0800165 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700166}
167
168/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800169 * Create the path name for device encrypted user data for a certain userid.
170 */
171std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
172 std::string data(create_data_path(volume_uuid));
173 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
174}
175
176/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700177 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700178 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700179std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
180 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700181}
182
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700183std::string create_data_media_obb_path(const char* volume_uuid, const char* package_name) {
184 return StringPrintf("%s/media/obb/%s", create_data_path(volume_uuid).c_str(), package_name);
185}
186
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700187std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
188 const char* data_type, const char* package_name) {
189 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
190 data_type, package_name);
191}
192
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600193std::string create_data_misc_legacy_path(userid_t userid) {
194 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
195}
196
Calin Juravle114f0812017-03-08 19:05:07 -0800197std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600198 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000199}
200
Calin Juravle114f0812017-03-08 19:05:07 -0800201std::string create_primary_current_profile_package_dir_path(userid_t user,
202 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800203 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800204 return StringPrintf("%s/%s",
205 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700206}
207
Calin Juravle114f0812017-03-08 19:05:07 -0800208std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600209 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000210}
211
Calin Juravle114f0812017-03-08 19:05:07 -0800212std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800213 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600214 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000215}
216
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700217std::string create_data_dalvik_cache_path() {
218 return "/data/dalvik-cache";
219}
220
Calin Juravle114f0812017-03-08 19:05:07 -0800221// Keep profile paths in sync with ActivityThread and LoadedApk.
222const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700223const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle114f0812017-03-08 19:05:07 -0800224const std::string PRIMARY_PROFILE_NAME = "primary" + PROFILE_EXT;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700225
Calin Juravle3760ad32017-07-27 16:31:55 -0700226// Gets the parent directory and the file name for the given secondary dex path.
227// Returns true on success, false on failure (if the dex_path does not have the expected
228// structure).
229static bool get_secondary_dex_location(const std::string& dex_path,
230 std::string* out_dir_name, std::string* out_file_name) {
231 size_t dirIndex = dex_path.rfind('/');
232 if (dirIndex == std::string::npos) {
233 return false;
234 }
235 if (dirIndex == dex_path.size() - 1) {
236 return false;
237 }
238 *out_dir_name = dex_path.substr(0, dirIndex);
239 *out_file_name = dex_path.substr(dirIndex + 1);
240
241 return true;
242}
243
Calin Juravle114f0812017-03-08 19:05:07 -0800244std::string create_current_profile_path(userid_t user, const std::string& location,
245 bool is_secondary_dex) {
246 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700247 // Secondary dex current profiles are stored next to the dex files under the oat folder.
248 std::string dex_dir;
249 std::string dex_name;
250 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
251 << "Unexpected dir structure for secondary dex " << location;
252 return StringPrintf("%s/oat/%s%s%s",
253 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
254 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800255 } else {
256 // Profiles for primary apks are under /data/misc/profiles/cur.
257 std::string profile_dir = create_primary_current_profile_package_dir_path(user, location);
258 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME.c_str());
259 }
260}
261
262std::string create_reference_profile_path(const std::string& location, bool is_secondary_dex) {
263 if (is_secondary_dex) {
264 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700265 std::string dex_dir;
266 std::string dex_name;
267 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800268 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800269 return StringPrintf("%s/oat/%s%s",
270 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
271 } else {
272 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
273 std::string profile_dir = create_primary_reference_profile_package_dir_path(location);
274 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME.c_str());
275 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700276}
277
Jeff Sharkeye3637242015-04-08 20:56:42 -0700278std::vector<userid_t> get_known_users(const char* volume_uuid) {
279 std::vector<userid_t> users;
280
281 // We always have an owner
282 users.push_back(0);
283
284 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
285 DIR* dir = opendir(path.c_str());
286 if (dir == NULL) {
287 // Unable to discover other users, but at least return owner
288 PLOG(ERROR) << "Failed to opendir " << path;
289 return users;
290 }
291
292 struct dirent* ent;
293 while ((ent = readdir(dir))) {
294 if (ent->d_type != DT_DIR) {
295 continue;
296 }
297
298 char* end;
299 userid_t user = strtol(ent->d_name, &end, 10);
300 if (*end == '\0' && user != 0) {
301 LOG(DEBUG) << "Found valid user " << user;
302 users.push_back(user);
303 }
304 }
305 closedir(dir);
306
307 return users;
308}
309
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700310int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700311 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700312 FTS *fts;
313 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700314 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700315 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700316 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700317 if (errno != ENOENT) {
318 PLOG(ERROR) << "Failed to fts_open " << path;
319 }
320 return -1;
321 }
322 while ((p = fts_read(fts)) != NULL) {
323 switch (p->fts_info) {
324 case FTS_D:
325 case FTS_DEFAULT:
326 case FTS_F:
327 case FTS_SL:
328 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700329 int32_t uid = p->fts_statp->st_uid;
330 int32_t gid = p->fts_statp->st_gid;
331 int32_t user_uid = multiuser_get_app_id(uid);
332 int32_t user_gid = multiuser_get_app_id(gid);
333 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
334 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
335 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
336 // Don't traverse inside or measure
337 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700338 break;
339 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700340 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700341 break;
342 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700343 if (exclude_gid != -1 && gid == exclude_gid) {
344 break;
345 }
346 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700347 break;
348 }
349 }
350 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700351#if MEASURE_DEBUG
352 if ((include_gid == -1) && (exclude_gid == -1)) {
353 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
354 } else {
355 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
356 << " exclude " << exclude_gid;
357 }
358#endif
359 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700360 return 0;
361}
362
Mike Lockwood94afecf2012-10-24 10:45:23 -0700363/**
364 * Checks whether the package name is valid. Returns -1 on error and
365 * 0 on success.
366 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700367bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700368 // This logic is borrowed from PackageParser.java
369 bool hasSep = false;
370 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700371
Jeff Sharkey367ace22017-03-07 22:12:03 -0700372 auto it = packageName.begin();
373 for (; it != packageName.end() && *it != '-'; it++) {
374 char c = *it;
375 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
376 front = false;
377 continue;
378 }
379 if (!front) {
380 if ((c >= '0' && c <= '9') || c == '_') {
381 continue;
382 }
383 }
384 if (c == '.') {
385 hasSep = true;
386 front = true;
387 continue;
388 }
389 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700390 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700391 }
392
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700393 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700394 LOG(WARNING) << "Missing separator in " << packageName;
395 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700396 }
397
Jeff Sharkey367ace22017-03-07 22:12:03 -0700398 for (; it != packageName.end(); it++) {
399 char c = *it;
400 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
401 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
402 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
403 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700404 }
405
Jeff Sharkey423e7462016-12-09 18:18:43 -0700406 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700407}
408
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100409static int _delete_dir_contents(DIR *d,
410 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700411{
412 int result = 0;
413 struct dirent *de;
414 int dfd;
415
416 dfd = dirfd(d);
417
418 if (dfd < 0) return -1;
419
420 while ((de = readdir(d))) {
421 const char *name = de->d_name;
422
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100423 /* check using the exclusion predicate, if provided */
424 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
425 continue;
426 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700427
428 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700429 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700430 DIR *subdir;
431
432 /* always skip "." and ".." */
433 if (name[0] == '.') {
434 if (name[1] == 0) continue;
435 if ((name[1] == '.') && (name[2] == 0)) continue;
436 }
437
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700438 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700439 if (subfd < 0) {
440 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
441 result = -1;
442 continue;
443 }
444 subdir = fdopendir(subfd);
445 if (subdir == NULL) {
446 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
447 close(subfd);
448 result = -1;
449 continue;
450 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100451 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700452 result = -1;
453 }
454 closedir(subdir);
455 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
456 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
457 result = -1;
458 }
459 } else {
460 if (unlinkat(dfd, name, 0) < 0) {
461 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
462 result = -1;
463 }
464 }
465 }
466
467 return result;
468}
469
Calin Juravleb06f98a2016-03-28 15:11:01 +0100470int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
471 return delete_dir_contents(pathname.c_str(), 0, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700472}
473
Calin Juravleb06f98a2016-03-28 15:11:01 +0100474int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
475 return delete_dir_contents(pathname.c_str(), 1, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700476}
477
Mike Lockwood94afecf2012-10-24 10:45:23 -0700478int delete_dir_contents(const char *pathname,
479 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100480 int (*exclusion_predicate)(const char*, const int),
481 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700482{
483 int res = 0;
484 DIR *d;
485
486 d = opendir(pathname);
487 if (d == NULL) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100488 if (ignore_if_missing && (errno == ENOENT)) {
489 return 0;
490 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700491 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
492 return -errno;
493 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100494 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700495 closedir(d);
496 if (also_delete_dir) {
497 if (rmdir(pathname)) {
498 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
499 res = -1;
500 }
501 }
502 return res;
503}
504
505int delete_dir_contents_fd(int dfd, const char *name)
506{
507 int fd, res;
508 DIR *d;
509
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700510 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700511 if (fd < 0) {
512 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
513 return -1;
514 }
515 d = fdopendir(fd);
516 if (d == NULL) {
517 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
518 close(fd);
519 return -1;
520 }
521 res = _delete_dir_contents(d, 0);
522 closedir(d);
523 return res;
524}
525
Robin Lee60fd3fe2014-10-07 16:55:02 +0100526static int _copy_owner_permissions(int srcfd, int dstfd)
527{
528 struct stat st;
529 if (fstat(srcfd, &st) != 0) {
530 return -1;
531 }
532 if (fchmod(dstfd, st.st_mode) != 0) {
533 return -1;
534 }
535 return 0;
536}
537
538static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
539{
540 int result = 0;
541 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
542 ALOGE("_copy_dir_files failed to copy dir permissions\n");
543 }
544 if (fchown(ddfd, owner, group) != 0) {
545 ALOGE("_copy_dir_files failed to change dir owner\n");
546 }
547
548 DIR *ds = fdopendir(sdfd);
549 if (ds == NULL) {
550 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
551 return -1;
552 }
553 struct dirent *de;
554 while ((de = readdir(ds))) {
555 if (de->d_type != DT_REG) {
556 continue;
557 }
558
559 const char *name = de->d_name;
560 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
561 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
562 if (fsfd == -1 || fdfd == -1) {
563 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
564 } else {
565 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
566 ALOGE("Failed to change file permissions\n");
567 }
568 if (fchown(fdfd, owner, group) != 0) {
569 ALOGE("Failed to change file owner\n");
570 }
571
572 char buf[8192];
573 ssize_t size;
574 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
575 write(fdfd, buf, size);
576 }
577 if (size < 0) {
578 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
579 result = -1;
580 }
581 }
582 close(fdfd);
583 close(fsfd);
584 }
585
586 return result;
587}
588
589int copy_dir_files(const char *srcname,
590 const char *dstname,
591 uid_t owner,
592 uid_t group)
593{
594 int res = 0;
595 DIR *ds = NULL;
596 DIR *dd = NULL;
597
598 ds = opendir(srcname);
599 if (ds == NULL) {
600 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
601 return -errno;
602 }
603
604 mkdir(dstname, 0600);
605 dd = opendir(dstname);
606 if (dd == NULL) {
607 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
608 closedir(ds);
609 return -errno;
610 }
611
612 int sdfd = dirfd(ds);
613 int ddfd = dirfd(dd);
614 if (sdfd != -1 && ddfd != -1) {
615 res = _copy_dir_files(sdfd, ddfd, owner, group);
616 } else {
617 res = -errno;
618 }
619 closedir(dd);
620 closedir(ds);
621 return res;
622}
623
Jeff Sharkeya836c472017-04-02 23:29:30 -0600624int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600625 struct statvfs sfs;
626 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600627 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700628 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600629 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700630 return -1;
631 }
632}
633
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600634int get_path_inode(const std::string& path, ino_t *inode) {
635 struct stat buf;
636 memset(&buf, 0, sizeof(buf));
637 if (stat(path.c_str(), &buf) != 0) {
638 PLOG(WARNING) << "Failed to stat " << path;
639 return -1;
640 } else {
641 *inode = buf.st_ino;
642 return 0;
643 }
644}
645
646/**
647 * Write the inode of a specific child file into the given xattr on the
648 * parent directory. This allows you to find the child later, even if its
649 * name is encrypted.
650 */
651int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
652 ino_t inode = 0;
653 uint64_t inode_raw = 0;
654 auto path = StringPrintf("%s/%s", parent.c_str(), name);
655
656 if (get_path_inode(path, &inode) != 0) {
657 // Path probably doesn't exist yet; ignore
658 return 0;
659 }
660
661 // Check to see if already set correctly
662 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
663 if (inode_raw == inode) {
664 // Already set correctly; skip writing
665 return 0;
666 } else {
667 PLOG(WARNING) << "Mismatched inode value; found " << inode
668 << " on disk but marked value was " << inode_raw << "; overwriting";
669 }
670 }
671
672 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600673 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600674 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
675 return -1;
676 } else {
677 return 0;
678 }
679}
680
681/**
682 * Read the inode of a specific child file from the given xattr on the
683 * parent directory. Returns a currently valid path for that child, which
684 * might have an encrypted name.
685 */
686std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
687 ino_t inode = 0;
688 uint64_t inode_raw = 0;
689 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
690
691 // Lookup the inode value written earlier
692 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
693 inode = inode_raw;
694 }
695
696 // For testing purposes, rely on the inode when defined; this could be
697 // optimized to use access() in the future.
698 if (inode != 0) {
699 DIR* dir = opendir(parent.c_str());
700 if (dir == nullptr) {
701 PLOG(ERROR) << "Failed to opendir " << parent;
702 return fallback;
703 }
704
705 struct dirent* ent;
706 while ((ent = readdir(dir))) {
707 if (ent->d_ino == inode) {
708 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
709#if DEBUG_XATTRS
710 if (resolved != fallback) {
711 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
712 << " instead of " << fallback;
713 }
714#endif
715 closedir(dir);
716 return resolved;
717 }
718 }
719 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
720 closedir(dir);
721 return fallback;
722 } else {
723 return fallback;
724 }
725}
726
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900727void remove_path_xattr(const std::string& path, const char* inode_xattr) {
728 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
729 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
730 }
731}
732
Mike Lockwood94afecf2012-10-24 10:45:23 -0700733/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100734 * Validate that the path is valid in the context of the provided directory.
735 * The path is allowed to have at most one subdirectory and no indirections
736 * to top level directories (i.e. have "..").
737 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600738static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
739 // Argument sanity checking
740 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
741 || dir.find("..") != std::string::npos) {
742 LOG(ERROR) << "Invalid directory " << dir;
743 return -1;
744 }
745 if (path.find("..") != std::string::npos) {
746 LOG(ERROR) << "Invalid path " << path;
747 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100748 }
749
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600750 if (path.compare(0, dir.size(), dir) != 0) {
751 // Common case, path isn't under directory
752 return -1;
753 }
754
755 // Count number of subdirectories
756 auto pos = path.find('/', dir.size());
757 int count = 0;
758 while (pos != std::string::npos) {
759 pos = path.find('/', pos + 1);
760 count++;
761 }
762
763 if (count > maxSubdirs) {
764 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100765 return -1;
766 }
767
768 return 0;
769}
770
771/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700772 * Checks whether a path points to a system app (.apk file). Returns 0
773 * if it is a system app or -1 if it is not.
774 */
775int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600776 std::string path_ = path;
777 for (const auto& dir : android_system_dirs) {
778 if (validate_path(dir, path, 1) == 0) {
779 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700780 }
781 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700782 return -1;
783}
784
Calin Juravle114f0812017-03-08 19:05:07 -0800785bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravledd42e272017-09-11 11:50:36 -0700786 const char* volume_uuid, int uid, int storage_flag, bool validate_package_path) {
Calin Juravle42451c02017-01-17 14:43:25 -0800787 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
788
Calin Juravle3760ad32017-07-27 16:31:55 -0700789 // Empty paths are not allowed.
790 if (dex_path.empty()) { return false; }
791 // First character should always be '/'. No relative paths.
792 if (dex_path[0] != '/') { return false; }
793 // The last character should not be '/'.
794 if (dex_path[dex_path.size() - 1] == '/') { return false; }
795 // There should be no '.' after the directory marker.
796 if (dex_path.find("/.") != std::string::npos) { return false; }
797 // The path should be at most PKG_PATH_MAX long.
798 if (dex_path.size() > PKG_PATH_MAX) { return false; }
799
Calin Juravledd42e272017-09-11 11:50:36 -0700800 if (validate_package_path) {
801 // If we are asked to validate the package path check that
802 // the dex_path is under the app data directory.
803 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
804 ? create_data_user_ce_package_path(
805 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
806 : create_data_user_de_package_path(
807 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -0700808
Calin Juravledd42e272017-09-11 11:50:36 -0700809 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
810 return false;
811 }
Calin Juravle42451c02017-01-17 14:43:25 -0800812 }
Calin Juravle3760ad32017-07-27 16:31:55 -0700813
814 // If we got here we have a valid path.
815 return true;
Calin Juravle42451c02017-01-17 14:43:25 -0800816}
817
Mike Lockwood94afecf2012-10-24 10:45:23 -0700818/**
Narayan Kamathd845c962015-06-04 13:20:27 +0100819 * Check whether path points to a valid path for an APK file. The path must
820 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
821 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
822 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700823 */
Narayan Kamathd845c962015-06-04 13:20:27 +0100824static int validate_apk_path_internal(const char *path, int maxSubdirs) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600825 std::string path_ = path;
826 if (validate_path(android_app_dir, path_, maxSubdirs) == 0) {
827 return 0;
828 } else if (validate_path(android_app_private_dir, path_, maxSubdirs) == 0) {
829 return 0;
830 } else if (validate_path(android_app_ephemeral_dir, path_, maxSubdirs) == 0) {
831 return 0;
832 } else if (validate_path(android_asec_dir, path_, maxSubdirs) == 0) {
833 return 0;
834 } else if (validate_path(android_mnt_expand_dir, path_, std::max(maxSubdirs, 2)) == 0) {
835 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700836 } else {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700837 return -1;
838 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700839}
840
Narayan Kamathd845c962015-06-04 13:20:27 +0100841int validate_apk_path(const char* path) {
842 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
843}
844
845int validate_apk_path_subdirs(const char* path) {
846 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
847}
848
Robin Lee095c7632014-04-25 15:05:19 +0100849int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +0100850 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +0100851 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
852 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +0100853
854 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600855 auto path = create_data_misc_legacy_path(userid);
856 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +0100857}
Andreas Gampe02d0de52015-11-11 20:43:16 -0800858
859int wait_child(pid_t pid)
860{
861 int status;
862 pid_t got_pid;
863
864 while (1) {
865 got_pid = waitpid(pid, &status, 0);
866 if (got_pid == -1 && errno == EINTR) {
867 printf("waitpid interrupted, retrying\n");
868 } else {
869 break;
870 }
871 }
872 if (got_pid != pid) {
873 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
874 (int) pid, (int) got_pid, strerror(errno));
875 return 1;
876 }
877
878 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
879 return 0;
880 } else {
881 return status; /* always nonzero */
882 }
883}
884
Calin Juravle42451c02017-01-17 14:43:25 -0800885/**
886 * Prepare an app cache directory, which offers to fix-up the GID and
887 * directory mode flags during a platform upgrade.
888 * The app cache directory path will be 'parent'/'name'.
889 */
890int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
891 uid_t uid, gid_t gid) {
892 auto path = StringPrintf("%s/%s", parent.c_str(), name);
893 struct stat st;
894 if (stat(path.c_str(), &st) != 0) {
895 if (errno == ENOENT) {
896 // This is fine, just create it
897 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
898 PLOG(ERROR) << "Failed to prepare " << path;
899 return -1;
900 } else {
901 return 0;
902 }
903 } else {
904 PLOG(ERROR) << "Failed to stat " << path;
905 return -1;
906 }
907 }
908
909 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
910 if (st.st_uid != uid) {
911 // Mismatched UID is real trouble; we can't recover
912 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
913 << " but expected " << uid;
914 return -1;
915 } else if (st.st_gid == gid && actual_mode == target_mode) {
916 // Everything looks good!
917 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600918 } else {
919 // Mismatched GID/mode is recoverable; fall through to update
920 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -0700921 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -0800922 }
923
924 // Directory is owned correctly, but GID or mode mismatch means it's
925 // probably a platform upgrade so we need to fix them
926 FTS *fts;
927 FTSENT *p;
928 char *argv[] = { (char*) path.c_str(), nullptr };
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700929 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
Calin Juravle42451c02017-01-17 14:43:25 -0800930 PLOG(ERROR) << "Failed to fts_open " << path;
931 return -1;
932 }
933 while ((p = fts_read(fts)) != NULL) {
934 switch (p->fts_info) {
935 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600936 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800937 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
938 }
939 // Intentional fall through to also set GID
940 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600941 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800942 PLOG(WARNING) << "Failed to chown " << p->fts_path;
943 }
944 break;
945 case FTS_SL:
946 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600947 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800948 PLOG(WARNING) << "Failed to chown " << p->fts_path;
949 }
950 break;
951 }
952 }
953 fts_close(fts);
954 return 0;
955}
956
Andreas Gampe02d0de52015-11-11 20:43:16 -0800957} // namespace installd
958} // namespace android