blob: ba411cd478a690167ee730d5873dee1126ce9195 [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
17#include "installd.h"
18
Jeff Sharkeyc03de092015-04-07 18:14:05 -070019#include <base/stringprintf.h>
20#include <base/logging.h>
21
Mike Lockwood94afecf2012-10-24 10:45:23 -070022#define CACHE_NOISY(x) //x
23
Jeff Sharkeyc03de092015-04-07 18:14:05 -070024using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070025
Jeff Sharkeyc03de092015-04-07 18:14:05 -070026/**
27 * Check that given string is valid filename, and that it attempts no
28 * parent or child directory traversal.
29 */
30static bool is_valid_filename(const std::string& name) {
31 if (name.empty() || (name == ".") || (name == "..")
32 || (name.find('/') != std::string::npos)) {
33 return false;
34 } else {
35 return true;
36 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070037}
38
39/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070040 * Create the path name where package data should be stored for the given
41 * volume UUID, package name, and user ID. An empty UUID is assumed to be
42 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070043 */
Jeff Sharkeyc03de092015-04-07 18:14:05 -070044std::string create_package_data_path(const char* volume_uuid,
45 const char* package_name, userid_t user) {
46 CHECK(is_valid_filename(package_name));
47 CHECK(is_valid_package_name(package_name) == 0);
48
Jeff Sharkey41ea4242015-04-09 11:34:03 -070049 return StringPrintf("%s/%s", create_data_user_path(volume_uuid, user).c_str(), package_name);
Jeff Sharkeyc03de092015-04-07 18:14:05 -070050}
Mike Lockwood94afecf2012-10-24 10:45:23 -070051
Jeff Sharkeyc03de092015-04-07 18:14:05 -070052int create_pkg_path(char path[PKG_PATH_MAX], const char *pkgname,
53 const char *postfix, userid_t userid) {
54 if (is_valid_package_name(pkgname) != 0) {
55 path[0] = '\0';
Mike Lockwood94afecf2012-10-24 10:45:23 -070056 return -1;
57 }
58
Jeff Sharkeyc03de092015-04-07 18:14:05 -070059 std::string _tmp(create_package_data_path(nullptr, pkgname, userid) + postfix);
60 const char* tmp = _tmp.c_str();
61 if (strlen(tmp) >= PKG_PATH_MAX) {
62 path[0] = '\0';
63 return -1;
64 } else {
65 strcpy(path, tmp);
66 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -070067 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070068}
69
Jeff Sharkey41ea4242015-04-09 11:34:03 -070070std::string create_data_path(const char* volume_uuid) {
71 if (volume_uuid == nullptr) {
72 return "/data";
73 } else {
74 CHECK(is_valid_filename(volume_uuid));
75 return StringPrintf("/mnt/expand/%s", volume_uuid);
76 }
77}
78
Mike Lockwood94afecf2012-10-24 10:45:23 -070079/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -070080 * Create the path name for user data for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -070081 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -070082std::string create_data_user_path(const char* volume_uuid, userid_t userid) {
83 std::string data(create_data_path(volume_uuid));
84 if (volume_uuid == nullptr) {
85 if (userid == 0) {
86 return StringPrintf("%s/data", data.c_str());
87 } else {
88 return StringPrintf("%s/user/%u", data.c_str(), userid);
89 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070090 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -070091 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -070092 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070093}
94
95/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -070096 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -070097 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -070098std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
99 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700100}
101
Jeff Sharkeye3637242015-04-08 20:56:42 -0700102std::vector<userid_t> get_known_users(const char* volume_uuid) {
103 std::vector<userid_t> users;
104
105 // We always have an owner
106 users.push_back(0);
107
108 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
109 DIR* dir = opendir(path.c_str());
110 if (dir == NULL) {
111 // Unable to discover other users, but at least return owner
112 PLOG(ERROR) << "Failed to opendir " << path;
113 return users;
114 }
115
116 struct dirent* ent;
117 while ((ent = readdir(dir))) {
118 if (ent->d_type != DT_DIR) {
119 continue;
120 }
121
122 char* end;
123 userid_t user = strtol(ent->d_name, &end, 10);
124 if (*end == '\0' && user != 0) {
125 LOG(DEBUG) << "Found valid user " << user;
126 users.push_back(user);
127 }
128 }
129 closedir(dir);
130
131 return users;
132}
133
Robin Lee095c7632014-04-25 15:05:19 +0100134/**
135 * Create the path name for config for a certain userid.
136 * Returns 0 on success, and -1 on failure.
137 */
138int create_user_config_path(char path[PATH_MAX], userid_t userid) {
139 if (snprintf(path, PATH_MAX, "%s%d", "/data/misc/user/", userid) > PATH_MAX) {
140 return -1;
141 }
142 return 0;
143}
144
Mike Lockwood94afecf2012-10-24 10:45:23 -0700145int create_move_path(char path[PKG_PATH_MAX],
146 const char* pkgname,
147 const char* leaf,
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700148 userid_t userid __unused)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700149{
150 if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
151 >= PKG_PATH_MAX) {
152 return -1;
153 }
154
155 sprintf(path, "%s%s%s/%s", android_data_dir.path, PRIMARY_USER_PREFIX, pkgname, leaf);
156 return 0;
157}
158
159/**
160 * Checks whether the package name is valid. Returns -1 on error and
161 * 0 on success.
162 */
163int is_valid_package_name(const char* pkgname) {
164 const char *x = pkgname;
165 int alpha = -1;
166
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700167 if (strlen(pkgname) > PKG_NAME_MAX) {
168 return -1;
169 }
170
Mike Lockwood94afecf2012-10-24 10:45:23 -0700171 while (*x) {
172 if (isalnum(*x) || (*x == '_')) {
173 /* alphanumeric or underscore are fine */
174 } else if (*x == '.') {
175 if ((x == pkgname) || (x[1] == '.') || (x[1] == 0)) {
176 /* periods must not be first, last, or doubled */
177 ALOGE("invalid package name '%s'\n", pkgname);
178 return -1;
179 }
180 } else if (*x == '-') {
181 /* Suffix -X is fine to let versioning of packages.
182 But whatever follows should be alphanumeric.*/
183 alpha = 1;
184 } else {
185 /* anything not A-Z, a-z, 0-9, _, or . is invalid */
186 ALOGE("invalid package name '%s'\n", pkgname);
187 return -1;
188 }
189
190 x++;
191 }
192
193 if (alpha == 1) {
194 // Skip current character
195 x++;
196 while (*x) {
197 if (!isalnum(*x)) {
198 ALOGE("invalid package name '%s' should include only numbers after -\n", pkgname);
199 return -1;
200 }
201 x++;
202 }
203 }
204
205 return 0;
206}
207
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100208static int _delete_dir_contents(DIR *d,
209 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700210{
211 int result = 0;
212 struct dirent *de;
213 int dfd;
214
215 dfd = dirfd(d);
216
217 if (dfd < 0) return -1;
218
219 while ((de = readdir(d))) {
220 const char *name = de->d_name;
221
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100222 /* check using the exclusion predicate, if provided */
223 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
224 continue;
225 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700226
227 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700228 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700229 DIR *subdir;
230
231 /* always skip "." and ".." */
232 if (name[0] == '.') {
233 if (name[1] == 0) continue;
234 if ((name[1] == '.') && (name[2] == 0)) continue;
235 }
236
237 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
238 if (subfd < 0) {
239 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
240 result = -1;
241 continue;
242 }
243 subdir = fdopendir(subfd);
244 if (subdir == NULL) {
245 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
246 close(subfd);
247 result = -1;
248 continue;
249 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100250 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700251 result = -1;
252 }
253 closedir(subdir);
254 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
255 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
256 result = -1;
257 }
258 } else {
259 if (unlinkat(dfd, name, 0) < 0) {
260 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
261 result = -1;
262 }
263 }
264 }
265
266 return result;
267}
268
269int delete_dir_contents(const char *pathname,
270 int also_delete_dir,
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100271 int (*exclusion_predicate)(const char*, const int))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700272{
273 int res = 0;
274 DIR *d;
275
276 d = opendir(pathname);
277 if (d == NULL) {
278 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
279 return -errno;
280 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100281 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700282 closedir(d);
283 if (also_delete_dir) {
284 if (rmdir(pathname)) {
285 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
286 res = -1;
287 }
288 }
289 return res;
290}
291
292int delete_dir_contents_fd(int dfd, const char *name)
293{
294 int fd, res;
295 DIR *d;
296
297 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
298 if (fd < 0) {
299 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
300 return -1;
301 }
302 d = fdopendir(fd);
303 if (d == NULL) {
304 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
305 close(fd);
306 return -1;
307 }
308 res = _delete_dir_contents(d, 0);
309 closedir(d);
310 return res;
311}
312
Robin Lee60fd3fe2014-10-07 16:55:02 +0100313static int _copy_owner_permissions(int srcfd, int dstfd)
314{
315 struct stat st;
316 if (fstat(srcfd, &st) != 0) {
317 return -1;
318 }
319 if (fchmod(dstfd, st.st_mode) != 0) {
320 return -1;
321 }
322 return 0;
323}
324
325static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
326{
327 int result = 0;
328 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
329 ALOGE("_copy_dir_files failed to copy dir permissions\n");
330 }
331 if (fchown(ddfd, owner, group) != 0) {
332 ALOGE("_copy_dir_files failed to change dir owner\n");
333 }
334
335 DIR *ds = fdopendir(sdfd);
336 if (ds == NULL) {
337 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
338 return -1;
339 }
340 struct dirent *de;
341 while ((de = readdir(ds))) {
342 if (de->d_type != DT_REG) {
343 continue;
344 }
345
346 const char *name = de->d_name;
347 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
348 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
349 if (fsfd == -1 || fdfd == -1) {
350 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
351 } else {
352 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
353 ALOGE("Failed to change file permissions\n");
354 }
355 if (fchown(fdfd, owner, group) != 0) {
356 ALOGE("Failed to change file owner\n");
357 }
358
359 char buf[8192];
360 ssize_t size;
361 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
362 write(fdfd, buf, size);
363 }
364 if (size < 0) {
365 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
366 result = -1;
367 }
368 }
369 close(fdfd);
370 close(fsfd);
371 }
372
373 return result;
374}
375
376int copy_dir_files(const char *srcname,
377 const char *dstname,
378 uid_t owner,
379 uid_t group)
380{
381 int res = 0;
382 DIR *ds = NULL;
383 DIR *dd = NULL;
384
385 ds = opendir(srcname);
386 if (ds == NULL) {
387 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
388 return -errno;
389 }
390
391 mkdir(dstname, 0600);
392 dd = opendir(dstname);
393 if (dd == NULL) {
394 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
395 closedir(ds);
396 return -errno;
397 }
398
399 int sdfd = dirfd(ds);
400 int ddfd = dirfd(dd);
401 if (sdfd != -1 && ddfd != -1) {
402 res = _copy_dir_files(sdfd, ddfd, owner, group);
403 } else {
404 res = -errno;
405 }
406 closedir(dd);
407 closedir(ds);
408 return res;
409}
410
Mike Lockwood94afecf2012-10-24 10:45:23 -0700411int lookup_media_dir(char basepath[PATH_MAX], const char *dir)
412{
413 DIR *d;
414 struct dirent *de;
415 struct stat s;
416 char* dirpos = basepath + strlen(basepath);
417
418 if ((*(dirpos-1)) != '/') {
419 *dirpos = '/';
420 dirpos++;
421 }
422
423 CACHE_NOISY(ALOGI("Looking up %s in %s\n", dir, basepath));
424 // Verify the path won't extend beyond our buffer, to avoid
425 // repeated checking later.
426 if ((dirpos-basepath+strlen(dir)) >= (PATH_MAX-1)) {
427 ALOGW("Path exceeds limit: %s%s", basepath, dir);
428 return -1;
429 }
430
431 // First, can we find this directory with the case that is given?
432 strcpy(dirpos, dir);
433 if (stat(basepath, &s) >= 0) {
434 CACHE_NOISY(ALOGI("Found direct: %s\n", basepath));
435 return 0;
436 }
437
438 // Not found with that case... search through all entries to find
439 // one that matches regardless of case.
440 *dirpos = 0;
441
442 d = opendir(basepath);
443 if (d == NULL) {
444 return -1;
445 }
446
447 while ((de = readdir(d))) {
448 if (strcasecmp(de->d_name, dir) == 0) {
449 strcpy(dirpos, de->d_name);
450 closedir(d);
451 CACHE_NOISY(ALOGI("Found search: %s\n", basepath));
452 return 0;
453 }
454 }
455
456 ALOGW("Couldn't find %s in %s", dir, basepath);
457 closedir(d);
458 return -1;
459}
460
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700461int64_t data_disk_free(const std::string& data_path)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700462{
463 struct statfs sfs;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700464 if (statfs(data_path.c_str(), &sfs) == 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700465 return sfs.f_bavail * sfs.f_bsize;
466 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700467 PLOG(ERROR) << "Couldn't statfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700468 return -1;
469 }
470}
471
472cache_t* start_cache_collection()
473{
474 cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
475 return cache;
476}
477
478#define CACHE_BLOCK_SIZE (512*1024)
479
480static void* _cache_malloc(cache_t* cache, size_t len)
481{
482 len = (len+3)&~3;
483 if (len > (CACHE_BLOCK_SIZE/2)) {
484 // It doesn't make sense to try to put this allocation into one
485 // of our blocks, because it is so big. Instead, make a new dedicated
486 // block for it.
487 int8_t* res = (int8_t*)malloc(len+sizeof(void*));
488 if (res == NULL) {
489 return NULL;
490 }
491 CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %d", res, len));
492 // Link it into our list of blocks, not disrupting the current one.
493 if (cache->memBlocks == NULL) {
494 *(void**)res = NULL;
495 cache->memBlocks = res;
496 } else {
497 *(void**)res = *(void**)cache->memBlocks;
498 *(void**)cache->memBlocks = res;
499 }
500 return res + sizeof(void*);
501 }
502 int8_t* res = cache->curMemBlockAvail;
503 int8_t* nextPos = res + len;
504 if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
Jeff Sharkey19803802015-04-07 12:44:51 -0700505 int8_t* newBlock = (int8_t*) malloc(CACHE_BLOCK_SIZE);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700506 if (newBlock == NULL) {
507 return NULL;
508 }
509 CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
510 *(void**)newBlock = cache->memBlocks;
511 cache->memBlocks = newBlock;
512 res = cache->curMemBlockAvail = newBlock + sizeof(void*);
513 cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
514 nextPos = res + len;
515 }
516 CACHE_NOISY(ALOGI("cache_malloc: ret %p size %d, block=%p, nextPos=%p",
517 res, len, cache->memBlocks, nextPos));
518 cache->curMemBlockAvail = nextPos;
519 return res;
520}
521
522static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
523{
524 // This isn't really a realloc, but it is good enough for our purposes here.
525 void* alloc = _cache_malloc(cache, len);
526 if (alloc != NULL && cur != NULL) {
527 memcpy(alloc, cur, origLen < len ? origLen : len);
528 }
529 return alloc;
530}
531
532static void _inc_num_cache_collected(cache_t* cache)
533{
534 cache->numCollected++;
535 if ((cache->numCollected%20000) == 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700536 ALOGI("Collected cache so far: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700537 cache->numDirs, cache->numFiles);
538 }
539}
540
541static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
542{
543 size_t nameLen = strlen(name);
544 cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
545 if (dir != NULL) {
546 dir->parent = parent;
547 dir->childCount = 0;
548 dir->hiddenCount = 0;
549 dir->deleted = 0;
550 strcpy(dir->name, name);
551 if (cache->numDirs >= cache->availDirs) {
552 size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
553 cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
554 cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
555 if (newDirs == NULL) {
556 ALOGE("Failure growing cache dirs array for %s\n", name);
557 return NULL;
558 }
559 cache->availDirs = newAvail;
560 cache->dirs = newDirs;
561 }
562 cache->dirs[cache->numDirs] = dir;
563 cache->numDirs++;
564 if (parent != NULL) {
565 parent->childCount++;
566 }
567 _inc_num_cache_collected(cache);
568 } else {
569 ALOGE("Failure allocating cache_dir_t for %s\n", name);
570 }
571 return dir;
572}
573
574static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
575 const char *name)
576{
577 size_t nameLen = strlen(name);
578 cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
579 if (file != NULL) {
580 file->dir = dir;
581 file->modTime = modTime;
582 strcpy(file->name, name);
583 if (cache->numFiles >= cache->availFiles) {
584 size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
585 cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
586 cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
587 if (newFiles == NULL) {
588 ALOGE("Failure growing cache file array for %s\n", name);
589 return NULL;
590 }
591 cache->availFiles = newAvail;
592 cache->files = newFiles;
593 }
594 CACHE_NOISY(ALOGI("Setting file %p at position %d in array %p", file,
595 cache->numFiles, cache->files));
596 cache->files[cache->numFiles] = file;
597 cache->numFiles++;
598 dir->childCount++;
599 _inc_num_cache_collected(cache);
600 } else {
601 ALOGE("Failure allocating cache_file_t for %s\n", name);
602 }
603 return file;
604}
605
606static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
607 DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
608{
609 struct dirent *de;
610 cache_dir_t* cacheDir = NULL;
611 int dfd;
612
613 CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
614 parentDir, dirName, dir, pathBase));
615
616 dfd = dirfd(dir);
617
618 if (dfd < 0) return 0;
619
620 // Sub-directories always get added to the data structure, so if they
621 // are empty we will know about them to delete them later.
622 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
623
624 while ((de = readdir(dir))) {
625 const char *name = de->d_name;
626
627 if (de->d_type == DT_DIR) {
628 int subfd;
629 DIR *subdir;
630
631 /* always skip "." and ".." */
632 if (name[0] == '.') {
633 if (name[1] == 0) continue;
634 if ((name[1] == '.') && (name[2] == 0)) continue;
635 }
636
637 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
638 if (subfd < 0) {
639 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
640 continue;
641 }
642 subdir = fdopendir(subfd);
643 if (subdir == NULL) {
644 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
645 close(subfd);
646 continue;
647 }
648 if (cacheDir == NULL) {
649 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
650 }
651 if (cacheDir != NULL) {
652 // Update pathBase for the new path... this may change dirName
653 // if that is also pointing to the path, but we are done with it
654 // now.
655 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
656 CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
657 if (finallen < pathAvailLen) {
658 _add_cache_files(cache, cacheDir, name, subdir, pathBase,
659 pathPos+finallen, pathAvailLen-finallen);
660 } else {
661 // Whoops, the final path is too long! We'll just delete
662 // this directory.
663 ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
664 name, pathBase);
665 _delete_dir_contents(subdir, NULL);
666 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
667 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
668 }
669 }
670 }
671 closedir(subdir);
672 } else if (de->d_type == DT_REG) {
673 // Skip files that start with '.'; they will be deleted if
674 // their entire directory is deleted. This allows for metadata
675 // like ".nomedia" to remain in the directory until the entire
676 // directory is deleted.
677 if (cacheDir == NULL) {
678 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
679 }
680 if (name[0] == '.') {
681 cacheDir->hiddenCount++;
682 continue;
683 }
684 if (cacheDir != NULL) {
685 // Build final full path for file... this may change dirName
686 // if that is also pointing to the path, but we are done with it
687 // now.
688 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
689 CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
690 if (finallen < pathAvailLen) {
691 struct stat s;
692 if (stat(pathBase, &s) >= 0) {
693 _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
694 } else {
695 ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
696 if (unlink(pathBase) < 0) {
697 ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
698 }
699 }
700 } else {
701 // Whoops, the final path is too long! We'll just delete
702 // this file.
703 ALOGW("Cache file %s truncated in path %s; deleting\n",
704 name, pathBase);
705 if (unlinkat(dfd, name, 0) < 0) {
706 *pathPos = 0;
707 ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
708 strerror(errno));
709 }
710 }
711 }
712 } else {
713 cacheDir->hiddenCount++;
714 }
715 }
716 return 0;
717}
718
719void add_cache_files(cache_t* cache, const char *basepath, const char *cachedir)
720{
721 DIR *d;
722 struct dirent *de;
723 char dirname[PATH_MAX];
724
725 CACHE_NOISY(ALOGI("add_cache_files: base=%s cachedir=%s\n", basepath, cachedir));
726
727 d = opendir(basepath);
728 if (d == NULL) {
729 return;
730 }
731
732 while ((de = readdir(d))) {
733 if (de->d_type == DT_DIR) {
734 DIR* subdir;
735 const char *name = de->d_name;
736 char* pathpos;
737
738 /* always skip "." and ".." */
739 if (name[0] == '.') {
740 if (name[1] == 0) continue;
741 if ((name[1] == '.') && (name[2] == 0)) continue;
742 }
743
744 strcpy(dirname, basepath);
745 pathpos = dirname + strlen(dirname);
746 if ((*(pathpos-1)) != '/') {
747 *pathpos = '/';
748 pathpos++;
749 *pathpos = 0;
750 }
751 if (cachedir != NULL) {
752 snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s/%s", name, cachedir);
753 } else {
754 snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s", name);
755 }
756 CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
757 subdir = opendir(dirname);
758 if (subdir != NULL) {
759 size_t dirnameLen = strlen(dirname);
760 _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
761 PATH_MAX - dirnameLen);
762 closedir(subdir);
763 }
764 }
765 }
766
767 closedir(d);
768}
769
770static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
771{
772 char *pos = path;
773 if (dir->parent != NULL) {
774 pos = create_dir_path(path, dir->parent);
775 }
776 // Note that we don't need to worry about going beyond the buffer,
777 // since when we were constructing the cache entries our maximum
778 // buffer size for full paths was PATH_MAX.
779 strcpy(pos, dir->name);
780 pos += strlen(pos);
781 *pos = '/';
782 pos++;
783 *pos = 0;
784 return pos;
785}
786
787static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
788{
789 if (dir->parent != NULL) {
790 create_dir_path(path, dir);
791 ALOGI("DEL DIR %s\n", path);
792 if (dir->hiddenCount <= 0) {
793 if (rmdir(path)) {
794 ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
795 return;
796 }
797 } else {
798 // The directory contains hidden files so we need to delete
799 // them along with the directory itself.
800 if (delete_dir_contents(path, 1, NULL)) {
801 return;
802 }
803 }
804 dir->parent->childCount--;
805 dir->deleted = 1;
806 if (dir->parent->childCount <= 0) {
807 delete_cache_dir(path, dir->parent);
808 }
809 } else if (dir->hiddenCount > 0) {
810 // This is a root directory, but it has hidden files. Get rid of
811 // all of those files, but not the directory itself.
812 create_dir_path(path, dir);
813 ALOGI("DEL CONTENTS %s\n", path);
814 delete_dir_contents(path, 0, NULL);
815 }
816}
817
818static int cache_modtime_sort(const void *lhsP, const void *rhsP)
819{
820 const cache_file_t *lhs = *(const cache_file_t**)lhsP;
821 const cache_file_t *rhs = *(const cache_file_t**)rhsP;
822 return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
823}
824
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700825void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700826{
827 size_t i;
828 int skip = 0;
829 char path[PATH_MAX];
830
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700831 ALOGI("Collected cache files: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700832 cache->numDirs, cache->numFiles);
833
834 CACHE_NOISY(ALOGI("Sorting files..."));
835 qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
836 cache_modtime_sort);
837
838 CACHE_NOISY(ALOGI("Cleaning empty directories..."));
839 for (i=cache->numDirs; i>0; i--) {
840 cache_dir_t* dir = cache->dirs[i-1];
841 if (dir->childCount <= 0 && !dir->deleted) {
842 delete_cache_dir(path, dir);
843 }
844 }
845
846 CACHE_NOISY(ALOGI("Trimming files..."));
847 for (i=0; i<cache->numFiles; i++) {
848 skip++;
849 if (skip > 10) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700850 if (data_disk_free(data_path) > free_size) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700851 return;
852 }
853 skip = 0;
854 }
855 cache_file_t* file = cache->files[i];
856 strcpy(create_dir_path(path, file->dir), file->name);
857 ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
858 if (unlink(path) < 0) {
859 ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
860 }
861 file->dir->childCount--;
862 if (file->dir->childCount <= 0) {
863 delete_cache_dir(path, file->dir);
864 }
865 }
866}
867
868void finish_cache_collection(cache_t* cache)
869{
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700870 CACHE_NOISY(size_t i;)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700871
872 CACHE_NOISY(ALOGI("clear_cache_files: %d dirs, %d files\n", cache->numDirs, cache->numFiles));
873 CACHE_NOISY(
874 for (i=0; i<cache->numDirs; i++) {
875 cache_dir_t* dir = cache->dirs[i];
876 ALOGI("dir #%d: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
877 })
878 CACHE_NOISY(
879 for (i=0; i<cache->numFiles; i++) {
880 cache_file_t* file = cache->files[i];
881 ALOGI("file #%d: %p %s time=%d dir=%p\n", i, file, file->name,
882 (int)file->modTime, file->dir);
883 })
884 void* block = cache->memBlocks;
885 while (block != NULL) {
886 void* nextBlock = *(void**)block;
887 CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
888 free(block);
889 block = nextBlock;
890 }
891 free(cache);
892}
893
894/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100895 * Validate that the path is valid in the context of the provided directory.
896 * The path is allowed to have at most one subdirectory and no indirections
897 * to top level directories (i.e. have "..").
898 */
Jeff Sharkeye23a1322015-04-06 16:19:39 -0700899static int validate_path(const dir_rec_t* dir, const char* path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +0100900 size_t dir_len = dir->len;
901 const char* subdir = strchr(path + dir_len, '/');
902
903 // Only allow the path to have at most one subdirectory.
904 if (subdir != NULL) {
905 ++subdir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -0700906 if ((--maxSubdirs == 0) && strchr(subdir, '/') != NULL) {
Calin Juravlec597b6d2014-08-19 17:43:05 +0100907 ALOGE("invalid apk path '%s' (subdir?)\n", path);
908 return -1;
909 }
910 }
911
912 // Directories can't have a period directly after the directory markers to prevent "..".
913 if ((path[dir_len] == '.') || ((subdir != NULL) && (*subdir == '.'))) {
914 ALOGE("invalid apk path '%s' (trickery)\n", path);
915 return -1;
916 }
917
918 return 0;
919}
920
921/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700922 * Checks whether a path points to a system app (.apk file). Returns 0
923 * if it is a system app or -1 if it is not.
924 */
925int validate_system_app_path(const char* path) {
926 size_t i;
927
928 for (i = 0; i < android_system_dirs.count; i++) {
929 const size_t dir_len = android_system_dirs.dirs[i].len;
930 if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
Jeff Sharkeye23a1322015-04-06 16:19:39 -0700931 return validate_path(android_system_dirs.dirs + i, path, 1);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700932 }
933 }
934
935 return -1;
936}
937
938/**
939 * Get the contents of a environment variable that contains a path. Caller
940 * owns the string that is inserted into the directory record. Returns
941 * 0 on success and -1 on error.
942 */
943int get_path_from_env(dir_rec_t* rec, const char* var) {
944 const char* path = getenv(var);
945 int ret = get_path_from_string(rec, path);
946 if (ret < 0) {
947 ALOGW("Problem finding value for environment variable %s\n", var);
948 }
949 return ret;
950}
951
952/**
953 * Puts the string into the record as a directory. Appends '/' to the end
954 * of all paths. Caller owns the string that is inserted into the directory
955 * record. A null value will result in an error.
956 *
957 * Returns 0 on success and -1 on error.
958 */
959int get_path_from_string(dir_rec_t* rec, const char* path) {
960 if (path == NULL) {
961 return -1;
962 } else {
963 const size_t path_len = strlen(path);
964 if (path_len <= 0) {
965 return -1;
966 }
967
968 // Make sure path is absolute.
969 if (path[0] != '/') {
970 return -1;
971 }
972
973 if (path[path_len - 1] == '/') {
974 // Path ends with a forward slash. Make our own copy.
975
976 rec->path = strdup(path);
977 if (rec->path == NULL) {
978 return -1;
979 }
980
981 rec->len = path_len;
982 } else {
983 // Path does not end with a slash. Generate a new string.
984 char *dst;
985
986 // Add space for slash and terminating null.
987 size_t dst_size = path_len + 2;
988
Jeff Sharkey19803802015-04-07 12:44:51 -0700989 rec->path = (char*) malloc(dst_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700990 if (rec->path == NULL) {
991 return -1;
992 }
993
994 dst = rec->path;
995
996 if (append_and_increment(&dst, path, &dst_size) < 0
997 || append_and_increment(&dst, "/", &dst_size)) {
998 ALOGE("Error canonicalizing path");
999 return -1;
1000 }
1001
1002 rec->len = dst - rec->path;
1003 }
1004 }
1005 return 0;
1006}
1007
1008int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
1009 dst->len = src->len + strlen(suffix);
1010 const size_t dstSize = dst->len + 1;
1011 dst->path = (char*) malloc(dstSize);
1012
1013 if (dst->path == NULL
1014 || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
1015 != (ssize_t) dst->len) {
1016 ALOGE("Could not allocate memory to hold appended path; aborting\n");
1017 return -1;
1018 }
1019
1020 return 0;
1021}
1022
1023/**
Calin Juravlefd88ff22014-08-15 15:45:51 +01001024 * Check whether path points to a valid path for an APK file. Only one level of
1025 * subdirectory names is allowed. Returns -1 when an invalid path is encountered
1026 * and 0 when a valid path is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001027 */
1028int validate_apk_path(const char *path)
1029{
Calin Juravlec597b6d2014-08-19 17:43:05 +01001030 const dir_rec_t* dir = NULL;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001031 int maxSubdirs = 1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001032
1033 if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001034 dir = &android_app_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001035 } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001036 dir = &android_app_private_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001037 } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001038 dir = &android_asec_dir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001039 } else if (!strncmp(path, android_mnt_expand_dir.path, android_mnt_expand_dir.len)) {
1040 dir = &android_mnt_expand_dir;
1041 maxSubdirs = 2;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001042 } else {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001043 return -1;
1044 }
1045
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001046 return validate_path(dir, path, maxSubdirs);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001047}
1048
1049int append_and_increment(char** dst, const char* src, size_t* dst_size) {
1050 ssize_t ret = strlcpy(*dst, src, *dst_size);
1051 if (ret < 0 || (size_t) ret >= *dst_size) {
1052 return -1;
1053 }
1054 *dst += ret;
1055 *dst_size -= ret;
1056 return 0;
1057}
1058
Jeff Sharkey19803802015-04-07 12:44:51 -07001059char *build_string2(const char *s1, const char *s2) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001060 if (s1 == NULL || s2 == NULL) return NULL;
1061
1062 int len_s1 = strlen(s1);
1063 int len_s2 = strlen(s2);
1064 int len = len_s1 + len_s2 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001065 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001066 if (result == NULL) return NULL;
1067
1068 strcpy(result, s1);
1069 strcpy(result + len_s1, s2);
1070
1071 return result;
1072}
1073
Jeff Sharkey19803802015-04-07 12:44:51 -07001074char *build_string3(const char *s1, const char *s2, const char *s3) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001075 if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
1076
1077 int len_s1 = strlen(s1);
1078 int len_s2 = strlen(s2);
1079 int len_s3 = strlen(s3);
1080 int len = len_s1 + len_s2 + len_s3 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001081 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001082 if (result == NULL) return NULL;
1083
1084 strcpy(result, s1);
1085 strcpy(result + len_s1, s2);
1086 strcpy(result + len_s1 + len_s2, s3);
1087
1088 return result;
1089}
1090
1091/* Ensure that /data/media directories are prepared for given user. */
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001092int ensure_media_user_dirs(const char* uuid, userid_t userid) {
1093 std::string media_user_path(create_data_media_path(uuid, userid));
1094 if (fs_prepare_dir(media_user_path.c_str(), 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001095 return -1;
1096 }
1097
1098 return 0;
1099}
Dave Allisond9370732014-01-30 14:19:23 -08001100
Robin Lee095c7632014-04-25 15:05:19 +01001101int ensure_config_user_dirs(userid_t userid) {
1102 char config_user_path[PATH_MAX];
Robin Lee095c7632014-04-25 15:05:19 +01001103
1104 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001105 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1106 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001107
1108 // Ensure /data/misc/user/<userid> exists
1109 create_user_config_path(config_user_path, userid);
1110 if (fs_prepare_dir(config_user_path, 0750, uid, gid) == -1) {
1111 return -1;
1112 }
1113
1114 return 0;
1115}
1116
Dave Allisond9370732014-01-30 14:19:23 -08001117int create_profile_file(const char *pkgname, gid_t gid) {
1118 const char *profile_dir = DALVIK_CACHE_PREFIX "profiles";
Dave Allisond9370732014-01-30 14:19:23 -08001119 char profile_file[PKG_PATH_MAX];
1120
Dave Allisond9370732014-01-30 14:19:23 -08001121 snprintf(profile_file, sizeof(profile_file), "%s/%s", profile_dir, pkgname);
1122
1123 // The 'system' user needs to be able to read the profile to determine if dex2oat
1124 // needs to be run. This is done in dalvik.system.DexFile.isDexOptNeededInternal(). So
Nick Kralevich0db0f972014-06-11 18:23:59 -07001125 // we assign ownership to AID_SYSTEM and ensure it's not world-readable.
Dave Allisond9370732014-01-30 14:19:23 -08001126
Nick Kralevich0db0f972014-06-11 18:23:59 -07001127 int fd = open(profile_file, O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0660);
Dave Allisond9370732014-01-30 14:19:23 -08001128
Nick Kralevich0db0f972014-06-11 18:23:59 -07001129 // Always set the uid/gid/permissions. The file could have been previously created
1130 // with different permissions.
Dave Allisond9370732014-01-30 14:19:23 -08001131 if (fd >= 0) {
Nick Kralevich0db0f972014-06-11 18:23:59 -07001132 if (fchown(fd, AID_SYSTEM, gid) < 0) {
Dave Allisond9370732014-01-30 14:19:23 -08001133 ALOGE("cannot chown profile file '%s': %s\n", profile_file, strerror(errno));
1134 close(fd);
1135 unlink(profile_file);
1136 return -1;
1137 }
1138
Nick Kralevich0db0f972014-06-11 18:23:59 -07001139 if (fchmod(fd, 0660) < 0) {
Dave Allisond9370732014-01-30 14:19:23 -08001140 ALOGE("cannot chmod profile file '%s': %s\n", profile_file, strerror(errno));
1141 close(fd);
1142 unlink(profile_file);
1143 return -1;
1144 }
1145 close(fd);
1146 }
1147 return 0;
1148}
1149
1150void remove_profile_file(const char *pkgname) {
1151 char profile_file[PKG_PATH_MAX];
1152 snprintf(profile_file, sizeof(profile_file), "%s/%s", DALVIK_CACHE_PREFIX "profiles", pkgname);
1153 unlink(profile_file);
1154}