blob: 4a38fa6b3b979724aef67e8bb8f6c2cbc6994dcf [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>
21#include <stdlib.h>
22#include <sys/stat.h>
23#include <sys/wait.h>
Jeff Sharkey9a998f42016-07-14 18:16:22 -060024#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080025
26#if defined(__APPLE__)
27#include <sys/mount.h>
28#else
29#include <sys/statfs.h>
30#endif
31
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080032#include <android-base/logging.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080033#include <android-base/stringprintf.h>
34#include <cutils/fs.h>
35#include <cutils/log.h>
36#include <private/android_filesystem_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070037
Andreas Gampe02d0de52015-11-11 20:43:16 -080038#include "globals.h" // extern variables.
39
40#ifndef LOG_TAG
41#define LOG_TAG "installd"
42#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060043
Mike Lockwood94afecf2012-10-24 10:45:23 -070044#define CACHE_NOISY(x) //x
Jeff Sharkey9a998f42016-07-14 18:16:22 -060045#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070046
Jeff Sharkeyc03de092015-04-07 18:14:05 -070047using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070048
Andreas Gampe02d0de52015-11-11 20:43:16 -080049namespace android {
50namespace installd {
51
Jeff Sharkeyc03de092015-04-07 18:14:05 -070052/**
53 * Check that given string is valid filename, and that it attempts no
54 * parent or child directory traversal.
55 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070056bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070057 if (name.empty() || (name == ".") || (name == "..")
58 || (name.find('/') != std::string::npos)) {
59 return false;
60 } else {
61 return true;
62 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070063}
64
Calin Juravle6a1648e2016-02-01 12:12:16 +000065static void check_package_name(const char* package_name) {
66 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070067 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000068}
69
Mike Lockwood94afecf2012-10-24 10:45:23 -070070/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -070071 * Create the path name where package app contents should be stored for
72 * the given volume UUID and package name. An empty UUID is assumed to
73 * be internal storage.
74 */
75std::string create_data_app_package_path(const char* volume_uuid,
76 const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000077 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070078 return StringPrintf("%s/%s",
79 create_data_app_path(volume_uuid).c_str(), package_name);
80}
81
82/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070083 * Create the path name where package data should be stored for the given
84 * volume UUID, package name, and user ID. An empty UUID is assumed to be
85 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070086 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -060087std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -070088 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000089 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070090 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -060091 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
92}
93
94std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
95 const char* package_name, ino_t ce_data_inode) {
96 // For testing purposes, rely on the inode when defined; this could be
97 // optimized to use access() in the future.
98 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
99 if (ce_data_inode != 0) {
100 auto user_path = create_data_user_ce_path(volume_uuid, user);
101 DIR* dir = opendir(user_path.c_str());
102 if (dir == nullptr) {
103 PLOG(ERROR) << "Failed to opendir " << user_path;
104 return fallback;
105 }
106
107 struct dirent* ent;
108 while ((ent = readdir(dir))) {
109 if (ent->d_ino == ce_data_inode) {
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600110 auto resolved = StringPrintf("%s/%s", user_path.c_str(), ent->d_name);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600111#if DEBUG_XATTRS
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600112 if (resolved != fallback) {
113 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
114 << " instead of " << fallback;
115 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600116#endif
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600117 closedir(dir);
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600118 return resolved;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600119 }
120 }
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600121 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600122 closedir(dir);
123 return fallback;
124 } else {
125 return fallback;
126 }
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700127}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700128
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800129std::string create_data_user_de_package_path(const char* volume_uuid,
130 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000131 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800132 return StringPrintf("%s/%s",
133 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
134}
135
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700136int create_pkg_path(char path[PKG_PATH_MAX], const char *pkgname,
137 const char *postfix, userid_t userid) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700138 if (!is_valid_package_name(pkgname)) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700139 path[0] = '\0';
Mike Lockwood94afecf2012-10-24 10:45:23 -0700140 return -1;
141 }
142
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600143 std::string _tmp(create_data_user_ce_package_path(nullptr, userid, pkgname) + postfix);
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700144 const char* tmp = _tmp.c_str();
145 if (strlen(tmp) >= PKG_PATH_MAX) {
146 path[0] = '\0';
147 return -1;
148 } else {
149 strcpy(path, tmp);
150 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700151 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700152}
153
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700154std::string create_data_path(const char* volume_uuid) {
155 if (volume_uuid == nullptr) {
156 return "/data";
157 } 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.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700172 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600173std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700174 std::string data(create_data_path(volume_uuid));
175 if (volume_uuid == nullptr) {
176 if (userid == 0) {
177 return StringPrintf("%s/data", data.c_str());
178 } else {
179 return StringPrintf("%s/user/%u", data.c_str(), userid);
180 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700181 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700182 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700183 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700184}
185
186/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800187 * Create the path name for device encrypted user data for a certain userid.
188 */
189std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
190 std::string data(create_data_path(volume_uuid));
191 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
192}
193
194/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700195 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700196 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700197std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
198 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700199}
200
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600201std::string create_data_misc_legacy_path(userid_t userid) {
202 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
203}
204
Calin Juravle6a1648e2016-02-01 12:12:16 +0000205std::string create_data_user_profiles_path(userid_t userid) {
206 return StringPrintf("%s/cur/%u", android_profiles_dir.path, userid);
207}
208
209std::string create_data_user_profile_package_path(userid_t user, const char* package_name) {
210 check_package_name(package_name);
211 return StringPrintf("%s/%s",create_data_user_profiles_path(user).c_str(), package_name);
212}
213
214std::string create_data_ref_profile_package_path(const char* package_name) {
215 check_package_name(package_name);
216 return StringPrintf("%s/ref/%s", android_profiles_dir.path, package_name);
217}
218
Jeff Sharkeye3637242015-04-08 20:56:42 -0700219std::vector<userid_t> get_known_users(const char* volume_uuid) {
220 std::vector<userid_t> users;
221
222 // We always have an owner
223 users.push_back(0);
224
225 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
226 DIR* dir = opendir(path.c_str());
227 if (dir == NULL) {
228 // Unable to discover other users, but at least return owner
229 PLOG(ERROR) << "Failed to opendir " << path;
230 return users;
231 }
232
233 struct dirent* ent;
234 while ((ent = readdir(dir))) {
235 if (ent->d_type != DT_DIR) {
236 continue;
237 }
238
239 char* end;
240 userid_t user = strtol(ent->d_name, &end, 10);
241 if (*end == '\0' && user != 0) {
242 LOG(DEBUG) << "Found valid user " << user;
243 users.push_back(user);
244 }
245 }
246 closedir(dir);
247
248 return users;
249}
250
Mike Lockwood94afecf2012-10-24 10:45:23 -0700251int create_move_path(char path[PKG_PATH_MAX],
252 const char* pkgname,
253 const char* leaf,
Andreas Gampe02d0de52015-11-11 20:43:16 -0800254 userid_t userid ATTRIBUTE_UNUSED)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700255{
256 if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
257 >= PKG_PATH_MAX) {
258 return -1;
259 }
260
261 sprintf(path, "%s%s%s/%s", android_data_dir.path, PRIMARY_USER_PREFIX, pkgname, leaf);
262 return 0;
263}
264
265/**
266 * Checks whether the package name is valid. Returns -1 on error and
267 * 0 on success.
268 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700269bool is_valid_package_name(const std::string& packageName) {
270 const char* pkgname = packageName.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700271 const char *x = pkgname;
272 int alpha = -1;
273
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700274 if (strlen(pkgname) > PKG_NAME_MAX) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700275 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700276 }
277
Mike Lockwood94afecf2012-10-24 10:45:23 -0700278 while (*x) {
279 if (isalnum(*x) || (*x == '_')) {
280 /* alphanumeric or underscore are fine */
281 } else if (*x == '.') {
282 if ((x == pkgname) || (x[1] == '.') || (x[1] == 0)) {
283 /* periods must not be first, last, or doubled */
284 ALOGE("invalid package name '%s'\n", pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700285 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700286 }
287 } else if (*x == '-') {
288 /* Suffix -X is fine to let versioning of packages.
289 But whatever follows should be alphanumeric.*/
290 alpha = 1;
291 } else {
292 /* anything not A-Z, a-z, 0-9, _, or . is invalid */
293 ALOGE("invalid package name '%s'\n", pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700294 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700295 }
296
297 x++;
298 }
299
300 if (alpha == 1) {
301 // Skip current character
302 x++;
303 while (*x) {
304 if (!isalnum(*x)) {
305 ALOGE("invalid package name '%s' should include only numbers after -\n", pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700306 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700307 }
308 x++;
309 }
310 }
311
Jeff Sharkey423e7462016-12-09 18:18:43 -0700312 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700313}
314
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100315static int _delete_dir_contents(DIR *d,
316 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700317{
318 int result = 0;
319 struct dirent *de;
320 int dfd;
321
322 dfd = dirfd(d);
323
324 if (dfd < 0) return -1;
325
326 while ((de = readdir(d))) {
327 const char *name = de->d_name;
328
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100329 /* check using the exclusion predicate, if provided */
330 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
331 continue;
332 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700333
334 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700335 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700336 DIR *subdir;
337
338 /* always skip "." and ".." */
339 if (name[0] == '.') {
340 if (name[1] == 0) continue;
341 if ((name[1] == '.') && (name[2] == 0)) continue;
342 }
343
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700344 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700345 if (subfd < 0) {
346 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
347 result = -1;
348 continue;
349 }
350 subdir = fdopendir(subfd);
351 if (subdir == NULL) {
352 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
353 close(subfd);
354 result = -1;
355 continue;
356 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100357 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700358 result = -1;
359 }
360 closedir(subdir);
361 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
362 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
363 result = -1;
364 }
365 } else {
366 if (unlinkat(dfd, name, 0) < 0) {
367 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
368 result = -1;
369 }
370 }
371 }
372
373 return result;
374}
375
Calin Juravleb06f98a2016-03-28 15:11:01 +0100376int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
377 return delete_dir_contents(pathname.c_str(), 0, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700378}
379
Calin Juravleb06f98a2016-03-28 15:11:01 +0100380int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
381 return delete_dir_contents(pathname.c_str(), 1, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700382}
383
Mike Lockwood94afecf2012-10-24 10:45:23 -0700384int delete_dir_contents(const char *pathname,
385 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100386 int (*exclusion_predicate)(const char*, const int),
387 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700388{
389 int res = 0;
390 DIR *d;
391
392 d = opendir(pathname);
393 if (d == NULL) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100394 if (ignore_if_missing && (errno == ENOENT)) {
395 return 0;
396 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700397 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
398 return -errno;
399 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100400 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700401 closedir(d);
402 if (also_delete_dir) {
403 if (rmdir(pathname)) {
404 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
405 res = -1;
406 }
407 }
408 return res;
409}
410
411int delete_dir_contents_fd(int dfd, const char *name)
412{
413 int fd, res;
414 DIR *d;
415
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700416 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700417 if (fd < 0) {
418 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
419 return -1;
420 }
421 d = fdopendir(fd);
422 if (d == NULL) {
423 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
424 close(fd);
425 return -1;
426 }
427 res = _delete_dir_contents(d, 0);
428 closedir(d);
429 return res;
430}
431
Robin Lee60fd3fe2014-10-07 16:55:02 +0100432static int _copy_owner_permissions(int srcfd, int dstfd)
433{
434 struct stat st;
435 if (fstat(srcfd, &st) != 0) {
436 return -1;
437 }
438 if (fchmod(dstfd, st.st_mode) != 0) {
439 return -1;
440 }
441 return 0;
442}
443
444static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
445{
446 int result = 0;
447 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
448 ALOGE("_copy_dir_files failed to copy dir permissions\n");
449 }
450 if (fchown(ddfd, owner, group) != 0) {
451 ALOGE("_copy_dir_files failed to change dir owner\n");
452 }
453
454 DIR *ds = fdopendir(sdfd);
455 if (ds == NULL) {
456 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
457 return -1;
458 }
459 struct dirent *de;
460 while ((de = readdir(ds))) {
461 if (de->d_type != DT_REG) {
462 continue;
463 }
464
465 const char *name = de->d_name;
466 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
467 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
468 if (fsfd == -1 || fdfd == -1) {
469 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
470 } else {
471 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
472 ALOGE("Failed to change file permissions\n");
473 }
474 if (fchown(fdfd, owner, group) != 0) {
475 ALOGE("Failed to change file owner\n");
476 }
477
478 char buf[8192];
479 ssize_t size;
480 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
481 write(fdfd, buf, size);
482 }
483 if (size < 0) {
484 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
485 result = -1;
486 }
487 }
488 close(fdfd);
489 close(fsfd);
490 }
491
492 return result;
493}
494
495int copy_dir_files(const char *srcname,
496 const char *dstname,
497 uid_t owner,
498 uid_t group)
499{
500 int res = 0;
501 DIR *ds = NULL;
502 DIR *dd = NULL;
503
504 ds = opendir(srcname);
505 if (ds == NULL) {
506 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
507 return -errno;
508 }
509
510 mkdir(dstname, 0600);
511 dd = opendir(dstname);
512 if (dd == NULL) {
513 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
514 closedir(ds);
515 return -errno;
516 }
517
518 int sdfd = dirfd(ds);
519 int ddfd = dirfd(dd);
520 if (sdfd != -1 && ddfd != -1) {
521 res = _copy_dir_files(sdfd, ddfd, owner, group);
522 } else {
523 res = -errno;
524 }
525 closedir(dd);
526 closedir(ds);
527 return res;
528}
529
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700530int64_t data_disk_free(const std::string& data_path)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700531{
532 struct statfs sfs;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700533 if (statfs(data_path.c_str(), &sfs) == 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700534 return sfs.f_bavail * sfs.f_bsize;
535 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700536 PLOG(ERROR) << "Couldn't statfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700537 return -1;
538 }
539}
540
541cache_t* start_cache_collection()
542{
543 cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
544 return cache;
545}
546
547#define CACHE_BLOCK_SIZE (512*1024)
548
549static void* _cache_malloc(cache_t* cache, size_t len)
550{
551 len = (len+3)&~3;
552 if (len > (CACHE_BLOCK_SIZE/2)) {
553 // It doesn't make sense to try to put this allocation into one
554 // of our blocks, because it is so big. Instead, make a new dedicated
555 // block for it.
556 int8_t* res = (int8_t*)malloc(len+sizeof(void*));
557 if (res == NULL) {
558 return NULL;
559 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600560 CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %zu", res, len));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700561 // Link it into our list of blocks, not disrupting the current one.
562 if (cache->memBlocks == NULL) {
563 *(void**)res = NULL;
564 cache->memBlocks = res;
565 } else {
566 *(void**)res = *(void**)cache->memBlocks;
567 *(void**)cache->memBlocks = res;
568 }
569 return res + sizeof(void*);
570 }
571 int8_t* res = cache->curMemBlockAvail;
572 int8_t* nextPos = res + len;
573 if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
Jeff Sharkey19803802015-04-07 12:44:51 -0700574 int8_t* newBlock = (int8_t*) malloc(CACHE_BLOCK_SIZE);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700575 if (newBlock == NULL) {
576 return NULL;
577 }
578 CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
579 *(void**)newBlock = cache->memBlocks;
580 cache->memBlocks = newBlock;
581 res = cache->curMemBlockAvail = newBlock + sizeof(void*);
582 cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
583 nextPos = res + len;
584 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600585 CACHE_NOISY(ALOGI("cache_malloc: ret %p size %zu, block=%p, nextPos=%p",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700586 res, len, cache->memBlocks, nextPos));
587 cache->curMemBlockAvail = nextPos;
588 return res;
589}
590
591static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
592{
593 // This isn't really a realloc, but it is good enough for our purposes here.
594 void* alloc = _cache_malloc(cache, len);
595 if (alloc != NULL && cur != NULL) {
596 memcpy(alloc, cur, origLen < len ? origLen : len);
597 }
598 return alloc;
599}
600
601static void _inc_num_cache_collected(cache_t* cache)
602{
603 cache->numCollected++;
604 if ((cache->numCollected%20000) == 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700605 ALOGI("Collected cache so far: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700606 cache->numDirs, cache->numFiles);
607 }
608}
609
610static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
611{
612 size_t nameLen = strlen(name);
613 cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
614 if (dir != NULL) {
615 dir->parent = parent;
616 dir->childCount = 0;
617 dir->hiddenCount = 0;
618 dir->deleted = 0;
619 strcpy(dir->name, name);
620 if (cache->numDirs >= cache->availDirs) {
621 size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
622 cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
623 cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
624 if (newDirs == NULL) {
625 ALOGE("Failure growing cache dirs array for %s\n", name);
626 return NULL;
627 }
628 cache->availDirs = newAvail;
629 cache->dirs = newDirs;
630 }
631 cache->dirs[cache->numDirs] = dir;
632 cache->numDirs++;
633 if (parent != NULL) {
634 parent->childCount++;
635 }
636 _inc_num_cache_collected(cache);
637 } else {
638 ALOGE("Failure allocating cache_dir_t for %s\n", name);
639 }
640 return dir;
641}
642
643static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
644 const char *name)
645{
646 size_t nameLen = strlen(name);
647 cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
648 if (file != NULL) {
649 file->dir = dir;
650 file->modTime = modTime;
651 strcpy(file->name, name);
652 if (cache->numFiles >= cache->availFiles) {
653 size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
654 cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
655 cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
656 if (newFiles == NULL) {
657 ALOGE("Failure growing cache file array for %s\n", name);
658 return NULL;
659 }
660 cache->availFiles = newAvail;
661 cache->files = newFiles;
662 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600663 CACHE_NOISY(ALOGI("Setting file %p at position %zd in array %p", file,
Mike Lockwood94afecf2012-10-24 10:45:23 -0700664 cache->numFiles, cache->files));
665 cache->files[cache->numFiles] = file;
666 cache->numFiles++;
667 dir->childCount++;
668 _inc_num_cache_collected(cache);
669 } else {
670 ALOGE("Failure allocating cache_file_t for %s\n", name);
671 }
672 return file;
673}
674
675static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
676 DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
677{
678 struct dirent *de;
679 cache_dir_t* cacheDir = NULL;
680 int dfd;
681
682 CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
683 parentDir, dirName, dir, pathBase));
684
685 dfd = dirfd(dir);
686
687 if (dfd < 0) return 0;
688
689 // Sub-directories always get added to the data structure, so if they
690 // are empty we will know about them to delete them later.
691 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
692
693 while ((de = readdir(dir))) {
694 const char *name = de->d_name;
695
696 if (de->d_type == DT_DIR) {
697 int subfd;
698 DIR *subdir;
699
700 /* always skip "." and ".." */
701 if (name[0] == '.') {
702 if (name[1] == 0) continue;
703 if ((name[1] == '.') && (name[2] == 0)) continue;
704 }
705
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700706 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700707 if (subfd < 0) {
708 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
709 continue;
710 }
711 subdir = fdopendir(subfd);
712 if (subdir == NULL) {
713 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
714 close(subfd);
715 continue;
716 }
717 if (cacheDir == NULL) {
718 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
719 }
720 if (cacheDir != NULL) {
721 // Update pathBase for the new path... this may change dirName
722 // if that is also pointing to the path, but we are done with it
723 // now.
724 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
725 CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
726 if (finallen < pathAvailLen) {
727 _add_cache_files(cache, cacheDir, name, subdir, pathBase,
728 pathPos+finallen, pathAvailLen-finallen);
729 } else {
730 // Whoops, the final path is too long! We'll just delete
731 // this directory.
732 ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
733 name, pathBase);
734 _delete_dir_contents(subdir, NULL);
735 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
736 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
737 }
738 }
739 }
740 closedir(subdir);
741 } else if (de->d_type == DT_REG) {
742 // Skip files that start with '.'; they will be deleted if
743 // their entire directory is deleted. This allows for metadata
744 // like ".nomedia" to remain in the directory until the entire
745 // directory is deleted.
746 if (cacheDir == NULL) {
747 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
748 }
749 if (name[0] == '.') {
750 cacheDir->hiddenCount++;
751 continue;
752 }
753 if (cacheDir != NULL) {
754 // Build final full path for file... this may change dirName
755 // if that is also pointing to the path, but we are done with it
756 // now.
757 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
758 CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
759 if (finallen < pathAvailLen) {
760 struct stat s;
761 if (stat(pathBase, &s) >= 0) {
762 _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
763 } else {
764 ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
765 if (unlink(pathBase) < 0) {
766 ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
767 }
768 }
769 } else {
770 // Whoops, the final path is too long! We'll just delete
771 // this file.
772 ALOGW("Cache file %s truncated in path %s; deleting\n",
773 name, pathBase);
774 if (unlinkat(dfd, name, 0) < 0) {
775 *pathPos = 0;
776 ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
777 strerror(errno));
778 }
779 }
780 }
781 } else {
782 cacheDir->hiddenCount++;
783 }
784 }
785 return 0;
786}
787
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600788int get_path_inode(const std::string& path, ino_t *inode) {
789 struct stat buf;
790 memset(&buf, 0, sizeof(buf));
791 if (stat(path.c_str(), &buf) != 0) {
792 PLOG(WARNING) << "Failed to stat " << path;
793 return -1;
794 } else {
795 *inode = buf.st_ino;
796 return 0;
797 }
798}
799
800/**
801 * Write the inode of a specific child file into the given xattr on the
802 * parent directory. This allows you to find the child later, even if its
803 * name is encrypted.
804 */
805int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
806 ino_t inode = 0;
807 uint64_t inode_raw = 0;
808 auto path = StringPrintf("%s/%s", parent.c_str(), name);
809
810 if (get_path_inode(path, &inode) != 0) {
811 // Path probably doesn't exist yet; ignore
812 return 0;
813 }
814
815 // Check to see if already set correctly
816 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
817 if (inode_raw == inode) {
818 // Already set correctly; skip writing
819 return 0;
820 } else {
821 PLOG(WARNING) << "Mismatched inode value; found " << inode
822 << " on disk but marked value was " << inode_raw << "; overwriting";
823 }
824 }
825
826 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600827 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600828 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
829 return -1;
830 } else {
831 return 0;
832 }
833}
834
835/**
836 * Read the inode of a specific child file from the given xattr on the
837 * parent directory. Returns a currently valid path for that child, which
838 * might have an encrypted name.
839 */
840std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
841 ino_t inode = 0;
842 uint64_t inode_raw = 0;
843 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
844
845 // Lookup the inode value written earlier
846 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
847 inode = inode_raw;
848 }
849
850 // For testing purposes, rely on the inode when defined; this could be
851 // optimized to use access() in the future.
852 if (inode != 0) {
853 DIR* dir = opendir(parent.c_str());
854 if (dir == nullptr) {
855 PLOG(ERROR) << "Failed to opendir " << parent;
856 return fallback;
857 }
858
859 struct dirent* ent;
860 while ((ent = readdir(dir))) {
861 if (ent->d_ino == inode) {
862 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
863#if DEBUG_XATTRS
864 if (resolved != fallback) {
865 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
866 << " instead of " << fallback;
867 }
868#endif
869 closedir(dir);
870 return resolved;
871 }
872 }
873 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
874 closedir(dir);
875 return fallback;
876 } else {
877 return fallback;
878 }
879}
880
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600881void add_cache_files(cache_t* cache, const std::string& data_path) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700882 DIR *d;
883 struct dirent *de;
884 char dirname[PATH_MAX];
885
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600886 const char* basepath = data_path.c_str();
887 CACHE_NOISY(ALOGI("add_cache_files: basepath=%s\n", basepath));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700888
889 d = opendir(basepath);
890 if (d == NULL) {
891 return;
892 }
893
894 while ((de = readdir(d))) {
895 if (de->d_type == DT_DIR) {
896 DIR* subdir;
897 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700898
899 /* always skip "." and ".." */
900 if (name[0] == '.') {
901 if (name[1] == 0) continue;
902 if ((name[1] == '.') && (name[2] == 0)) continue;
903 }
904
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600905 auto parent = StringPrintf("%s/%s", basepath, name);
906 auto resolved = read_path_inode(parent, "cache", kXattrInodeCache);
907 strcpy(dirname, resolved.c_str());
Mike Lockwood94afecf2012-10-24 10:45:23 -0700908 CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600909
Mike Lockwood94afecf2012-10-24 10:45:23 -0700910 subdir = opendir(dirname);
911 if (subdir != NULL) {
912 size_t dirnameLen = strlen(dirname);
913 _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
914 PATH_MAX - dirnameLen);
915 closedir(subdir);
916 }
917 }
918 }
919
920 closedir(d);
921}
922
923static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
924{
925 char *pos = path;
926 if (dir->parent != NULL) {
927 pos = create_dir_path(path, dir->parent);
928 }
929 // Note that we don't need to worry about going beyond the buffer,
930 // since when we were constructing the cache entries our maximum
931 // buffer size for full paths was PATH_MAX.
932 strcpy(pos, dir->name);
933 pos += strlen(pos);
934 *pos = '/';
935 pos++;
936 *pos = 0;
937 return pos;
938}
939
940static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
941{
942 if (dir->parent != NULL) {
943 create_dir_path(path, dir);
944 ALOGI("DEL DIR %s\n", path);
945 if (dir->hiddenCount <= 0) {
946 if (rmdir(path)) {
947 ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
948 return;
949 }
950 } else {
951 // The directory contains hidden files so we need to delete
952 // them along with the directory itself.
953 if (delete_dir_contents(path, 1, NULL)) {
954 return;
955 }
956 }
957 dir->parent->childCount--;
958 dir->deleted = 1;
959 if (dir->parent->childCount <= 0) {
960 delete_cache_dir(path, dir->parent);
961 }
962 } else if (dir->hiddenCount > 0) {
963 // This is a root directory, but it has hidden files. Get rid of
964 // all of those files, but not the directory itself.
965 create_dir_path(path, dir);
966 ALOGI("DEL CONTENTS %s\n", path);
967 delete_dir_contents(path, 0, NULL);
968 }
969}
970
971static int cache_modtime_sort(const void *lhsP, const void *rhsP)
972{
973 const cache_file_t *lhs = *(const cache_file_t**)lhsP;
974 const cache_file_t *rhs = *(const cache_file_t**)rhsP;
975 return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
976}
977
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700978void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700979{
980 size_t i;
981 int skip = 0;
982 char path[PATH_MAX];
983
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700984 ALOGI("Collected cache files: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700985 cache->numDirs, cache->numFiles);
986
987 CACHE_NOISY(ALOGI("Sorting files..."));
988 qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
989 cache_modtime_sort);
990
991 CACHE_NOISY(ALOGI("Cleaning empty directories..."));
992 for (i=cache->numDirs; i>0; i--) {
993 cache_dir_t* dir = cache->dirs[i-1];
994 if (dir->childCount <= 0 && !dir->deleted) {
995 delete_cache_dir(path, dir);
996 }
997 }
998
999 CACHE_NOISY(ALOGI("Trimming files..."));
1000 for (i=0; i<cache->numFiles; i++) {
1001 skip++;
1002 if (skip > 10) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001003 if (data_disk_free(data_path) > free_size) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001004 return;
1005 }
1006 skip = 0;
1007 }
1008 cache_file_t* file = cache->files[i];
1009 strcpy(create_dir_path(path, file->dir), file->name);
1010 ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
1011 if (unlink(path) < 0) {
1012 ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
1013 }
1014 file->dir->childCount--;
1015 if (file->dir->childCount <= 0) {
1016 delete_cache_dir(path, file->dir);
1017 }
1018 }
1019}
1020
1021void finish_cache_collection(cache_t* cache)
1022{
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -07001023 CACHE_NOISY(size_t i;)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001024
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001025 CACHE_NOISY(ALOGI("clear_cache_files: %zu dirs, %zu files\n", cache->numDirs, cache->numFiles));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001026 CACHE_NOISY(
1027 for (i=0; i<cache->numDirs; i++) {
1028 cache_dir_t* dir = cache->dirs[i];
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001029 ALOGI("dir #%zu: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001030 })
1031 CACHE_NOISY(
1032 for (i=0; i<cache->numFiles; i++) {
1033 cache_file_t* file = cache->files[i];
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001034 ALOGI("file #%zu: %p %s time=%d dir=%p\n", i, file, file->name,
Mike Lockwood94afecf2012-10-24 10:45:23 -07001035 (int)file->modTime, file->dir);
1036 })
1037 void* block = cache->memBlocks;
1038 while (block != NULL) {
1039 void* nextBlock = *(void**)block;
1040 CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
1041 free(block);
1042 block = nextBlock;
1043 }
1044 free(cache);
1045}
1046
1047/**
Calin Juravlec597b6d2014-08-19 17:43:05 +01001048 * Validate that the path is valid in the context of the provided directory.
1049 * The path is allowed to have at most one subdirectory and no indirections
1050 * to top level directories (i.e. have "..").
1051 */
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001052static int validate_path(const dir_rec_t* dir, const char* path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001053 size_t dir_len = dir->len;
1054 const char* subdir = strchr(path + dir_len, '/');
1055
1056 // Only allow the path to have at most one subdirectory.
1057 if (subdir != NULL) {
1058 ++subdir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001059 if ((--maxSubdirs == 0) && strchr(subdir, '/') != NULL) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001060 ALOGE("invalid apk path '%s' (subdir?)\n", path);
1061 return -1;
1062 }
1063 }
1064
1065 // Directories can't have a period directly after the directory markers to prevent "..".
1066 if ((path[dir_len] == '.') || ((subdir != NULL) && (*subdir == '.'))) {
1067 ALOGE("invalid apk path '%s' (trickery)\n", path);
1068 return -1;
1069 }
1070
1071 return 0;
1072}
1073
1074/**
Mike Lockwood94afecf2012-10-24 10:45:23 -07001075 * 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 */
1078int validate_system_app_path(const char* path) {
1079 size_t i;
1080
1081 for (i = 0; i < android_system_dirs.count; i++) {
1082 const size_t dir_len = android_system_dirs.dirs[i].len;
1083 if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001084 return validate_path(android_system_dirs.dirs + i, path, 1);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001085 }
1086 }
1087
1088 return -1;
1089}
1090
1091/**
1092 * Get the contents of a environment variable that contains a path. Caller
1093 * owns the string that is inserted into the directory record. Returns
1094 * 0 on success and -1 on error.
1095 */
1096int get_path_from_env(dir_rec_t* rec, const char* var) {
1097 const char* path = getenv(var);
1098 int ret = get_path_from_string(rec, path);
1099 if (ret < 0) {
1100 ALOGW("Problem finding value for environment variable %s\n", var);
1101 }
1102 return ret;
1103}
1104
1105/**
1106 * Puts the string into the record as a directory. Appends '/' to the end
1107 * of all paths. Caller owns the string that is inserted into the directory
1108 * record. A null value will result in an error.
1109 *
1110 * Returns 0 on success and -1 on error.
1111 */
1112int get_path_from_string(dir_rec_t* rec, const char* path) {
1113 if (path == NULL) {
1114 return -1;
1115 } else {
1116 const size_t path_len = strlen(path);
1117 if (path_len <= 0) {
1118 return -1;
1119 }
1120
1121 // Make sure path is absolute.
1122 if (path[0] != '/') {
1123 return -1;
1124 }
1125
1126 if (path[path_len - 1] == '/') {
1127 // Path ends with a forward slash. Make our own copy.
1128
1129 rec->path = strdup(path);
1130 if (rec->path == NULL) {
1131 return -1;
1132 }
1133
1134 rec->len = path_len;
1135 } else {
1136 // Path does not end with a slash. Generate a new string.
1137 char *dst;
1138
1139 // Add space for slash and terminating null.
1140 size_t dst_size = path_len + 2;
1141
Jeff Sharkey19803802015-04-07 12:44:51 -07001142 rec->path = (char*) malloc(dst_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001143 if (rec->path == NULL) {
1144 return -1;
1145 }
1146
1147 dst = rec->path;
1148
1149 if (append_and_increment(&dst, path, &dst_size) < 0
1150 || append_and_increment(&dst, "/", &dst_size)) {
1151 ALOGE("Error canonicalizing path");
1152 return -1;
1153 }
1154
1155 rec->len = dst - rec->path;
1156 }
1157 }
1158 return 0;
1159}
1160
1161int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
1162 dst->len = src->len + strlen(suffix);
1163 const size_t dstSize = dst->len + 1;
1164 dst->path = (char*) malloc(dstSize);
1165
1166 if (dst->path == NULL
1167 || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
1168 != (ssize_t) dst->len) {
1169 ALOGE("Could not allocate memory to hold appended path; aborting\n");
1170 return -1;
1171 }
1172
1173 return 0;
1174}
1175
1176/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001177 * Check whether path points to a valid path for an APK file. The path must
1178 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1179 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1180 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001181 */
Narayan Kamathd845c962015-06-04 13:20:27 +01001182static int validate_apk_path_internal(const char *path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001183 const dir_rec_t* dir = NULL;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001184 if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001185 dir = &android_app_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001186 } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001187 dir = &android_app_private_dir;
Todd Kennedy5c1a9102015-11-23 15:18:10 -08001188 } else if (!strncmp(path, android_app_ephemeral_dir.path, android_app_ephemeral_dir.len)) {
1189 dir = &android_app_ephemeral_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001190 } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001191 dir = &android_asec_dir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001192 } else if (!strncmp(path, android_mnt_expand_dir.path, android_mnt_expand_dir.len)) {
1193 dir = &android_mnt_expand_dir;
Narayan Kamathd845c962015-06-04 13:20:27 +01001194 if (maxSubdirs < 2) {
1195 maxSubdirs = 2;
1196 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001197 } else {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001198 return -1;
1199 }
1200
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001201 return validate_path(dir, path, maxSubdirs);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001202}
1203
Narayan Kamathd845c962015-06-04 13:20:27 +01001204int validate_apk_path(const char* path) {
1205 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
1206}
1207
1208int validate_apk_path_subdirs(const char* path) {
1209 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
1210}
1211
Mike Lockwood94afecf2012-10-24 10:45:23 -07001212int append_and_increment(char** dst, const char* src, size_t* dst_size) {
1213 ssize_t ret = strlcpy(*dst, src, *dst_size);
1214 if (ret < 0 || (size_t) ret >= *dst_size) {
1215 return -1;
1216 }
1217 *dst += ret;
1218 *dst_size -= ret;
1219 return 0;
1220}
1221
Jeff Sharkey19803802015-04-07 12:44:51 -07001222char *build_string2(const char *s1, const char *s2) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001223 if (s1 == NULL || s2 == NULL) return NULL;
1224
1225 int len_s1 = strlen(s1);
1226 int len_s2 = strlen(s2);
1227 int len = len_s1 + len_s2 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001228 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001229 if (result == NULL) return NULL;
1230
1231 strcpy(result, s1);
1232 strcpy(result + len_s1, s2);
1233
1234 return result;
1235}
1236
Jeff Sharkey19803802015-04-07 12:44:51 -07001237char *build_string3(const char *s1, const char *s2, const char *s3) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001238 if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
1239
1240 int len_s1 = strlen(s1);
1241 int len_s2 = strlen(s2);
1242 int len_s3 = strlen(s3);
1243 int len = len_s1 + len_s2 + len_s3 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001244 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001245 if (result == NULL) return NULL;
1246
1247 strcpy(result, s1);
1248 strcpy(result + len_s1, s2);
1249 strcpy(result + len_s1 + len_s2, s3);
1250
1251 return result;
1252}
1253
Robin Lee095c7632014-04-25 15:05:19 +01001254int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001255 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001256 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1257 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001258
1259 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001260 auto path = create_data_misc_legacy_path(userid);
1261 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001262}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001263
1264int wait_child(pid_t pid)
1265{
1266 int status;
1267 pid_t got_pid;
1268
1269 while (1) {
1270 got_pid = waitpid(pid, &status, 0);
1271 if (got_pid == -1 && errno == EINTR) {
1272 printf("waitpid interrupted, retrying\n");
1273 } else {
1274 break;
1275 }
1276 }
1277 if (got_pid != pid) {
1278 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1279 (int) pid, (int) got_pid, strerror(errno));
1280 return 1;
1281 }
1282
1283 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1284 return 0;
1285 } else {
1286 return status; /* always nonzero */
1287 }
1288}
1289
1290} // namespace installd
1291} // namespace android