1/*
2** Copyright 2008, The Android Open Source Project
3**
4** Licensed under the Apache License, Version 2.0 (the "License");
5** you may not use this file except in compliance with the License.
6** You may obtain a copy of the License at
7**
8**     http://www.apache.org/licenses/LICENSE-2.0
9**
10** Unless required by applicable law or agreed to in writing, software
11** distributed under the License is distributed on an "AS IS" BASIS,
12** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13** See the License for the specific language governing permissions and
14** limitations under the License.
15*/
16
17#include "installd.h"
18
19#define CACHE_NOISY(x) //x
20
21int create_pkg_path_in_dir(char path[PKG_PATH_MAX],
22                                const dir_rec_t* dir,
23                                const char* pkgname,
24                                const char* postfix)
25{
26     const size_t postfix_len = strlen(postfix);
27
28     const size_t pkgname_len = strlen(pkgname);
29     if (pkgname_len > PKG_NAME_MAX) {
30         return -1;
31     }
32
33     if (is_valid_package_name(pkgname) < 0) {
34         return -1;
35     }
36
37     if ((pkgname_len + dir->len + postfix_len) >= PKG_PATH_MAX) {
38         return -1;
39     }
40
41     char *dst = path;
42     size_t dst_size = PKG_PATH_MAX;
43
44     if (append_and_increment(&dst, dir->path, &dst_size) < 0
45             || append_and_increment(&dst, pkgname, &dst_size) < 0
46             || append_and_increment(&dst, postfix, &dst_size) < 0) {
47         ALOGE("Error building APK path");
48         return -1;
49     }
50
51     return 0;
52}
53
54/**
55 * Create the package path name for a given package name with a postfix for
56 * a certain persona. Returns 0 on success, and -1 on failure.
57 */
58int create_pkg_path(char path[PKG_PATH_MAX],
59                    const char *pkgname,
60                    const char *postfix,
61                    uid_t persona)
62{
63    size_t uid_len;
64    char* persona_prefix;
65    if (persona == 0) {
66        persona_prefix = PRIMARY_USER_PREFIX;
67        uid_len = 0;
68    } else {
69        persona_prefix = SECONDARY_USER_PREFIX;
70        uid_len = snprintf(NULL, 0, "%d", persona);
71    }
72
73    const size_t prefix_len = android_data_dir.len + strlen(persona_prefix) + uid_len + 1 /*slash*/;
74    char prefix[prefix_len + 1];
75
76    char *dst = prefix;
77    size_t dst_size = sizeof(prefix);
78
79    if (append_and_increment(&dst, android_data_dir.path, &dst_size) < 0
80            || append_and_increment(&dst, persona_prefix, &dst_size) < 0) {
81        ALOGE("Error building prefix for APK path");
82        return -1;
83    }
84
85    if (persona != 0) {
86        int ret = snprintf(dst, dst_size, "%d/", persona);
87        if (ret < 0 || (size_t) ret != uid_len + 1) {
88            ALOGW("Error appending UID to APK path");
89            return -1;
90        }
91    }
92
93    dir_rec_t dir;
94    dir.path = prefix;
95    dir.len = prefix_len;
96
97    return create_pkg_path_in_dir(path, &dir, pkgname, postfix);
98}
99
100/**
101 * Create the path name for user data for a certain persona.
102 * Returns 0 on success, and -1 on failure.
103 */
104int create_persona_path(char path[PKG_PATH_MAX],
105                    uid_t persona)
106{
107    size_t uid_len;
108    char* persona_prefix;
109    if (persona == 0) {
110        persona_prefix = PRIMARY_USER_PREFIX;
111        uid_len = 0;
112    } else {
113        persona_prefix = SECONDARY_USER_PREFIX;
114        uid_len = snprintf(NULL, 0, "%d/", persona);
115    }
116
117    char *dst = path;
118    size_t dst_size = PKG_PATH_MAX;
119
120    if (append_and_increment(&dst, android_data_dir.path, &dst_size) < 0
121            || append_and_increment(&dst, persona_prefix, &dst_size) < 0) {
122        ALOGE("Error building prefix for user path");
123        return -1;
124    }
125
126    if (persona != 0) {
127        if (dst_size < uid_len + 1) {
128            ALOGE("Error building user path");
129            return -1;
130        }
131        int ret = snprintf(dst, dst_size, "%d/", persona);
132        if (ret < 0 || (size_t) ret != uid_len) {
133            ALOGE("Error appending persona id to path");
134            return -1;
135        }
136    }
137    return 0;
138}
139
140/**
141 * Create the path name for media for a certain persona.
142 * Returns 0 on success, and -1 on failure.
143 */
144int create_persona_media_path(char path[PATH_MAX], userid_t userid) {
145    if (snprintf(path, PATH_MAX, "%s%d", android_media_dir.path, userid) > PATH_MAX) {
146        return -1;
147    }
148    return 0;
149}
150
151int create_move_path(char path[PKG_PATH_MAX],
152    const char* pkgname,
153    const char* leaf,
154    uid_t persona)
155{
156    if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
157            >= PKG_PATH_MAX) {
158        return -1;
159    }
160
161    sprintf(path, "%s%s%s/%s", android_data_dir.path, PRIMARY_USER_PREFIX, pkgname, leaf);
162    return 0;
163}
164
165/**
166 * Checks whether the package name is valid. Returns -1 on error and
167 * 0 on success.
168 */
169int is_valid_package_name(const char* pkgname) {
170    const char *x = pkgname;
171    int alpha = -1;
172
173    while (*x) {
174        if (isalnum(*x) || (*x == '_')) {
175                /* alphanumeric or underscore are fine */
176        } else if (*x == '.') {
177            if ((x == pkgname) || (x[1] == '.') || (x[1] == 0)) {
178                    /* periods must not be first, last, or doubled */
179                ALOGE("invalid package name '%s'\n", pkgname);
180                return -1;
181            }
182        } else if (*x == '-') {
183            /* Suffix -X is fine to let versioning of packages.
184               But whatever follows should be alphanumeric.*/
185            alpha = 1;
186        } else {
187                /* anything not A-Z, a-z, 0-9, _, or . is invalid */
188            ALOGE("invalid package name '%s'\n", pkgname);
189            return -1;
190        }
191
192        x++;
193    }
194
195    if (alpha == 1) {
196        // Skip current character
197        x++;
198        while (*x) {
199            if (!isalnum(*x)) {
200                ALOGE("invalid package name '%s' should include only numbers after -\n", pkgname);
201                return -1;
202            }
203            x++;
204        }
205    }
206
207    return 0;
208}
209
210static int _delete_dir_contents(DIR *d, const char *ignore)
211{
212    int result = 0;
213    struct dirent *de;
214    int dfd;
215
216    dfd = dirfd(d);
217
218    if (dfd < 0) return -1;
219
220    while ((de = readdir(d))) {
221        const char *name = de->d_name;
222
223            /* skip the ignore name if provided */
224        if (ignore && !strcmp(name, ignore)) continue;
225
226        if (de->d_type == DT_DIR) {
227            int r, subfd;
228            DIR *subdir;
229
230                /* always skip "." and ".." */
231            if (name[0] == '.') {
232                if (name[1] == 0) continue;
233                if ((name[1] == '.') && (name[2] == 0)) continue;
234            }
235
236            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
237            if (subfd < 0) {
238                ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
239                result = -1;
240                continue;
241            }
242            subdir = fdopendir(subfd);
243            if (subdir == NULL) {
244                ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
245                close(subfd);
246                result = -1;
247                continue;
248            }
249            if (_delete_dir_contents(subdir, 0)) {
250                result = -1;
251            }
252            closedir(subdir);
253            if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
254                ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
255                result = -1;
256            }
257        } else {
258            if (unlinkat(dfd, name, 0) < 0) {
259                ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
260                result = -1;
261            }
262        }
263    }
264
265    return result;
266}
267
268int delete_dir_contents(const char *pathname,
269                        int also_delete_dir,
270                        const char *ignore)
271{
272    int res = 0;
273    DIR *d;
274
275    d = opendir(pathname);
276    if (d == NULL) {
277        ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
278        return -errno;
279    }
280    res = _delete_dir_contents(d, ignore);
281    closedir(d);
282    if (also_delete_dir) {
283        if (rmdir(pathname)) {
284            ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
285            res = -1;
286        }
287    }
288    return res;
289}
290
291int delete_dir_contents_fd(int dfd, const char *name)
292{
293    int fd, res;
294    DIR *d;
295
296    fd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
297    if (fd < 0) {
298        ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
299        return -1;
300    }
301    d = fdopendir(fd);
302    if (d == NULL) {
303        ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
304        close(fd);
305        return -1;
306    }
307    res = _delete_dir_contents(d, 0);
308    closedir(d);
309    return res;
310}
311
312int lookup_media_dir(char basepath[PATH_MAX], const char *dir)
313{
314    DIR *d;
315    struct dirent *de;
316    struct stat s;
317    char* dirpos = basepath + strlen(basepath);
318
319    if ((*(dirpos-1)) != '/') {
320        *dirpos = '/';
321        dirpos++;
322    }
323
324    CACHE_NOISY(ALOGI("Looking up %s in %s\n", dir, basepath));
325    // Verify the path won't extend beyond our buffer, to avoid
326    // repeated checking later.
327    if ((dirpos-basepath+strlen(dir)) >= (PATH_MAX-1)) {
328        ALOGW("Path exceeds limit: %s%s", basepath, dir);
329        return -1;
330    }
331
332    // First, can we find this directory with the case that is given?
333    strcpy(dirpos, dir);
334    if (stat(basepath, &s) >= 0) {
335        CACHE_NOISY(ALOGI("Found direct: %s\n", basepath));
336        return 0;
337    }
338
339    // Not found with that case...  search through all entries to find
340    // one that matches regardless of case.
341    *dirpos = 0;
342
343    d = opendir(basepath);
344    if (d == NULL) {
345        return -1;
346    }
347
348    while ((de = readdir(d))) {
349        if (strcasecmp(de->d_name, dir) == 0) {
350            strcpy(dirpos, de->d_name);
351            closedir(d);
352            CACHE_NOISY(ALOGI("Found search: %s\n", basepath));
353            return 0;
354        }
355    }
356
357    ALOGW("Couldn't find %s in %s", dir, basepath);
358    closedir(d);
359    return -1;
360}
361
362int64_t data_disk_free()
363{
364    struct statfs sfs;
365    if (statfs(android_data_dir.path, &sfs) == 0) {
366        return sfs.f_bavail * sfs.f_bsize;
367    } else {
368        ALOGE("Couldn't statfs %s: %s\n", android_data_dir.path, strerror(errno));
369        return -1;
370    }
371}
372
373cache_t* start_cache_collection()
374{
375    cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
376    return cache;
377}
378
379#define CACHE_BLOCK_SIZE (512*1024)
380
381static void* _cache_malloc(cache_t* cache, size_t len)
382{
383    len = (len+3)&~3;
384    if (len > (CACHE_BLOCK_SIZE/2)) {
385        // It doesn't make sense to try to put this allocation into one
386        // of our blocks, because it is so big.  Instead, make a new dedicated
387        // block for it.
388        int8_t* res = (int8_t*)malloc(len+sizeof(void*));
389        if (res == NULL) {
390            return NULL;
391        }
392        CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %d", res, len));
393        // Link it into our list of blocks, not disrupting the current one.
394        if (cache->memBlocks == NULL) {
395            *(void**)res = NULL;
396            cache->memBlocks = res;
397        } else {
398            *(void**)res = *(void**)cache->memBlocks;
399            *(void**)cache->memBlocks = res;
400        }
401        return res + sizeof(void*);
402    }
403    int8_t* res = cache->curMemBlockAvail;
404    int8_t* nextPos = res + len;
405    if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
406        int8_t* newBlock = malloc(CACHE_BLOCK_SIZE);
407        if (newBlock == NULL) {
408            return NULL;
409        }
410        CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
411        *(void**)newBlock = cache->memBlocks;
412        cache->memBlocks = newBlock;
413        res = cache->curMemBlockAvail = newBlock + sizeof(void*);
414        cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
415        nextPos = res + len;
416    }
417    CACHE_NOISY(ALOGI("cache_malloc: ret %p size %d, block=%p, nextPos=%p",
418            res, len, cache->memBlocks, nextPos));
419    cache->curMemBlockAvail = nextPos;
420    return res;
421}
422
423static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
424{
425    // This isn't really a realloc, but it is good enough for our purposes here.
426    void* alloc = _cache_malloc(cache, len);
427    if (alloc != NULL && cur != NULL) {
428        memcpy(alloc, cur, origLen < len ? origLen : len);
429    }
430    return alloc;
431}
432
433static void _inc_num_cache_collected(cache_t* cache)
434{
435    cache->numCollected++;
436    if ((cache->numCollected%20000) == 0) {
437        ALOGI("Collected cache so far: %d directories, %d files",
438            cache->numDirs, cache->numFiles);
439    }
440}
441
442static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
443{
444    size_t nameLen = strlen(name);
445    cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
446    if (dir != NULL) {
447        dir->parent = parent;
448        dir->childCount = 0;
449        dir->hiddenCount = 0;
450        dir->deleted = 0;
451        strcpy(dir->name, name);
452        if (cache->numDirs >= cache->availDirs) {
453            size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
454            cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
455                    cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
456            if (newDirs == NULL) {
457                ALOGE("Failure growing cache dirs array for %s\n", name);
458                return NULL;
459            }
460            cache->availDirs = newAvail;
461            cache->dirs = newDirs;
462        }
463        cache->dirs[cache->numDirs] = dir;
464        cache->numDirs++;
465        if (parent != NULL) {
466            parent->childCount++;
467        }
468        _inc_num_cache_collected(cache);
469    } else {
470        ALOGE("Failure allocating cache_dir_t for %s\n", name);
471    }
472    return dir;
473}
474
475static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
476        const char *name)
477{
478    size_t nameLen = strlen(name);
479    cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
480    if (file != NULL) {
481        file->dir = dir;
482        file->modTime = modTime;
483        strcpy(file->name, name);
484        if (cache->numFiles >= cache->availFiles) {
485            size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
486            cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
487                    cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
488            if (newFiles == NULL) {
489                ALOGE("Failure growing cache file array for %s\n", name);
490                return NULL;
491            }
492            cache->availFiles = newAvail;
493            cache->files = newFiles;
494        }
495        CACHE_NOISY(ALOGI("Setting file %p at position %d in array %p", file,
496                cache->numFiles, cache->files));
497        cache->files[cache->numFiles] = file;
498        cache->numFiles++;
499        dir->childCount++;
500        _inc_num_cache_collected(cache);
501    } else {
502        ALOGE("Failure allocating cache_file_t for %s\n", name);
503    }
504    return file;
505}
506
507static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
508        DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
509{
510    struct dirent *de;
511    cache_dir_t* cacheDir = NULL;
512    int dfd;
513
514    CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
515            parentDir, dirName, dir, pathBase));
516
517    dfd = dirfd(dir);
518
519    if (dfd < 0) return 0;
520
521    // Sub-directories always get added to the data structure, so if they
522    // are empty we will know about them to delete them later.
523    cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
524
525    while ((de = readdir(dir))) {
526        const char *name = de->d_name;
527
528        if (de->d_type == DT_DIR) {
529            int subfd;
530            DIR *subdir;
531
532                /* always skip "." and ".." */
533            if (name[0] == '.') {
534                if (name[1] == 0) continue;
535                if ((name[1] == '.') && (name[2] == 0)) continue;
536            }
537
538            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
539            if (subfd < 0) {
540                ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
541                continue;
542            }
543            subdir = fdopendir(subfd);
544            if (subdir == NULL) {
545                ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
546                close(subfd);
547                continue;
548            }
549            if (cacheDir == NULL) {
550                cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
551            }
552            if (cacheDir != NULL) {
553                // Update pathBase for the new path...  this may change dirName
554                // if that is also pointing to the path, but we are done with it
555                // now.
556                size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
557                CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
558                if (finallen < pathAvailLen) {
559                    _add_cache_files(cache, cacheDir, name, subdir, pathBase,
560                            pathPos+finallen, pathAvailLen-finallen);
561                } else {
562                    // Whoops, the final path is too long!  We'll just delete
563                    // this directory.
564                    ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
565                            name, pathBase);
566                    _delete_dir_contents(subdir, NULL);
567                    if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
568                        ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
569                    }
570                }
571            }
572            closedir(subdir);
573        } else if (de->d_type == DT_REG) {
574            // Skip files that start with '.'; they will be deleted if
575            // their entire directory is deleted.  This allows for metadata
576            // like ".nomedia" to remain in the directory until the entire
577            // directory is deleted.
578            if (cacheDir == NULL) {
579                cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
580            }
581            if (name[0] == '.') {
582                cacheDir->hiddenCount++;
583                continue;
584            }
585            if (cacheDir != NULL) {
586                // Build final full path for file...  this may change dirName
587                // if that is also pointing to the path, but we are done with it
588                // now.
589                size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
590                CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
591                if (finallen < pathAvailLen) {
592                    struct stat s;
593                    if (stat(pathBase, &s) >= 0) {
594                        _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
595                    } else {
596                        ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
597                        if (unlink(pathBase) < 0) {
598                            ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
599                        }
600                    }
601                } else {
602                    // Whoops, the final path is too long!  We'll just delete
603                    // this file.
604                    ALOGW("Cache file %s truncated in path %s; deleting\n",
605                            name, pathBase);
606                    if (unlinkat(dfd, name, 0) < 0) {
607                        *pathPos = 0;
608                        ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
609                                strerror(errno));
610                    }
611                }
612            }
613        } else {
614            cacheDir->hiddenCount++;
615        }
616    }
617    return 0;
618}
619
620void add_cache_files(cache_t* cache, const char *basepath, const char *cachedir)
621{
622    DIR *d;
623    struct dirent *de;
624    char dirname[PATH_MAX];
625
626    CACHE_NOISY(ALOGI("add_cache_files: base=%s cachedir=%s\n", basepath, cachedir));
627
628    d = opendir(basepath);
629    if (d == NULL) {
630        return;
631    }
632
633    while ((de = readdir(d))) {
634        if (de->d_type == DT_DIR) {
635            DIR* subdir;
636            const char *name = de->d_name;
637            char* pathpos;
638
639                /* always skip "." and ".." */
640            if (name[0] == '.') {
641                if (name[1] == 0) continue;
642                if ((name[1] == '.') && (name[2] == 0)) continue;
643            }
644
645            strcpy(dirname, basepath);
646            pathpos = dirname + strlen(dirname);
647            if ((*(pathpos-1)) != '/') {
648                *pathpos = '/';
649                pathpos++;
650                *pathpos = 0;
651            }
652            if (cachedir != NULL) {
653                snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s/%s", name, cachedir);
654            } else {
655                snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s", name);
656            }
657            CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
658            subdir = opendir(dirname);
659            if (subdir != NULL) {
660                size_t dirnameLen = strlen(dirname);
661                _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
662                        PATH_MAX - dirnameLen);
663                closedir(subdir);
664            }
665        }
666    }
667
668    closedir(d);
669}
670
671static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
672{
673    char *pos = path;
674    if (dir->parent != NULL) {
675        pos = create_dir_path(path, dir->parent);
676    }
677    // Note that we don't need to worry about going beyond the buffer,
678    // since when we were constructing the cache entries our maximum
679    // buffer size for full paths was PATH_MAX.
680    strcpy(pos, dir->name);
681    pos += strlen(pos);
682    *pos = '/';
683    pos++;
684    *pos = 0;
685    return pos;
686}
687
688static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
689{
690    if (dir->parent != NULL) {
691        create_dir_path(path, dir);
692        ALOGI("DEL DIR %s\n", path);
693        if (dir->hiddenCount <= 0) {
694            if (rmdir(path)) {
695                ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
696                return;
697            }
698        } else {
699            // The directory contains hidden files so we need to delete
700            // them along with the directory itself.
701            if (delete_dir_contents(path, 1, NULL)) {
702                return;
703            }
704        }
705        dir->parent->childCount--;
706        dir->deleted = 1;
707        if (dir->parent->childCount <= 0) {
708            delete_cache_dir(path, dir->parent);
709        }
710    } else if (dir->hiddenCount > 0) {
711        // This is a root directory, but it has hidden files.  Get rid of
712        // all of those files, but not the directory itself.
713        create_dir_path(path, dir);
714        ALOGI("DEL CONTENTS %s\n", path);
715        delete_dir_contents(path, 0, NULL);
716    }
717}
718
719static int cache_modtime_sort(const void *lhsP, const void *rhsP)
720{
721    const cache_file_t *lhs = *(const cache_file_t**)lhsP;
722    const cache_file_t *rhs = *(const cache_file_t**)rhsP;
723    return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
724}
725
726void clear_cache_files(cache_t* cache, int64_t free_size)
727{
728    size_t i;
729    int skip = 0;
730    char path[PATH_MAX];
731
732    ALOGI("Collected cache files: %d directories, %d files",
733        cache->numDirs, cache->numFiles);
734
735    CACHE_NOISY(ALOGI("Sorting files..."));
736    qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
737            cache_modtime_sort);
738
739    CACHE_NOISY(ALOGI("Cleaning empty directories..."));
740    for (i=cache->numDirs; i>0; i--) {
741        cache_dir_t* dir = cache->dirs[i-1];
742        if (dir->childCount <= 0 && !dir->deleted) {
743            delete_cache_dir(path, dir);
744        }
745    }
746
747    CACHE_NOISY(ALOGI("Trimming files..."));
748    for (i=0; i<cache->numFiles; i++) {
749        skip++;
750        if (skip > 10) {
751            if (data_disk_free() > free_size) {
752                return;
753            }
754            skip = 0;
755        }
756        cache_file_t* file = cache->files[i];
757        strcpy(create_dir_path(path, file->dir), file->name);
758        ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
759        if (unlink(path) < 0) {
760            ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
761        }
762        file->dir->childCount--;
763        if (file->dir->childCount <= 0) {
764            delete_cache_dir(path, file->dir);
765        }
766    }
767}
768
769void finish_cache_collection(cache_t* cache)
770{
771    size_t i;
772
773    CACHE_NOISY(ALOGI("clear_cache_files: %d dirs, %d files\n", cache->numDirs, cache->numFiles));
774    CACHE_NOISY(
775        for (i=0; i<cache->numDirs; i++) {
776            cache_dir_t* dir = cache->dirs[i];
777            ALOGI("dir #%d: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
778        })
779    CACHE_NOISY(
780        for (i=0; i<cache->numFiles; i++) {
781            cache_file_t* file = cache->files[i];
782            ALOGI("file #%d: %p %s time=%d dir=%p\n", i, file, file->name,
783                    (int)file->modTime, file->dir);
784        })
785    void* block = cache->memBlocks;
786    while (block != NULL) {
787        void* nextBlock = *(void**)block;
788        CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
789        free(block);
790        block = nextBlock;
791    }
792    free(cache);
793}
794
795/**
796 * Checks whether a path points to a system app (.apk file). Returns 0
797 * if it is a system app or -1 if it is not.
798 */
799int validate_system_app_path(const char* path) {
800    size_t i;
801
802    for (i = 0; i < android_system_dirs.count; i++) {
803        const size_t dir_len = android_system_dirs.dirs[i].len;
804        if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
805            if (path[dir_len] == '.' || strchr(path + dir_len, '/') != NULL) {
806                ALOGE("invalid system apk path '%s' (trickery)\n", path);
807                return -1;
808            }
809            return 0;
810        }
811    }
812
813    return -1;
814}
815
816/**
817 * Get the contents of a environment variable that contains a path. Caller
818 * owns the string that is inserted into the directory record. Returns
819 * 0 on success and -1 on error.
820 */
821int get_path_from_env(dir_rec_t* rec, const char* var) {
822    const char* path = getenv(var);
823    int ret = get_path_from_string(rec, path);
824    if (ret < 0) {
825        ALOGW("Problem finding value for environment variable %s\n", var);
826    }
827    return ret;
828}
829
830/**
831 * Puts the string into the record as a directory. Appends '/' to the end
832 * of all paths. Caller owns the string that is inserted into the directory
833 * record. A null value will result in an error.
834 *
835 * Returns 0 on success and -1 on error.
836 */
837int get_path_from_string(dir_rec_t* rec, const char* path) {
838    if (path == NULL) {
839        return -1;
840    } else {
841        const size_t path_len = strlen(path);
842        if (path_len <= 0) {
843            return -1;
844        }
845
846        // Make sure path is absolute.
847        if (path[0] != '/') {
848            return -1;
849        }
850
851        if (path[path_len - 1] == '/') {
852            // Path ends with a forward slash. Make our own copy.
853
854            rec->path = strdup(path);
855            if (rec->path == NULL) {
856                return -1;
857            }
858
859            rec->len = path_len;
860        } else {
861            // Path does not end with a slash. Generate a new string.
862            char *dst;
863
864            // Add space for slash and terminating null.
865            size_t dst_size = path_len + 2;
866
867            rec->path = malloc(dst_size);
868            if (rec->path == NULL) {
869                return -1;
870            }
871
872            dst = rec->path;
873
874            if (append_and_increment(&dst, path, &dst_size) < 0
875                    || append_and_increment(&dst, "/", &dst_size)) {
876                ALOGE("Error canonicalizing path");
877                return -1;
878            }
879
880            rec->len = dst - rec->path;
881        }
882    }
883    return 0;
884}
885
886int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
887    dst->len = src->len + strlen(suffix);
888    const size_t dstSize = dst->len + 1;
889    dst->path = (char*) malloc(dstSize);
890
891    if (dst->path == NULL
892            || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
893                    != (ssize_t) dst->len) {
894        ALOGE("Could not allocate memory to hold appended path; aborting\n");
895        return -1;
896    }
897
898    return 0;
899}
900
901/**
902 * Check whether path points to a valid path for an APK file. An ASEC
903 * directory is allowed to have one level of subdirectory names. Returns -1
904 * when an invalid path is encountered and 0 when a valid path is encountered.
905 */
906int validate_apk_path(const char *path)
907{
908    int allowsubdir = 0;
909    char *subdir = NULL;
910    size_t dir_len;
911    size_t path_len;
912
913    if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
914        dir_len = android_app_dir.len;
915    } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
916        dir_len = android_app_private_dir.len;
917    } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
918        dir_len = android_asec_dir.len;
919        allowsubdir = 1;
920    } else {
921        ALOGE("invalid apk path '%s' (bad prefix)\n", path);
922        return -1;
923    }
924
925    path_len = strlen(path);
926
927    /*
928     * Only allow the path to have a subdirectory if it's been marked as being allowed.
929     */
930    if ((subdir = strchr(path + dir_len, '/')) != NULL) {
931        ++subdir;
932        if (!allowsubdir
933                || (path_len > (size_t) (subdir - path) && (strchr(subdir, '/') != NULL))) {
934            ALOGE("invalid apk path '%s' (subdir?)\n", path);
935            return -1;
936        }
937    }
938
939    /*
940     *  Directories can't have a period directly after the directory markers
941     *  to prevent ".."
942     */
943    if (path[dir_len] == '.'
944            || (subdir != NULL && ((*subdir == '.') || (strchr(subdir, '/') != NULL)))) {
945        ALOGE("invalid apk path '%s' (trickery)\n", path);
946        return -1;
947    }
948
949    return 0;
950}
951
952int append_and_increment(char** dst, const char* src, size_t* dst_size) {
953    ssize_t ret = strlcpy(*dst, src, *dst_size);
954    if (ret < 0 || (size_t) ret >= *dst_size) {
955        return -1;
956    }
957    *dst += ret;
958    *dst_size -= ret;
959    return 0;
960}
961
962char *build_string2(char *s1, char *s2) {
963    if (s1 == NULL || s2 == NULL) return NULL;
964
965    int len_s1 = strlen(s1);
966    int len_s2 = strlen(s2);
967    int len = len_s1 + len_s2 + 1;
968    char *result = malloc(len);
969    if (result == NULL) return NULL;
970
971    strcpy(result, s1);
972    strcpy(result + len_s1, s2);
973
974    return result;
975}
976
977char *build_string3(char *s1, char *s2, char *s3) {
978    if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
979
980    int len_s1 = strlen(s1);
981    int len_s2 = strlen(s2);
982    int len_s3 = strlen(s3);
983    int len = len_s1 + len_s2 + len_s3 + 1;
984    char *result = malloc(len);
985    if (result == NULL) return NULL;
986
987    strcpy(result, s1);
988    strcpy(result + len_s1, s2);
989    strcpy(result + len_s1 + len_s2, s3);
990
991    return result;
992}
993
994/* Ensure that /data/media directories are prepared for given user. */
995int ensure_media_user_dirs(userid_t userid) {
996    char media_user_path[PATH_MAX];
997    char path[PATH_MAX];
998
999    // Ensure /data/media/<userid> exists
1000    create_persona_media_path(media_user_path, userid);
1001    if (fs_prepare_dir(media_user_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
1002        return -1;
1003    }
1004
1005    return 0;
1006}
1007