blob: 6d50f558a2479e409e3d2268c6109d15c84ffbaf [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
Andreas Gampe02d0de52015-11-11 20:43:16 -080017#include "utils.h"
Mike Lockwood94afecf2012-10-24 10:45:23 -070018
Andreas Gampe02d0de52015-11-11 20:43:16 -080019#include <errno.h>
20#include <fcntl.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070021#include <fts.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080022#include <stdlib.h>
23#include <sys/stat.h>
24#include <sys/wait.h>
Jeff Sharkey9a998f42016-07-14 18:16:22 -060025#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026
27#if defined(__APPLE__)
28#include <sys/mount.h>
29#else
30#include <sys/statfs.h>
31#endif
32
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080033#include <android-base/logging.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080034#include <android-base/stringprintf.h>
35#include <cutils/fs.h>
Jeff Sharkey871a8f22017-02-21 18:30:28 -070036#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070037#include <log/log.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080038#include <private/android_filesystem_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070039
Andreas Gampe02d0de52015-11-11 20:43:16 -080040#include "globals.h" // extern variables.
41
42#ifndef LOG_TAG
43#define LOG_TAG "installd"
44#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060045
Mike Lockwood94afecf2012-10-24 10:45:23 -070046#define CACHE_NOISY(x) //x
Jeff Sharkey9a998f42016-07-14 18:16:22 -060047#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070048
Jeff Sharkeyc03de092015-04-07 18:14:05 -070049using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070050
Andreas Gampe02d0de52015-11-11 20:43:16 -080051namespace android {
52namespace installd {
53
Jeff Sharkeyc03de092015-04-07 18:14:05 -070054/**
55 * Check that given string is valid filename, and that it attempts no
56 * parent or child directory traversal.
57 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070058bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070059 if (name.empty() || (name == ".") || (name == "..")
60 || (name.find('/') != std::string::npos)) {
61 return false;
62 } else {
63 return true;
64 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070065}
66
Calin Juravle6a1648e2016-02-01 12:12:16 +000067static void check_package_name(const char* package_name) {
68 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070069 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000070}
71
Mike Lockwood94afecf2012-10-24 10:45:23 -070072/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -070073 * Create the path name where package app contents should be stored for
74 * the given volume UUID and package name. An empty UUID is assumed to
75 * be internal storage.
76 */
77std::string create_data_app_package_path(const char* volume_uuid,
78 const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000079 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070080 return StringPrintf("%s/%s",
81 create_data_app_path(volume_uuid).c_str(), package_name);
82}
83
84/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070085 * Create the path name where package data should be stored for the given
86 * volume UUID, package name, and user ID. An empty UUID is assumed to be
87 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070088 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -060089std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -070090 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000091 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070092 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -060093 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
94}
95
96std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
97 const char* package_name, ino_t ce_data_inode) {
98 // For testing purposes, rely on the inode when defined; this could be
99 // optimized to use access() in the future.
100 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
101 if (ce_data_inode != 0) {
102 auto user_path = create_data_user_ce_path(volume_uuid, user);
103 DIR* dir = opendir(user_path.c_str());
104 if (dir == nullptr) {
105 PLOG(ERROR) << "Failed to opendir " << user_path;
106 return fallback;
107 }
108
109 struct dirent* ent;
110 while ((ent = readdir(dir))) {
111 if (ent->d_ino == ce_data_inode) {
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600112 auto resolved = StringPrintf("%s/%s", user_path.c_str(), ent->d_name);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600113#if DEBUG_XATTRS
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600114 if (resolved != fallback) {
115 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
116 << " instead of " << fallback;
117 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600118#endif
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600119 closedir(dir);
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600120 return resolved;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600121 }
122 }
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600123 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600124 closedir(dir);
125 return fallback;
126 } else {
127 return fallback;
128 }
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700129}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700130
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800131std::string create_data_user_de_package_path(const char* volume_uuid,
132 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000133 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800134 return StringPrintf("%s/%s",
135 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
136}
137
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700138int create_pkg_path(char path[PKG_PATH_MAX], const char *pkgname,
139 const char *postfix, userid_t userid) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700140 if (!is_valid_package_name(pkgname)) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700141 path[0] = '\0';
Mike Lockwood94afecf2012-10-24 10:45:23 -0700142 return -1;
143 }
144
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600145 std::string _tmp(create_data_user_ce_package_path(nullptr, userid, pkgname) + postfix);
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700146 const char* tmp = _tmp.c_str();
147 if (strlen(tmp) >= PKG_PATH_MAX) {
148 path[0] = '\0';
149 return -1;
150 } else {
151 strcpy(path, tmp);
152 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700153 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700154}
155
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700156std::string create_data_path(const char* volume_uuid) {
157 if (volume_uuid == nullptr) {
158 return "/data";
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700159 } else if (!strcmp(volume_uuid, "TEST")) {
160 CHECK(property_get_bool("ro.debuggable", false));
161 return "/data/local/tmp";
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700162 } else {
163 CHECK(is_valid_filename(volume_uuid));
164 return StringPrintf("/mnt/expand/%s", volume_uuid);
165 }
166}
167
Mike Lockwood94afecf2012-10-24 10:45:23 -0700168/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700169 * Create the path name for app data.
170 */
171std::string create_data_app_path(const char* volume_uuid) {
172 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
173}
174
175/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700176 * Create the path name for user data for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700177 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600178std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700179 std::string data(create_data_path(volume_uuid));
180 if (volume_uuid == nullptr) {
181 if (userid == 0) {
182 return StringPrintf("%s/data", data.c_str());
183 } else {
184 return StringPrintf("%s/user/%u", data.c_str(), userid);
185 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700186 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700187 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700188 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700189}
190
191/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800192 * Create the path name for device encrypted user data for a certain userid.
193 */
194std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
195 std::string data(create_data_path(volume_uuid));
196 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
197}
198
199/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700200 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700201 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700202std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
203 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700204}
205
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700206std::string create_data_media_obb_path(const char* volume_uuid, const char* package_name) {
207 return StringPrintf("%s/media/obb/%s", create_data_path(volume_uuid).c_str(), package_name);
208}
209
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700210std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
211 const char* data_type, const char* package_name) {
212 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
213 data_type, package_name);
214}
215
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600216std::string create_data_misc_legacy_path(userid_t userid) {
217 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
218}
219
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700220std::string create_data_user_profile_path(userid_t userid) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000221 return StringPrintf("%s/cur/%u", android_profiles_dir.path, userid);
222}
223
224std::string create_data_user_profile_package_path(userid_t user, const char* package_name) {
225 check_package_name(package_name);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700226 return StringPrintf("%s/%s",create_data_user_profile_path(user).c_str(), package_name);
227}
228
229std::string create_data_ref_profile_path() {
230 return StringPrintf("%s/ref", android_profiles_dir.path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000231}
232
233std::string create_data_ref_profile_package_path(const char* package_name) {
234 check_package_name(package_name);
235 return StringPrintf("%s/ref/%s", android_profiles_dir.path, package_name);
236}
237
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700238std::string create_data_dalvik_cache_path() {
239 return "/data/dalvik-cache";
240}
241
242std::string create_data_misc_foreign_dex_path(userid_t userid) {
243 return StringPrintf("/data/misc/profiles/cur/%d/foreign-dex", userid);
244}
245
Jeff Sharkey90aff262016-12-12 14:28:24 -0700246// Keep profile paths in sync with ActivityThread.
247constexpr const char* PRIMARY_PROFILE_NAME = "primary.prof";
248
249std::string create_primary_profile(const std::string& profile_dir) {
250 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME);
251}
252
Jeff Sharkeye3637242015-04-08 20:56:42 -0700253std::vector<userid_t> get_known_users(const char* volume_uuid) {
254 std::vector<userid_t> users;
255
256 // We always have an owner
257 users.push_back(0);
258
259 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
260 DIR* dir = opendir(path.c_str());
261 if (dir == NULL) {
262 // Unable to discover other users, but at least return owner
263 PLOG(ERROR) << "Failed to opendir " << path;
264 return users;
265 }
266
267 struct dirent* ent;
268 while ((ent = readdir(dir))) {
269 if (ent->d_type != DT_DIR) {
270 continue;
271 }
272
273 char* end;
274 userid_t user = strtol(ent->d_name, &end, 10);
275 if (*end == '\0' && user != 0) {
276 LOG(DEBUG) << "Found valid user " << user;
277 users.push_back(user);
278 }
279 }
280 closedir(dir);
281
282 return users;
283}
284
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700285int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700286 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700287 FTS *fts;
288 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700289 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700290 char *argv[] = { (char*) path.c_str(), nullptr };
291 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
292 if (errno != ENOENT) {
293 PLOG(ERROR) << "Failed to fts_open " << path;
294 }
295 return -1;
296 }
297 while ((p = fts_read(fts)) != NULL) {
298 switch (p->fts_info) {
299 case FTS_D:
300 case FTS_DEFAULT:
301 case FTS_F:
302 case FTS_SL:
303 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700304 int32_t uid = p->fts_statp->st_uid;
305 int32_t gid = p->fts_statp->st_gid;
306 int32_t user_uid = multiuser_get_app_id(uid);
307 int32_t user_gid = multiuser_get_app_id(gid);
308 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
309 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
310 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
311 // Don't traverse inside or measure
312 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700313 break;
314 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700315 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700316 break;
317 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700318 if (exclude_gid != -1 && gid == exclude_gid) {
319 break;
320 }
321 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700322 break;
323 }
324 }
325 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700326#if MEASURE_DEBUG
327 if ((include_gid == -1) && (exclude_gid == -1)) {
328 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
329 } else {
330 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
331 << " exclude " << exclude_gid;
332 }
333#endif
334 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700335 return 0;
336}
337
Mike Lockwood94afecf2012-10-24 10:45:23 -0700338int create_move_path(char path[PKG_PATH_MAX],
339 const char* pkgname,
340 const char* leaf,
Andreas Gampe02d0de52015-11-11 20:43:16 -0800341 userid_t userid ATTRIBUTE_UNUSED)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700342{
343 if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
344 >= PKG_PATH_MAX) {
345 return -1;
346 }
347
348 sprintf(path, "%s%s%s/%s", android_data_dir.path, PRIMARY_USER_PREFIX, pkgname, leaf);
349 return 0;
350}
351
352/**
353 * Checks whether the package name is valid. Returns -1 on error and
354 * 0 on success.
355 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700356bool is_valid_package_name(const std::string& packageName) {
357 const char* pkgname = packageName.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700358 const char *x = pkgname;
359 int alpha = -1;
360
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700361 if (strlen(pkgname) > PKG_NAME_MAX) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700362 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700363 }
364
Mike Lockwood94afecf2012-10-24 10:45:23 -0700365 while (*x) {
366 if (isalnum(*x) || (*x == '_')) {
367 /* alphanumeric or underscore are fine */
368 } else if (*x == '.') {
369 if ((x == pkgname) || (x[1] == '.') || (x[1] == 0)) {
370 /* periods must not be first, last, or doubled */
371 ALOGE("invalid package name '%s'\n", pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700372 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700373 }
374 } else if (*x == '-') {
375 /* Suffix -X is fine to let versioning of packages.
376 But whatever follows should be alphanumeric.*/
377 alpha = 1;
378 } else {
379 /* anything not A-Z, a-z, 0-9, _, or . is invalid */
380 ALOGE("invalid package name '%s'\n", pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700381 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700382 }
383
384 x++;
385 }
386
387 if (alpha == 1) {
388 // Skip current character
389 x++;
390 while (*x) {
391 if (!isalnum(*x)) {
392 ALOGE("invalid package name '%s' should include only numbers after -\n", pkgname);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700393 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700394 }
395 x++;
396 }
397 }
398
Jeff Sharkey423e7462016-12-09 18:18:43 -0700399 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700400}
401
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100402static int _delete_dir_contents(DIR *d,
403 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700404{
405 int result = 0;
406 struct dirent *de;
407 int dfd;
408
409 dfd = dirfd(d);
410
411 if (dfd < 0) return -1;
412
413 while ((de = readdir(d))) {
414 const char *name = de->d_name;
415
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100416 /* check using the exclusion predicate, if provided */
417 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
418 continue;
419 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700420
421 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700422 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700423 DIR *subdir;
424
425 /* always skip "." and ".." */
426 if (name[0] == '.') {
427 if (name[1] == 0) continue;
428 if ((name[1] == '.') && (name[2] == 0)) continue;
429 }
430
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700431 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700432 if (subfd < 0) {
433 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
434 result = -1;
435 continue;
436 }
437 subdir = fdopendir(subfd);
438 if (subdir == NULL) {
439 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
440 close(subfd);
441 result = -1;
442 continue;
443 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100444 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700445 result = -1;
446 }
447 closedir(subdir);
448 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
449 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
450 result = -1;
451 }
452 } else {
453 if (unlinkat(dfd, name, 0) < 0) {
454 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
455 result = -1;
456 }
457 }
458 }
459
460 return result;
461}
462
Calin Juravleb06f98a2016-03-28 15:11:01 +0100463int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
464 return delete_dir_contents(pathname.c_str(), 0, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700465}
466
Calin Juravleb06f98a2016-03-28 15:11:01 +0100467int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
468 return delete_dir_contents(pathname.c_str(), 1, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700469}
470
Mike Lockwood94afecf2012-10-24 10:45:23 -0700471int delete_dir_contents(const char *pathname,
472 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100473 int (*exclusion_predicate)(const char*, const int),
474 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700475{
476 int res = 0;
477 DIR *d;
478
479 d = opendir(pathname);
480 if (d == NULL) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100481 if (ignore_if_missing && (errno == ENOENT)) {
482 return 0;
483 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700484 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
485 return -errno;
486 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100487 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700488 closedir(d);
489 if (also_delete_dir) {
490 if (rmdir(pathname)) {
491 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
492 res = -1;
493 }
494 }
495 return res;
496}
497
498int delete_dir_contents_fd(int dfd, const char *name)
499{
500 int fd, res;
501 DIR *d;
502
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700503 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700504 if (fd < 0) {
505 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
506 return -1;
507 }
508 d = fdopendir(fd);
509 if (d == NULL) {
510 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
511 close(fd);
512 return -1;
513 }
514 res = _delete_dir_contents(d, 0);
515 closedir(d);
516 return res;
517}
518
Robin Lee60fd3fe2014-10-07 16:55:02 +0100519static int _copy_owner_permissions(int srcfd, int dstfd)
520{
521 struct stat st;
522 if (fstat(srcfd, &st) != 0) {
523 return -1;
524 }
525 if (fchmod(dstfd, st.st_mode) != 0) {
526 return -1;
527 }
528 return 0;
529}
530
531static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
532{
533 int result = 0;
534 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
535 ALOGE("_copy_dir_files failed to copy dir permissions\n");
536 }
537 if (fchown(ddfd, owner, group) != 0) {
538 ALOGE("_copy_dir_files failed to change dir owner\n");
539 }
540
541 DIR *ds = fdopendir(sdfd);
542 if (ds == NULL) {
543 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
544 return -1;
545 }
546 struct dirent *de;
547 while ((de = readdir(ds))) {
548 if (de->d_type != DT_REG) {
549 continue;
550 }
551
552 const char *name = de->d_name;
553 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
554 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
555 if (fsfd == -1 || fdfd == -1) {
556 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
557 } else {
558 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
559 ALOGE("Failed to change file permissions\n");
560 }
561 if (fchown(fdfd, owner, group) != 0) {
562 ALOGE("Failed to change file owner\n");
563 }
564
565 char buf[8192];
566 ssize_t size;
567 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
568 write(fdfd, buf, size);
569 }
570 if (size < 0) {
571 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
572 result = -1;
573 }
574 }
575 close(fdfd);
576 close(fsfd);
577 }
578
579 return result;
580}
581
582int copy_dir_files(const char *srcname,
583 const char *dstname,
584 uid_t owner,
585 uid_t group)
586{
587 int res = 0;
588 DIR *ds = NULL;
589 DIR *dd = NULL;
590
591 ds = opendir(srcname);
592 if (ds == NULL) {
593 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
594 return -errno;
595 }
596
597 mkdir(dstname, 0600);
598 dd = opendir(dstname);
599 if (dd == NULL) {
600 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
601 closedir(ds);
602 return -errno;
603 }
604
605 int sdfd = dirfd(ds);
606 int ddfd = dirfd(dd);
607 if (sdfd != -1 && ddfd != -1) {
608 res = _copy_dir_files(sdfd, ddfd, owner, group);
609 } else {
610 res = -errno;
611 }
612 closedir(dd);
613 closedir(ds);
614 return res;
615}
616
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700617int64_t data_disk_free(const std::string& data_path)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700618{
619 struct statfs sfs;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700620 if (statfs(data_path.c_str(), &sfs) == 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700621 return sfs.f_bavail * sfs.f_bsize;
622 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700623 PLOG(ERROR) << "Couldn't statfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700624 return -1;
625 }
626}
627
628cache_t* start_cache_collection()
629{
630 cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
631 return cache;
632}
633
634#define CACHE_BLOCK_SIZE (512*1024)
635
636static void* _cache_malloc(cache_t* cache, size_t len)
637{
638 len = (len+3)&~3;
639 if (len > (CACHE_BLOCK_SIZE/2)) {
640 // It doesn't make sense to try to put this allocation into one
641 // of our blocks, because it is so big. Instead, make a new dedicated
642 // block for it.
643 int8_t* res = (int8_t*)malloc(len+sizeof(void*));
644 if (res == NULL) {
645 return NULL;
646 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600647 CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %zu", res, len));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700648 // Link it into our list of blocks, not disrupting the current one.
649 if (cache->memBlocks == NULL) {
650 *(void**)res = NULL;
651 cache->memBlocks = res;
652 } else {
653 *(void**)res = *(void**)cache->memBlocks;
654 *(void**)cache->memBlocks = res;
655 }
656 return res + sizeof(void*);
657 }
658 int8_t* res = cache->curMemBlockAvail;
659 int8_t* nextPos = res + len;
660 if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
Jeff Sharkey19803802015-04-07 12:44:51 -0700661 int8_t* newBlock = (int8_t*) malloc(CACHE_BLOCK_SIZE);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700662 if (newBlock == NULL) {
663 return NULL;
664 }
665 CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
666 *(void**)newBlock = cache->memBlocks;
667 cache->memBlocks = newBlock;
668 res = cache->curMemBlockAvail = newBlock + sizeof(void*);
669 cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
670 nextPos = res + len;
671 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600672 CACHE_NOISY(ALOGI("cache_malloc: ret %p size %zu, block=%p, nextPos=%p",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700673 res, len, cache->memBlocks, nextPos));
674 cache->curMemBlockAvail = nextPos;
675 return res;
676}
677
678static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
679{
680 // This isn't really a realloc, but it is good enough for our purposes here.
681 void* alloc = _cache_malloc(cache, len);
682 if (alloc != NULL && cur != NULL) {
683 memcpy(alloc, cur, origLen < len ? origLen : len);
684 }
685 return alloc;
686}
687
688static void _inc_num_cache_collected(cache_t* cache)
689{
690 cache->numCollected++;
691 if ((cache->numCollected%20000) == 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700692 ALOGI("Collected cache so far: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700693 cache->numDirs, cache->numFiles);
694 }
695}
696
697static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
698{
699 size_t nameLen = strlen(name);
700 cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
701 if (dir != NULL) {
702 dir->parent = parent;
703 dir->childCount = 0;
704 dir->hiddenCount = 0;
705 dir->deleted = 0;
706 strcpy(dir->name, name);
707 if (cache->numDirs >= cache->availDirs) {
708 size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
709 cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
710 cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
711 if (newDirs == NULL) {
712 ALOGE("Failure growing cache dirs array for %s\n", name);
713 return NULL;
714 }
715 cache->availDirs = newAvail;
716 cache->dirs = newDirs;
717 }
718 cache->dirs[cache->numDirs] = dir;
719 cache->numDirs++;
720 if (parent != NULL) {
721 parent->childCount++;
722 }
723 _inc_num_cache_collected(cache);
724 } else {
725 ALOGE("Failure allocating cache_dir_t for %s\n", name);
726 }
727 return dir;
728}
729
730static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
731 const char *name)
732{
733 size_t nameLen = strlen(name);
734 cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
735 if (file != NULL) {
736 file->dir = dir;
737 file->modTime = modTime;
738 strcpy(file->name, name);
739 if (cache->numFiles >= cache->availFiles) {
740 size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
741 cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
742 cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
743 if (newFiles == NULL) {
744 ALOGE("Failure growing cache file array for %s\n", name);
745 return NULL;
746 }
747 cache->availFiles = newAvail;
748 cache->files = newFiles;
749 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600750 CACHE_NOISY(ALOGI("Setting file %p at position %zd in array %p", file,
Mike Lockwood94afecf2012-10-24 10:45:23 -0700751 cache->numFiles, cache->files));
752 cache->files[cache->numFiles] = file;
753 cache->numFiles++;
754 dir->childCount++;
755 _inc_num_cache_collected(cache);
756 } else {
757 ALOGE("Failure allocating cache_file_t for %s\n", name);
758 }
759 return file;
760}
761
762static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
763 DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
764{
765 struct dirent *de;
766 cache_dir_t* cacheDir = NULL;
767 int dfd;
768
769 CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
770 parentDir, dirName, dir, pathBase));
771
772 dfd = dirfd(dir);
773
774 if (dfd < 0) return 0;
775
776 // Sub-directories always get added to the data structure, so if they
777 // are empty we will know about them to delete them later.
778 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
779
780 while ((de = readdir(dir))) {
781 const char *name = de->d_name;
782
783 if (de->d_type == DT_DIR) {
784 int subfd;
785 DIR *subdir;
786
787 /* always skip "." and ".." */
788 if (name[0] == '.') {
789 if (name[1] == 0) continue;
790 if ((name[1] == '.') && (name[2] == 0)) continue;
791 }
792
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700793 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700794 if (subfd < 0) {
795 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
796 continue;
797 }
798 subdir = fdopendir(subfd);
799 if (subdir == NULL) {
800 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
801 close(subfd);
802 continue;
803 }
804 if (cacheDir == NULL) {
805 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
806 }
807 if (cacheDir != NULL) {
808 // Update pathBase for the new path... this may change dirName
809 // if that is also pointing to the path, but we are done with it
810 // now.
811 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
812 CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
813 if (finallen < pathAvailLen) {
814 _add_cache_files(cache, cacheDir, name, subdir, pathBase,
815 pathPos+finallen, pathAvailLen-finallen);
816 } else {
817 // Whoops, the final path is too long! We'll just delete
818 // this directory.
819 ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
820 name, pathBase);
821 _delete_dir_contents(subdir, NULL);
822 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
823 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
824 }
825 }
826 }
827 closedir(subdir);
828 } else if (de->d_type == DT_REG) {
829 // Skip files that start with '.'; they will be deleted if
830 // their entire directory is deleted. This allows for metadata
831 // like ".nomedia" to remain in the directory until the entire
832 // directory is deleted.
833 if (cacheDir == NULL) {
834 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
835 }
836 if (name[0] == '.') {
837 cacheDir->hiddenCount++;
838 continue;
839 }
840 if (cacheDir != NULL) {
841 // Build final full path for file... this may change dirName
842 // if that is also pointing to the path, but we are done with it
843 // now.
844 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
845 CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
846 if (finallen < pathAvailLen) {
847 struct stat s;
848 if (stat(pathBase, &s) >= 0) {
849 _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
850 } else {
851 ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
852 if (unlink(pathBase) < 0) {
853 ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
854 }
855 }
856 } else {
857 // Whoops, the final path is too long! We'll just delete
858 // this file.
859 ALOGW("Cache file %s truncated in path %s; deleting\n",
860 name, pathBase);
861 if (unlinkat(dfd, name, 0) < 0) {
862 *pathPos = 0;
863 ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
864 strerror(errno));
865 }
866 }
867 }
868 } else {
869 cacheDir->hiddenCount++;
870 }
871 }
872 return 0;
873}
874
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600875int get_path_inode(const std::string& path, ino_t *inode) {
876 struct stat buf;
877 memset(&buf, 0, sizeof(buf));
878 if (stat(path.c_str(), &buf) != 0) {
879 PLOG(WARNING) << "Failed to stat " << path;
880 return -1;
881 } else {
882 *inode = buf.st_ino;
883 return 0;
884 }
885}
886
887/**
888 * Write the inode of a specific child file into the given xattr on the
889 * parent directory. This allows you to find the child later, even if its
890 * name is encrypted.
891 */
892int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
893 ino_t inode = 0;
894 uint64_t inode_raw = 0;
895 auto path = StringPrintf("%s/%s", parent.c_str(), name);
896
897 if (get_path_inode(path, &inode) != 0) {
898 // Path probably doesn't exist yet; ignore
899 return 0;
900 }
901
902 // Check to see if already set correctly
903 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
904 if (inode_raw == inode) {
905 // Already set correctly; skip writing
906 return 0;
907 } else {
908 PLOG(WARNING) << "Mismatched inode value; found " << inode
909 << " on disk but marked value was " << inode_raw << "; overwriting";
910 }
911 }
912
913 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600914 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600915 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
916 return -1;
917 } else {
918 return 0;
919 }
920}
921
922/**
923 * Read the inode of a specific child file from the given xattr on the
924 * parent directory. Returns a currently valid path for that child, which
925 * might have an encrypted name.
926 */
927std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
928 ino_t inode = 0;
929 uint64_t inode_raw = 0;
930 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
931
932 // Lookup the inode value written earlier
933 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
934 inode = inode_raw;
935 }
936
937 // For testing purposes, rely on the inode when defined; this could be
938 // optimized to use access() in the future.
939 if (inode != 0) {
940 DIR* dir = opendir(parent.c_str());
941 if (dir == nullptr) {
942 PLOG(ERROR) << "Failed to opendir " << parent;
943 return fallback;
944 }
945
946 struct dirent* ent;
947 while ((ent = readdir(dir))) {
948 if (ent->d_ino == inode) {
949 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
950#if DEBUG_XATTRS
951 if (resolved != fallback) {
952 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
953 << " instead of " << fallback;
954 }
955#endif
956 closedir(dir);
957 return resolved;
958 }
959 }
960 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
961 closedir(dir);
962 return fallback;
963 } else {
964 return fallback;
965 }
966}
967
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600968void add_cache_files(cache_t* cache, const std::string& data_path) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700969 DIR *d;
970 struct dirent *de;
971 char dirname[PATH_MAX];
972
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600973 const char* basepath = data_path.c_str();
974 CACHE_NOISY(ALOGI("add_cache_files: basepath=%s\n", basepath));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700975
976 d = opendir(basepath);
977 if (d == NULL) {
978 return;
979 }
980
981 while ((de = readdir(d))) {
982 if (de->d_type == DT_DIR) {
983 DIR* subdir;
984 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700985
986 /* always skip "." and ".." */
987 if (name[0] == '.') {
988 if (name[1] == 0) continue;
989 if ((name[1] == '.') && (name[2] == 0)) continue;
990 }
991
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600992 auto parent = StringPrintf("%s/%s", basepath, name);
993 auto resolved = read_path_inode(parent, "cache", kXattrInodeCache);
994 strcpy(dirname, resolved.c_str());
Mike Lockwood94afecf2012-10-24 10:45:23 -0700995 CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600996
Mike Lockwood94afecf2012-10-24 10:45:23 -0700997 subdir = opendir(dirname);
998 if (subdir != NULL) {
999 size_t dirnameLen = strlen(dirname);
1000 _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
1001 PATH_MAX - dirnameLen);
1002 closedir(subdir);
1003 }
1004 }
1005 }
1006
1007 closedir(d);
1008}
1009
Fyodor Kupolovf3124d82016-09-07 13:07:45 -07001010void add_preloads_file_cache(cache_t* cache, const char* volume_uuid) {
1011 char dirname[PATH_MAX];
1012 DIR* subdir;
1013 auto cache_path = StringPrintf("%s/preloads/file_cache", create_data_path(volume_uuid).c_str());
1014 strcpy(dirname, cache_path.c_str());
1015 CACHE_NOISY(ALOGI("add_preloads_file_cache: dirname=%s\n", dirname));
1016 subdir = opendir(dirname);
1017 if (subdir != NULL) {
1018 size_t dirnameLen = strlen(dirname);
1019 _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname + dirnameLen,
1020 PATH_MAX - dirnameLen);
1021 closedir(subdir);
1022 }
1023}
1024
Mike Lockwood94afecf2012-10-24 10:45:23 -07001025static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
1026{
1027 char *pos = path;
1028 if (dir->parent != NULL) {
1029 pos = create_dir_path(path, dir->parent);
1030 }
1031 // Note that we don't need to worry about going beyond the buffer,
1032 // since when we were constructing the cache entries our maximum
1033 // buffer size for full paths was PATH_MAX.
1034 strcpy(pos, dir->name);
1035 pos += strlen(pos);
1036 *pos = '/';
1037 pos++;
1038 *pos = 0;
1039 return pos;
1040}
1041
1042static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
1043{
1044 if (dir->parent != NULL) {
1045 create_dir_path(path, dir);
1046 ALOGI("DEL DIR %s\n", path);
1047 if (dir->hiddenCount <= 0) {
1048 if (rmdir(path)) {
1049 ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
1050 return;
1051 }
1052 } else {
1053 // The directory contains hidden files so we need to delete
1054 // them along with the directory itself.
1055 if (delete_dir_contents(path, 1, NULL)) {
1056 return;
1057 }
1058 }
1059 dir->parent->childCount--;
1060 dir->deleted = 1;
1061 if (dir->parent->childCount <= 0) {
1062 delete_cache_dir(path, dir->parent);
1063 }
1064 } else if (dir->hiddenCount > 0) {
1065 // This is a root directory, but it has hidden files. Get rid of
1066 // all of those files, but not the directory itself.
1067 create_dir_path(path, dir);
1068 ALOGI("DEL CONTENTS %s\n", path);
1069 delete_dir_contents(path, 0, NULL);
1070 }
1071}
1072
1073static int cache_modtime_sort(const void *lhsP, const void *rhsP)
1074{
1075 const cache_file_t *lhs = *(const cache_file_t**)lhsP;
1076 const cache_file_t *rhs = *(const cache_file_t**)rhsP;
1077 return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
1078}
1079
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001080void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001081{
1082 size_t i;
1083 int skip = 0;
1084 char path[PATH_MAX];
1085
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001086 ALOGI("Collected cache files: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -07001087 cache->numDirs, cache->numFiles);
1088
1089 CACHE_NOISY(ALOGI("Sorting files..."));
1090 qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
1091 cache_modtime_sort);
1092
1093 CACHE_NOISY(ALOGI("Cleaning empty directories..."));
1094 for (i=cache->numDirs; i>0; i--) {
1095 cache_dir_t* dir = cache->dirs[i-1];
1096 if (dir->childCount <= 0 && !dir->deleted) {
1097 delete_cache_dir(path, dir);
1098 }
1099 }
1100
1101 CACHE_NOISY(ALOGI("Trimming files..."));
1102 for (i=0; i<cache->numFiles; i++) {
1103 skip++;
1104 if (skip > 10) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001105 if (data_disk_free(data_path) > free_size) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001106 return;
1107 }
1108 skip = 0;
1109 }
1110 cache_file_t* file = cache->files[i];
1111 strcpy(create_dir_path(path, file->dir), file->name);
1112 ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
1113 if (unlink(path) < 0) {
1114 ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
1115 }
1116 file->dir->childCount--;
1117 if (file->dir->childCount <= 0) {
1118 delete_cache_dir(path, file->dir);
1119 }
1120 }
1121}
1122
1123void finish_cache_collection(cache_t* cache)
1124{
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -07001125 CACHE_NOISY(size_t i;)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001126
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001127 CACHE_NOISY(ALOGI("clear_cache_files: %zu dirs, %zu files\n", cache->numDirs, cache->numFiles));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001128 CACHE_NOISY(
1129 for (i=0; i<cache->numDirs; i++) {
1130 cache_dir_t* dir = cache->dirs[i];
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001131 ALOGI("dir #%zu: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001132 })
1133 CACHE_NOISY(
1134 for (i=0; i<cache->numFiles; i++) {
1135 cache_file_t* file = cache->files[i];
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001136 ALOGI("file #%zu: %p %s time=%d dir=%p\n", i, file, file->name,
Mike Lockwood94afecf2012-10-24 10:45:23 -07001137 (int)file->modTime, file->dir);
1138 })
1139 void* block = cache->memBlocks;
1140 while (block != NULL) {
1141 void* nextBlock = *(void**)block;
1142 CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
1143 free(block);
1144 block = nextBlock;
1145 }
1146 free(cache);
1147}
1148
1149/**
Calin Juravlec597b6d2014-08-19 17:43:05 +01001150 * Validate that the path is valid in the context of the provided directory.
1151 * The path is allowed to have at most one subdirectory and no indirections
1152 * to top level directories (i.e. have "..").
1153 */
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001154static int validate_path(const dir_rec_t* dir, const char* path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001155 size_t dir_len = dir->len;
1156 const char* subdir = strchr(path + dir_len, '/');
1157
1158 // Only allow the path to have at most one subdirectory.
1159 if (subdir != NULL) {
1160 ++subdir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001161 if ((--maxSubdirs == 0) && strchr(subdir, '/') != NULL) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001162 ALOGE("invalid apk path '%s' (subdir?)\n", path);
1163 return -1;
1164 }
1165 }
1166
1167 // Directories can't have a period directly after the directory markers to prevent "..".
1168 if ((path[dir_len] == '.') || ((subdir != NULL) && (*subdir == '.'))) {
1169 ALOGE("invalid apk path '%s' (trickery)\n", path);
1170 return -1;
1171 }
1172
1173 return 0;
1174}
1175
1176/**
Mike Lockwood94afecf2012-10-24 10:45:23 -07001177 * Checks whether a path points to a system app (.apk file). Returns 0
1178 * if it is a system app or -1 if it is not.
1179 */
1180int validate_system_app_path(const char* path) {
1181 size_t i;
1182
1183 for (i = 0; i < android_system_dirs.count; i++) {
1184 const size_t dir_len = android_system_dirs.dirs[i].len;
1185 if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001186 return validate_path(android_system_dirs.dirs + i, path, 1);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001187 }
1188 }
1189
1190 return -1;
1191}
1192
Calin Juravle42451c02017-01-17 14:43:25 -08001193bool validate_secondary_dex_path(const char* pkgname, const char* path,
1194 const char* volume_uuid, int uid, int storage_flag) {
1195 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1196
1197 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
1198 ? create_data_user_ce_package_path(volume_uuid, multiuser_get_user_id(uid), pkgname)
1199 : create_data_user_de_package_path(volume_uuid, multiuser_get_user_id(uid), pkgname);
1200 dir_rec_t dir;
1201 if (get_path_from_string(&dir, app_private_dir.c_str()) != 0) {
1202 LOG(WARNING) << "Could not get dir rec for " << app_private_dir;
1203 return false;
1204 }
1205 // Usually secondary dex files have a nested directory structure.
1206 // Pick at most 10 subdirectories when validating (arbitrary value).
1207 // If the secondary dex file is >10 directory nested then validation will
1208 // fail and the file will not be compiled.
1209 return validate_path(&dir, path, /*max_subdirs*/ 10) == 0;
1210}
1211
Mike Lockwood94afecf2012-10-24 10:45:23 -07001212/**
1213 * Get the contents of a environment variable that contains a path. Caller
1214 * owns the string that is inserted into the directory record. Returns
1215 * 0 on success and -1 on error.
1216 */
1217int get_path_from_env(dir_rec_t* rec, const char* var) {
1218 const char* path = getenv(var);
1219 int ret = get_path_from_string(rec, path);
1220 if (ret < 0) {
1221 ALOGW("Problem finding value for environment variable %s\n", var);
1222 }
1223 return ret;
1224}
1225
1226/**
1227 * Puts the string into the record as a directory. Appends '/' to the end
1228 * of all paths. Caller owns the string that is inserted into the directory
1229 * record. A null value will result in an error.
1230 *
1231 * Returns 0 on success and -1 on error.
1232 */
1233int get_path_from_string(dir_rec_t* rec, const char* path) {
1234 if (path == NULL) {
1235 return -1;
1236 } else {
1237 const size_t path_len = strlen(path);
1238 if (path_len <= 0) {
1239 return -1;
1240 }
1241
1242 // Make sure path is absolute.
1243 if (path[0] != '/') {
1244 return -1;
1245 }
1246
1247 if (path[path_len - 1] == '/') {
1248 // Path ends with a forward slash. Make our own copy.
1249
1250 rec->path = strdup(path);
1251 if (rec->path == NULL) {
1252 return -1;
1253 }
1254
1255 rec->len = path_len;
1256 } else {
1257 // Path does not end with a slash. Generate a new string.
1258 char *dst;
1259
1260 // Add space for slash and terminating null.
1261 size_t dst_size = path_len + 2;
1262
Jeff Sharkey19803802015-04-07 12:44:51 -07001263 rec->path = (char*) malloc(dst_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001264 if (rec->path == NULL) {
1265 return -1;
1266 }
1267
1268 dst = rec->path;
1269
1270 if (append_and_increment(&dst, path, &dst_size) < 0
1271 || append_and_increment(&dst, "/", &dst_size)) {
1272 ALOGE("Error canonicalizing path");
1273 return -1;
1274 }
1275
1276 rec->len = dst - rec->path;
1277 }
1278 }
1279 return 0;
1280}
1281
1282int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
1283 dst->len = src->len + strlen(suffix);
1284 const size_t dstSize = dst->len + 1;
1285 dst->path = (char*) malloc(dstSize);
1286
1287 if (dst->path == NULL
1288 || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
1289 != (ssize_t) dst->len) {
1290 ALOGE("Could not allocate memory to hold appended path; aborting\n");
1291 return -1;
1292 }
1293
1294 return 0;
1295}
1296
1297/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001298 * Check whether path points to a valid path for an APK file. The path must
1299 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1300 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1301 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001302 */
Narayan Kamathd845c962015-06-04 13:20:27 +01001303static int validate_apk_path_internal(const char *path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001304 const dir_rec_t* dir = NULL;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001305 if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001306 dir = &android_app_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001307 } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001308 dir = &android_app_private_dir;
Todd Kennedy5c1a9102015-11-23 15:18:10 -08001309 } else if (!strncmp(path, android_app_ephemeral_dir.path, android_app_ephemeral_dir.len)) {
1310 dir = &android_app_ephemeral_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001311 } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001312 dir = &android_asec_dir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001313 } else if (!strncmp(path, android_mnt_expand_dir.path, android_mnt_expand_dir.len)) {
1314 dir = &android_mnt_expand_dir;
Narayan Kamathd845c962015-06-04 13:20:27 +01001315 if (maxSubdirs < 2) {
1316 maxSubdirs = 2;
1317 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001318 } else {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001319 return -1;
1320 }
1321
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001322 return validate_path(dir, path, maxSubdirs);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001323}
1324
Narayan Kamathd845c962015-06-04 13:20:27 +01001325int validate_apk_path(const char* path) {
1326 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
1327}
1328
1329int validate_apk_path_subdirs(const char* path) {
1330 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
1331}
1332
Mike Lockwood94afecf2012-10-24 10:45:23 -07001333int append_and_increment(char** dst, const char* src, size_t* dst_size) {
1334 ssize_t ret = strlcpy(*dst, src, *dst_size);
1335 if (ret < 0 || (size_t) ret >= *dst_size) {
1336 return -1;
1337 }
1338 *dst += ret;
1339 *dst_size -= ret;
1340 return 0;
1341}
1342
Jeff Sharkey19803802015-04-07 12:44:51 -07001343char *build_string2(const char *s1, const char *s2) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001344 if (s1 == NULL || s2 == NULL) return NULL;
1345
1346 int len_s1 = strlen(s1);
1347 int len_s2 = strlen(s2);
1348 int len = len_s1 + len_s2 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001349 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001350 if (result == NULL) return NULL;
1351
1352 strcpy(result, s1);
1353 strcpy(result + len_s1, s2);
1354
1355 return result;
1356}
1357
Jeff Sharkey19803802015-04-07 12:44:51 -07001358char *build_string3(const char *s1, const char *s2, const char *s3) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001359 if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
1360
1361 int len_s1 = strlen(s1);
1362 int len_s2 = strlen(s2);
1363 int len_s3 = strlen(s3);
1364 int len = len_s1 + len_s2 + len_s3 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001365 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001366 if (result == NULL) return NULL;
1367
1368 strcpy(result, s1);
1369 strcpy(result + len_s1, s2);
1370 strcpy(result + len_s1 + len_s2, s3);
1371
1372 return result;
1373}
1374
Robin Lee095c7632014-04-25 15:05:19 +01001375int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001376 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001377 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1378 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001379
1380 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001381 auto path = create_data_misc_legacy_path(userid);
1382 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001383}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001384
1385int wait_child(pid_t pid)
1386{
1387 int status;
1388 pid_t got_pid;
1389
1390 while (1) {
1391 got_pid = waitpid(pid, &status, 0);
1392 if (got_pid == -1 && errno == EINTR) {
1393 printf("waitpid interrupted, retrying\n");
1394 } else {
1395 break;
1396 }
1397 }
1398 if (got_pid != pid) {
1399 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1400 (int) pid, (int) got_pid, strerror(errno));
1401 return 1;
1402 }
1403
1404 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1405 return 0;
1406 } else {
1407 return status; /* always nonzero */
1408 }
1409}
1410
Calin Juravle42451c02017-01-17 14:43:25 -08001411/**
1412 * Prepare an app cache directory, which offers to fix-up the GID and
1413 * directory mode flags during a platform upgrade.
1414 * The app cache directory path will be 'parent'/'name'.
1415 */
1416int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1417 uid_t uid, gid_t gid) {
1418 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1419 struct stat st;
1420 if (stat(path.c_str(), &st) != 0) {
1421 if (errno == ENOENT) {
1422 // This is fine, just create it
1423 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1424 PLOG(ERROR) << "Failed to prepare " << path;
1425 return -1;
1426 } else {
1427 return 0;
1428 }
1429 } else {
1430 PLOG(ERROR) << "Failed to stat " << path;
1431 return -1;
1432 }
1433 }
1434
1435 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1436 if (st.st_uid != uid) {
1437 // Mismatched UID is real trouble; we can't recover
1438 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1439 << " but expected " << uid;
1440 return -1;
1441 } else if (st.st_gid == gid && actual_mode == target_mode) {
1442 // Everything looks good!
1443 return 0;
1444 }
1445
1446 // Directory is owned correctly, but GID or mode mismatch means it's
1447 // probably a platform upgrade so we need to fix them
1448 FTS *fts;
1449 FTSENT *p;
1450 char *argv[] = { (char*) path.c_str(), nullptr };
1451 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1452 PLOG(ERROR) << "Failed to fts_open " << path;
1453 return -1;
1454 }
1455 while ((p = fts_read(fts)) != NULL) {
1456 switch (p->fts_info) {
1457 case FTS_DP:
1458 if (chmod(p->fts_accpath, target_mode) != 0) {
1459 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1460 }
1461 // Intentional fall through to also set GID
1462 case FTS_F:
1463 if (chown(p->fts_accpath, -1, gid) != 0) {
1464 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1465 }
1466 break;
1467 case FTS_SL:
1468 case FTS_SLNONE:
1469 if (lchown(p->fts_accpath, -1, gid) != 0) {
1470 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1471 }
1472 break;
1473 }
1474 }
1475 fts_close(fts);
1476 return 0;
1477}
1478
Andreas Gampe02d0de52015-11-11 20:43:16 -08001479} // namespace installd
1480} // namespace android