utils.cpp revision 6a1648e2f161cb1d7c46aa9d27e8062521a9f314
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) {
345    return delete_dir_contents(pathname.c_str(), 0, NULL);
346}
347
348int delete_dir_contents_and_dir(const std::string& pathname) {
349    return delete_dir_contents(pathname.c_str(), 1, NULL);
350}
351
352int delete_dir_contents(const char *pathname,
353                        int also_delete_dir,
354                        int (*exclusion_predicate)(const char*, const int))
355{
356    int res = 0;
357    DIR *d;
358
359    d = opendir(pathname);
360    if (d == NULL) {
361        ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
362        return -errno;
363    }
364    res = _delete_dir_contents(d, exclusion_predicate);
365    closedir(d);
366    if (also_delete_dir) {
367        if (rmdir(pathname)) {
368            ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
369            res = -1;
370        }
371    }
372    return res;
373}
374
375int delete_dir_contents_fd(int dfd, const char *name)
376{
377    int fd, res;
378    DIR *d;
379
380    fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
381    if (fd < 0) {
382        ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
383        return -1;
384    }
385    d = fdopendir(fd);
386    if (d == NULL) {
387        ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
388        close(fd);
389        return -1;
390    }
391    res = _delete_dir_contents(d, 0);
392    closedir(d);
393    return res;
394}
395
396static int _copy_owner_permissions(int srcfd, int dstfd)
397{
398    struct stat st;
399    if (fstat(srcfd, &st) != 0) {
400        return -1;
401    }
402    if (fchmod(dstfd, st.st_mode) != 0) {
403        return -1;
404    }
405    return 0;
406}
407
408static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
409{
410    int result = 0;
411    if (_copy_owner_permissions(sdfd, ddfd) != 0) {
412        ALOGE("_copy_dir_files failed to copy dir permissions\n");
413    }
414    if (fchown(ddfd, owner, group) != 0) {
415        ALOGE("_copy_dir_files failed to change dir owner\n");
416    }
417
418    DIR *ds = fdopendir(sdfd);
419    if (ds == NULL) {
420        ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
421        return -1;
422    }
423    struct dirent *de;
424    while ((de = readdir(ds))) {
425        if (de->d_type != DT_REG) {
426            continue;
427        }
428
429        const char *name = de->d_name;
430        int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
431        int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
432        if (fsfd == -1 || fdfd == -1) {
433            ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
434        } else {
435            if (_copy_owner_permissions(fsfd, fdfd) != 0) {
436                ALOGE("Failed to change file permissions\n");
437            }
438            if (fchown(fdfd, owner, group) != 0) {
439                ALOGE("Failed to change file owner\n");
440            }
441
442            char buf[8192];
443            ssize_t size;
444            while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
445                write(fdfd, buf, size);
446            }
447            if (size < 0) {
448                ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
449                result = -1;
450            }
451        }
452        close(fdfd);
453        close(fsfd);
454    }
455
456    return result;
457}
458
459int copy_dir_files(const char *srcname,
460                   const char *dstname,
461                   uid_t owner,
462                   uid_t group)
463{
464    int res = 0;
465    DIR *ds = NULL;
466    DIR *dd = NULL;
467
468    ds = opendir(srcname);
469    if (ds == NULL) {
470        ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
471        return -errno;
472    }
473
474    mkdir(dstname, 0600);
475    dd = opendir(dstname);
476    if (dd == NULL) {
477        ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
478        closedir(ds);
479        return -errno;
480    }
481
482    int sdfd = dirfd(ds);
483    int ddfd = dirfd(dd);
484    if (sdfd != -1 && ddfd != -1) {
485        res = _copy_dir_files(sdfd, ddfd, owner, group);
486    } else {
487        res = -errno;
488    }
489    closedir(dd);
490    closedir(ds);
491    return res;
492}
493
494int lookup_media_dir(char basepath[PATH_MAX], const char *dir)
495{
496    DIR *d;
497    struct dirent *de;
498    struct stat s;
499    char* dirpos = basepath + strlen(basepath);
500
501    if ((*(dirpos-1)) != '/') {
502        *dirpos = '/';
503        dirpos++;
504    }
505
506    CACHE_NOISY(ALOGI("Looking up %s in %s\n", dir, basepath));
507    // Verify the path won't extend beyond our buffer, to avoid
508    // repeated checking later.
509    if ((dirpos-basepath+strlen(dir)) >= (PATH_MAX-1)) {
510        ALOGW("Path exceeds limit: %s%s", basepath, dir);
511        return -1;
512    }
513
514    // First, can we find this directory with the case that is given?
515    strcpy(dirpos, dir);
516    if (stat(basepath, &s) >= 0) {
517        CACHE_NOISY(ALOGI("Found direct: %s\n", basepath));
518        return 0;
519    }
520
521    // Not found with that case...  search through all entries to find
522    // one that matches regardless of case.
523    *dirpos = 0;
524
525    d = opendir(basepath);
526    if (d == NULL) {
527        return -1;
528    }
529
530    while ((de = readdir(d))) {
531        if (strcasecmp(de->d_name, dir) == 0) {
532            strcpy(dirpos, de->d_name);
533            closedir(d);
534            CACHE_NOISY(ALOGI("Found search: %s\n", basepath));
535            return 0;
536        }
537    }
538
539    ALOGW("Couldn't find %s in %s", dir, basepath);
540    closedir(d);
541    return -1;
542}
543
544int64_t data_disk_free(const std::string& data_path)
545{
546    struct statfs sfs;
547    if (statfs(data_path.c_str(), &sfs) == 0) {
548        return sfs.f_bavail * sfs.f_bsize;
549    } else {
550        PLOG(ERROR) << "Couldn't statfs " << data_path;
551        return -1;
552    }
553}
554
555cache_t* start_cache_collection()
556{
557    cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
558    return cache;
559}
560
561#define CACHE_BLOCK_SIZE (512*1024)
562
563static void* _cache_malloc(cache_t* cache, size_t len)
564{
565    len = (len+3)&~3;
566    if (len > (CACHE_BLOCK_SIZE/2)) {
567        // It doesn't make sense to try to put this allocation into one
568        // of our blocks, because it is so big.  Instead, make a new dedicated
569        // block for it.
570        int8_t* res = (int8_t*)malloc(len+sizeof(void*));
571        if (res == NULL) {
572            return NULL;
573        }
574        CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %d", res, len));
575        // Link it into our list of blocks, not disrupting the current one.
576        if (cache->memBlocks == NULL) {
577            *(void**)res = NULL;
578            cache->memBlocks = res;
579        } else {
580            *(void**)res = *(void**)cache->memBlocks;
581            *(void**)cache->memBlocks = res;
582        }
583        return res + sizeof(void*);
584    }
585    int8_t* res = cache->curMemBlockAvail;
586    int8_t* nextPos = res + len;
587    if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
588        int8_t* newBlock = (int8_t*) malloc(CACHE_BLOCK_SIZE);
589        if (newBlock == NULL) {
590            return NULL;
591        }
592        CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
593        *(void**)newBlock = cache->memBlocks;
594        cache->memBlocks = newBlock;
595        res = cache->curMemBlockAvail = newBlock + sizeof(void*);
596        cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
597        nextPos = res + len;
598    }
599    CACHE_NOISY(ALOGI("cache_malloc: ret %p size %d, block=%p, nextPos=%p",
600            res, len, cache->memBlocks, nextPos));
601    cache->curMemBlockAvail = nextPos;
602    return res;
603}
604
605static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
606{
607    // This isn't really a realloc, but it is good enough for our purposes here.
608    void* alloc = _cache_malloc(cache, len);
609    if (alloc != NULL && cur != NULL) {
610        memcpy(alloc, cur, origLen < len ? origLen : len);
611    }
612    return alloc;
613}
614
615static void _inc_num_cache_collected(cache_t* cache)
616{
617    cache->numCollected++;
618    if ((cache->numCollected%20000) == 0) {
619        ALOGI("Collected cache so far: %zd directories, %zd files",
620            cache->numDirs, cache->numFiles);
621    }
622}
623
624static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
625{
626    size_t nameLen = strlen(name);
627    cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
628    if (dir != NULL) {
629        dir->parent = parent;
630        dir->childCount = 0;
631        dir->hiddenCount = 0;
632        dir->deleted = 0;
633        strcpy(dir->name, name);
634        if (cache->numDirs >= cache->availDirs) {
635            size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
636            cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
637                    cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
638            if (newDirs == NULL) {
639                ALOGE("Failure growing cache dirs array for %s\n", name);
640                return NULL;
641            }
642            cache->availDirs = newAvail;
643            cache->dirs = newDirs;
644        }
645        cache->dirs[cache->numDirs] = dir;
646        cache->numDirs++;
647        if (parent != NULL) {
648            parent->childCount++;
649        }
650        _inc_num_cache_collected(cache);
651    } else {
652        ALOGE("Failure allocating cache_dir_t for %s\n", name);
653    }
654    return dir;
655}
656
657static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
658        const char *name)
659{
660    size_t nameLen = strlen(name);
661    cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
662    if (file != NULL) {
663        file->dir = dir;
664        file->modTime = modTime;
665        strcpy(file->name, name);
666        if (cache->numFiles >= cache->availFiles) {
667            size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
668            cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
669                    cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
670            if (newFiles == NULL) {
671                ALOGE("Failure growing cache file array for %s\n", name);
672                return NULL;
673            }
674            cache->availFiles = newAvail;
675            cache->files = newFiles;
676        }
677        CACHE_NOISY(ALOGI("Setting file %p at position %d in array %p", file,
678                cache->numFiles, cache->files));
679        cache->files[cache->numFiles] = file;
680        cache->numFiles++;
681        dir->childCount++;
682        _inc_num_cache_collected(cache);
683    } else {
684        ALOGE("Failure allocating cache_file_t for %s\n", name);
685    }
686    return file;
687}
688
689static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
690        DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
691{
692    struct dirent *de;
693    cache_dir_t* cacheDir = NULL;
694    int dfd;
695
696    CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
697            parentDir, dirName, dir, pathBase));
698
699    dfd = dirfd(dir);
700
701    if (dfd < 0) return 0;
702
703    // Sub-directories always get added to the data structure, so if they
704    // are empty we will know about them to delete them later.
705    cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
706
707    while ((de = readdir(dir))) {
708        const char *name = de->d_name;
709
710        if (de->d_type == DT_DIR) {
711            int subfd;
712            DIR *subdir;
713
714                /* always skip "." and ".." */
715            if (name[0] == '.') {
716                if (name[1] == 0) continue;
717                if ((name[1] == '.') && (name[2] == 0)) continue;
718            }
719
720            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
721            if (subfd < 0) {
722                ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
723                continue;
724            }
725            subdir = fdopendir(subfd);
726            if (subdir == NULL) {
727                ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
728                close(subfd);
729                continue;
730            }
731            if (cacheDir == NULL) {
732                cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
733            }
734            if (cacheDir != NULL) {
735                // Update pathBase for the new path...  this may change dirName
736                // if that is also pointing to the path, but we are done with it
737                // now.
738                size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
739                CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
740                if (finallen < pathAvailLen) {
741                    _add_cache_files(cache, cacheDir, name, subdir, pathBase,
742                            pathPos+finallen, pathAvailLen-finallen);
743                } else {
744                    // Whoops, the final path is too long!  We'll just delete
745                    // this directory.
746                    ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
747                            name, pathBase);
748                    _delete_dir_contents(subdir, NULL);
749                    if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
750                        ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
751                    }
752                }
753            }
754            closedir(subdir);
755        } else if (de->d_type == DT_REG) {
756            // Skip files that start with '.'; they will be deleted if
757            // their entire directory is deleted.  This allows for metadata
758            // like ".nomedia" to remain in the directory until the entire
759            // directory is deleted.
760            if (cacheDir == NULL) {
761                cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
762            }
763            if (name[0] == '.') {
764                cacheDir->hiddenCount++;
765                continue;
766            }
767            if (cacheDir != NULL) {
768                // Build final full path for file...  this may change dirName
769                // if that is also pointing to the path, but we are done with it
770                // now.
771                size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
772                CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
773                if (finallen < pathAvailLen) {
774                    struct stat s;
775                    if (stat(pathBase, &s) >= 0) {
776                        _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
777                    } else {
778                        ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
779                        if (unlink(pathBase) < 0) {
780                            ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
781                        }
782                    }
783                } else {
784                    // Whoops, the final path is too long!  We'll just delete
785                    // this file.
786                    ALOGW("Cache file %s truncated in path %s; deleting\n",
787                            name, pathBase);
788                    if (unlinkat(dfd, name, 0) < 0) {
789                        *pathPos = 0;
790                        ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
791                                strerror(errno));
792                    }
793                }
794            }
795        } else {
796            cacheDir->hiddenCount++;
797        }
798    }
799    return 0;
800}
801
802void add_cache_files(cache_t* cache, const char *basepath, const char *cachedir)
803{
804    DIR *d;
805    struct dirent *de;
806    char dirname[PATH_MAX];
807
808    CACHE_NOISY(ALOGI("add_cache_files: base=%s cachedir=%s\n", basepath, cachedir));
809
810    d = opendir(basepath);
811    if (d == NULL) {
812        return;
813    }
814
815    while ((de = readdir(d))) {
816        if (de->d_type == DT_DIR) {
817            DIR* subdir;
818            const char *name = de->d_name;
819            char* pathpos;
820
821                /* always skip "." and ".." */
822            if (name[0] == '.') {
823                if (name[1] == 0) continue;
824                if ((name[1] == '.') && (name[2] == 0)) continue;
825            }
826
827            strcpy(dirname, basepath);
828            pathpos = dirname + strlen(dirname);
829            if ((*(pathpos-1)) != '/') {
830                *pathpos = '/';
831                pathpos++;
832                *pathpos = 0;
833            }
834            if (cachedir != NULL) {
835                snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s/%s", name, cachedir);
836            } else {
837                snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s", name);
838            }
839            CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
840            subdir = opendir(dirname);
841            if (subdir != NULL) {
842                size_t dirnameLen = strlen(dirname);
843                _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
844                        PATH_MAX - dirnameLen);
845                closedir(subdir);
846            }
847        }
848    }
849
850    closedir(d);
851}
852
853static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
854{
855    char *pos = path;
856    if (dir->parent != NULL) {
857        pos = create_dir_path(path, dir->parent);
858    }
859    // Note that we don't need to worry about going beyond the buffer,
860    // since when we were constructing the cache entries our maximum
861    // buffer size for full paths was PATH_MAX.
862    strcpy(pos, dir->name);
863    pos += strlen(pos);
864    *pos = '/';
865    pos++;
866    *pos = 0;
867    return pos;
868}
869
870static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
871{
872    if (dir->parent != NULL) {
873        create_dir_path(path, dir);
874        ALOGI("DEL DIR %s\n", path);
875        if (dir->hiddenCount <= 0) {
876            if (rmdir(path)) {
877                ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
878                return;
879            }
880        } else {
881            // The directory contains hidden files so we need to delete
882            // them along with the directory itself.
883            if (delete_dir_contents(path, 1, NULL)) {
884                return;
885            }
886        }
887        dir->parent->childCount--;
888        dir->deleted = 1;
889        if (dir->parent->childCount <= 0) {
890            delete_cache_dir(path, dir->parent);
891        }
892    } else if (dir->hiddenCount > 0) {
893        // This is a root directory, but it has hidden files.  Get rid of
894        // all of those files, but not the directory itself.
895        create_dir_path(path, dir);
896        ALOGI("DEL CONTENTS %s\n", path);
897        delete_dir_contents(path, 0, NULL);
898    }
899}
900
901static int cache_modtime_sort(const void *lhsP, const void *rhsP)
902{
903    const cache_file_t *lhs = *(const cache_file_t**)lhsP;
904    const cache_file_t *rhs = *(const cache_file_t**)rhsP;
905    return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
906}
907
908void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size)
909{
910    size_t i;
911    int skip = 0;
912    char path[PATH_MAX];
913
914    ALOGI("Collected cache files: %zd directories, %zd files",
915        cache->numDirs, cache->numFiles);
916
917    CACHE_NOISY(ALOGI("Sorting files..."));
918    qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
919            cache_modtime_sort);
920
921    CACHE_NOISY(ALOGI("Cleaning empty directories..."));
922    for (i=cache->numDirs; i>0; i--) {
923        cache_dir_t* dir = cache->dirs[i-1];
924        if (dir->childCount <= 0 && !dir->deleted) {
925            delete_cache_dir(path, dir);
926        }
927    }
928
929    CACHE_NOISY(ALOGI("Trimming files..."));
930    for (i=0; i<cache->numFiles; i++) {
931        skip++;
932        if (skip > 10) {
933            if (data_disk_free(data_path) > free_size) {
934                return;
935            }
936            skip = 0;
937        }
938        cache_file_t* file = cache->files[i];
939        strcpy(create_dir_path(path, file->dir), file->name);
940        ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
941        if (unlink(path) < 0) {
942            ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
943        }
944        file->dir->childCount--;
945        if (file->dir->childCount <= 0) {
946            delete_cache_dir(path, file->dir);
947        }
948    }
949}
950
951void finish_cache_collection(cache_t* cache)
952{
953    CACHE_NOISY(size_t i;)
954
955    CACHE_NOISY(ALOGI("clear_cache_files: %d dirs, %d files\n", cache->numDirs, cache->numFiles));
956    CACHE_NOISY(
957        for (i=0; i<cache->numDirs; i++) {
958            cache_dir_t* dir = cache->dirs[i];
959            ALOGI("dir #%d: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
960        })
961    CACHE_NOISY(
962        for (i=0; i<cache->numFiles; i++) {
963            cache_file_t* file = cache->files[i];
964            ALOGI("file #%d: %p %s time=%d dir=%p\n", i, file, file->name,
965                    (int)file->modTime, file->dir);
966        })
967    void* block = cache->memBlocks;
968    while (block != NULL) {
969        void* nextBlock = *(void**)block;
970        CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
971        free(block);
972        block = nextBlock;
973    }
974    free(cache);
975}
976
977/**
978 * Validate that the path is valid in the context of the provided directory.
979 * The path is allowed to have at most one subdirectory and no indirections
980 * to top level directories (i.e. have "..").
981 */
982static int validate_path(const dir_rec_t* dir, const char* path, int maxSubdirs) {
983    size_t dir_len = dir->len;
984    const char* subdir = strchr(path + dir_len, '/');
985
986    // Only allow the path to have at most one subdirectory.
987    if (subdir != NULL) {
988        ++subdir;
989        if ((--maxSubdirs == 0) && strchr(subdir, '/') != NULL) {
990            ALOGE("invalid apk path '%s' (subdir?)\n", path);
991            return -1;
992        }
993    }
994
995    // Directories can't have a period directly after the directory markers to prevent "..".
996    if ((path[dir_len] == '.') || ((subdir != NULL) && (*subdir == '.'))) {
997        ALOGE("invalid apk path '%s' (trickery)\n", path);
998        return -1;
999    }
1000
1001    return 0;
1002}
1003
1004/**
1005 * Checks whether a path points to a system app (.apk file). Returns 0
1006 * if it is a system app or -1 if it is not.
1007 */
1008int validate_system_app_path(const char* path) {
1009    size_t i;
1010
1011    for (i = 0; i < android_system_dirs.count; i++) {
1012        const size_t dir_len = android_system_dirs.dirs[i].len;
1013        if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
1014            return validate_path(android_system_dirs.dirs + i, path, 1);
1015        }
1016    }
1017
1018    return -1;
1019}
1020
1021/**
1022 * Get the contents of a environment variable that contains a path. Caller
1023 * owns the string that is inserted into the directory record. Returns
1024 * 0 on success and -1 on error.
1025 */
1026int get_path_from_env(dir_rec_t* rec, const char* var) {
1027    const char* path = getenv(var);
1028    int ret = get_path_from_string(rec, path);
1029    if (ret < 0) {
1030        ALOGW("Problem finding value for environment variable %s\n", var);
1031    }
1032    return ret;
1033}
1034
1035/**
1036 * Puts the string into the record as a directory. Appends '/' to the end
1037 * of all paths. Caller owns the string that is inserted into the directory
1038 * record. A null value will result in an error.
1039 *
1040 * Returns 0 on success and -1 on error.
1041 */
1042int get_path_from_string(dir_rec_t* rec, const char* path) {
1043    if (path == NULL) {
1044        return -1;
1045    } else {
1046        const size_t path_len = strlen(path);
1047        if (path_len <= 0) {
1048            return -1;
1049        }
1050
1051        // Make sure path is absolute.
1052        if (path[0] != '/') {
1053            return -1;
1054        }
1055
1056        if (path[path_len - 1] == '/') {
1057            // Path ends with a forward slash. Make our own copy.
1058
1059            rec->path = strdup(path);
1060            if (rec->path == NULL) {
1061                return -1;
1062            }
1063
1064            rec->len = path_len;
1065        } else {
1066            // Path does not end with a slash. Generate a new string.
1067            char *dst;
1068
1069            // Add space for slash and terminating null.
1070            size_t dst_size = path_len + 2;
1071
1072            rec->path = (char*) malloc(dst_size);
1073            if (rec->path == NULL) {
1074                return -1;
1075            }
1076
1077            dst = rec->path;
1078
1079            if (append_and_increment(&dst, path, &dst_size) < 0
1080                    || append_and_increment(&dst, "/", &dst_size)) {
1081                ALOGE("Error canonicalizing path");
1082                return -1;
1083            }
1084
1085            rec->len = dst - rec->path;
1086        }
1087    }
1088    return 0;
1089}
1090
1091int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
1092    dst->len = src->len + strlen(suffix);
1093    const size_t dstSize = dst->len + 1;
1094    dst->path = (char*) malloc(dstSize);
1095
1096    if (dst->path == NULL
1097            || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
1098                    != (ssize_t) dst->len) {
1099        ALOGE("Could not allocate memory to hold appended path; aborting\n");
1100        return -1;
1101    }
1102
1103    return 0;
1104}
1105
1106/**
1107 * Check whether path points to a valid path for an APK file. The path must
1108 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1109 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1110 * is encountered.
1111 */
1112static int validate_apk_path_internal(const char *path, int maxSubdirs) {
1113    const dir_rec_t* dir = NULL;
1114    if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
1115        dir = &android_app_dir;
1116    } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
1117        dir = &android_app_private_dir;
1118    } else if (!strncmp(path, android_app_ephemeral_dir.path, android_app_ephemeral_dir.len)) {
1119        dir = &android_app_ephemeral_dir;
1120    } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
1121        dir = &android_asec_dir;
1122    } else if (!strncmp(path, android_mnt_expand_dir.path, android_mnt_expand_dir.len)) {
1123        dir = &android_mnt_expand_dir;
1124        if (maxSubdirs < 2) {
1125            maxSubdirs = 2;
1126        }
1127    } else {
1128        return -1;
1129    }
1130
1131    return validate_path(dir, path, maxSubdirs);
1132}
1133
1134int validate_apk_path(const char* path) {
1135    return validate_apk_path_internal(path, 1 /* maxSubdirs */);
1136}
1137
1138int validate_apk_path_subdirs(const char* path) {
1139    return validate_apk_path_internal(path, 3 /* maxSubdirs */);
1140}
1141
1142int append_and_increment(char** dst, const char* src, size_t* dst_size) {
1143    ssize_t ret = strlcpy(*dst, src, *dst_size);
1144    if (ret < 0 || (size_t) ret >= *dst_size) {
1145        return -1;
1146    }
1147    *dst += ret;
1148    *dst_size -= ret;
1149    return 0;
1150}
1151
1152char *build_string2(const char *s1, const char *s2) {
1153    if (s1 == NULL || s2 == NULL) return NULL;
1154
1155    int len_s1 = strlen(s1);
1156    int len_s2 = strlen(s2);
1157    int len = len_s1 + len_s2 + 1;
1158    char *result = (char *) malloc(len);
1159    if (result == NULL) return NULL;
1160
1161    strcpy(result, s1);
1162    strcpy(result + len_s1, s2);
1163
1164    return result;
1165}
1166
1167char *build_string3(const char *s1, const char *s2, const char *s3) {
1168    if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
1169
1170    int len_s1 = strlen(s1);
1171    int len_s2 = strlen(s2);
1172    int len_s3 = strlen(s3);
1173    int len = len_s1 + len_s2 + len_s3 + 1;
1174    char *result = (char *) malloc(len);
1175    if (result == NULL) return NULL;
1176
1177    strcpy(result, s1);
1178    strcpy(result + len_s1, s2);
1179    strcpy(result + len_s1 + len_s2, s3);
1180
1181    return result;
1182}
1183
1184int ensure_config_user_dirs(userid_t userid) {
1185    char config_user_path[PATH_MAX];
1186
1187    // writable by system, readable by any app within the same user
1188    const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1189    const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
1190
1191    // Ensure /data/misc/user/<userid> exists
1192    create_user_config_path(config_user_path, userid);
1193    if (fs_prepare_dir(config_user_path, 0750, uid, gid) == -1) {
1194        return -1;
1195    }
1196
1197   return 0;
1198}
1199
1200int wait_child(pid_t pid)
1201{
1202    int status;
1203    pid_t got_pid;
1204
1205    while (1) {
1206        got_pid = waitpid(pid, &status, 0);
1207        if (got_pid == -1 && errno == EINTR) {
1208            printf("waitpid interrupted, retrying\n");
1209        } else {
1210            break;
1211        }
1212    }
1213    if (got_pid != pid) {
1214        ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1215            (int) pid, (int) got_pid, strerror(errno));
1216        return 1;
1217    }
1218
1219    if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1220        return 0;
1221    } else {
1222        return status;      /* always nonzero */
1223    }
1224}
1225
1226}  // namespace installd
1227}  // namespace android
1228