blob: bdd62e6554eb3d6bd59c904d8d7715f1fab6589e [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>
Mark Salyzyn7823e122016-09-29 08:08:05 -070036#include <log/log.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080037#include <private/android_filesystem_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070038
Andreas Gampe02d0de52015-11-11 20:43:16 -080039#include "globals.h" // extern variables.
40
41#ifndef LOG_TAG
42#define LOG_TAG "installd"
43#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060044
Mike Lockwood94afecf2012-10-24 10:45:23 -070045#define CACHE_NOISY(x) //x
Jeff Sharkey9a998f42016-07-14 18:16:22 -060046#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070047
Jeff Sharkeyc03de092015-04-07 18:14:05 -070048using android::base::StringPrintf;
Mike Lockwood94afecf2012-10-24 10:45:23 -070049
Andreas Gampe02d0de52015-11-11 20:43:16 -080050namespace android {
51namespace installd {
52
Jeff Sharkeyc03de092015-04-07 18:14:05 -070053/**
54 * Check that given string is valid filename, and that it attempts no
55 * parent or child directory traversal.
56 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070057bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070058 if (name.empty() || (name == ".") || (name == "..")
59 || (name.find('/') != std::string::npos)) {
60 return false;
61 } else {
62 return true;
63 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070064}
65
Calin Juravle6a1648e2016-02-01 12:12:16 +000066static void check_package_name(const char* package_name) {
67 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070068 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000069}
70
Mike Lockwood94afecf2012-10-24 10:45:23 -070071/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -070072 * Create the path name where package app contents should be stored for
73 * the given volume UUID and package name. An empty UUID is assumed to
74 * be internal storage.
75 */
76std::string create_data_app_package_path(const char* volume_uuid,
77 const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000078 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070079 return StringPrintf("%s/%s",
80 create_data_app_path(volume_uuid).c_str(), package_name);
81}
82
83/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070084 * Create the path name where package data should be stored for the given
85 * volume UUID, package name, and user ID. An empty UUID is assumed to be
86 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070087 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -060088std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -070089 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000090 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070091 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -060092 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
93}
94
95std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
96 const char* package_name, ino_t ce_data_inode) {
97 // For testing purposes, rely on the inode when defined; this could be
98 // optimized to use access() in the future.
99 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
100 if (ce_data_inode != 0) {
101 auto user_path = create_data_user_ce_path(volume_uuid, user);
102 DIR* dir = opendir(user_path.c_str());
103 if (dir == nullptr) {
104 PLOG(ERROR) << "Failed to opendir " << user_path;
105 return fallback;
106 }
107
108 struct dirent* ent;
109 while ((ent = readdir(dir))) {
110 if (ent->d_ino == ce_data_inode) {
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600111 auto resolved = StringPrintf("%s/%s", user_path.c_str(), ent->d_name);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600112#if DEBUG_XATTRS
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600113 if (resolved != fallback) {
114 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
115 << " instead of " << fallback;
116 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600117#endif
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600118 closedir(dir);
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600119 return resolved;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600120 }
121 }
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600122 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600123 closedir(dir);
124 return fallback;
125 } else {
126 return fallback;
127 }
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700128}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700129
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800130std::string create_data_user_de_package_path(const char* volume_uuid,
131 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000132 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800133 return StringPrintf("%s/%s",
134 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
135}
136
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700137int create_pkg_path(char path[PKG_PATH_MAX], const char *pkgname,
138 const char *postfix, userid_t userid) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700139 if (!is_valid_package_name(pkgname)) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700140 path[0] = '\0';
Mike Lockwood94afecf2012-10-24 10:45:23 -0700141 return -1;
142 }
143
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600144 std::string _tmp(create_data_user_ce_package_path(nullptr, userid, pkgname) + postfix);
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700145 const char* tmp = _tmp.c_str();
146 if (strlen(tmp) >= PKG_PATH_MAX) {
147 path[0] = '\0';
148 return -1;
149 } else {
150 strcpy(path, tmp);
151 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700152 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700153}
154
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700155std::string create_data_path(const char* volume_uuid) {
156 if (volume_uuid == nullptr) {
157 return "/data";
158 } else {
159 CHECK(is_valid_filename(volume_uuid));
160 return StringPrintf("/mnt/expand/%s", volume_uuid);
161 }
162}
163
Mike Lockwood94afecf2012-10-24 10:45:23 -0700164/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700165 * Create the path name for app data.
166 */
167std::string create_data_app_path(const char* volume_uuid) {
168 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
169}
170
171/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700172 * Create the path name for user data for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700173 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600174std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700175 std::string data(create_data_path(volume_uuid));
176 if (volume_uuid == nullptr) {
177 if (userid == 0) {
178 return StringPrintf("%s/data", data.c_str());
179 } else {
180 return StringPrintf("%s/user/%u", data.c_str(), userid);
181 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700182 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700183 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700184 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700185}
186
187/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800188 * Create the path name for device encrypted user data for a certain userid.
189 */
190std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
191 std::string data(create_data_path(volume_uuid));
192 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
193}
194
195/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700196 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700197 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700198std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
199 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700200}
201
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700202std::string create_data_media_obb_path(const char* volume_uuid, const char* package_name) {
203 return StringPrintf("%s/media/obb/%s", create_data_path(volume_uuid).c_str(), package_name);
204}
205
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700206std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
207 const char* data_type, const char* package_name) {
208 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
209 data_type, package_name);
210}
211
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600212std::string create_data_misc_legacy_path(userid_t userid) {
213 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
214}
215
Calin Juravle114f0812017-03-08 19:05:07 -0800216std::string create_primary_cur_profile_dir_path(userid_t userid) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000217 return StringPrintf("%s/cur/%u", android_profiles_dir.path, userid);
218}
219
Calin Juravle114f0812017-03-08 19:05:07 -0800220std::string create_primary_current_profile_package_dir_path(userid_t user,
221 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800222 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800223 return StringPrintf("%s/%s",
224 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700225}
226
Calin Juravle114f0812017-03-08 19:05:07 -0800227std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700228 return StringPrintf("%s/ref", android_profiles_dir.path);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000229}
230
Calin Juravle114f0812017-03-08 19:05:07 -0800231std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800232 check_package_name(package_name.c_str());
233 return StringPrintf("%s/ref/%s", android_profiles_dir.path, package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000234}
235
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700236std::string create_data_dalvik_cache_path() {
237 return "/data/dalvik-cache";
238}
239
Calin Juravle114f0812017-03-08 19:05:07 -0800240// Keep profile paths in sync with ActivityThread and LoadedApk.
241const std::string PROFILE_EXT = ".prof";
242const std::string PRIMARY_PROFILE_NAME = "primary" + PROFILE_EXT;
Jeff Sharkey90aff262016-12-12 14:28:24 -0700243
Calin Juravle114f0812017-03-08 19:05:07 -0800244std::string create_current_profile_path(userid_t user, const std::string& location,
245 bool is_secondary_dex) {
246 if (is_secondary_dex) {
247 // Secondary dex profiles are stored next to the dex files using .prof extension.
248 return StringPrintf("%s%s", location.c_str(), PROFILE_EXT.c_str());
249 } else {
250 // Profiles for primary apks are under /data/misc/profiles/cur.
251 std::string profile_dir = create_primary_current_profile_package_dir_path(user, location);
252 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME.c_str());
253 }
254}
255
256std::string create_reference_profile_path(const std::string& location, bool is_secondary_dex) {
257 if (is_secondary_dex) {
258 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
259 size_t dirIndex = location.rfind('/');
260 CHECK(dirIndex != std::string::npos)
261 << "Unexpected dir structure for secondary dex " << location;
262
263 std::string dex_dir = location.substr(0, dirIndex);
264 std::string dex_name = location.substr(dirIndex +1);
265 return StringPrintf("%s/oat/%s%s",
266 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
267 } else {
268 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
269 std::string profile_dir = create_primary_reference_profile_package_dir_path(location);
270 return StringPrintf("%s/%s", profile_dir.c_str(), PRIMARY_PROFILE_NAME.c_str());
271 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700272}
273
Jeff Sharkeye3637242015-04-08 20:56:42 -0700274std::vector<userid_t> get_known_users(const char* volume_uuid) {
275 std::vector<userid_t> users;
276
277 // We always have an owner
278 users.push_back(0);
279
280 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
281 DIR* dir = opendir(path.c_str());
282 if (dir == NULL) {
283 // Unable to discover other users, but at least return owner
284 PLOG(ERROR) << "Failed to opendir " << path;
285 return users;
286 }
287
288 struct dirent* ent;
289 while ((ent = readdir(dir))) {
290 if (ent->d_type != DT_DIR) {
291 continue;
292 }
293
294 char* end;
295 userid_t user = strtol(ent->d_name, &end, 10);
296 if (*end == '\0' && user != 0) {
297 LOG(DEBUG) << "Found valid user " << user;
298 users.push_back(user);
299 }
300 }
301 closedir(dir);
302
303 return users;
304}
305
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700306int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700307 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700308 FTS *fts;
309 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700310 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700311 char *argv[] = { (char*) path.c_str(), nullptr };
312 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
313 if (errno != ENOENT) {
314 PLOG(ERROR) << "Failed to fts_open " << path;
315 }
316 return -1;
317 }
318 while ((p = fts_read(fts)) != NULL) {
319 switch (p->fts_info) {
320 case FTS_D:
321 case FTS_DEFAULT:
322 case FTS_F:
323 case FTS_SL:
324 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700325 int32_t uid = p->fts_statp->st_uid;
326 int32_t gid = p->fts_statp->st_gid;
327 int32_t user_uid = multiuser_get_app_id(uid);
328 int32_t user_gid = multiuser_get_app_id(gid);
329 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
330 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
331 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
332 // Don't traverse inside or measure
333 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700334 break;
335 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700336 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700337 break;
338 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700339 if (exclude_gid != -1 && gid == exclude_gid) {
340 break;
341 }
342 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700343 break;
344 }
345 }
346 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700347#if MEASURE_DEBUG
348 if ((include_gid == -1) && (exclude_gid == -1)) {
349 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
350 } else {
351 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
352 << " exclude " << exclude_gid;
353 }
354#endif
355 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700356 return 0;
357}
358
Mike Lockwood94afecf2012-10-24 10:45:23 -0700359int create_move_path(char path[PKG_PATH_MAX],
360 const char* pkgname,
361 const char* leaf,
Andreas Gampe02d0de52015-11-11 20:43:16 -0800362 userid_t userid ATTRIBUTE_UNUSED)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700363{
364 if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
365 >= PKG_PATH_MAX) {
366 return -1;
367 }
368
369 sprintf(path, "%s%s%s/%s", android_data_dir.path, PRIMARY_USER_PREFIX, pkgname, leaf);
370 return 0;
371}
372
373/**
374 * Checks whether the package name is valid. Returns -1 on error and
375 * 0 on success.
376 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700377bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey068ef222017-03-07 22:12:03 -0700378 // This logic is borrowed from PackageParser.java
379 bool hasSep = false;
380 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700381
Jeff Sharkey068ef222017-03-07 22:12:03 -0700382 auto it = packageName.begin();
383 for (; it != packageName.end() && *it != '-'; it++) {
384 char c = *it;
385 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
386 front = false;
387 continue;
388 }
389 if (!front) {
390 if ((c >= '0' && c <= '9') || c == '_') {
391 continue;
392 }
393 }
394 if (c == '.') {
395 hasSep = true;
396 front = true;
397 continue;
398 }
399 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700400 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700401 }
402
Jeff Sharkey2ee8cc02017-03-08 12:39:46 -0700403 if (front) {
Jeff Sharkey068ef222017-03-07 22:12:03 -0700404 LOG(WARNING) << "Missing separator in " << packageName;
405 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700406 }
407
Jeff Sharkey068ef222017-03-07 22:12:03 -0700408 for (; it != packageName.end(); it++) {
409 char c = *it;
410 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
411 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
412 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
413 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700414 }
415
Jeff Sharkey423e7462016-12-09 18:18:43 -0700416 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700417}
418
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100419static int _delete_dir_contents(DIR *d,
420 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700421{
422 int result = 0;
423 struct dirent *de;
424 int dfd;
425
426 dfd = dirfd(d);
427
428 if (dfd < 0) return -1;
429
430 while ((de = readdir(d))) {
431 const char *name = de->d_name;
432
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100433 /* check using the exclusion predicate, if provided */
434 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
435 continue;
436 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700437
438 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700439 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700440 DIR *subdir;
441
442 /* always skip "." and ".." */
443 if (name[0] == '.') {
444 if (name[1] == 0) continue;
445 if ((name[1] == '.') && (name[2] == 0)) continue;
446 }
447
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700448 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700449 if (subfd < 0) {
450 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
451 result = -1;
452 continue;
453 }
454 subdir = fdopendir(subfd);
455 if (subdir == NULL) {
456 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
457 close(subfd);
458 result = -1;
459 continue;
460 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100461 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700462 result = -1;
463 }
464 closedir(subdir);
465 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
466 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
467 result = -1;
468 }
469 } else {
470 if (unlinkat(dfd, name, 0) < 0) {
471 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
472 result = -1;
473 }
474 }
475 }
476
477 return result;
478}
479
Calin Juravleb06f98a2016-03-28 15:11:01 +0100480int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
481 return delete_dir_contents(pathname.c_str(), 0, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700482}
483
Calin Juravleb06f98a2016-03-28 15:11:01 +0100484int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
485 return delete_dir_contents(pathname.c_str(), 1, NULL, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700486}
487
Mike Lockwood94afecf2012-10-24 10:45:23 -0700488int delete_dir_contents(const char *pathname,
489 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100490 int (*exclusion_predicate)(const char*, const int),
491 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700492{
493 int res = 0;
494 DIR *d;
495
496 d = opendir(pathname);
497 if (d == NULL) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100498 if (ignore_if_missing && (errno == ENOENT)) {
499 return 0;
500 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700501 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
502 return -errno;
503 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100504 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700505 closedir(d);
506 if (also_delete_dir) {
507 if (rmdir(pathname)) {
508 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
509 res = -1;
510 }
511 }
512 return res;
513}
514
515int delete_dir_contents_fd(int dfd, const char *name)
516{
517 int fd, res;
518 DIR *d;
519
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700520 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700521 if (fd < 0) {
522 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
523 return -1;
524 }
525 d = fdopendir(fd);
526 if (d == NULL) {
527 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
528 close(fd);
529 return -1;
530 }
531 res = _delete_dir_contents(d, 0);
532 closedir(d);
533 return res;
534}
535
Robin Lee60fd3fe2014-10-07 16:55:02 +0100536static int _copy_owner_permissions(int srcfd, int dstfd)
537{
538 struct stat st;
539 if (fstat(srcfd, &st) != 0) {
540 return -1;
541 }
542 if (fchmod(dstfd, st.st_mode) != 0) {
543 return -1;
544 }
545 return 0;
546}
547
548static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
549{
550 int result = 0;
551 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
552 ALOGE("_copy_dir_files failed to copy dir permissions\n");
553 }
554 if (fchown(ddfd, owner, group) != 0) {
555 ALOGE("_copy_dir_files failed to change dir owner\n");
556 }
557
558 DIR *ds = fdopendir(sdfd);
559 if (ds == NULL) {
560 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
561 return -1;
562 }
563 struct dirent *de;
564 while ((de = readdir(ds))) {
565 if (de->d_type != DT_REG) {
566 continue;
567 }
568
569 const char *name = de->d_name;
570 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
571 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
572 if (fsfd == -1 || fdfd == -1) {
573 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
574 } else {
575 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
576 ALOGE("Failed to change file permissions\n");
577 }
578 if (fchown(fdfd, owner, group) != 0) {
579 ALOGE("Failed to change file owner\n");
580 }
581
582 char buf[8192];
583 ssize_t size;
584 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
585 write(fdfd, buf, size);
586 }
587 if (size < 0) {
588 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
589 result = -1;
590 }
591 }
592 close(fdfd);
593 close(fsfd);
594 }
595
596 return result;
597}
598
599int copy_dir_files(const char *srcname,
600 const char *dstname,
601 uid_t owner,
602 uid_t group)
603{
604 int res = 0;
605 DIR *ds = NULL;
606 DIR *dd = NULL;
607
608 ds = opendir(srcname);
609 if (ds == NULL) {
610 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
611 return -errno;
612 }
613
614 mkdir(dstname, 0600);
615 dd = opendir(dstname);
616 if (dd == NULL) {
617 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
618 closedir(ds);
619 return -errno;
620 }
621
622 int sdfd = dirfd(ds);
623 int ddfd = dirfd(dd);
624 if (sdfd != -1 && ddfd != -1) {
625 res = _copy_dir_files(sdfd, ddfd, owner, group);
626 } else {
627 res = -errno;
628 }
629 closedir(dd);
630 closedir(ds);
631 return res;
632}
633
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700634int64_t data_disk_free(const std::string& data_path)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700635{
636 struct statfs sfs;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700637 if (statfs(data_path.c_str(), &sfs) == 0) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700638 return sfs.f_bavail * sfs.f_bsize;
639 } else {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700640 PLOG(ERROR) << "Couldn't statfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700641 return -1;
642 }
643}
644
645cache_t* start_cache_collection()
646{
647 cache_t* cache = (cache_t*)calloc(1, sizeof(cache_t));
648 return cache;
649}
650
651#define CACHE_BLOCK_SIZE (512*1024)
652
653static void* _cache_malloc(cache_t* cache, size_t len)
654{
655 len = (len+3)&~3;
656 if (len > (CACHE_BLOCK_SIZE/2)) {
657 // It doesn't make sense to try to put this allocation into one
658 // of our blocks, because it is so big. Instead, make a new dedicated
659 // block for it.
660 int8_t* res = (int8_t*)malloc(len+sizeof(void*));
661 if (res == NULL) {
662 return NULL;
663 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600664 CACHE_NOISY(ALOGI("Allocated large cache mem block: %p size %zu", res, len));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700665 // Link it into our list of blocks, not disrupting the current one.
666 if (cache->memBlocks == NULL) {
667 *(void**)res = NULL;
668 cache->memBlocks = res;
669 } else {
670 *(void**)res = *(void**)cache->memBlocks;
671 *(void**)cache->memBlocks = res;
672 }
673 return res + sizeof(void*);
674 }
675 int8_t* res = cache->curMemBlockAvail;
676 int8_t* nextPos = res + len;
677 if (cache->memBlocks == NULL || nextPos > cache->curMemBlockEnd) {
Jeff Sharkey19803802015-04-07 12:44:51 -0700678 int8_t* newBlock = (int8_t*) malloc(CACHE_BLOCK_SIZE);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700679 if (newBlock == NULL) {
680 return NULL;
681 }
682 CACHE_NOISY(ALOGI("Allocated new cache mem block: %p", newBlock));
683 *(void**)newBlock = cache->memBlocks;
684 cache->memBlocks = newBlock;
685 res = cache->curMemBlockAvail = newBlock + sizeof(void*);
686 cache->curMemBlockEnd = newBlock + CACHE_BLOCK_SIZE;
687 nextPos = res + len;
688 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600689 CACHE_NOISY(ALOGI("cache_malloc: ret %p size %zu, block=%p, nextPos=%p",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700690 res, len, cache->memBlocks, nextPos));
691 cache->curMemBlockAvail = nextPos;
692 return res;
693}
694
695static void* _cache_realloc(cache_t* cache, void* cur, size_t origLen, size_t len)
696{
697 // This isn't really a realloc, but it is good enough for our purposes here.
698 void* alloc = _cache_malloc(cache, len);
699 if (alloc != NULL && cur != NULL) {
700 memcpy(alloc, cur, origLen < len ? origLen : len);
701 }
702 return alloc;
703}
704
705static void _inc_num_cache_collected(cache_t* cache)
706{
707 cache->numCollected++;
708 if ((cache->numCollected%20000) == 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700709 ALOGI("Collected cache so far: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -0700710 cache->numDirs, cache->numFiles);
711 }
712}
713
714static cache_dir_t* _add_cache_dir_t(cache_t* cache, cache_dir_t* parent, const char *name)
715{
716 size_t nameLen = strlen(name);
717 cache_dir_t* dir = (cache_dir_t*)_cache_malloc(cache, sizeof(cache_dir_t)+nameLen+1);
718 if (dir != NULL) {
719 dir->parent = parent;
720 dir->childCount = 0;
721 dir->hiddenCount = 0;
722 dir->deleted = 0;
723 strcpy(dir->name, name);
724 if (cache->numDirs >= cache->availDirs) {
725 size_t newAvail = cache->availDirs < 1000 ? 1000 : cache->availDirs*2;
726 cache_dir_t** newDirs = (cache_dir_t**)_cache_realloc(cache, cache->dirs,
727 cache->availDirs*sizeof(cache_dir_t*), newAvail*sizeof(cache_dir_t*));
728 if (newDirs == NULL) {
729 ALOGE("Failure growing cache dirs array for %s\n", name);
730 return NULL;
731 }
732 cache->availDirs = newAvail;
733 cache->dirs = newDirs;
734 }
735 cache->dirs[cache->numDirs] = dir;
736 cache->numDirs++;
737 if (parent != NULL) {
738 parent->childCount++;
739 }
740 _inc_num_cache_collected(cache);
741 } else {
742 ALOGE("Failure allocating cache_dir_t for %s\n", name);
743 }
744 return dir;
745}
746
747static cache_file_t* _add_cache_file_t(cache_t* cache, cache_dir_t* dir, time_t modTime,
748 const char *name)
749{
750 size_t nameLen = strlen(name);
751 cache_file_t* file = (cache_file_t*)_cache_malloc(cache, sizeof(cache_file_t)+nameLen+1);
752 if (file != NULL) {
753 file->dir = dir;
754 file->modTime = modTime;
755 strcpy(file->name, name);
756 if (cache->numFiles >= cache->availFiles) {
757 size_t newAvail = cache->availFiles < 1000 ? 1000 : cache->availFiles*2;
758 cache_file_t** newFiles = (cache_file_t**)_cache_realloc(cache, cache->files,
759 cache->availFiles*sizeof(cache_file_t*), newAvail*sizeof(cache_file_t*));
760 if (newFiles == NULL) {
761 ALOGE("Failure growing cache file array for %s\n", name);
762 return NULL;
763 }
764 cache->availFiles = newAvail;
765 cache->files = newFiles;
766 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600767 CACHE_NOISY(ALOGI("Setting file %p at position %zd in array %p", file,
Mike Lockwood94afecf2012-10-24 10:45:23 -0700768 cache->numFiles, cache->files));
769 cache->files[cache->numFiles] = file;
770 cache->numFiles++;
771 dir->childCount++;
772 _inc_num_cache_collected(cache);
773 } else {
774 ALOGE("Failure allocating cache_file_t for %s\n", name);
775 }
776 return file;
777}
778
779static int _add_cache_files(cache_t *cache, cache_dir_t *parentDir, const char *dirName,
780 DIR* dir, char *pathBase, char *pathPos, size_t pathAvailLen)
781{
782 struct dirent *de;
783 cache_dir_t* cacheDir = NULL;
784 int dfd;
785
786 CACHE_NOISY(ALOGI("_add_cache_files: parent=%p dirName=%s dir=%p pathBase=%s",
787 parentDir, dirName, dir, pathBase));
788
789 dfd = dirfd(dir);
790
791 if (dfd < 0) return 0;
792
793 // Sub-directories always get added to the data structure, so if they
794 // are empty we will know about them to delete them later.
795 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
796
797 while ((de = readdir(dir))) {
798 const char *name = de->d_name;
799
800 if (de->d_type == DT_DIR) {
801 int subfd;
802 DIR *subdir;
803
804 /* always skip "." and ".." */
805 if (name[0] == '.') {
806 if (name[1] == 0) continue;
807 if ((name[1] == '.') && (name[2] == 0)) continue;
808 }
809
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700810 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700811 if (subfd < 0) {
812 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
813 continue;
814 }
815 subdir = fdopendir(subfd);
816 if (subdir == NULL) {
817 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
818 close(subfd);
819 continue;
820 }
821 if (cacheDir == NULL) {
822 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
823 }
824 if (cacheDir != NULL) {
825 // Update pathBase for the new path... this may change dirName
826 // if that is also pointing to the path, but we are done with it
827 // now.
828 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
829 CACHE_NOISY(ALOGI("Collecting dir %s\n", pathBase));
830 if (finallen < pathAvailLen) {
831 _add_cache_files(cache, cacheDir, name, subdir, pathBase,
832 pathPos+finallen, pathAvailLen-finallen);
833 } else {
834 // Whoops, the final path is too long! We'll just delete
835 // this directory.
836 ALOGW("Cache dir %s truncated in path %s; deleting dir\n",
837 name, pathBase);
838 _delete_dir_contents(subdir, NULL);
839 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
840 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
841 }
842 }
843 }
844 closedir(subdir);
845 } else if (de->d_type == DT_REG) {
846 // Skip files that start with '.'; they will be deleted if
847 // their entire directory is deleted. This allows for metadata
848 // like ".nomedia" to remain in the directory until the entire
849 // directory is deleted.
850 if (cacheDir == NULL) {
851 cacheDir = _add_cache_dir_t(cache, parentDir, dirName);
852 }
853 if (name[0] == '.') {
854 cacheDir->hiddenCount++;
855 continue;
856 }
857 if (cacheDir != NULL) {
858 // Build final full path for file... this may change dirName
859 // if that is also pointing to the path, but we are done with it
860 // now.
861 size_t finallen = snprintf(pathPos, pathAvailLen, "/%s", name);
862 CACHE_NOISY(ALOGI("Collecting file %s\n", pathBase));
863 if (finallen < pathAvailLen) {
864 struct stat s;
865 if (stat(pathBase, &s) >= 0) {
866 _add_cache_file_t(cache, cacheDir, s.st_mtime, name);
867 } else {
868 ALOGW("Unable to stat cache file %s; deleting\n", pathBase);
869 if (unlink(pathBase) < 0) {
870 ALOGE("Couldn't unlink %s: %s\n", pathBase, strerror(errno));
871 }
872 }
873 } else {
874 // Whoops, the final path is too long! We'll just delete
875 // this file.
876 ALOGW("Cache file %s truncated in path %s; deleting\n",
877 name, pathBase);
878 if (unlinkat(dfd, name, 0) < 0) {
879 *pathPos = 0;
880 ALOGE("Couldn't unlinkat %s in %s: %s\n", name, pathBase,
881 strerror(errno));
882 }
883 }
884 }
885 } else {
886 cacheDir->hiddenCount++;
887 }
888 }
889 return 0;
890}
891
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600892int get_path_inode(const std::string& path, ino_t *inode) {
893 struct stat buf;
894 memset(&buf, 0, sizeof(buf));
895 if (stat(path.c_str(), &buf) != 0) {
896 PLOG(WARNING) << "Failed to stat " << path;
897 return -1;
898 } else {
899 *inode = buf.st_ino;
900 return 0;
901 }
902}
903
904/**
905 * Write the inode of a specific child file into the given xattr on the
906 * parent directory. This allows you to find the child later, even if its
907 * name is encrypted.
908 */
909int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
910 ino_t inode = 0;
911 uint64_t inode_raw = 0;
912 auto path = StringPrintf("%s/%s", parent.c_str(), name);
913
914 if (get_path_inode(path, &inode) != 0) {
915 // Path probably doesn't exist yet; ignore
916 return 0;
917 }
918
919 // Check to see if already set correctly
920 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
921 if (inode_raw == inode) {
922 // Already set correctly; skip writing
923 return 0;
924 } else {
925 PLOG(WARNING) << "Mismatched inode value; found " << inode
926 << " on disk but marked value was " << inode_raw << "; overwriting";
927 }
928 }
929
930 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600931 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600932 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
933 return -1;
934 } else {
935 return 0;
936 }
937}
938
939/**
940 * Read the inode of a specific child file from the given xattr on the
941 * parent directory. Returns a currently valid path for that child, which
942 * might have an encrypted name.
943 */
944std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
945 ino_t inode = 0;
946 uint64_t inode_raw = 0;
947 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
948
949 // Lookup the inode value written earlier
950 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
951 inode = inode_raw;
952 }
953
954 // For testing purposes, rely on the inode when defined; this could be
955 // optimized to use access() in the future.
956 if (inode != 0) {
957 DIR* dir = opendir(parent.c_str());
958 if (dir == nullptr) {
959 PLOG(ERROR) << "Failed to opendir " << parent;
960 return fallback;
961 }
962
963 struct dirent* ent;
964 while ((ent = readdir(dir))) {
965 if (ent->d_ino == inode) {
966 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
967#if DEBUG_XATTRS
968 if (resolved != fallback) {
969 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
970 << " instead of " << fallback;
971 }
972#endif
973 closedir(dir);
974 return resolved;
975 }
976 }
977 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
978 closedir(dir);
979 return fallback;
980 } else {
981 return fallback;
982 }
983}
984
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600985void add_cache_files(cache_t* cache, const std::string& data_path) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700986 DIR *d;
987 struct dirent *de;
988 char dirname[PATH_MAX];
989
Jeff Sharkey54e292e2016-05-10 17:21:13 -0600990 const char* basepath = data_path.c_str();
991 CACHE_NOISY(ALOGI("add_cache_files: basepath=%s\n", basepath));
Mike Lockwood94afecf2012-10-24 10:45:23 -0700992
993 d = opendir(basepath);
994 if (d == NULL) {
995 return;
996 }
997
998 while ((de = readdir(d))) {
999 if (de->d_type == DT_DIR) {
1000 DIR* subdir;
1001 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001002
1003 /* always skip "." and ".." */
1004 if (name[0] == '.') {
1005 if (name[1] == 0) continue;
1006 if ((name[1] == '.') && (name[2] == 0)) continue;
1007 }
1008
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001009 auto parent = StringPrintf("%s/%s", basepath, name);
1010 auto resolved = read_path_inode(parent, "cache", kXattrInodeCache);
1011 strcpy(dirname, resolved.c_str());
Mike Lockwood94afecf2012-10-24 10:45:23 -07001012 CACHE_NOISY(ALOGI("Adding cache files from dir: %s\n", dirname));
Jeff Sharkey54e292e2016-05-10 17:21:13 -06001013
Mike Lockwood94afecf2012-10-24 10:45:23 -07001014 subdir = opendir(dirname);
1015 if (subdir != NULL) {
1016 size_t dirnameLen = strlen(dirname);
1017 _add_cache_files(cache, NULL, dirname, subdir, dirname, dirname+dirnameLen,
1018 PATH_MAX - dirnameLen);
1019 closedir(subdir);
1020 }
1021 }
1022 }
1023
1024 closedir(d);
1025}
1026
1027static char *create_dir_path(char path[PATH_MAX], cache_dir_t* dir)
1028{
1029 char *pos = path;
1030 if (dir->parent != NULL) {
1031 pos = create_dir_path(path, dir->parent);
1032 }
1033 // Note that we don't need to worry about going beyond the buffer,
1034 // since when we were constructing the cache entries our maximum
1035 // buffer size for full paths was PATH_MAX.
1036 strcpy(pos, dir->name);
1037 pos += strlen(pos);
1038 *pos = '/';
1039 pos++;
1040 *pos = 0;
1041 return pos;
1042}
1043
1044static void delete_cache_dir(char path[PATH_MAX], cache_dir_t* dir)
1045{
1046 if (dir->parent != NULL) {
1047 create_dir_path(path, dir);
1048 ALOGI("DEL DIR %s\n", path);
1049 if (dir->hiddenCount <= 0) {
1050 if (rmdir(path)) {
1051 ALOGE("Couldn't rmdir %s: %s\n", path, strerror(errno));
1052 return;
1053 }
1054 } else {
1055 // The directory contains hidden files so we need to delete
1056 // them along with the directory itself.
1057 if (delete_dir_contents(path, 1, NULL)) {
1058 return;
1059 }
1060 }
1061 dir->parent->childCount--;
1062 dir->deleted = 1;
1063 if (dir->parent->childCount <= 0) {
1064 delete_cache_dir(path, dir->parent);
1065 }
1066 } else if (dir->hiddenCount > 0) {
1067 // This is a root directory, but it has hidden files. Get rid of
1068 // all of those files, but not the directory itself.
1069 create_dir_path(path, dir);
1070 ALOGI("DEL CONTENTS %s\n", path);
1071 delete_dir_contents(path, 0, NULL);
1072 }
1073}
1074
1075static int cache_modtime_sort(const void *lhsP, const void *rhsP)
1076{
1077 const cache_file_t *lhs = *(const cache_file_t**)lhsP;
1078 const cache_file_t *rhs = *(const cache_file_t**)rhsP;
1079 return lhs->modTime < rhs->modTime ? -1 : (lhs->modTime > rhs->modTime ? 1 : 0);
1080}
1081
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001082void clear_cache_files(const std::string& data_path, cache_t* cache, int64_t free_size)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001083{
1084 size_t i;
1085 int skip = 0;
1086 char path[PATH_MAX];
1087
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -07001088 ALOGI("Collected cache files: %zd directories, %zd files",
Mike Lockwood94afecf2012-10-24 10:45:23 -07001089 cache->numDirs, cache->numFiles);
1090
1091 CACHE_NOISY(ALOGI("Sorting files..."));
1092 qsort(cache->files, cache->numFiles, sizeof(cache_file_t*),
1093 cache_modtime_sort);
1094
1095 CACHE_NOISY(ALOGI("Cleaning empty directories..."));
1096 for (i=cache->numDirs; i>0; i--) {
1097 cache_dir_t* dir = cache->dirs[i-1];
1098 if (dir->childCount <= 0 && !dir->deleted) {
1099 delete_cache_dir(path, dir);
1100 }
1101 }
1102
1103 CACHE_NOISY(ALOGI("Trimming files..."));
1104 for (i=0; i<cache->numFiles; i++) {
1105 skip++;
1106 if (skip > 10) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001107 if (data_disk_free(data_path) > free_size) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001108 return;
1109 }
1110 skip = 0;
1111 }
1112 cache_file_t* file = cache->files[i];
1113 strcpy(create_dir_path(path, file->dir), file->name);
1114 ALOGI("DEL (mod %d) %s\n", (int)file->modTime, path);
1115 if (unlink(path) < 0) {
1116 ALOGE("Couldn't unlink %s: %s\n", path, strerror(errno));
1117 }
1118 file->dir->childCount--;
1119 if (file->dir->childCount <= 0) {
1120 delete_cache_dir(path, file->dir);
1121 }
1122 }
1123}
1124
1125void finish_cache_collection(cache_t* cache)
1126{
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -07001127 CACHE_NOISY(size_t i;)
Mike Lockwood94afecf2012-10-24 10:45:23 -07001128
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001129 CACHE_NOISY(ALOGI("clear_cache_files: %zu dirs, %zu files\n", cache->numDirs, cache->numFiles));
Mike Lockwood94afecf2012-10-24 10:45:23 -07001130 CACHE_NOISY(
1131 for (i=0; i<cache->numDirs; i++) {
1132 cache_dir_t* dir = cache->dirs[i];
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001133 ALOGI("dir #%zu: %p %s parent=%p\n", i, dir, dir->name, dir->parent);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001134 })
1135 CACHE_NOISY(
1136 for (i=0; i<cache->numFiles; i++) {
1137 cache_file_t* file = cache->files[i];
Jeff Sharkey9a998f42016-07-14 18:16:22 -06001138 ALOGI("file #%zu: %p %s time=%d dir=%p\n", i, file, file->name,
Mike Lockwood94afecf2012-10-24 10:45:23 -07001139 (int)file->modTime, file->dir);
1140 })
1141 void* block = cache->memBlocks;
1142 while (block != NULL) {
1143 void* nextBlock = *(void**)block;
1144 CACHE_NOISY(ALOGI("Freeing cache mem block: %p", block));
1145 free(block);
1146 block = nextBlock;
1147 }
1148 free(cache);
1149}
1150
1151/**
Calin Juravlec597b6d2014-08-19 17:43:05 +01001152 * Validate that the path is valid in the context of the provided directory.
1153 * The path is allowed to have at most one subdirectory and no indirections
1154 * to top level directories (i.e. have "..").
1155 */
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001156static int validate_path(const dir_rec_t* dir, const char* path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001157 size_t dir_len = dir->len;
1158 const char* subdir = strchr(path + dir_len, '/');
1159
1160 // Only allow the path to have at most one subdirectory.
1161 if (subdir != NULL) {
1162 ++subdir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001163 if ((--maxSubdirs == 0) && strchr(subdir, '/') != NULL) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001164 ALOGE("invalid apk path '%s' (subdir?)\n", path);
1165 return -1;
1166 }
1167 }
1168
1169 // Directories can't have a period directly after the directory markers to prevent "..".
1170 if ((path[dir_len] == '.') || ((subdir != NULL) && (*subdir == '.'))) {
1171 ALOGE("invalid apk path '%s' (trickery)\n", path);
1172 return -1;
1173 }
1174
1175 return 0;
1176}
1177
1178/**
Mike Lockwood94afecf2012-10-24 10:45:23 -07001179 * Checks whether a path points to a system app (.apk file). Returns 0
1180 * if it is a system app or -1 if it is not.
1181 */
1182int validate_system_app_path(const char* path) {
1183 size_t i;
1184
1185 for (i = 0; i < android_system_dirs.count; i++) {
1186 const size_t dir_len = android_system_dirs.dirs[i].len;
1187 if (!strncmp(path, android_system_dirs.dirs[i].path, dir_len)) {
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001188 return validate_path(android_system_dirs.dirs + i, path, 1);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001189 }
1190 }
1191
1192 return -1;
1193}
1194
Calin Juravle114f0812017-03-08 19:05:07 -08001195bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle80a21252017-01-17 14:43:25 -08001196 const char* volume_uuid, int uid, int storage_flag) {
1197 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1198
1199 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravle114f0812017-03-08 19:05:07 -08001200 ? create_data_user_ce_package_path(
1201 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1202 : create_data_user_de_package_path(
1203 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle80a21252017-01-17 14:43:25 -08001204 dir_rec_t dir;
1205 if (get_path_from_string(&dir, app_private_dir.c_str()) != 0) {
1206 LOG(WARNING) << "Could not get dir rec for " << app_private_dir;
1207 return false;
1208 }
1209 // Usually secondary dex files have a nested directory structure.
1210 // Pick at most 10 subdirectories when validating (arbitrary value).
1211 // If the secondary dex file is >10 directory nested then validation will
1212 // fail and the file will not be compiled.
Calin Juravle114f0812017-03-08 19:05:07 -08001213 return validate_path(&dir, dex_path.c_str(), /*max_subdirs*/ 10) == 0;
Calin Juravle80a21252017-01-17 14:43:25 -08001214}
1215
Mike Lockwood94afecf2012-10-24 10:45:23 -07001216/**
1217 * Get the contents of a environment variable that contains a path. Caller
1218 * owns the string that is inserted into the directory record. Returns
1219 * 0 on success and -1 on error.
1220 */
1221int get_path_from_env(dir_rec_t* rec, const char* var) {
1222 const char* path = getenv(var);
1223 int ret = get_path_from_string(rec, path);
1224 if (ret < 0) {
1225 ALOGW("Problem finding value for environment variable %s\n", var);
1226 }
1227 return ret;
1228}
1229
1230/**
1231 * Puts the string into the record as a directory. Appends '/' to the end
1232 * of all paths. Caller owns the string that is inserted into the directory
1233 * record. A null value will result in an error.
1234 *
1235 * Returns 0 on success and -1 on error.
1236 */
1237int get_path_from_string(dir_rec_t* rec, const char* path) {
1238 if (path == NULL) {
1239 return -1;
1240 } else {
1241 const size_t path_len = strlen(path);
1242 if (path_len <= 0) {
1243 return -1;
1244 }
1245
1246 // Make sure path is absolute.
1247 if (path[0] != '/') {
1248 return -1;
1249 }
1250
1251 if (path[path_len - 1] == '/') {
1252 // Path ends with a forward slash. Make our own copy.
1253
1254 rec->path = strdup(path);
1255 if (rec->path == NULL) {
1256 return -1;
1257 }
1258
1259 rec->len = path_len;
1260 } else {
1261 // Path does not end with a slash. Generate a new string.
1262 char *dst;
1263
1264 // Add space for slash and terminating null.
1265 size_t dst_size = path_len + 2;
1266
Jeff Sharkey19803802015-04-07 12:44:51 -07001267 rec->path = (char*) malloc(dst_size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001268 if (rec->path == NULL) {
1269 return -1;
1270 }
1271
1272 dst = rec->path;
1273
1274 if (append_and_increment(&dst, path, &dst_size) < 0
1275 || append_and_increment(&dst, "/", &dst_size)) {
1276 ALOGE("Error canonicalizing path");
1277 return -1;
1278 }
1279
1280 rec->len = dst - rec->path;
1281 }
1282 }
1283 return 0;
1284}
1285
1286int copy_and_append(dir_rec_t* dst, const dir_rec_t* src, const char* suffix) {
1287 dst->len = src->len + strlen(suffix);
1288 const size_t dstSize = dst->len + 1;
1289 dst->path = (char*) malloc(dstSize);
1290
1291 if (dst->path == NULL
1292 || snprintf(dst->path, dstSize, "%s%s", src->path, suffix)
1293 != (ssize_t) dst->len) {
1294 ALOGE("Could not allocate memory to hold appended path; aborting\n");
1295 return -1;
1296 }
1297
1298 return 0;
1299}
1300
1301/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001302 * Check whether path points to a valid path for an APK file. The path must
1303 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1304 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1305 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001306 */
Narayan Kamathd845c962015-06-04 13:20:27 +01001307static int validate_apk_path_internal(const char *path, int maxSubdirs) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001308 const dir_rec_t* dir = NULL;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001309 if (!strncmp(path, android_app_dir.path, android_app_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001310 dir = &android_app_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001311 } else if (!strncmp(path, android_app_private_dir.path, android_app_private_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001312 dir = &android_app_private_dir;
Todd Kennedy5c1a9102015-11-23 15:18:10 -08001313 } else if (!strncmp(path, android_app_ephemeral_dir.path, android_app_ephemeral_dir.len)) {
1314 dir = &android_app_ephemeral_dir;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001315 } else if (!strncmp(path, android_asec_dir.path, android_asec_dir.len)) {
Calin Juravlec597b6d2014-08-19 17:43:05 +01001316 dir = &android_asec_dir;
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001317 } else if (!strncmp(path, android_mnt_expand_dir.path, android_mnt_expand_dir.len)) {
1318 dir = &android_mnt_expand_dir;
Narayan Kamathd845c962015-06-04 13:20:27 +01001319 if (maxSubdirs < 2) {
1320 maxSubdirs = 2;
1321 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001322 } else {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001323 return -1;
1324 }
1325
Jeff Sharkeye23a1322015-04-06 16:19:39 -07001326 return validate_path(dir, path, maxSubdirs);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001327}
1328
Narayan Kamathd845c962015-06-04 13:20:27 +01001329int validate_apk_path(const char* path) {
1330 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
1331}
1332
1333int validate_apk_path_subdirs(const char* path) {
1334 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
1335}
1336
Mike Lockwood94afecf2012-10-24 10:45:23 -07001337int append_and_increment(char** dst, const char* src, size_t* dst_size) {
1338 ssize_t ret = strlcpy(*dst, src, *dst_size);
1339 if (ret < 0 || (size_t) ret >= *dst_size) {
1340 return -1;
1341 }
1342 *dst += ret;
1343 *dst_size -= ret;
1344 return 0;
1345}
1346
Jeff Sharkey19803802015-04-07 12:44:51 -07001347char *build_string2(const char *s1, const char *s2) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001348 if (s1 == NULL || s2 == NULL) return NULL;
1349
1350 int len_s1 = strlen(s1);
1351 int len_s2 = strlen(s2);
1352 int len = len_s1 + len_s2 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001353 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001354 if (result == NULL) return NULL;
1355
1356 strcpy(result, s1);
1357 strcpy(result + len_s1, s2);
1358
1359 return result;
1360}
1361
Jeff Sharkey19803802015-04-07 12:44:51 -07001362char *build_string3(const char *s1, const char *s2, const char *s3) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07001363 if (s1 == NULL || s2 == NULL || s3 == NULL) return NULL;
1364
1365 int len_s1 = strlen(s1);
1366 int len_s2 = strlen(s2);
1367 int len_s3 = strlen(s3);
1368 int len = len_s1 + len_s2 + len_s3 + 1;
Jeff Sharkey19803802015-04-07 12:44:51 -07001369 char *result = (char *) malloc(len);
Mike Lockwood94afecf2012-10-24 10:45:23 -07001370 if (result == NULL) return NULL;
1371
1372 strcpy(result, s1);
1373 strcpy(result + len_s1, s2);
1374 strcpy(result + len_s1 + len_s2, s3);
1375
1376 return result;
1377}
1378
Robin Lee095c7632014-04-25 15:05:19 +01001379int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001380 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001381 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1382 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001383
1384 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001385 auto path = create_data_misc_legacy_path(userid);
1386 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001387}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001388
1389int wait_child(pid_t pid)
1390{
1391 int status;
1392 pid_t got_pid;
1393
1394 while (1) {
1395 got_pid = waitpid(pid, &status, 0);
1396 if (got_pid == -1 && errno == EINTR) {
1397 printf("waitpid interrupted, retrying\n");
1398 } else {
1399 break;
1400 }
1401 }
1402 if (got_pid != pid) {
1403 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1404 (int) pid, (int) got_pid, strerror(errno));
1405 return 1;
1406 }
1407
1408 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1409 return 0;
1410 } else {
1411 return status; /* always nonzero */
1412 }
1413}
1414
Calin Juravle80a21252017-01-17 14:43:25 -08001415/**
1416 * Prepare an app cache directory, which offers to fix-up the GID and
1417 * directory mode flags during a platform upgrade.
1418 * The app cache directory path will be 'parent'/'name'.
1419 */
1420int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1421 uid_t uid, gid_t gid) {
1422 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1423 struct stat st;
1424 if (stat(path.c_str(), &st) != 0) {
1425 if (errno == ENOENT) {
1426 // This is fine, just create it
1427 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1428 PLOG(ERROR) << "Failed to prepare " << path;
1429 return -1;
1430 } else {
1431 return 0;
1432 }
1433 } else {
1434 PLOG(ERROR) << "Failed to stat " << path;
1435 return -1;
1436 }
1437 }
1438
1439 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1440 if (st.st_uid != uid) {
1441 // Mismatched UID is real trouble; we can't recover
1442 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1443 << " but expected " << uid;
1444 return -1;
1445 } else if (st.st_gid == gid && actual_mode == target_mode) {
1446 // Everything looks good!
1447 return 0;
1448 }
1449
1450 // Directory is owned correctly, but GID or mode mismatch means it's
1451 // probably a platform upgrade so we need to fix them
1452 FTS *fts;
1453 FTSENT *p;
1454 char *argv[] = { (char*) path.c_str(), nullptr };
1455 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_XDEV, NULL))) {
1456 PLOG(ERROR) << "Failed to fts_open " << path;
1457 return -1;
1458 }
1459 while ((p = fts_read(fts)) != NULL) {
1460 switch (p->fts_info) {
1461 case FTS_DP:
1462 if (chmod(p->fts_accpath, target_mode) != 0) {
1463 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1464 }
1465 // Intentional fall through to also set GID
1466 case FTS_F:
1467 if (chown(p->fts_accpath, -1, gid) != 0) {
1468 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1469 }
1470 break;
1471 case FTS_SL:
1472 case FTS_SLNONE:
1473 if (lchown(p->fts_accpath, -1, gid) != 0) {
1474 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1475 }
1476 break;
1477 }
1478 }
1479 fts_close(fts);
1480 return 0;
1481}
1482
Andreas Gampe02d0de52015-11-11 20:43:16 -08001483} // namespace installd
1484} // namespace android