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