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