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