blob: e10116eb835c57cc6441c901e871e1a71a0ddc7b [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
Jeff Sharkeyc03de092015-04-07 18:14:05 -070019#include <base/stringprintf.h>
20#include <base/logging.h>
21
Mike Lockwood94afecf2012-10-24 10:45:23 -070022#define CACHE_NOISY(x) //x
23
Jeff Sharkeyc03de092015-04-07 18:14:05 -070024using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070025
Jeff Sharkeyc03de092015-04-07 18:14:05 -070026/**
27 * Check that given string is valid filename, and that it attempts no
28 * parent or child directory traversal.
29 */
30static bool is_valid_filename(const std::string& name) {
31 if (name.empty() || (name == ".") || (name == "..")
32 || (name.find('/') != std::string::npos)) {
33 return false;
34 } else {
35 return true;
36 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070037}
38
39/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070040 * Create the path name where package data should be stored for the given
41 * volume UUID, package name, and user ID. An empty UUID is assumed to be
42 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070043 */
Jeff Sharkeyc03de092015-04-07 18:14:05 -070044std::string create_package_data_path(const char* volume_uuid,
45 const char* package_name, userid_t user) {
46 CHECK(is_valid_filename(package_name));
47 CHECK(is_valid_package_name(package_name) == 0);
48
Jeff Sharkey41ea4242015-04-09 11:34:03 -070049 return StringPrintf("%s/%s", create_data_user_path(volume_uuid, user).c_str(), package_name);
Jeff Sharkeyc03de092015-04-07 18:14:05 -070050}
Mike Lockwood94afecf2012-10-24 10:45:23 -070051
Jeff Sharkeyc03de092015-04-07 18:14:05 -070052int create_pkg_path(char path[PKG_PATH_MAX], const char *pkgname,
53 const char *postfix, userid_t userid) {
54 if (is_valid_package_name(pkgname) != 0) {
55 path[0] = '\0';
Mike Lockwood94afecf2012-10-24 10:45:23 -070056 return -1;
57 }
58
Jeff Sharkeyc03de092015-04-07 18:14:05 -070059 std::string _tmp(create_package_data_path(nullptr, pkgname, userid) + postfix);
60 const char* tmp = _tmp.c_str();
61 if (strlen(tmp) >= PKG_PATH_MAX) {
62 path[0] = '\0';
63 return -1;
64 } else {
65 strcpy(path, tmp);
66 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -070067 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070068}
69
Jeff Sharkey41ea4242015-04-09 11:34:03 -070070std::string create_data_path(const char* volume_uuid) {
71 if (volume_uuid == nullptr) {
72 return "/data";
73 } else {
74 CHECK(is_valid_filename(volume_uuid));
75 return StringPrintf("/mnt/expand/%s", volume_uuid);
76 }
77}
78
Mike Lockwood94afecf2012-10-24 10:45:23 -070079/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -070080 * Create the path name for user data for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -070081 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -070082std::string create_data_user_path(const char* volume_uuid, userid_t userid) {
83 std::string data(create_data_path(volume_uuid));
84 if (volume_uuid == nullptr) {
85 if (userid == 0) {
86 return StringPrintf("%s/data", data.c_str());
87 } else {
88 return StringPrintf("%s/user/%u", data.c_str(), userid);
89 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070090 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -070091 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -070092 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070093}
94
95/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -070096 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -070097 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -070098std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
99 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700100}
101
Robin Lee095c7632014-04-25 15:05:19 +0100102/**
103 * Create the path name for config for a certain userid.
104 * Returns 0 on success, and -1 on failure.
105 */
106int create_user_config_path(char path[PATH_MAX], userid_t userid) {
107 if (snprintf(path, PATH_MAX, "%s%d", "/data/misc/user/", userid) > PATH_MAX) {
108 return -1;
109 }
110 return 0;
111}
112
Mike Lockwood94afecf2012-10-24 10:45:23 -0700113int create_move_path(char path[PKG_PATH_MAX],
114 const char* pkgname,
115 const char* leaf,
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700116 userid_t userid __unused)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700117{
118 if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
119 >= PKG_PATH_MAX) {
120 return -1;
121 }
122
123 sprintf(path, "%s%s%s/%s", android_data_dir.path, PRIMARY_USER_PREFIX, pkgname, leaf);
124 return 0;
125}
126
127/**
128 * Checks whether the package name is valid. Returns -1 on error and
129 * 0 on success.
130 */
131int is_valid_package_name(const char* pkgname) {
132 const char *x = pkgname;
133 int alpha = -1;
134
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700135 if (strlen(pkgname) > PKG_NAME_MAX) {
136 return -1;
137 }
138
Mike Lockwood94afecf2012-10-24 10:45:23 -0700139 while (*x) {
140 if (isalnum(*x) || (*x == '_')) {
141 /* alphanumeric or underscore are fine */
142 } else if (*x == '.') {
143 if ((x == pkgname) || (x[1] == '.') || (x[1] == 0)) {
144 /* periods must not be first, last, or doubled */
145 ALOGE("invalid package name '%s'\n", pkgname);
146 return -1;
147 }
148 } else if (*x == '-') {
149 /* Suffix -X is fine to let versioning of packages.
150 But whatever follows should be alphanumeric.*/
151 alpha = 1;
152 } else {
153 /* anything not A-Z, a-z, 0-9, _, or . is invalid */
154 ALOGE("invalid package name '%s'\n", pkgname);
155 return -1;
156 }
157
158 x++;
159 }
160
161 if (alpha == 1) {
162 // Skip current character
163 x++;
164 while (*x) {
165 if (!isalnum(*x)) {
166 ALOGE("invalid package name '%s' should include only numbers after -\n", pkgname);
167 return -1;
168 }
169 x++;
170 }
171 }
172
173 return 0;
174}
175
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100176static int _delete_dir_contents(DIR *d,
177 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700178{
179 int result = 0;
180 struct dirent *de;
181 int dfd;
182
183 dfd = dirfd(d);
184
185 if (dfd < 0) return -1;
186
187 while ((de = readdir(d))) {
188 const char *name = de->d_name;
189
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100190 /* check using the exclusion predicate, if provided */
191 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
192 continue;
193 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700194
195 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700196 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700197 DIR *subdir;
198
199 /* always skip "." and ".." */
200 if (name[0] == '.') {
201 if (name[1] == 0) continue;
202 if ((name[1] == '.') && (name[2] == 0)) continue;
203 }
204
205 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
206 if (subfd < 0) {
207 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
208 result = -1;
209 continue;
210 }
211 subdir = fdopendir(subfd);
212 if (subdir == NULL) {
213 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
214 close(subfd);
215 result = -1;
216 continue;
217 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100218 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700219 result = -1;
220 }
221 closedir(subdir);
222 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
223 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
224 result = -1;
225 }
226 } else {
227 if (unlinkat(dfd, name, 0) < 0) {
228 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
229 result = -1;
230 }
231 }
232 }
233
234 return result;
235}
236
237int delete_dir_contents(const char *pathname,
238 int also_delete_dir,
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100239 int (*exclusion_predicate)(const char*, const int))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700240{
241 int res = 0;
242 DIR *d;
243
244 d = opendir(pathname);
245 if (d == NULL) {
246 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
247 return -errno;
248 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100249 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700250 closedir(d);
251 if (also_delete_dir) {
252 if (rmdir(pathname)) {
253 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
254 res = -1;
255 }
256 }
257 return res;
258}
259
260int delete_dir_contents_fd(int dfd, const char *name)
261{
262 int fd, res;
263 DIR *d;
264
265 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
266 if (fd < 0) {
267 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
268 return -1;
269 }
270 d = fdopendir(fd);
271 if (d == NULL) {
272 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
273 close(fd);
274 return -1;
275 }
276 res = _delete_dir_contents(d, 0);
277 closedir(d);
278 return res;
279}
280
Robin Lee60fd3fe2014-10-07 16:55:02 +0100281static int _copy_owner_permissions(int srcfd, int dstfd)
282{
283 struct stat st;
284 if (fstat(srcfd, &st) != 0) {
285 return -1;
286 }
287 if (fchmod(dstfd, st.st_mode) != 0) {
288 return -1;
289 }
290 return 0;
291}
292
293static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
294{
295 int result = 0;
296 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
297 ALOGE("_copy_dir_files failed to copy dir permissions\n");
298 }
299 if (fchown(ddfd, owner, group) != 0) {
300 ALOGE("_copy_dir_files failed to change dir owner\n");
301 }
302
303 DIR *ds = fdopendir(sdfd);
304 if (ds == NULL) {
305 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
306 return -1;
307 }
308 struct dirent *de;
309 while ((de = readdir(ds))) {
310 if (de->d_type != DT_REG) {
311 continue;
312 }
313
314 const char *name = de->d_name;
315 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
316 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
317 if (fsfd == -1 || fdfd == -1) {
318 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
319 } else {
320 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
321 ALOGE("Failed to change file permissions\n");
322 }
323 if (fchown(fdfd, owner, group) != 0) {
324 ALOGE("Failed to change file owner\n");
325 }
326
327 char buf[8192];
328 ssize_t size;
329 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
330 write(fdfd, buf, size);
331 }
332 if (size < 0) {
333 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
334 result = -1;
335 }
336 }
337 close(fdfd);
338 close(fsfd);
339 }
340
341 return result;
342}
343
344int copy_dir_files(const char *srcname,
345 const char *dstname,
346 uid_t owner,
347 uid_t group)
348{
349 int res = 0;
350 DIR *ds = NULL;
351 DIR *dd = NULL;
352
353 ds = opendir(srcname);
354 if (ds == NULL) {
355 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
356 return -errno;
357 }
358
359 mkdir(dstname, 0600);
360 dd = opendir(dstname);
361 if (dd == NULL) {
362 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
363 closedir(ds);
364 return -errno;
365 }
366
367 int sdfd = dirfd(ds);
368 int ddfd = dirfd(dd);
369 if (sdfd != -1 && ddfd != -1) {
370 res = _copy_dir_files(sdfd, ddfd, owner, group);
371 } else {
372 res = -errno;
373 }
374 closedir(dd);
375 closedir(ds);
376 return res;
377}
378
Mike Lockwood94afecf2012-10-24 10:45:23 -0700379int lookup_media_dir(char basepath[PATH_MAX], const char *dir)
380{
381 DIR *d;
382 struct dirent *de;
383 struct stat s;
384 char* dirpos = basepath + strlen(basepath);
385
386 if ((*(dirpos-1)) != '/') {
387 *dirpos = '/';
388 dirpos++;
389 }
390
391 CACHE_NOISY(ALOGI("Looking up %s in %s\n", dir, basepath));
392 // Verify the path won't extend beyond our buffer, to avoid
393 // repeated checking later.
394 if ((dirpos-basepath+strlen(dir)) >= (PATH_MAX-1)) {
395 ALOGW("Path exceeds limit: %s%s", basepath, dir);
396 return -1;
397 }
398
399 // First, can we find this directory with the case that is given?
400 strcpy(dirpos, dir);
401 if (stat(basepath, &s) >= 0) {
402 CACHE_NOISY(ALOGI("Found direct: %s\n", basepath));
403 return 0;
404 }
405
406 // Not found with that case... search through all entries to find
407 // one that matches regardless of case.
408 *dirpos = 0;
409
410 d = opendir(basepath);
411 if (d == NULL) {
412 return -1;
413 }
414
415 while ((de = readdir(d))) {
416 if (strcasecmp(de->d_name, dir) == 0) {
417 strcpy(dirpos, de->d_name);
418 closedir(d);
419 CACHE_NOISY(ALOGI("Found search: %s\n", basepath));
420 return 0;
421 }
422 }
423
424 ALOGW("Couldn't find %s in %s", dir, basepath);
425 closedir(d);
426 return -1;
427}
428
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700429int64_t data_disk_free(const std::string& data_path)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700430{
431 struct statfs sfs;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700432 if (statfs(data_path.c_str(), &sfs) == 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700433 return sfs.f_bavail * sfs.f_bsize;
434 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700435 PLOG(ERROR) << "Couldn't statfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700436 return -1;
437 }
438}
439
440cache_t* start_cache_collection()
441{
442 cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
443 return cache;
444}
445
446#define CACHE_BLOCK_SIZE (512*1024)
447
448static void* _cache_malloc(cache_t* cache, size_t len)
449{
450 len = (len+3)&~3;
451 if (len > (CACHE_BLOCK_SIZE/2)) {
452 // It doesn't make sense to try to put this allocation into one
453 // of our blocks, because it is so big. Instead, make a new dedicated
454 // block for it.
455 int8_t* res = (int8_t*)malloc(len+sizeof(void*));
456 if (res == NULL) {
457 return NULL;
458 }
459 CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %d", res, len));
460 // Link it into our list of blocks, not disrupting the current one.
461 if (cache->memBlocks == NULL) {
462 *(void**)res = NULL;
463 cache->memBlocks = res;
464 } else {
465 *(void**)res = *(void**)cache->memBlocks;
466 *(void**)cache->memBlocks = res;
467 }
468 return res + sizeof(void*);
469 }
470 int8_t* res = cache->curMemBlockAvail;
471 int8_t* nextPos = res + len;
472 if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
Jeff Sharkey19803802015-04-07 12:44:51 -0700473 int8_t* newBlock = (int8_t*) malloc(CACHE_BLOCK_SIZE);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700474 if (newBlock == NULL) {
475 return NULL;
476 }
477 CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
478 *(void**)newBlock = cache->memBlocks;
479 cache->memBlocks = newBlock;
480 res = cache->curMemBlockAvail = newBlock + sizeof(void*);
481 cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
482 nextPos = res + len;
483 }
484 CACHE_NOISY(ALOGI("cache_malloc: ret %p size %d, block=%p, nextPos=%p",
485 res, len, cache->memBlocks, nextPos));
486 cache->curMemBlockAvail = nextPos;
487 return res;
488}
489
490static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
491{
492 // This isn't really a realloc, but it is good enough for our purposes here.
493 void* alloc = _cache_malloc(cache, len);
494 if (alloc != NULL && cur != NULL) {
495 memcpy(alloc, cur, origLen < len ? origLen : len);
496 }
497 return alloc;
498}
499
500static void _inc_num_cache_collected(cache_t* cache)
501{
502 cache->numCollected++;
503 if ((cache->numCollected%20000) == 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700504 ALOGI("Collected cache so far: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700505 cache->numDirs, cache->numFiles);
506 }
507}
508
509static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
510{
511 size_t nameLen = strlen(name);
512 cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
513 if (dir != NULL) {
514 dir->parent = parent;
515 dir->childCount = 0;
516 dir->hiddenCount = 0;
517 dir->deleted = 0;
518 strcpy(dir->name, name);
519 if (cache->numDirs >= cache->availDirs) {
520 size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
521 cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
522 cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
523 if (newDirs == NULL) {
524 ALOGE("Failure growing cache dirs array for %s\n", name);
525 return NULL;
526 }
527 cache->availDirs = newAvail;
528 cache->dirs = newDirs;
529 }
530 cache->dirs[cache->numDirs] = dir;
531 cache->numDirs++;
532 if (parent != NULL) {
533 parent->childCount++;
534 }
535 _inc_num_cache_collected(cache);
536 } else {
537 ALOGE("Failure allocating cache_dir_t for %s\n", name);
538 }
539 return dir;
540}
541
542static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
543 const char *name)
544{
545 size_t nameLen = strlen(name);
546 cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
547 if (file != NULL) {
548 file->dir = dir;
549 file->modTime = modTime;
550 strcpy(file->name, name);
551 if (cache->numFiles >= cache->availFiles) {
552 size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
553 cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
554 cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
555 if (newFiles == NULL) {
556 ALOGE("Failure growing cache file array for %s\n", name);
557 return NULL;
558 }
559 cache->availFiles = newAvail;
560 cache->files = newFiles;
561 }
562 CACHE_NOISY(ALOGI("Setting file %p at position %d in array %p", file,
563 cache->numFiles, cache->files));
564 cache->files[cache->numFiles] = file;
565 cache->numFiles++;
566 dir->childCount++;
567 _inc_num_cache_collected(cache);
568 } else {
569 ALOGE("Failure allocating cache_file_t for %s\n", name);
570 }
571 return file;
572}
573
574static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
575 DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
576{
577 struct dirent *de;
578 cache_dir_t* cacheDir = NULL;
579 int dfd;
580
581 CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
582 parentDir, dirName, dir, pathBase));
583
584 dfd = dirfd(dir);
585
586 if (dfd < 0) return 0;
587
588 // Sub-directories always get added to the data structure, so if they
589 // are empty we will know about them to delete them later.
590 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
591
592 while ((de = readdir(dir))) {
593 const char *name = de->d_name;
594
595 if (de->d_type == DT_DIR) {
596 int subfd;
597 DIR *subdir;
598
599 /* always skip "." and ".." */
600 if (name[0] == '.') {
601 if (name[1] == 0) continue;
602 if ((name[1] == '.') && (name[2] == 0)) continue;
603 }
604
605 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
606 if (subfd < 0) {
607 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
608 continue;
609 }
610 subdir = fdopendir(subfd);
611 if (subdir == NULL) {
612 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
613 close(subfd);
614 continue;
615 }
616 if (cacheDir == NULL) {
617 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
618 }
619 if (cacheDir != NULL) {
620 // Update pathBase for the new path... this may change dirName
621 // if that is also pointing to the path, but we are done with it
622 // now.
623 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
624 CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
625 if (finallen < pathAvailLen) {
626 _add_cache_files(cache, cacheDir, name, subdir, pathBase,
627 pathPos+finallen, pathAvailLen-finallen);
628 } else {
629 // Whoops, the final path is too long! We'll just delete
630 // this directory.
631 ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
632 name, pathBase);
633 _delete_dir_contents(subdir, NULL);
634 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
635 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
636 }
637 }
638 }
639 closedir(subdir);
640 } else if (de->d_type == DT_REG) {
641 // Skip files that start with '.'; they will be deleted if
642 // their entire directory is deleted. This allows for metadata
643 // like ".nomedia" to remain in the directory until the entire
644 // directory is deleted.
645 if (cacheDir == NULL) {
646 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
647 }
648 if (name[0] == '.') {
649 cacheDir->hiddenCount++;
650 continue;
651 }
652 if (cacheDir != NULL) {
653 // Build final full path for file... this may change dirName
654 // if that is also pointing to the path, but we are done with it
655 // now.
656 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
657 CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
658 if (finallen < pathAvailLen) {
659 struct stat s;
660 if (stat(pathBase, &s) >= 0) {
661 _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
662 } else {
663 ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
664 if (unlink(pathBase) < 0) {
665 ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
666 }
667 }
668 } else {
669 // Whoops, the final path is too long! We'll just delete
670 // this file.
671 ALOGW("Cache file %s truncated in path %s; deleting\n",
672 name, pathBase);
673 if (unlinkat(dfd, name, 0) < 0) {
674 *pathPos = 0;
675 ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
676 strerror(errno));
677 }
678 }
679 }
680 } else {
681 cacheDir->hiddenCount++;
682 }
683 }
684 return 0;
685}
686
687void add_cache_files(cache_t* cache, const char *basepath, const char *cachedir)
688{
689 DIR *d;
690 struct dirent *de;
691 char dirname[PATH_MAX];
692
693 CACHE_NOISY(ALOGI("add_cache_files: base=%s cachedir=%s\n", basepath, cachedir));
694
695 d = opendir(basepath);
696 if (d == NULL) {
697 return;
698 }
699
700 while ((de = readdir(d))) {
701 if (de->d_type == DT_DIR) {
702 DIR* subdir;
703 const char *name = de->d_name;
704 char* pathpos;
705
706 /* always skip "." and ".." */
707 if (name[0] == '.') {
708 if (name[1] == 0) continue;
709 if ((name[1] == '.') && (name[2] == 0)) continue;
710 }
711
712 strcpy(dirname, basepath);
713 pathpos = dirname + strlen(dirname);
714 if ((*(pathpos-1)) != '/') {
715 *pathpos = '/';
716 pathpos++;
717 *pathpos = 0;
718 }
719 if (cachedir != NULL) {
720 snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s/%s", name, cachedir);
721 } else {
722 snprintf(pathpos, sizeof(dirname)-(pathpos-dirname), "%s", name);
723 }
724 CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
725 subdir = opendir(dirname);
726 if (subdir != NULL) {
727 size_t dirnameLen = strlen(dirname);
728 _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
729 PATH_MAX - dirnameLen);
730 closedir(subdir);
731 }
732 }
733 }
734
735 closedir(d);
736}
737
738static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
739{
740 char *pos = path;
741 if (dir->parent != NULL) {
742 pos = create_dir_path(path, dir->parent);
743 }
744 // Note that we don't need to worry about going beyond the buffer,
745 // since when we were constructing the cache entries our maximum
746 // buffer size for full paths was PATH_MAX.
747 strcpy(pos, dir->name);
748 pos += strlen(pos);
749 *pos = '/';
750 pos++;
751 *pos = 0;
752 return pos;
753}
754
755static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
756{
757 if (dir->parent != NULL) {
758 create_dir_path(path, dir);
759 ALOGI("DEL DIR %s\n", path);
760 if (dir->hiddenCount <= 0) {
761 if (rmdir(path)) {
762 ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
763 return;
764 }
765 } else {
766 // The directory contains hidden files so we need to delete
767 // them along with the directory itself.
768 if (delete_dir_contents(path, 1, NULL)) {
769 return;
770 }
771 }
772 dir->parent->childCount--;
773 dir->deleted = 1;
774 if (dir->parent->childCount <= 0) {
775 delete_cache_dir(path, dir->parent);
776 }
777 } else if (dir->hiddenCount > 0) {
778 // This is a root directory, but it has hidden files. Get rid of
779 // all of those files, but not the directory itself.
780 create_dir_path(path, dir);
781 ALOGI("DEL CONTENTS %s\n", path);
782 delete_dir_contents(path, 0, NULL);
783 }
784}
785
786static int cache_modtime_sort(const void *lhsP, const void *rhsP)
787{
788 const cache_file_t *lhs = *(const cache_file_t**)lhsP;
789 const cache_file_t *rhs = *(const cache_file_t**)rhsP;
790 return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
791}
792
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700793void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700794{
795 size_t i;
796 int skip = 0;
797 char path[PATH_MAX];
798
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700799 ALOGI("Collected cache files: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700800 cache->numDirs, cache->numFiles);
801
802 CACHE_NOISY(ALOGI("Sorting files..."));
803 qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
804 cache_modtime_sort);
805
806 CACHE_NOISY(ALOGI("Cleaning empty directories..."));
807 for (i=cache->numDirs; i>0; i--) {
808 cache_dir_t* dir = cache->dirs[i-1];
809 if (dir->childCount <= 0 && !dir->deleted) {
810 delete_cache_dir(path, dir);
811 }
812 }
813
814 CACHE_NOISY(ALOGI("Trimming files..."));
815 for (i=0; i<cache->numFiles; i++) {
816 skip++;
817 if (skip > 10) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700818 if (data_disk_free(data_path) > free_size) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700819 return;
820 }
821 skip = 0;
822 }
823 cache_file_t* file = cache->files[i];
824 strcpy(create_dir_path(path, file->dir), file->name);
825 ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
826 if (unlink(path) < 0) {
827 ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
828 }
829 file->dir->childCount--;
830 if (file->dir->childCount <= 0) {
831 delete_cache_dir(path, file->dir);
832 }
833 }
834}
835
836void finish_cache_collection(cache_t* cache)
837{
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700838 CACHE_NOISY(size_t i;)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700839
840 CACHE_NOISY(ALOGI("clear_cache_files: %d dirs, %d files\n", cache->numDirs, cache->numFiles));
841 CACHE_NOISY(
842 for (i=0; i<cache->numDirs; i++) {
843 cache_dir_t* dir = cache->dirs[i];
844 ALOGI("dir #%d: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
845 })
846 CACHE_NOISY(
847 for (i=0; i<cache->numFiles; i++) {
848 cache_file_t* file = cache->files[i];
849 ALOGI("file #%d: %p %s time=%d dir=%p\n", i, file, file->name,
850 (int)file->modTime, file->dir);
851 })
852 void* block = cache->memBlocks;
853 while (block != NULL) {
854 void* nextBlock = *(void**)block;
855 CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
856 free(block);
857 block = nextBlock;
858 }
859 free(cache);
860}
861
862/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100863 * Validate that the path is valid in the context of the provided directory.
864 * The path is allowed to have at most one subdirectory and no indirections
865 * to top level directories (i.e. have "..").
866 */
Jeff Sharkeye23a1322015-04-06 16:19:39 -0700867static int validate_path(const dir_rec_t* dir, const char* path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +0100868 size_t dir_len = dir->len;
869 const char* subdir = strchr(path + dir_len, '/');
870
871 // Only allow the path to have at most one subdirectory.
872 if (subdir != NULL) {
873 ++subdir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -0700874 if ((--maxSubdirs == 0) && strchr(subdir, '/') != NULL) {
Calin Juravlec597b6d2014-08-19 17:43:05 +0100875 ALOGE("invalid apk path '%s' (subdir?)\n", path);
876 return -1;
877 }
878 }
879
880 // Directories can't have a period directly after the directory markers to prevent "..".
881 if ((path[dir_len] == '.') || ((subdir != NULL) && (*subdir == '.'))) {
882 ALOGE("invalid apk path '%s' (trickery)\n", path);
883 return -1;
884 }
885
886 return 0;
887}
888
889/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700890 * Checks whether a path points to a system app (.apk file). Returns 0
891 * if it is a system app or -1 if it is not.
892 */
893int validate_system_app_path(const char* path) {
894 size_t i;
895
896 for (i = 0; i < android_system_dirs.count; i++) {
897 const size_t dir_len = android_system_dirs.dirs[i].len;
898 if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
Jeff Sharkeye23a1322015-04-06 16:19:39 -0700899 return validate_path(android_system_dirs.dirs + i, path, 1);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700900 }
901 }
902
903 return -1;
904}
905
906/**
907 * Get the contents of a environment variable that contains a path. Caller
908 * owns the string that is inserted into the directory record. Returns
909 * 0 on success and -1 on error.
910 */
911int get_path_from_env(dir_rec_t* rec, const char* var) {
912 const char* path = getenv(var);
913 int ret = get_path_from_string(rec, path);
914 if (ret < 0) {
915 ALOGW("Problem finding value for environment variable %s\n", var);
916 }
917 return ret;
918}
919
920/**
921 * Puts the string into the record as a directory. Appends '/' to the end
922 * of all paths. Caller owns the string that is inserted into the directory
923 * record. A null value will result in an error.
924 *
925 * Returns 0 on success and -1 on error.
926 */
927int get_path_from_string(dir_rec_t* rec, const char* path) {
928 if (path == NULL) {
929 return -1;
930 } else {
931 const size_t path_len = strlen(path);
932 if (path_len <= 0) {
933 return -1;
934 }
935
936 // Make sure path is absolute.
937 if (path[0] != '/') {
938 return -1;
939 }
940
941 if (path[path_len - 1] == '/') {
942 // Path ends with a forward slash. Make our own copy.
943
944 rec->path = strdup(path);
945 if (rec->path == NULL) {
946 return -1;
947 }
948
949 rec->len = path_len;
950 } else {
951 // Path does not end with a slash. Generate a new string.
952 char *dst;
953
954 // Add space for slash and terminating null.
955 size_t dst_size = path_len + 2;
956
Jeff Sharkey19803802015-04-07 12:44:51 -0700957 rec->path = (char*) malloc(dst_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700958 if (rec->path == NULL) {
959 return -1;
960 }
961
962 dst = rec->path;
963
964 if (append_and_increment(&dst, path, &dst_size) < 0
965 || append_and_increment(&dst, "/", &dst_size)) {
966 ALOGE("Error canonicalizing path");
967 return -1;
968 }
969
970 rec->len = dst - rec->path;
971 }
972 }
973 return 0;
974}
975
976int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
977 dst->len = src->len + strlen(suffix);
978 const size_t dstSize = dst->len + 1;
979 dst->path = (char*) malloc(dstSize);
980
981 if (dst->path == NULL
982 || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
983 != (ssize_t) dst->len) {
984 ALOGE("Could not allocate memory to hold appended path; aborting\n");
985 return -1;
986 }
987
988 return 0;
989}
990
991/**
Calin Juravlefd88ff22014-08-15 15:45:51 +0100992 * Check whether path points to a valid path for an APK file. Only one level of
993 * subdirectory names is allowed. Returns -1 when an invalid path is encountered
994 * and 0 when a valid path is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700995 */
996int validate_apk_path(const char *path)
997{
Calin Juravlec597b6d2014-08-19 17:43:05 +0100998 const dir_rec_t* dir = NULL;
Jeff Sharkeye23a1322015-04-06 16:19:39 -0700999 int maxSubdirs = 1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001000
1001 if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001002 dir = &android_app_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001003 } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001004 dir = &android_app_private_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001005 } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001006 dir = &android_asec_dir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001007 } else if (!strncmp(path, android_mnt_expand_dir.path, android_mnt_expand_dir.len)) {
1008 dir = &android_mnt_expand_dir;
1009 maxSubdirs = 2;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001010 } else {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001011 return -1;
1012 }
1013
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001014 return validate_path(dir, path, maxSubdirs);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001015}
1016
1017int append_and_increment(char** dst, const char* src, size_t* dst_size) {
1018 ssize_t ret = strlcpy(*dst, src, *dst_size);
1019 if (ret < 0 || (size_t) ret >= *dst_size) {
1020 return -1;
1021 }
1022 *dst += ret;
1023 *dst_size -= ret;
1024 return 0;
1025}
1026
Jeff Sharkey19803802015-04-07 12:44:51 -07001027char *build_string2(const char *s1, const char *s2) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001028 if (s1 == NULL || s2 == NULL) return NULL;
1029
1030 int len_s1 = strlen(s1);
1031 int len_s2 = strlen(s2);
1032 int len = len_s1 + len_s2 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001033 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001034 if (result == NULL) return NULL;
1035
1036 strcpy(result, s1);
1037 strcpy(result + len_s1, s2);
1038
1039 return result;
1040}
1041
Jeff Sharkey19803802015-04-07 12:44:51 -07001042char *build_string3(const char *s1, const char *s2, const char *s3) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001043 if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
1044
1045 int len_s1 = strlen(s1);
1046 int len_s2 = strlen(s2);
1047 int len_s3 = strlen(s3);
1048 int len = len_s1 + len_s2 + len_s3 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001049 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001050 if (result == NULL) return NULL;
1051
1052 strcpy(result, s1);
1053 strcpy(result + len_s1, s2);
1054 strcpy(result + len_s1 + len_s2, s3);
1055
1056 return result;
1057}
1058
1059/* Ensure that /data/media directories are prepared for given user. */
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001060int ensure_media_user_dirs(const char* uuid, userid_t userid) {
1061 std::string media_user_path(create_data_media_path(uuid, userid));
1062 if (fs_prepare_dir(media_user_path.c_str(), 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001063 return -1;
1064 }
1065
1066 return 0;
1067}
Dave Allisond9370732014-01-30 14:19:23 -08001068
Robin Lee095c7632014-04-25 15:05:19 +01001069int ensure_config_user_dirs(userid_t userid) {
1070 char config_user_path[PATH_MAX];
Robin Lee095c7632014-04-25 15:05:19 +01001071
1072 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001073 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1074 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001075
1076 // Ensure /data/misc/user/<userid> exists
1077 create_user_config_path(config_user_path, userid);
1078 if (fs_prepare_dir(config_user_path, 0750, uid, gid) == -1) {
1079 return -1;
1080 }
1081
1082 return 0;
1083}
1084
Dave Allisond9370732014-01-30 14:19:23 -08001085int create_profile_file(const char *pkgname, gid_t gid) {
1086 const char *profile_dir = DALVIK_CACHE_PREFIX "profiles";
Dave Allisond9370732014-01-30 14:19:23 -08001087 char profile_file[PKG_PATH_MAX];
1088
Dave Allisond9370732014-01-30 14:19:23 -08001089 snprintf(profile_file, sizeof(profile_file), "%s/%s", profile_dir, pkgname);
1090
1091 // The 'system' user needs to be able to read the profile to determine if dex2oat
1092 // needs to be run. This is done in dalvik.system.DexFile.isDexOptNeededInternal(). So
Nick Kralevich0db0f972014-06-11 18:23:59 -07001093 // we assign ownership to AID_SYSTEM and ensure it's not world-readable.
Dave Allisond9370732014-01-30 14:19:23 -08001094
Nick Kralevich0db0f972014-06-11 18:23:59 -07001095 int fd = open(profile_file, O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0660);
Dave Allisond9370732014-01-30 14:19:23 -08001096
Nick Kralevich0db0f972014-06-11 18:23:59 -07001097 // Always set the uid/gid/permissions. The file could have been previously created
1098 // with different permissions.
Dave Allisond9370732014-01-30 14:19:23 -08001099 if (fd >= 0) {
Nick Kralevich0db0f972014-06-11 18:23:59 -07001100 if (fchown(fd, AID_SYSTEM, gid) < 0) {
Dave Allisond9370732014-01-30 14:19:23 -08001101 ALOGE("cannot chown profile file '%s': %s\n", profile_file, strerror(errno));
1102 close(fd);
1103 unlink(profile_file);
1104 return -1;
1105 }
1106
Nick Kralevich0db0f972014-06-11 18:23:59 -07001107 if (fchmod(fd, 0660) < 0) {
Dave Allisond9370732014-01-30 14:19:23 -08001108 ALOGE("cannot chmod profile file '%s': %s\n", profile_file, strerror(errno));
1109 close(fd);
1110 unlink(profile_file);
1111 return -1;
1112 }
1113 close(fd);
1114 }
1115 return 0;
1116}
1117
1118void remove_profile_file(const char *pkgname) {
1119 char profile_file[PKG_PATH_MAX];
1120 snprintf(profile_file, sizeof(profile_file), "%s/%s", DALVIK_CACHE_PREFIX "profiles", pkgname);
1121 unlink(profile_file);
1122}