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