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