blob: 8cd116874da74d0cd3246b889adab883cfd8ea6b [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
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100222static int _delete_dir_contents(DIR *d,
223 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700224{
225 int result = 0;
226 struct dirent *de;
227 int dfd;
228
229 dfd = dirfd(d);
230
231 if (dfd < 0) return -1;
232
233 while ((de = readdir(d))) {
234 const char *name = de->d_name;
235
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100236 /* check using the exclusion predicate, if provided */
237 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
238 continue;
239 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700240
241 if (de->d_type == DT_DIR) {
242 int r, subfd;
243 DIR *subdir;
244
245 /* always skip "." and ".." */
246 if (name[0] == '.') {
247 if (name[1] == 0) continue;
248 if ((name[1] == '.') && (name[2] == 0)) continue;
249 }
250
251 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
252 if (subfd < 0) {
253 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
254 result = -1;
255 continue;
256 }
257 subdir = fdopendir(subfd);
258 if (subdir == NULL) {
259 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
260 close(subfd);
261 result = -1;
262 continue;
263 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100264 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700265 result = -1;
266 }
267 closedir(subdir);
268 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
269 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
270 result = -1;
271 }
272 } else {
273 if (unlinkat(dfd, name, 0) < 0) {
274 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
275 result = -1;
276 }
277 }
278 }
279
280 return result;
281}
282
283int delete_dir_contents(const char *pathname,
284 int also_delete_dir,
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100285 int (*exclusion_predicate)(const char*, const int))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700286{
287 int res = 0;
288 DIR *d;
289
290 d = opendir(pathname);
291 if (d == NULL) {
292 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
293 return -errno;
294 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100295 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700296 closedir(d);
297 if (also_delete_dir) {
298 if (rmdir(pathname)) {
299 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
300 res = -1;
301 }
302 }
303 return res;
304}
305
306int delete_dir_contents_fd(int dfd, const char *name)
307{
308 int fd, res;
309 DIR *d;
310
311 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
312 if (fd < 0) {
313 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
314 return -1;
315 }
316 d = fdopendir(fd);
317 if (d == NULL) {
318 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
319 close(fd);
320 return -1;
321 }
322 res = _delete_dir_contents(d, 0);
323 closedir(d);
324 return res;
325}
326
327int lookup_media_dir(char basepath[PATH_MAX], const char *dir)
328{
329 DIR *d;
330 struct dirent *de;
331 struct stat s;
332 char* dirpos = basepath + strlen(basepath);
333
334 if ((*(dirpos-1)) != '/') {
335 *dirpos = '/';
336 dirpos++;
337 }
338
339 CACHE_NOISY(ALOGI("Looking up %s in %s\n", dir, basepath));
340 // Verify the path won't extend beyond our buffer, to avoid
341 // repeated checking later.
342 if ((dirpos-basepath+strlen(dir)) >= (PATH_MAX-1)) {
343 ALOGW("Path exceeds limit: %s%s", basepath, dir);
344 return -1;
345 }
346
347 // First, can we find this directory with the case that is given?
348 strcpy(dirpos, dir);
349 if (stat(basepath, &s) >= 0) {
350 CACHE_NOISY(ALOGI("Found direct: %s\n", basepath));
351 return 0;
352 }
353
354 // Not found with that case... search through all entries to find
355 // one that matches regardless of case.
356 *dirpos = 0;
357
358 d = opendir(basepath);
359 if (d == NULL) {
360 return -1;
361 }
362
363 while ((de = readdir(d))) {
364 if (strcasecmp(de->d_name, dir) == 0) {
365 strcpy(dirpos, de->d_name);
366 closedir(d);
367 CACHE_NOISY(ALOGI("Found search: %s\n", basepath));
368 return 0;
369 }
370 }
371
372 ALOGW("Couldn't find %s in %s", dir, basepath);
373 closedir(d);
374 return -1;
375}
376
377int64_t data_disk_free()
378{
379 struct statfs sfs;
380 if (statfs(android_data_dir.path, &sfs) == 0) {
381 return sfs.f_bavail * sfs.f_bsize;
382 } else {
383 ALOGE("Couldn't statfs %s: %s\n", android_data_dir.path, strerror(errno));
384 return -1;
385 }
386}
387
388cache_t* start_cache_collection()
389{
390 cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
391 return cache;
392}
393
394#define CACHE_BLOCK_SIZE (512*1024)
395
396static void* _cache_malloc(cache_t* cache, size_t len)
397{
398 len = (len+3)&~3;
399 if (len > (CACHE_BLOCK_SIZE/2)) {
400 // It doesn't make sense to try to put this allocation into one
401 // of our blocks, because it is so big. Instead, make a new dedicated
402 // block for it.
403 int8_t* res = (int8_t*)malloc(len+sizeof(void*));
404 if (res == NULL) {
405 return NULL;
406 }
407 CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %d", res, len));
408 // Link it into our list of blocks, not disrupting the current one.
409 if (cache->memBlocks == NULL) {
410 *(void**)res = NULL;
411 cache->memBlocks = res;
412 } else {
413 *(void**)res = *(void**)cache->memBlocks;
414 *(void**)cache->memBlocks = res;
415 }
416 return res + sizeof(void*);
417 }
418 int8_t* res = cache->curMemBlockAvail;
419 int8_t* nextPos = res + len;
420 if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
421 int8_t* newBlock = malloc(CACHE_BLOCK_SIZE);
422 if (newBlock == NULL) {
423 return NULL;
424 }
425 CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
426 *(void**)newBlock = cache->memBlocks;
427 cache->memBlocks = newBlock;
428 res = cache->curMemBlockAvail = newBlock + sizeof(void*);
429 cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
430 nextPos = res + len;
431 }
432 CACHE_NOISY(ALOGI("cache_malloc: ret %p size %d, block=%p, nextPos=%p",
433 res, len, cache->memBlocks, nextPos));
434 cache->curMemBlockAvail = nextPos;
435 return res;
436}
437
438static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
439{
440 // This isn't really a realloc, but it is good enough for our purposes here.
441 void* alloc = _cache_malloc(cache, len);
442 if (alloc != NULL && cur != NULL) {
443 memcpy(alloc, cur, origLen < len ? origLen : len);
444 }
445 return alloc;
446}
447
448static void _inc_num_cache_collected(cache_t* cache)
449{
450 cache->numCollected++;
451 if ((cache->numCollected%20000) == 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700452 ALOGI("Collected cache so far: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700453 cache->numDirs, cache->numFiles);
454 }
455}
456
457static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
458{
459 size_t nameLen = strlen(name);
460 cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
461 if (dir != NULL) {
462 dir->parent = parent;
463 dir->childCount = 0;
464 dir->hiddenCount = 0;
465 dir->deleted = 0;
466 strcpy(dir->name, name);
467 if (cache->numDirs >= cache->availDirs) {
468 size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
469 cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
470 cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
471 if (newDirs == NULL) {
472 ALOGE("Failure growing cache dirs array for %s\n", name);
473 return NULL;
474 }
475 cache->availDirs = newAvail;
476 cache->dirs = newDirs;
477 }
478 cache->dirs[cache->numDirs] = dir;
479 cache->numDirs++;
480 if (parent != NULL) {
481 parent->childCount++;
482 }
483 _inc_num_cache_collected(cache);
484 } else {
485 ALOGE("Failure allocating cache_dir_t for %s\n", name);
486 }
487 return dir;
488}
489
490static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
491 const char *name)
492{
493 size_t nameLen = strlen(name);
494 cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
495 if (file != NULL) {
496 file->dir = dir;
497 file->modTime = modTime;
498 strcpy(file->name, name);
499 if (cache->numFiles >= cache->availFiles) {
500 size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
501 cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
502 cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
503 if (newFiles == NULL) {
504 ALOGE("Failure growing cache file array for %s\n", name);
505 return NULL;
506 }
507 cache->availFiles = newAvail;
508 cache->files = newFiles;
509 }
510 CACHE_NOISY(ALOGI("Setting file %p at position %d in array %p", file,
511 cache->numFiles, cache->files));
512 cache->files[cache->numFiles] = file;
513 cache->numFiles++;
514 dir->childCount++;
515 _inc_num_cache_collected(cache);
516 } else {
517 ALOGE("Failure allocating cache_file_t for %s\n", name);
518 }
519 return file;
520}
521
522static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
523 DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
524{
525 struct dirent *de;
526 cache_dir_t* cacheDir = NULL;
527 int dfd;
528
529 CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
530 parentDir, dirName, dir, pathBase));
531
532 dfd = dirfd(dir);
533
534 if (dfd < 0) return 0;
535
536 // Sub-directories always get added to the data structure, so if they
537 // are empty we will know about them to delete them later.
538 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
539
540 while ((de = readdir(dir))) {
541 const char *name = de->d_name;
542
543 if (de->d_type == DT_DIR) {
544 int subfd;
545 DIR *subdir;
546
547 /* always skip "." and ".." */
548 if (name[0] == '.') {
549 if (name[1] == 0) continue;
550 if ((name[1] == '.') && (name[2] == 0)) continue;
551 }
552
553 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
554 if (subfd < 0) {
555 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
556 continue;
557 }
558 subdir = fdopendir(subfd);
559 if (subdir == NULL) {
560 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
561 close(subfd);
562 continue;
563 }
564 if (cacheDir == NULL) {
565 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
566 }
567 if (cacheDir != NULL) {
568 // Update pathBase for the new path... this may change dirName
569 // if that is also pointing to the path, but we are done with it
570 // now.
571 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
572 CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
573 if (finallen < pathAvailLen) {
574 _add_cache_files(cache, cacheDir, name, subdir, pathBase,
575 pathPos+finallen, pathAvailLen-finallen);
576 } else {
577 // Whoops, the final path is too long! We'll just delete
578 // this directory.
579 ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
580 name, pathBase);
581 _delete_dir_contents(subdir, NULL);
582 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
583 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
584 }
585 }
586 }
587 closedir(subdir);
588 } else if (de->d_type == DT_REG) {
589 // Skip files that start with '.'; they will be deleted if
590 // their entire directory is deleted. This allows for metadata
591 // like ".nomedia" to remain in the directory until the entire
592 // directory is deleted.
593 if (cacheDir == NULL) {
594 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
595 }
596 if (name[0] == '.') {
597 cacheDir->hiddenCount++;
598 continue;
599 }
600 if (cacheDir != NULL) {
601 // Build final full path for file... this may change dirName
602 // if that is also pointing to the path, but we are done with it
603 // now.
604 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
605 CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
606 if (finallen < pathAvailLen) {
607 struct stat s;
608 if (stat(pathBase, &s) >= 0) {
609 _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
610 } else {
611 ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
612 if (unlink(pathBase) < 0) {
613 ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
614 }
615 }
616 } else {
617 // Whoops, the final path is too long! We'll just delete
618 // this file.
619 ALOGW("Cache file %s truncated in path %s; deleting\n",
620 name, pathBase);
621 if (unlinkat(dfd, name, 0) < 0) {
622 *pathPos = 0;
623 ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
624 strerror(errno));
625 }
626 }
627 }
628 } else {
629 cacheDir->hiddenCount++;
630 }
631 }
632 return 0;
633}
634
635void add_cache_files(cache_t* cache, const char *basepath, const char *cachedir)
636{
637 DIR *d;
638 struct dirent *de;
639 char dirname[PATH_MAX];
640
641 CACHE_NOISY(ALOGI("add_cache_files: base=%s cachedir=%s\n", basepath, cachedir));
642
643 d = opendir(basepath);
644 if (d == NULL) {
645 return;
646 }
647
648 while ((de = readdir(d))) {
649 if (de->d_type == DT_DIR) {
650 DIR* subdir;
651 const char *name = de->d_name;
652 char* pathpos;
653
654 /* always skip "." and ".." */
655 if (name[0] == '.') {
656 if (name[1] == 0) continue;
657 if ((name[1] == '.') && (name[2] == 0)) continue;
658 }
659
660 strcpy(dirname, basepath);
661 pathpos = dirname + strlen(dirname);
662 if ((*(pathpos-1)) != '/') {
663 *pathpos = '/';
664 pathpos++;
665 *pathpos = 0;
666 }
667 if (cachedir != NULL) {
668 snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s/%s", name, cachedir);
669 } else {
670 snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s", name);
671 }
672 CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
673 subdir = opendir(dirname);
674 if (subdir != NULL) {
675 size_t dirnameLen = strlen(dirname);
676 _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
677 PATH_MAX - dirnameLen);
678 closedir(subdir);
679 }
680 }
681 }
682
683 closedir(d);
684}
685
686static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
687{
688 char *pos = path;
689 if (dir->parent != NULL) {
690 pos = create_dir_path(path, dir->parent);
691 }
692 // Note that we don't need to worry about going beyond the buffer,
693 // since when we were constructing the cache entries our maximum
694 // buffer size for full paths was PATH_MAX.
695 strcpy(pos, dir->name);
696 pos += strlen(pos);
697 *pos = '/';
698 pos++;
699 *pos = 0;
700 return pos;
701}
702
703static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
704{
705 if (dir->parent != NULL) {
706 create_dir_path(path, dir);
707 ALOGI("DEL DIR %s\n", path);
708 if (dir->hiddenCount <= 0) {
709 if (rmdir(path)) {
710 ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
711 return;
712 }
713 } else {
714 // The directory contains hidden files so we need to delete
715 // them along with the directory itself.
716 if (delete_dir_contents(path, 1, NULL)) {
717 return;
718 }
719 }
720 dir->parent->childCount--;
721 dir->deleted = 1;
722 if (dir->parent->childCount <= 0) {
723 delete_cache_dir(path, dir->parent);
724 }
725 } else if (dir->hiddenCount > 0) {
726 // This is a root directory, but it has hidden files. Get rid of
727 // all of those files, but not the directory itself.
728 create_dir_path(path, dir);
729 ALOGI("DEL CONTENTS %s\n", path);
730 delete_dir_contents(path, 0, NULL);
731 }
732}
733
734static int cache_modtime_sort(const void *lhsP, const void *rhsP)
735{
736 const cache_file_t *lhs = *(const cache_file_t**)lhsP;
737 const cache_file_t *rhs = *(const cache_file_t**)rhsP;
738 return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
739}
740
741void clear_cache_files(cache_t* cache, int64_t free_size)
742{
743 size_t i;
744 int skip = 0;
745 char path[PATH_MAX];
746
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700747 ALOGI("Collected cache files: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700748 cache->numDirs, cache->numFiles);
749
750 CACHE_NOISY(ALOGI("Sorting files..."));
751 qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
752 cache_modtime_sort);
753
754 CACHE_NOISY(ALOGI("Cleaning empty directories..."));
755 for (i=cache->numDirs; i>0; i--) {
756 cache_dir_t* dir = cache->dirs[i-1];
757 if (dir->childCount <= 0 && !dir->deleted) {
758 delete_cache_dir(path, dir);
759 }
760 }
761
762 CACHE_NOISY(ALOGI("Trimming files..."));
763 for (i=0; i<cache->numFiles; i++) {
764 skip++;
765 if (skip > 10) {
766 if (data_disk_free() > free_size) {
767 return;
768 }
769 skip = 0;
770 }
771 cache_file_t* file = cache->files[i];
772 strcpy(create_dir_path(path, file->dir), file->name);
773 ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
774 if (unlink(path) < 0) {
775 ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
776 }
777 file->dir->childCount--;
778 if (file->dir->childCount <= 0) {
779 delete_cache_dir(path, file->dir);
780 }
781 }
782}
783
784void finish_cache_collection(cache_t* cache)
785{
786 size_t i;
787
788 CACHE_NOISY(ALOGI("clear_cache_files: %d dirs, %d files\n", cache->numDirs, cache->numFiles));
789 CACHE_NOISY(
790 for (i=0; i<cache->numDirs; i++) {
791 cache_dir_t* dir = cache->dirs[i];
792 ALOGI("dir #%d: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
793 })
794 CACHE_NOISY(
795 for (i=0; i<cache->numFiles; i++) {
796 cache_file_t* file = cache->files[i];
797 ALOGI("file #%d: %p %s time=%d dir=%p\n", i, file, file->name,
798 (int)file->modTime, file->dir);
799 })
800 void* block = cache->memBlocks;
801 while (block != NULL) {
802 void* nextBlock = *(void**)block;
803 CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
804 free(block);
805 block = nextBlock;
806 }
807 free(cache);
808}
809
810/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100811 * Validate that the path is valid in the context of the provided directory.
812 * The path is allowed to have at most one subdirectory and no indirections
813 * to top level directories (i.e. have "..").
814 */
815static int validate_path(const dir_rec_t* dir, const char* path) {
816 size_t dir_len = dir->len;
817 const char* subdir = strchr(path + dir_len, '/');
818
819 // Only allow the path to have at most one subdirectory.
820 if (subdir != NULL) {
821 ++subdir;
822 if (strchr(subdir, '/') != NULL) {
823 ALOGE("invalid apk path '%s' (subdir?)\n", path);
824 return -1;
825 }
826 }
827
828 // Directories can't have a period directly after the directory markers to prevent "..".
829 if ((path[dir_len] == '.') || ((subdir != NULL) && (*subdir == '.'))) {
830 ALOGE("invalid apk path '%s' (trickery)\n", path);
831 return -1;
832 }
833
834 return 0;
835}
836
837/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700838 * Checks whether a path points to a system app (.apk file). Returns 0
839 * if it is a system app or -1 if it is not.
840 */
841int validate_system_app_path(const char* path) {
842 size_t i;
843
844 for (i = 0; i < android_system_dirs.count; i++) {
845 const size_t dir_len = android_system_dirs.dirs[i].len;
846 if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +0100847 return validate_path(android_system_dirs.dirs + i, path);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700848 }
849 }
850
851 return -1;
852}
853
854/**
855 * Get the contents of a environment variable that contains a path. Caller
856 * owns the string that is inserted into the directory record. Returns
857 * 0 on success and -1 on error.
858 */
859int get_path_from_env(dir_rec_t* rec, const char* var) {
860 const char* path = getenv(var);
861 int ret = get_path_from_string(rec, path);
862 if (ret < 0) {
863 ALOGW("Problem finding value for environment variable %s\n", var);
864 }
865 return ret;
866}
867
868/**
869 * Puts the string into the record as a directory. Appends '/' to the end
870 * of all paths. Caller owns the string that is inserted into the directory
871 * record. A null value will result in an error.
872 *
873 * Returns 0 on success and -1 on error.
874 */
875int get_path_from_string(dir_rec_t* rec, const char* path) {
876 if (path == NULL) {
877 return -1;
878 } else {
879 const size_t path_len = strlen(path);
880 if (path_len <= 0) {
881 return -1;
882 }
883
884 // Make sure path is absolute.
885 if (path[0] != '/') {
886 return -1;
887 }
888
889 if (path[path_len - 1] == '/') {
890 // Path ends with a forward slash. Make our own copy.
891
892 rec->path = strdup(path);
893 if (rec->path == NULL) {
894 return -1;
895 }
896
897 rec->len = path_len;
898 } else {
899 // Path does not end with a slash. Generate a new string.
900 char *dst;
901
902 // Add space for slash and terminating null.
903 size_t dst_size = path_len + 2;
904
905 rec->path = malloc(dst_size);
906 if (rec->path == NULL) {
907 return -1;
908 }
909
910 dst = rec->path;
911
912 if (append_and_increment(&dst, path, &dst_size) < 0
913 || append_and_increment(&dst, "/", &dst_size)) {
914 ALOGE("Error canonicalizing path");
915 return -1;
916 }
917
918 rec->len = dst - rec->path;
919 }
920 }
921 return 0;
922}
923
924int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
925 dst->len = src->len + strlen(suffix);
926 const size_t dstSize = dst->len + 1;
927 dst->path = (char*) malloc(dstSize);
928
929 if (dst->path == NULL
930 || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
931 != (ssize_t) dst->len) {
932 ALOGE("Could not allocate memory to hold appended path; aborting\n");
933 return -1;
934 }
935
936 return 0;
937}
938
939/**
Calin Juravlefd88ff22014-08-15 15:45:51 +0100940 * Check whether path points to a valid path for an APK file. Only one level of
941 * subdirectory names is allowed. Returns -1 when an invalid path is encountered
942 * and 0 when a valid path is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700943 */
944int validate_apk_path(const char *path)
945{
Calin Juravlec597b6d2014-08-19 17:43:05 +0100946 const dir_rec_t* dir = NULL;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700947
948 if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +0100949 dir = &android_app_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700950 } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +0100951 dir = &android_app_private_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700952 } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +0100953 dir = &android_asec_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700954 } else {
955 ALOGE("invalid apk path '%s' (bad prefix)\n", path);
956 return -1;
957 }
958
Calin Juravlec597b6d2014-08-19 17:43:05 +0100959 return validate_path(dir, path);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700960}
961
962int append_and_increment(char** dst, const char* src, size_t* dst_size) {
963 ssize_t ret = strlcpy(*dst, src, *dst_size);
964 if (ret < 0 || (size_t) ret >= *dst_size) {
965 return -1;
966 }
967 *dst += ret;
968 *dst_size -= ret;
969 return 0;
970}
971
972char *build_string2(char *s1, char *s2) {
973 if (s1 == NULL || s2 == NULL) return NULL;
974
975 int len_s1 = strlen(s1);
976 int len_s2 = strlen(s2);
977 int len = len_s1 + len_s2 + 1;
978 char *result = malloc(len);
979 if (result == NULL) return NULL;
980
981 strcpy(result, s1);
982 strcpy(result + len_s1, s2);
983
984 return result;
985}
986
987char *build_string3(char *s1, char *s2, char *s3) {
988 if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
989
990 int len_s1 = strlen(s1);
991 int len_s2 = strlen(s2);
992 int len_s3 = strlen(s3);
993 int len = len_s1 + len_s2 + len_s3 + 1;
994 char *result = malloc(len);
995 if (result == NULL) return NULL;
996
997 strcpy(result, s1);
998 strcpy(result + len_s1, s2);
999 strcpy(result + len_s1 + len_s2, s3);
1000
1001 return result;
1002}
1003
1004/* Ensure that /data/media directories are prepared for given user. */
1005int ensure_media_user_dirs(userid_t userid) {
1006 char media_user_path[PATH_MAX];
1007 char path[PATH_MAX];
1008
1009 // Ensure /data/media/<userid> exists
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -07001010 create_user_media_path(media_user_path, userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001011 if (fs_prepare_dir(media_user_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
1012 return -1;
1013 }
1014
1015 return 0;
1016}
Dave Allisond9370732014-01-30 14:19:23 -08001017
Robin Lee095c7632014-04-25 15:05:19 +01001018int ensure_config_user_dirs(userid_t userid) {
1019 char config_user_path[PATH_MAX];
1020 char path[PATH_MAX];
1021
1022 // writable by system, readable by any app within the same user
1023 const int uid = (userid * AID_USER) + AID_SYSTEM;
1024 const int gid = (userid * AID_USER) + AID_EVERYBODY;
1025
1026 // Ensure /data/misc/user/<userid> exists
1027 create_user_config_path(config_user_path, userid);
1028 if (fs_prepare_dir(config_user_path, 0750, uid, gid) == -1) {
1029 return -1;
1030 }
1031
1032 return 0;
1033}
1034
Dave Allisond9370732014-01-30 14:19:23 -08001035int create_profile_file(const char *pkgname, gid_t gid) {
1036 const char *profile_dir = DALVIK_CACHE_PREFIX "profiles";
Dave Allisond9370732014-01-30 14:19:23 -08001037 char profile_file[PKG_PATH_MAX];
1038
Dave Allisond9370732014-01-30 14:19:23 -08001039 snprintf(profile_file, sizeof(profile_file), "%s/%s", profile_dir, pkgname);
1040
1041 // The 'system' user needs to be able to read the profile to determine if dex2oat
1042 // needs to be run. This is done in dalvik.system.DexFile.isDexOptNeededInternal(). So
Nick Kralevich0db0f972014-06-11 18:23:59 -07001043 // we assign ownership to AID_SYSTEM and ensure it's not world-readable.
Dave Allisond9370732014-01-30 14:19:23 -08001044
Nick Kralevich0db0f972014-06-11 18:23:59 -07001045 int fd = open(profile_file, O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0660);
Dave Allisond9370732014-01-30 14:19:23 -08001046
Nick Kralevich0db0f972014-06-11 18:23:59 -07001047 // Always set the uid/gid/permissions. The file could have been previously created
1048 // with different permissions.
Dave Allisond9370732014-01-30 14:19:23 -08001049 if (fd >= 0) {
Nick Kralevich0db0f972014-06-11 18:23:59 -07001050 if (fchown(fd, AID_SYSTEM, gid) < 0) {
Dave Allisond9370732014-01-30 14:19:23 -08001051 ALOGE("cannot chown profile file '%s': %s\n", profile_file, strerror(errno));
1052 close(fd);
1053 unlink(profile_file);
1054 return -1;
1055 }
1056
Nick Kralevich0db0f972014-06-11 18:23:59 -07001057 if (fchmod(fd, 0660) < 0) {
Dave Allisond9370732014-01-30 14:19:23 -08001058 ALOGE("cannot chmod profile file '%s': %s\n", profile_file, strerror(errno));
1059 close(fd);
1060 unlink(profile_file);
1061 return -1;
1062 }
1063 close(fd);
1064 }
1065 return 0;
1066}
1067
1068void remove_profile_file(const char *pkgname) {
1069 char profile_file[PKG_PATH_MAX];
1070 snprintf(profile_file, sizeof(profile_file), "%s/%s", DALVIK_CACHE_PREFIX "profiles", pkgname);
1071 unlink(profile_file);
1072}