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