blob: 878fb2daa81b394b773ffc76f9646f9e27c91e09 [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>
24
25#if defined(__APPLE__)
26#include <sys/mount.h>
27#else
28#include <sys/statfs.h>
29#endif
30
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080031#include <android-base/logging.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080032#include <android-base/stringprintf.h>
33#include <cutils/fs.h>
34#include <cutils/log.h>
35#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
Mike Lockwood94afecf2012-10-24 10:45:23 -070042#define CACHE_NOISY(x) //x
43
Jeff Sharkeyc03de092015-04-07 18:14:05 -070044using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070045
Andreas Gampe02d0de52015-11-11 20:43:16 -080046namespace android {
47namespace installd {
48
Jeff Sharkeyc03de092015-04-07 18:14:05 -070049/**
50 * Check that given string is valid filename, and that it attempts no
51 * parent or child directory traversal.
52 */
53static bool is_valid_filename(const std::string& name) {
54 if (name.empty() || (name == ".") || (name == "..")
55 || (name.find('/') != std::string::npos)) {
56 return false;
57 } else {
58 return true;
59 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070060}
61
Calin Juravle6a1648e2016-02-01 12:12:16 +000062static void check_package_name(const char* package_name) {
63 CHECK(is_valid_filename(package_name));
64 CHECK(is_valid_package_name(package_name) == 0);
65}
66
Mike Lockwood94afecf2012-10-24 10:45:23 -070067/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -070068 * Create the path name where package app contents should be stored for
69 * the given volume UUID and package name. An empty UUID is assumed to
70 * be internal storage.
71 */
72std::string create_data_app_package_path(const char* volume_uuid,
73 const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000074 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070075 return StringPrintf("%s/%s",
76 create_data_app_path(volume_uuid).c_str(), package_name);
77}
78
79/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070080 * Create the path name where package data should be stored for the given
81 * volume UUID, package name, and user ID. An empty UUID is assumed to be
82 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070083 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -060084std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -070085 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000086 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070087 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -060088 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
89}
90
91std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
92 const char* package_name, ino_t ce_data_inode) {
93 // For testing purposes, rely on the inode when defined; this could be
94 // optimized to use access() in the future.
95 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
96 if (ce_data_inode != 0) {
97 auto user_path = create_data_user_ce_path(volume_uuid, user);
98 DIR* dir = opendir(user_path.c_str());
99 if (dir == nullptr) {
100 PLOG(ERROR) << "Failed to opendir " << user_path;
101 return fallback;
102 }
103
104 struct dirent* ent;
105 while ((ent = readdir(dir))) {
106 if (ent->d_ino == ce_data_inode) {
107 closedir(dir);
108 return StringPrintf("%s/%s", user_path.c_str(), ent->d_name);
109 }
110 }
111 LOG(WARNING) << "Failed to find inode " << ce_data_inode << " for package " << package_name;
112 closedir(dir);
113 return fallback;
114 } else {
115 return fallback;
116 }
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700117}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700118
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800119std::string create_data_user_de_package_path(const char* volume_uuid,
120 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000121 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800122 return StringPrintf("%s/%s",
123 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
124}
125
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700126int create_pkg_path(char path[PKG_PATH_MAX], const char *pkgname,
127 const char *postfix, userid_t userid) {
128 if (is_valid_package_name(pkgname) != 0) {
129 path[0] = '\0';
Mike Lockwood94afecf2012-10-24 10:45:23 -0700130 return -1;
131 }
132
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600133 std::string _tmp(create_data_user_ce_package_path(nullptr, userid, pkgname) + postfix);
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700134 const char* tmp = _tmp.c_str();
135 if (strlen(tmp) >= PKG_PATH_MAX) {
136 path[0] = '\0';
137 return -1;
138 } else {
139 strcpy(path, tmp);
140 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700141 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700142}
143
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700144std::string create_data_path(const char* volume_uuid) {
145 if (volume_uuid == nullptr) {
146 return "/data";
147 } else {
148 CHECK(is_valid_filename(volume_uuid));
149 return StringPrintf("/mnt/expand/%s", volume_uuid);
150 }
151}
152
Mike Lockwood94afecf2012-10-24 10:45:23 -0700153/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700154 * Create the path name for app data.
155 */
156std::string create_data_app_path(const char* volume_uuid) {
157 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
158}
159
160/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700161 * Create the path name for user data for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700162 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600163std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700164 std::string data(create_data_path(volume_uuid));
165 if (volume_uuid == nullptr) {
166 if (userid == 0) {
167 return StringPrintf("%s/data", data.c_str());
168 } else {
169 return StringPrintf("%s/user/%u", data.c_str(), userid);
170 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700171 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700172 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700173 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700174}
175
176/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800177 * Create the path name for device encrypted user data for a certain userid.
178 */
179std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
180 std::string data(create_data_path(volume_uuid));
181 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
182}
183
184/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700185 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700186 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700187std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
188 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700189}
190
Calin Juravle6a1648e2016-02-01 12:12:16 +0000191std::string create_data_user_profiles_path(userid_t userid) {
192 return StringPrintf("%s/cur/%u", android_profiles_dir.path, userid);
193}
194
195std::string create_data_user_profile_package_path(userid_t user, const char* package_name) {
196 check_package_name(package_name);
197 return StringPrintf("%s/%s",create_data_user_profiles_path(user).c_str(), package_name);
198}
199
200std::string create_data_ref_profile_package_path(const char* package_name) {
201 check_package_name(package_name);
202 return StringPrintf("%s/ref/%s", android_profiles_dir.path, package_name);
203}
204
Jeff Sharkeye3637242015-04-08 20:56:42 -0700205std::vector<userid_t> get_known_users(const char* volume_uuid) {
206 std::vector<userid_t> users;
207
208 // We always have an owner
209 users.push_back(0);
210
211 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
212 DIR* dir = opendir(path.c_str());
213 if (dir == NULL) {
214 // Unable to discover other users, but at least return owner
215 PLOG(ERROR) << "Failed to opendir " << path;
216 return users;
217 }
218
219 struct dirent* ent;
220 while ((ent = readdir(dir))) {
221 if (ent->d_type != DT_DIR) {
222 continue;
223 }
224
225 char* end;
226 userid_t user = strtol(ent->d_name, &end, 10);
227 if (*end == '\0' && user != 0) {
228 LOG(DEBUG) << "Found valid user " << user;
229 users.push_back(user);
230 }
231 }
232 closedir(dir);
233
234 return users;
235}
236
Robin Lee095c7632014-04-25 15:05:19 +0100237/**
238 * Create the path name for config for a certain userid.
239 * Returns 0 on success, and -1 on failure.
240 */
241int create_user_config_path(char path[PATH_MAX], userid_t userid) {
242 if (snprintf(path, PATH_MAX, "%s%d", "/data/misc/user/", userid) > PATH_MAX) {
243 return -1;
244 }
245 return 0;
246}
247
Mike Lockwood94afecf2012-10-24 10:45:23 -0700248int create_move_path(char path[PKG_PATH_MAX],
249 const char* pkgname,
250 const char* leaf,
Andreas Gampe02d0de52015-11-11 20:43:16 -0800251 userid_t userid ATTRIBUTE_UNUSED)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700252{
253 if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
254 >= PKG_PATH_MAX) {
255 return -1;
256 }
257
258 sprintf(path, "%s%s%s/%s", android_data_dir.path, PRIMARY_USER_PREFIX, pkgname, leaf);
259 return 0;
260}
261
262/**
263 * Checks whether the package name is valid. Returns -1 on error and
264 * 0 on success.
265 */
266int is_valid_package_name(const char* pkgname) {
267 const char *x = pkgname;
268 int alpha = -1;
269
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700270 if (strlen(pkgname) > PKG_NAME_MAX) {
271 return -1;
272 }
273
Mike Lockwood94afecf2012-10-24 10:45:23 -0700274 while (*x) {
275 if (isalnum(*x) || (*x == '_')) {
276 /* alphanumeric or underscore are fine */
277 } else if (*x == '.') {
278 if ((x == pkgname) || (x[1] == '.') || (x[1] == 0)) {
279 /* periods must not be first, last, or doubled */
280 ALOGE("invalid package name '%s'\n", pkgname);
281 return -1;
282 }
283 } else if (*x == '-') {
284 /* Suffix -X is fine to let versioning of packages.
285 But whatever follows should be alphanumeric.*/
286 alpha = 1;
287 } else {
288 /* anything not A-Z, a-z, 0-9, _, or . is invalid */
289 ALOGE("invalid package name '%s'\n", pkgname);
290 return -1;
291 }
292
293 x++;
294 }
295
296 if (alpha == 1) {
297 // Skip current character
298 x++;
299 while (*x) {
300 if (!isalnum(*x)) {
301 ALOGE("invalid package name '%s' should include only numbers after -\n", pkgname);
302 return -1;
303 }
304 x++;
305 }
306 }
307
308 return 0;
309}
310
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100311static int _delete_dir_contents(DIR *d,
312 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700313{
314 int result = 0;
315 struct dirent *de;
316 int dfd;
317
318 dfd = dirfd(d);
319
320 if (dfd < 0) return -1;
321
322 while ((de = readdir(d))) {
323 const char *name = de->d_name;
324
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100325 /* check using the exclusion predicate, if provided */
326 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
327 continue;
328 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700329
330 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700331 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700332 DIR *subdir;
333
334 /* always skip "." and ".." */
335 if (name[0] == '.') {
336 if (name[1] == 0) continue;
337 if ((name[1] == '.') && (name[2] == 0)) continue;
338 }
339
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700340 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700341 if (subfd < 0) {
342 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
343 result = -1;
344 continue;
345 }
346 subdir = fdopendir(subfd);
347 if (subdir == NULL) {
348 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
349 close(subfd);
350 result = -1;
351 continue;
352 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100353 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700354 result = -1;
355 }
356 closedir(subdir);
357 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
358 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
359 result = -1;
360 }
361 } else {
362 if (unlinkat(dfd, name, 0) < 0) {
363 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
364 result = -1;
365 }
366 }
367 }
368
369 return result;
370}
371
Calin Juravleb06f98a2016-03-28 15:11:01 +0100372int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
373 return delete_dir_contents(pathname.c_str(), 0, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700374}
375
Calin Juravleb06f98a2016-03-28 15:11:01 +0100376int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
377 return delete_dir_contents(pathname.c_str(), 1, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700378}
379
Mike Lockwood94afecf2012-10-24 10:45:23 -0700380int delete_dir_contents(const char *pathname,
381 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100382 int (*exclusion_predicate)(const char*, const int),
383 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700384{
385 int res = 0;
386 DIR *d;
387
388 d = opendir(pathname);
389 if (d == NULL) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100390 if (ignore_if_missing && (errno == ENOENT)) {
391 return 0;
392 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700393 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
394 return -errno;
395 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100396 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700397 closedir(d);
398 if (also_delete_dir) {
399 if (rmdir(pathname)) {
400 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
401 res = -1;
402 }
403 }
404 return res;
405}
406
407int delete_dir_contents_fd(int dfd, const char *name)
408{
409 int fd, res;
410 DIR *d;
411
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700412 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700413 if (fd < 0) {
414 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
415 return -1;
416 }
417 d = fdopendir(fd);
418 if (d == NULL) {
419 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
420 close(fd);
421 return -1;
422 }
423 res = _delete_dir_contents(d, 0);
424 closedir(d);
425 return res;
426}
427
Robin Lee60fd3fe2014-10-07 16:55:02 +0100428static int _copy_owner_permissions(int srcfd, int dstfd)
429{
430 struct stat st;
431 if (fstat(srcfd, &st) != 0) {
432 return -1;
433 }
434 if (fchmod(dstfd, st.st_mode) != 0) {
435 return -1;
436 }
437 return 0;
438}
439
440static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
441{
442 int result = 0;
443 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
444 ALOGE("_copy_dir_files failed to copy dir permissions\n");
445 }
446 if (fchown(ddfd, owner, group) != 0) {
447 ALOGE("_copy_dir_files failed to change dir owner\n");
448 }
449
450 DIR *ds = fdopendir(sdfd);
451 if (ds == NULL) {
452 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
453 return -1;
454 }
455 struct dirent *de;
456 while ((de = readdir(ds))) {
457 if (de->d_type != DT_REG) {
458 continue;
459 }
460
461 const char *name = de->d_name;
462 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
463 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
464 if (fsfd == -1 || fdfd == -1) {
465 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
466 } else {
467 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
468 ALOGE("Failed to change file permissions\n");
469 }
470 if (fchown(fdfd, owner, group) != 0) {
471 ALOGE("Failed to change file owner\n");
472 }
473
474 char buf[8192];
475 ssize_t size;
476 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
477 write(fdfd, buf, size);
478 }
479 if (size < 0) {
480 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
481 result = -1;
482 }
483 }
484 close(fdfd);
485 close(fsfd);
486 }
487
488 return result;
489}
490
491int copy_dir_files(const char *srcname,
492 const char *dstname,
493 uid_t owner,
494 uid_t group)
495{
496 int res = 0;
497 DIR *ds = NULL;
498 DIR *dd = NULL;
499
500 ds = opendir(srcname);
501 if (ds == NULL) {
502 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
503 return -errno;
504 }
505
506 mkdir(dstname, 0600);
507 dd = opendir(dstname);
508 if (dd == NULL) {
509 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
510 closedir(ds);
511 return -errno;
512 }
513
514 int sdfd = dirfd(ds);
515 int ddfd = dirfd(dd);
516 if (sdfd != -1 && ddfd != -1) {
517 res = _copy_dir_files(sdfd, ddfd, owner, group);
518 } else {
519 res = -errno;
520 }
521 closedir(dd);
522 closedir(ds);
523 return res;
524}
525
Mike Lockwood94afecf2012-10-24 10:45:23 -0700526int lookup_media_dir(char basepath[PATH_MAX], const char *dir)
527{
528 DIR *d;
529 struct dirent *de;
530 struct stat s;
531 char* dirpos = basepath + strlen(basepath);
532
533 if ((*(dirpos-1)) != '/') {
534 *dirpos = '/';
535 dirpos++;
536 }
537
538 CACHE_NOISY(ALOGI("Looking up %s in %s\n", dir, basepath));
539 // Verify the path won't extend beyond our buffer, to avoid
540 // repeated checking later.
541 if ((dirpos-basepath+strlen(dir)) >= (PATH_MAX-1)) {
542 ALOGW("Path exceeds limit: %s%s", basepath, dir);
543 return -1;
544 }
545
546 // First, can we find this directory with the case that is given?
547 strcpy(dirpos, dir);
548 if (stat(basepath, &s) >= 0) {
549 CACHE_NOISY(ALOGI("Found direct: %s\n", basepath));
550 return 0;
551 }
552
553 // Not found with that case... search through all entries to find
554 // one that matches regardless of case.
555 *dirpos = 0;
556
557 d = opendir(basepath);
558 if (d == NULL) {
559 return -1;
560 }
561
562 while ((de = readdir(d))) {
563 if (strcasecmp(de->d_name, dir) == 0) {
564 strcpy(dirpos, de->d_name);
565 closedir(d);
566 CACHE_NOISY(ALOGI("Found search: %s\n", basepath));
567 return 0;
568 }
569 }
570
571 ALOGW("Couldn't find %s in %s", dir, basepath);
572 closedir(d);
573 return -1;
574}
575
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700576int64_t data_disk_free(const std::string& data_path)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700577{
578 struct statfs sfs;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700579 if (statfs(data_path.c_str(), &sfs) == 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700580 return sfs.f_bavail * sfs.f_bsize;
581 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700582 PLOG(ERROR) << "Couldn't statfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700583 return -1;
584 }
585}
586
587cache_t* start_cache_collection()
588{
589 cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
590 return cache;
591}
592
593#define CACHE_BLOCK_SIZE (512*1024)
594
595static void* _cache_malloc(cache_t* cache, size_t len)
596{
597 len = (len+3)&~3;
598 if (len > (CACHE_BLOCK_SIZE/2)) {
599 // It doesn't make sense to try to put this allocation into one
600 // of our blocks, because it is so big. Instead, make a new dedicated
601 // block for it.
602 int8_t* res = (int8_t*)malloc(len+sizeof(void*));
603 if (res == NULL) {
604 return NULL;
605 }
606 CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %d", res, len));
607 // Link it into our list of blocks, not disrupting the current one.
608 if (cache->memBlocks == NULL) {
609 *(void**)res = NULL;
610 cache->memBlocks = res;
611 } else {
612 *(void**)res = *(void**)cache->memBlocks;
613 *(void**)cache->memBlocks = res;
614 }
615 return res + sizeof(void*);
616 }
617 int8_t* res = cache->curMemBlockAvail;
618 int8_t* nextPos = res + len;
619 if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
Jeff Sharkey19803802015-04-07 12:44:51 -0700620 int8_t* newBlock = (int8_t*) malloc(CACHE_BLOCK_SIZE);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700621 if (newBlock == NULL) {
622 return NULL;
623 }
624 CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
625 *(void**)newBlock = cache->memBlocks;
626 cache->memBlocks = newBlock;
627 res = cache->curMemBlockAvail = newBlock + sizeof(void*);
628 cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
629 nextPos = res + len;
630 }
631 CACHE_NOISY(ALOGI("cache_malloc: ret %p size %d, block=%p, nextPos=%p",
632 res, len, cache->memBlocks, nextPos));
633 cache->curMemBlockAvail = nextPos;
634 return res;
635}
636
637static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
638{
639 // This isn't really a realloc, but it is good enough for our purposes here.
640 void* alloc = _cache_malloc(cache, len);
641 if (alloc != NULL && cur != NULL) {
642 memcpy(alloc, cur, origLen < len ? origLen : len);
643 }
644 return alloc;
645}
646
647static void _inc_num_cache_collected(cache_t* cache)
648{
649 cache->numCollected++;
650 if ((cache->numCollected%20000) == 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700651 ALOGI("Collected cache so far: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700652 cache->numDirs, cache->numFiles);
653 }
654}
655
656static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
657{
658 size_t nameLen = strlen(name);
659 cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
660 if (dir != NULL) {
661 dir->parent = parent;
662 dir->childCount = 0;
663 dir->hiddenCount = 0;
664 dir->deleted = 0;
665 strcpy(dir->name, name);
666 if (cache->numDirs >= cache->availDirs) {
667 size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
668 cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
669 cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
670 if (newDirs == NULL) {
671 ALOGE("Failure growing cache dirs array for %s\n", name);
672 return NULL;
673 }
674 cache->availDirs = newAvail;
675 cache->dirs = newDirs;
676 }
677 cache->dirs[cache->numDirs] = dir;
678 cache->numDirs++;
679 if (parent != NULL) {
680 parent->childCount++;
681 }
682 _inc_num_cache_collected(cache);
683 } else {
684 ALOGE("Failure allocating cache_dir_t for %s\n", name);
685 }
686 return dir;
687}
688
689static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
690 const char *name)
691{
692 size_t nameLen = strlen(name);
693 cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
694 if (file != NULL) {
695 file->dir = dir;
696 file->modTime = modTime;
697 strcpy(file->name, name);
698 if (cache->numFiles >= cache->availFiles) {
699 size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
700 cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
701 cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
702 if (newFiles == NULL) {
703 ALOGE("Failure growing cache file array for %s\n", name);
704 return NULL;
705 }
706 cache->availFiles = newAvail;
707 cache->files = newFiles;
708 }
709 CACHE_NOISY(ALOGI("Setting file %p at position %d in array %p", file,
710 cache->numFiles, cache->files));
711 cache->files[cache->numFiles] = file;
712 cache->numFiles++;
713 dir->childCount++;
714 _inc_num_cache_collected(cache);
715 } else {
716 ALOGE("Failure allocating cache_file_t for %s\n", name);
717 }
718 return file;
719}
720
721static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
722 DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
723{
724 struct dirent *de;
725 cache_dir_t* cacheDir = NULL;
726 int dfd;
727
728 CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
729 parentDir, dirName, dir, pathBase));
730
731 dfd = dirfd(dir);
732
733 if (dfd < 0) return 0;
734
735 // Sub-directories always get added to the data structure, so if they
736 // are empty we will know about them to delete them later.
737 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
738
739 while ((de = readdir(dir))) {
740 const char *name = de->d_name;
741
742 if (de->d_type == DT_DIR) {
743 int subfd;
744 DIR *subdir;
745
746 /* always skip "." and ".." */
747 if (name[0] == '.') {
748 if (name[1] == 0) continue;
749 if ((name[1] == '.') && (name[2] == 0)) continue;
750 }
751
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700752 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700753 if (subfd < 0) {
754 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
755 continue;
756 }
757 subdir = fdopendir(subfd);
758 if (subdir == NULL) {
759 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
760 close(subfd);
761 continue;
762 }
763 if (cacheDir == NULL) {
764 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
765 }
766 if (cacheDir != NULL) {
767 // Update pathBase for the new path... this may change dirName
768 // if that is also pointing to the path, but we are done with it
769 // now.
770 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
771 CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
772 if (finallen < pathAvailLen) {
773 _add_cache_files(cache, cacheDir, name, subdir, pathBase,
774 pathPos+finallen, pathAvailLen-finallen);
775 } else {
776 // Whoops, the final path is too long! We'll just delete
777 // this directory.
778 ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
779 name, pathBase);
780 _delete_dir_contents(subdir, NULL);
781 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
782 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
783 }
784 }
785 }
786 closedir(subdir);
787 } else if (de->d_type == DT_REG) {
788 // Skip files that start with '.'; they will be deleted if
789 // their entire directory is deleted. This allows for metadata
790 // like ".nomedia" to remain in the directory until the entire
791 // directory is deleted.
792 if (cacheDir == NULL) {
793 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
794 }
795 if (name[0] == '.') {
796 cacheDir->hiddenCount++;
797 continue;
798 }
799 if (cacheDir != NULL) {
800 // Build final full path for file... this may change dirName
801 // if that is also pointing to the path, but we are done with it
802 // now.
803 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
804 CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
805 if (finallen < pathAvailLen) {
806 struct stat s;
807 if (stat(pathBase, &s) >= 0) {
808 _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
809 } else {
810 ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
811 if (unlink(pathBase) < 0) {
812 ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
813 }
814 }
815 } else {
816 // Whoops, the final path is too long! We'll just delete
817 // this file.
818 ALOGW("Cache file %s truncated in path %s; deleting\n",
819 name, pathBase);
820 if (unlinkat(dfd, name, 0) < 0) {
821 *pathPos = 0;
822 ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
823 strerror(errno));
824 }
825 }
826 }
827 } else {
828 cacheDir->hiddenCount++;
829 }
830 }
831 return 0;
832}
833
834void add_cache_files(cache_t* cache, const char *basepath, const char *cachedir)
835{
836 DIR *d;
837 struct dirent *de;
838 char dirname[PATH_MAX];
839
840 CACHE_NOISY(ALOGI("add_cache_files: base=%s cachedir=%s\n", basepath, cachedir));
841
842 d = opendir(basepath);
843 if (d == NULL) {
844 return;
845 }
846
847 while ((de = readdir(d))) {
848 if (de->d_type == DT_DIR) {
849 DIR* subdir;
850 const char *name = de->d_name;
851 char* pathpos;
852
853 /* always skip "." and ".." */
854 if (name[0] == '.') {
855 if (name[1] == 0) continue;
856 if ((name[1] == '.') && (name[2] == 0)) continue;
857 }
858
859 strcpy(dirname, basepath);
860 pathpos = dirname + strlen(dirname);
861 if ((*(pathpos-1)) != '/') {
862 *pathpos = '/';
863 pathpos++;
864 *pathpos = 0;
865 }
866 if (cachedir != NULL) {
867 snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s/%s", name, cachedir);
868 } else {
869 snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s", name);
870 }
871 CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
872 subdir = opendir(dirname);
873 if (subdir != NULL) {
874 size_t dirnameLen = strlen(dirname);
875 _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
876 PATH_MAX - dirnameLen);
877 closedir(subdir);
878 }
879 }
880 }
881
882 closedir(d);
883}
884
885static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
886{
887 char *pos = path;
888 if (dir->parent != NULL) {
889 pos = create_dir_path(path, dir->parent);
890 }
891 // Note that we don't need to worry about going beyond the buffer,
892 // since when we were constructing the cache entries our maximum
893 // buffer size for full paths was PATH_MAX.
894 strcpy(pos, dir->name);
895 pos += strlen(pos);
896 *pos = '/';
897 pos++;
898 *pos = 0;
899 return pos;
900}
901
902static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
903{
904 if (dir->parent != NULL) {
905 create_dir_path(path, dir);
906 ALOGI("DEL DIR %s\n", path);
907 if (dir->hiddenCount <= 0) {
908 if (rmdir(path)) {
909 ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
910 return;
911 }
912 } else {
913 // The directory contains hidden files so we need to delete
914 // them along with the directory itself.
915 if (delete_dir_contents(path, 1, NULL)) {
916 return;
917 }
918 }
919 dir->parent->childCount--;
920 dir->deleted = 1;
921 if (dir->parent->childCount <= 0) {
922 delete_cache_dir(path, dir->parent);
923 }
924 } else if (dir->hiddenCount > 0) {
925 // This is a root directory, but it has hidden files. Get rid of
926 // all of those files, but not the directory itself.
927 create_dir_path(path, dir);
928 ALOGI("DEL CONTENTS %s\n", path);
929 delete_dir_contents(path, 0, NULL);
930 }
931}
932
933static int cache_modtime_sort(const void *lhsP, const void *rhsP)
934{
935 const cache_file_t *lhs = *(const cache_file_t**)lhsP;
936 const cache_file_t *rhs = *(const cache_file_t**)rhsP;
937 return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
938}
939
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700940void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700941{
942 size_t i;
943 int skip = 0;
944 char path[PATH_MAX];
945
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700946 ALOGI("Collected cache files: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700947 cache->numDirs, cache->numFiles);
948
949 CACHE_NOISY(ALOGI("Sorting files..."));
950 qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
951 cache_modtime_sort);
952
953 CACHE_NOISY(ALOGI("Cleaning empty directories..."));
954 for (i=cache->numDirs; i>0; i--) {
955 cache_dir_t* dir = cache->dirs[i-1];
956 if (dir->childCount <= 0 && !dir->deleted) {
957 delete_cache_dir(path, dir);
958 }
959 }
960
961 CACHE_NOISY(ALOGI("Trimming files..."));
962 for (i=0; i<cache->numFiles; i++) {
963 skip++;
964 if (skip > 10) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700965 if (data_disk_free(data_path) > free_size) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700966 return;
967 }
968 skip = 0;
969 }
970 cache_file_t* file = cache->files[i];
971 strcpy(create_dir_path(path, file->dir), file->name);
972 ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
973 if (unlink(path) < 0) {
974 ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
975 }
976 file->dir->childCount--;
977 if (file->dir->childCount <= 0) {
978 delete_cache_dir(path, file->dir);
979 }
980 }
981}
982
983void finish_cache_collection(cache_t* cache)
984{
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700985 CACHE_NOISY(size_t i;)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700986
987 CACHE_NOISY(ALOGI("clear_cache_files: %d dirs, %d files\n", cache->numDirs, cache->numFiles));
988 CACHE_NOISY(
989 for (i=0; i<cache->numDirs; i++) {
990 cache_dir_t* dir = cache->dirs[i];
991 ALOGI("dir #%d: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
992 })
993 CACHE_NOISY(
994 for (i=0; i<cache->numFiles; i++) {
995 cache_file_t* file = cache->files[i];
996 ALOGI("file #%d: %p %s time=%d dir=%p\n", i, file, file->name,
997 (int)file->modTime, file->dir);
998 })
999 void* block = cache->memBlocks;
1000 while (block != NULL) {
1001 void* nextBlock = *(void**)block;
1002 CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
1003 free(block);
1004 block = nextBlock;
1005 }
1006 free(cache);
1007}
1008
1009/**
Calin Juravlec597b6d2014-08-19 17:43:05 +01001010 * Validate that the path is valid in the context of the provided directory.
1011 * The path is allowed to have at most one subdirectory and no indirections
1012 * to top level directories (i.e. have "..").
1013 */
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001014static int validate_path(const dir_rec_t* dir, const char* path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001015 size_t dir_len = dir->len;
1016 const char* subdir = strchr(path + dir_len, '/');
1017
1018 // Only allow the path to have at most one subdirectory.
1019 if (subdir != NULL) {
1020 ++subdir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001021 if ((--maxSubdirs == 0) && strchr(subdir, '/') != NULL) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001022 ALOGE("invalid apk path '%s' (subdir?)\n", path);
1023 return -1;
1024 }
1025 }
1026
1027 // Directories can't have a period directly after the directory markers to prevent "..".
1028 if ((path[dir_len] == '.') || ((subdir != NULL) && (*subdir == '.'))) {
1029 ALOGE("invalid apk path '%s' (trickery)\n", path);
1030 return -1;
1031 }
1032
1033 return 0;
1034}
1035
1036/**
Mike Lockwood94afecf2012-10-24 10:45:23 -07001037 * Checks whether a path points to a system app (.apk file). Returns 0
1038 * if it is a system app or -1 if it is not.
1039 */
1040int validate_system_app_path(const char* path) {
1041 size_t i;
1042
1043 for (i = 0; i < android_system_dirs.count; i++) {
1044 const size_t dir_len = android_system_dirs.dirs[i].len;
1045 if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001046 return validate_path(android_system_dirs.dirs + i, path, 1);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001047 }
1048 }
1049
1050 return -1;
1051}
1052
1053/**
1054 * Get the contents of a environment variable that contains a path. Caller
1055 * owns the string that is inserted into the directory record. Returns
1056 * 0 on success and -1 on error.
1057 */
1058int get_path_from_env(dir_rec_t* rec, const char* var) {
1059 const char* path = getenv(var);
1060 int ret = get_path_from_string(rec, path);
1061 if (ret < 0) {
1062 ALOGW("Problem finding value for environment variable %s\n", var);
1063 }
1064 return ret;
1065}
1066
1067/**
1068 * Puts the string into the record as a directory. Appends '/' to the end
1069 * of all paths. Caller owns the string that is inserted into the directory
1070 * record. A null value will result in an error.
1071 *
1072 * Returns 0 on success and -1 on error.
1073 */
1074int get_path_from_string(dir_rec_t* rec, const char* path) {
1075 if (path == NULL) {
1076 return -1;
1077 } else {
1078 const size_t path_len = strlen(path);
1079 if (path_len <= 0) {
1080 return -1;
1081 }
1082
1083 // Make sure path is absolute.
1084 if (path[0] != '/') {
1085 return -1;
1086 }
1087
1088 if (path[path_len - 1] == '/') {
1089 // Path ends with a forward slash. Make our own copy.
1090
1091 rec->path = strdup(path);
1092 if (rec->path == NULL) {
1093 return -1;
1094 }
1095
1096 rec->len = path_len;
1097 } else {
1098 // Path does not end with a slash. Generate a new string.
1099 char *dst;
1100
1101 // Add space for slash and terminating null.
1102 size_t dst_size = path_len + 2;
1103
Jeff Sharkey19803802015-04-07 12:44:51 -07001104 rec->path = (char*) malloc(dst_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001105 if (rec->path == NULL) {
1106 return -1;
1107 }
1108
1109 dst = rec->path;
1110
1111 if (append_and_increment(&dst, path, &dst_size) < 0
1112 || append_and_increment(&dst, "/", &dst_size)) {
1113 ALOGE("Error canonicalizing path");
1114 return -1;
1115 }
1116
1117 rec->len = dst - rec->path;
1118 }
1119 }
1120 return 0;
1121}
1122
1123int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
1124 dst->len = src->len + strlen(suffix);
1125 const size_t dstSize = dst->len + 1;
1126 dst->path = (char*) malloc(dstSize);
1127
1128 if (dst->path == NULL
1129 || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
1130 != (ssize_t) dst->len) {
1131 ALOGE("Could not allocate memory to hold appended path; aborting\n");
1132 return -1;
1133 }
1134
1135 return 0;
1136}
1137
1138/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001139 * Check whether path points to a valid path for an APK file. The path must
1140 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1141 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1142 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001143 */
Narayan Kamathd845c962015-06-04 13:20:27 +01001144static int validate_apk_path_internal(const char *path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001145 const dir_rec_t* dir = NULL;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001146 if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001147 dir = &android_app_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001148 } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001149 dir = &android_app_private_dir;
Todd Kennedy5c1a9102015-11-23 15:18:10 -08001150 } else if (!strncmp(path, android_app_ephemeral_dir.path, android_app_ephemeral_dir.len)) {
1151 dir = &android_app_ephemeral_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001152 } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001153 dir = &android_asec_dir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001154 } else if (!strncmp(path, android_mnt_expand_dir.path, android_mnt_expand_dir.len)) {
1155 dir = &android_mnt_expand_dir;
Narayan Kamathd845c962015-06-04 13:20:27 +01001156 if (maxSubdirs < 2) {
1157 maxSubdirs = 2;
1158 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001159 } else {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001160 return -1;
1161 }
1162
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001163 return validate_path(dir, path, maxSubdirs);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001164}
1165
Narayan Kamathd845c962015-06-04 13:20:27 +01001166int validate_apk_path(const char* path) {
1167 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
1168}
1169
1170int validate_apk_path_subdirs(const char* path) {
1171 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
1172}
1173
Mike Lockwood94afecf2012-10-24 10:45:23 -07001174int append_and_increment(char** dst, const char* src, size_t* dst_size) {
1175 ssize_t ret = strlcpy(*dst, src, *dst_size);
1176 if (ret < 0 || (size_t) ret >= *dst_size) {
1177 return -1;
1178 }
1179 *dst += ret;
1180 *dst_size -= ret;
1181 return 0;
1182}
1183
Jeff Sharkey19803802015-04-07 12:44:51 -07001184char *build_string2(const char *s1, const char *s2) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001185 if (s1 == NULL || s2 == NULL) return NULL;
1186
1187 int len_s1 = strlen(s1);
1188 int len_s2 = strlen(s2);
1189 int len = len_s1 + len_s2 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001190 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001191 if (result == NULL) return NULL;
1192
1193 strcpy(result, s1);
1194 strcpy(result + len_s1, s2);
1195
1196 return result;
1197}
1198
Jeff Sharkey19803802015-04-07 12:44:51 -07001199char *build_string3(const char *s1, const char *s2, const char *s3) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001200 if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
1201
1202 int len_s1 = strlen(s1);
1203 int len_s2 = strlen(s2);
1204 int len_s3 = strlen(s3);
1205 int len = len_s1 + len_s2 + len_s3 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001206 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001207 if (result == NULL) return NULL;
1208
1209 strcpy(result, s1);
1210 strcpy(result + len_s1, s2);
1211 strcpy(result + len_s1 + len_s2, s3);
1212
1213 return result;
1214}
1215
Robin Lee095c7632014-04-25 15:05:19 +01001216int ensure_config_user_dirs(userid_t userid) {
1217 char config_user_path[PATH_MAX];
Robin Lee095c7632014-04-25 15:05:19 +01001218
1219 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001220 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1221 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001222
1223 // Ensure /data/misc/user/<userid> exists
1224 create_user_config_path(config_user_path, userid);
1225 if (fs_prepare_dir(config_user_path, 0750, uid, gid) == -1) {
1226 return -1;
1227 }
1228
1229 return 0;
1230}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001231
1232int wait_child(pid_t pid)
1233{
1234 int status;
1235 pid_t got_pid;
1236
1237 while (1) {
1238 got_pid = waitpid(pid, &status, 0);
1239 if (got_pid == -1 && errno == EINTR) {
1240 printf("waitpid interrupted, retrying\n");
1241 } else {
1242 break;
1243 }
1244 }
1245 if (got_pid != pid) {
1246 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1247 (int) pid, (int) got_pid, strerror(errno));
1248 return 1;
1249 }
1250
1251 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1252 return 0;
1253 } else {
1254 return status; /* always nonzero */
1255 }
1256}
1257
1258} // namespace installd
1259} // namespace android