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