blob: faccded34be6402f4ed51024c8e4401427d3a5a2 [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>
Eric Holk2af5e6a2019-01-09 18:17:27 -080023#include <sys/capability.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080024#include <sys/stat.h>
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080025#include <sys/statvfs.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026#include <sys/wait.h>
Jeff Sharkey9a998f42016-07-14 18:16:22 -060027#include <sys/xattr.h>
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080028#include <uuid/uuid.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080029
Martijn Coenen771cc342020-02-19 23:26:56 +010030#include <android-base/file.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080031#include <android-base/logging.h>
Calin Juravlecfcd6aa2018-01-18 20:23:17 -080032#include <android-base/strings.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080033#include <android-base/stringprintf.h>
Calin Juravlee61189e2018-01-23 19:54:11 -080034#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#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>
Martijn Coenen771cc342020-02-19 23:26:56 +010039#include <private/android_projectid_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070040
Eric Holk2af5e6a2019-01-09 18:17:27 -080041#include "dexopt_return_codes.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080042#include "globals.h" // extern variables.
Martijn Coenen771cc342020-02-19 23:26:56 +010043#include "QuotaUtils.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080044
45#ifndef LOG_TAG
46#define LOG_TAG "installd"
47#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060048
Jeff Sharkey9a998f42016-07-14 18:16:22 -060049#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070050
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080051using android::base::Dirname;
Calin Juravlee61189e2018-01-23 19:54:11 -080052using android::base::EndsWith;
Mathieu Chartier89883e32018-11-01 11:39:00 -070053using android::base::Fdopendir;
Jeff Sharkeyc03de092015-04-07 18:14:05 -070054using android::base::StringPrintf;
Calin Juravlee61189e2018-01-23 19:54:11 -080055using android::base::unique_fd;
Mike Lockwood94afecf2012-10-24 10:45:23 -070056
Andreas Gampe02d0de52015-11-11 20:43:16 -080057namespace android {
58namespace installd {
59
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080060using namespace std::literals;
61
62static constexpr auto deletedSuffix = "==deleted=="sv;
63
Jeff Sharkeyc03de092015-04-07 18:14:05 -070064/**
65 * Check that given string is valid filename, and that it attempts no
66 * parent or child directory traversal.
67 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070068bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070069 if (name.empty() || (name == ".") || (name == "..")
70 || (name.find('/') != std::string::npos)) {
71 return false;
72 } else {
73 return true;
74 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070075}
76
Calin Juravle6a1648e2016-02-01 12:12:16 +000077static void check_package_name(const char* package_name) {
78 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070079 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000080}
81
Nikita Ioffe8755f792019-01-25 13:54:43 +000082static std::string resolve_ce_path_by_inode_or_fallback(const std::string& root_path,
83 ino_t ce_data_inode, const std::string& fallback) {
84 if (ce_data_inode != 0) {
85 DIR* dir = opendir(root_path.c_str());
86 if (dir == nullptr) {
87 PLOG(ERROR) << "Failed to opendir " << root_path;
88 return fallback;
89 }
90
91 struct dirent* ent;
92 while ((ent = readdir(dir))) {
93 if (ent->d_ino == ce_data_inode) {
94 auto resolved = StringPrintf("%s/%s", root_path.c_str(), ent->d_name);
95 if (resolved != fallback) {
96 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
97 << " instead of " << fallback;
98 }
99 closedir(dir);
100 return resolved;
101 }
102 }
103 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
104 closedir(dir);
105 return fallback;
106 } else {
107 return fallback;
108 }
109}
110
Mike Lockwood94afecf2012-10-24 10:45:23 -0700111/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700112 * Create the path name where package data should be stored for the given
113 * volume UUID, package name, and user ID. An empty UUID is assumed to be
114 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700115 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600116std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700117 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000118 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700119 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600120 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
121}
122
Calin Juravle7d765462017-09-04 15:57:10 -0700123/**
124 * Create the path name where package data should be stored for the given
125 * volume UUID, package name, and user ID. An empty UUID is assumed to be
126 * internal storage.
127 * Compared to create_data_user_ce_package_path this method always return the
128 * ".../user/..." directory.
129 */
130std::string create_data_user_ce_package_path_as_user_link(
131 const char* volume_uuid, userid_t userid, const char* package_name) {
132 check_package_name(package_name);
133 std::string data(create_data_path(volume_uuid));
134 return StringPrintf("%s/user/%u/%s", data.c_str(), userid, package_name);
135}
136
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600137std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
138 const char* package_name, ino_t ce_data_inode) {
139 // For testing purposes, rely on the inode when defined; this could be
140 // optimized to use access() in the future.
141 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000142 auto user_path = create_data_user_ce_path(volume_uuid, user);
143 return resolve_ce_path_by_inode_or_fallback(user_path, ce_data_inode, fallback);
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700144}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700145
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800146std::string create_data_user_de_package_path(const char* volume_uuid,
147 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000148 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800149 return StringPrintf("%s/%s",
150 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
151}
152
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700153std::string create_data_path(const char* volume_uuid) {
154 if (volume_uuid == nullptr) {
155 return "/data";
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700156 } else if (!strcmp(volume_uuid, "TEST")) {
157 CHECK(property_get_bool("ro.debuggable", false));
158 return "/data/local/tmp";
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700159 } else {
160 CHECK(is_valid_filename(volume_uuid));
161 return StringPrintf("/mnt/expand/%s", volume_uuid);
162 }
163}
164
Mike Lockwood94afecf2012-10-24 10:45:23 -0700165/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700166 * Create the path name for app data.
167 */
168std::string create_data_app_path(const char* volume_uuid) {
169 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
170}
171
172/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700173 * Create the path name for user data for a certain userid.
cjbao75d4e572017-04-12 00:12:24 +0800174 * Keep same implementation as vold to minimize path walking overhead
Mike Lockwood94afecf2012-10-24 10:45:23 -0700175 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600176std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700177 std::string data(create_data_path(volume_uuid));
cjbao75d4e572017-04-12 00:12:24 +0800178 if (volume_uuid == nullptr && userid == 0) {
179 std::string legacy = StringPrintf("%s/data", data.c_str());
180 struct stat sb;
181 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
182 /* /data/data is dir, return /data/data for legacy system */
183 return legacy;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700184 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700185 }
cjbao75d4e572017-04-12 00:12:24 +0800186 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700187}
188
189/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800190 * Create the path name for device encrypted user data for a certain userid.
191 */
192std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
193 std::string data(create_data_path(volume_uuid));
194 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
195}
196
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000197std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000198 return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
199}
200
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000201std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000202 return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
203}
204
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000205std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
206 int32_t snapshot_id) {
207 return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
208 snapshot_id);
209}
210
211std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
212 int32_t snapshot_id) {
213 return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
214 snapshot_id);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000215}
216
Nikita Ioffe8755f792019-01-25 13:54:43 +0000217std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000218 userid_t user, int32_t snapshot_id, const char* package_name) {
219 return StringPrintf("%s/%s",
220 create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
221}
222
223std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
224 userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
225 auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
226 package_name);
227 auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000228 return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
229}
230
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000231std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000232 userid_t user, int32_t snapshot_id, const char* package_name) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000233 return StringPrintf("%s/%s",
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000234 create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000235}
236
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800237/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700238 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700239 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700240std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
241 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700242}
243
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700244std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
245 const char* data_type, const char* package_name) {
246 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
247 data_type, package_name);
248}
249
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600250std::string create_data_misc_legacy_path(userid_t userid) {
251 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
252}
253
Calin Juravle114f0812017-03-08 19:05:07 -0800254std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600255 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000256}
257
Calin Juravle114f0812017-03-08 19:05:07 -0800258std::string create_primary_current_profile_package_dir_path(userid_t user,
259 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800260 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800261 return StringPrintf("%s/%s",
262 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700263}
264
Calin Juravle114f0812017-03-08 19:05:07 -0800265std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600266 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000267}
268
Calin Juravle114f0812017-03-08 19:05:07 -0800269std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800270 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600271 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000272}
273
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700274std::string create_data_dalvik_cache_path() {
275 return "/data/dalvik-cache";
276}
277
Felka Chang2a0a2462019-11-20 14:20:40 +0800278std::string create_system_user_ce_path(userid_t userId) {
279 return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
280}
281
282std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
283 check_package_name(package_name);
284 return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
285}
286
Calin Juravle114f0812017-03-08 19:05:07 -0800287// Keep profile paths in sync with ActivityThread and LoadedApk.
288const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700289const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800290const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700291
Calin Juravle3760ad32017-07-27 16:31:55 -0700292// Gets the parent directory and the file name for the given secondary dex path.
293// Returns true on success, false on failure (if the dex_path does not have the expected
294// structure).
295static bool get_secondary_dex_location(const std::string& dex_path,
296 std::string* out_dir_name, std::string* out_file_name) {
297 size_t dirIndex = dex_path.rfind('/');
298 if (dirIndex == std::string::npos) {
299 return false;
300 }
301 if (dirIndex == dex_path.size() - 1) {
302 return false;
303 }
304 *out_dir_name = dex_path.substr(0, dirIndex);
305 *out_file_name = dex_path.substr(dirIndex + 1);
306
307 return true;
308}
309
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800310std::string create_current_profile_path(userid_t user, const std::string& package_name,
311 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800312 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700313 // Secondary dex current profiles are stored next to the dex files under the oat folder.
314 std::string dex_dir;
315 std::string dex_name;
316 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
317 << "Unexpected dir structure for secondary dex " << location;
318 return StringPrintf("%s/oat/%s%s%s",
319 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
320 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800321 } else {
322 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800323 std::string profile_dir = create_primary_current_profile_package_dir_path(
324 user, package_name);
325 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800326 }
327}
328
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800329std::string create_reference_profile_path(const std::string& package_name,
330 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800331 if (is_secondary_dex) {
332 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700333 std::string dex_dir;
334 std::string dex_name;
335 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800336 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800337 return StringPrintf("%s/oat/%s%s",
338 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
339 } else {
340 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800341 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
342 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800343 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700344}
345
Calin Juravle29591732017-11-20 17:46:19 -0800346std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800347 const std::string& profile_name) {
348 std::string ref_profile = create_reference_profile_path(package, profile_name,
349 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800350 return ref_profile + SNAPSHOT_PROFILE_EXT;
351}
352
Jeff Sharkeye3637242015-04-08 20:56:42 -0700353std::vector<userid_t> get_known_users(const char* volume_uuid) {
354 std::vector<userid_t> users;
355
356 // We always have an owner
357 users.push_back(0);
358
359 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
360 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700361 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700362 // Unable to discover other users, but at least return owner
363 PLOG(ERROR) << "Failed to opendir " << path;
364 return users;
365 }
366
367 struct dirent* ent;
368 while ((ent = readdir(dir))) {
369 if (ent->d_type != DT_DIR) {
370 continue;
371 }
372
373 char* end;
374 userid_t user = strtol(ent->d_name, &end, 10);
375 if (*end == '\0' && user != 0) {
376 LOG(DEBUG) << "Found valid user " << user;
377 users.push_back(user);
378 }
379 }
380 closedir(dir);
381
382 return users;
383}
384
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700385int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700386 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700387 FTS *fts;
388 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700389 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700390 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700391 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700392 if (errno != ENOENT) {
393 PLOG(ERROR) << "Failed to fts_open " << path;
394 }
395 return -1;
396 }
Yi Kong954cf642018-07-17 16:16:24 -0700397 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700398 switch (p->fts_info) {
399 case FTS_D:
400 case FTS_DEFAULT:
401 case FTS_F:
402 case FTS_SL:
403 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700404 int32_t uid = p->fts_statp->st_uid;
405 int32_t gid = p->fts_statp->st_gid;
406 int32_t user_uid = multiuser_get_app_id(uid);
407 int32_t user_gid = multiuser_get_app_id(gid);
408 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
409 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
410 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
411 // Don't traverse inside or measure
412 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700413 break;
414 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700415 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700416 break;
417 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700418 if (exclude_gid != -1 && gid == exclude_gid) {
419 break;
420 }
421 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700422 break;
423 }
424 }
425 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700426#if MEASURE_DEBUG
427 if ((include_gid == -1) && (exclude_gid == -1)) {
428 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
429 } else {
430 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
431 << " exclude " << exclude_gid;
432 }
433#endif
434 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700435 return 0;
436}
437
Mike Lockwood94afecf2012-10-24 10:45:23 -0700438/**
439 * Checks whether the package name is valid. Returns -1 on error and
440 * 0 on success.
441 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700442bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700443 // This logic is borrowed from PackageParser.java
444 bool hasSep = false;
445 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700446
Jeff Sharkey367ace22017-03-07 22:12:03 -0700447 auto it = packageName.begin();
448 for (; it != packageName.end() && *it != '-'; it++) {
449 char c = *it;
450 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
451 front = false;
452 continue;
453 }
454 if (!front) {
455 if ((c >= '0' && c <= '9') || c == '_') {
456 continue;
457 }
458 }
459 if (c == '.') {
460 hasSep = true;
461 front = true;
462 continue;
463 }
464 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700465 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700466 }
467
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700468 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700469 LOG(WARNING) << "Missing separator in " << packageName;
470 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700471 }
472
Jeff Sharkey367ace22017-03-07 22:12:03 -0700473 for (; it != packageName.end(); it++) {
474 char c = *it;
475 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
476 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
477 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
478 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700479 }
480
Jeff Sharkey423e7462016-12-09 18:18:43 -0700481 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700482}
483
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100484static int _delete_dir_contents(DIR *d,
485 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700486{
487 int result = 0;
488 struct dirent *de;
489 int dfd;
490
491 dfd = dirfd(d);
492
493 if (dfd < 0) return -1;
494
495 while ((de = readdir(d))) {
496 const char *name = de->d_name;
497
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100498 /* check using the exclusion predicate, if provided */
499 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
500 continue;
501 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700502
503 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700504 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700505 DIR *subdir;
506
507 /* always skip "." and ".." */
508 if (name[0] == '.') {
509 if (name[1] == 0) continue;
510 if ((name[1] == '.') && (name[2] == 0)) continue;
511 }
512
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700513 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700514 if (subfd < 0) {
515 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
516 result = -1;
517 continue;
518 }
519 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700520 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700521 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
522 close(subfd);
523 result = -1;
524 continue;
525 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100526 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700527 result = -1;
528 }
529 closedir(subdir);
530 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
531 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
532 result = -1;
533 }
534 } else {
535 if (unlinkat(dfd, name, 0) < 0) {
536 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
537 result = -1;
538 }
539 }
540 }
541
542 return result;
543}
544
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000545int create_dir_if_needed(const std::string& pathname, mode_t perms) {
546 struct stat st;
547
548 int rc;
549 if ((rc = stat(pathname.c_str(), &st)) != 0) {
550 if (errno == ENOENT) {
551 return mkdir(pathname.c_str(), perms);
552 } else {
553 return rc;
554 }
555 } else if (!S_ISDIR(st.st_mode)) {
556 LOG(DEBUG) << pathname << " is not a folder";
557 return -1;
558 }
559
560 mode_t actual_perms = st.st_mode & ALLPERMS;
561 if (actual_perms != perms) {
562 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
563 return -1;
564 }
565
566 return 0;
567}
568
Calin Juravleb06f98a2016-03-28 15:11:01 +0100569int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700570 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700571}
572
Calin Juravleb06f98a2016-03-28 15:11:01 +0100573int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700574 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700575}
576
Mike Lockwood94afecf2012-10-24 10:45:23 -0700577int delete_dir_contents(const char *pathname,
578 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100579 int (*exclusion_predicate)(const char*, const int),
580 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700581{
582 int res = 0;
583 DIR *d;
584
585 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700586 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100587 if (ignore_if_missing && (errno == ENOENT)) {
588 return 0;
589 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700590 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
591 return -errno;
592 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100593 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700594 closedir(d);
595 if (also_delete_dir) {
596 if (rmdir(pathname)) {
597 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
598 res = -1;
599 }
600 }
601 return res;
602}
603
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800604static std::string make_unique_name(std::string_view suffix) {
605 static constexpr auto uuidStringSize = 36;
606
607 uuid_t guid;
608 uuid_generate(guid);
609
610 std::string name;
611 const auto suffixSize = suffix.size();
612 name.reserve(uuidStringSize + suffixSize);
613
614 name.resize(uuidStringSize);
615 uuid_unparse(guid, name.data());
616 name.append(suffix);
617
618 return name;
619}
620
621static int rename_delete_dir_contents(const std::string& pathname,
622 int (*exclusion_predicate)(const char*, const int),
623 bool ignore_if_missing) {
624 auto temp_dir_name = make_unique_name(deletedSuffix);
625 auto temp_dir_path =
626 base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
627
628 if (::rename(pathname.c_str(), temp_dir_path.c_str())) {
629 if (ignore_if_missing && (errno == ENOENT)) {
630 return 0;
631 }
632 ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), temp_dir_path.c_str(),
633 strerror(errno));
634 return -errno;
635 }
636
637 return delete_dir_contents(temp_dir_path.c_str(), 1, exclusion_predicate, ignore_if_missing);
638}
639
Alex Buynytskyy4ab5d532022-02-17 21:20:10 +0000640bool is_renamed_deleted_dir(const std::string& path) {
641 if (path.size() < deletedSuffix.size()) {
642 return false;
643 }
644 std::string_view pathSuffix{path.c_str() + path.size() - deletedSuffix.size()};
645 return pathSuffix == deletedSuffix;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800646}
647
648int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
649 return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
650}
651
652static auto open_dir(const char* dir) {
653 struct DirCloser {
654 void operator()(DIR* d) const noexcept { ::closedir(d); }
655 };
656 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
657}
658
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800659void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800660 auto dir = open_dir(pathname.c_str());
661 if (!dir) {
662 return;
663 }
664 int dfd = dirfd(dir.get());
665 if (dfd < 0) {
666 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
667 return;
668 }
669
670 struct dirent* de;
671 while ((de = readdir(dir.get()))) {
672 if (de->d_type != DT_DIR) {
673 continue;
674 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800675
676 std::string name{de->d_name};
677 // always skip "." and ".."
678 if (name == "." || name == "..") {
679 continue;
680 }
681
682 if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
683 !is_valid_package_name(name)) {
684 ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800685 // Deleting the content.
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800686 delete_dir_contents_fd(dfd, name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800687 // Deleting the directory
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800688 if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
689 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800690 }
691 }
692 }
693}
694
Mike Lockwood94afecf2012-10-24 10:45:23 -0700695int delete_dir_contents_fd(int dfd, const char *name)
696{
697 int fd, res;
698 DIR *d;
699
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700700 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700701 if (fd < 0) {
702 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
703 return -1;
704 }
705 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700706 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700707 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
708 close(fd);
709 return -1;
710 }
Yi Kong954cf642018-07-17 16:16:24 -0700711 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700712 closedir(d);
713 return res;
714}
715
Robin Lee60fd3fe2014-10-07 16:55:02 +0100716static int _copy_owner_permissions(int srcfd, int dstfd)
717{
718 struct stat st;
719 if (fstat(srcfd, &st) != 0) {
720 return -1;
721 }
722 if (fchmod(dstfd, st.st_mode) != 0) {
723 return -1;
724 }
725 return 0;
726}
727
728static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
729{
730 int result = 0;
731 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
732 ALOGE("_copy_dir_files failed to copy dir permissions\n");
733 }
734 if (fchown(ddfd, owner, group) != 0) {
735 ALOGE("_copy_dir_files failed to change dir owner\n");
736 }
737
738 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700739 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100740 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
741 return -1;
742 }
743 struct dirent *de;
744 while ((de = readdir(ds))) {
745 if (de->d_type != DT_REG) {
746 continue;
747 }
748
749 const char *name = de->d_name;
750 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
751 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
752 if (fsfd == -1 || fdfd == -1) {
753 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
754 } else {
755 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
756 ALOGE("Failed to change file permissions\n");
757 }
758 if (fchown(fdfd, owner, group) != 0) {
759 ALOGE("Failed to change file owner\n");
760 }
761
762 char buf[8192];
763 ssize_t size;
764 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
765 write(fdfd, buf, size);
766 }
767 if (size < 0) {
768 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
769 result = -1;
770 }
771 }
772 close(fdfd);
773 close(fsfd);
774 }
775
776 return result;
777}
778
779int copy_dir_files(const char *srcname,
780 const char *dstname,
781 uid_t owner,
782 uid_t group)
783{
784 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700785 DIR *ds = nullptr;
786 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100787
788 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700789 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100790 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
791 return -errno;
792 }
793
794 mkdir(dstname, 0600);
795 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700796 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100797 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
798 closedir(ds);
799 return -errno;
800 }
801
802 int sdfd = dirfd(ds);
803 int ddfd = dirfd(dd);
804 if (sdfd != -1 && ddfd != -1) {
805 res = _copy_dir_files(sdfd, ddfd, owner, group);
806 } else {
807 res = -errno;
808 }
809 closedir(dd);
810 closedir(ds);
811 return res;
812}
813
Jeff Sharkeya836c472017-04-02 23:29:30 -0600814int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600815 struct statvfs sfs;
816 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600817 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700818 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600819 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700820 return -1;
821 }
822}
823
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600824int get_path_inode(const std::string& path, ino_t *inode) {
825 struct stat buf;
826 memset(&buf, 0, sizeof(buf));
827 if (stat(path.c_str(), &buf) != 0) {
828 PLOG(WARNING) << "Failed to stat " << path;
829 return -1;
830 } else {
831 *inode = buf.st_ino;
832 return 0;
833 }
834}
835
836/**
837 * Write the inode of a specific child file into the given xattr on the
838 * parent directory. This allows you to find the child later, even if its
839 * name is encrypted.
840 */
841int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
842 ino_t inode = 0;
843 uint64_t inode_raw = 0;
844 auto path = StringPrintf("%s/%s", parent.c_str(), name);
845
846 if (get_path_inode(path, &inode) != 0) {
847 // Path probably doesn't exist yet; ignore
848 return 0;
849 }
850
851 // Check to see if already set correctly
852 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
853 if (inode_raw == inode) {
854 // Already set correctly; skip writing
855 return 0;
856 } else {
857 PLOG(WARNING) << "Mismatched inode value; found " << inode
858 << " on disk but marked value was " << inode_raw << "; overwriting";
859 }
860 }
861
862 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600863 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600864 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
865 return -1;
866 } else {
867 return 0;
868 }
869}
870
871/**
872 * Read the inode of a specific child file from the given xattr on the
873 * parent directory. Returns a currently valid path for that child, which
874 * might have an encrypted name.
875 */
876std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
877 ino_t inode = 0;
878 uint64_t inode_raw = 0;
879 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
880
881 // Lookup the inode value written earlier
882 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
883 inode = inode_raw;
884 }
885
886 // For testing purposes, rely on the inode when defined; this could be
887 // optimized to use access() in the future.
888 if (inode != 0) {
889 DIR* dir = opendir(parent.c_str());
890 if (dir == nullptr) {
891 PLOG(ERROR) << "Failed to opendir " << parent;
892 return fallback;
893 }
894
895 struct dirent* ent;
896 while ((ent = readdir(dir))) {
897 if (ent->d_ino == inode) {
898 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
899#if DEBUG_XATTRS
900 if (resolved != fallback) {
901 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
902 << " instead of " << fallback;
903 }
904#endif
905 closedir(dir);
906 return resolved;
907 }
908 }
909 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
910 closedir(dir);
911 return fallback;
912 } else {
913 return fallback;
914 }
915}
916
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900917void remove_path_xattr(const std::string& path, const char* inode_xattr) {
918 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
919 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
920 }
921}
922
Mike Lockwood94afecf2012-10-24 10:45:23 -0700923/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100924 * Validate that the path is valid in the context of the provided directory.
925 * The path is allowed to have at most one subdirectory and no indirections
926 * to top level directories (i.e. have "..").
927 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600928static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000929 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600930 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
931 || dir.find("..") != std::string::npos) {
932 LOG(ERROR) << "Invalid directory " << dir;
933 return -1;
934 }
935 if (path.find("..") != std::string::npos) {
936 LOG(ERROR) << "Invalid path " << path;
937 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100938 }
939
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600940 if (path.compare(0, dir.size(), dir) != 0) {
941 // Common case, path isn't under directory
942 return -1;
943 }
944
945 // Count number of subdirectories
946 auto pos = path.find('/', dir.size());
947 int count = 0;
948 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600949 auto next = path.find('/', pos + 1);
950 if (next > pos + 1) {
951 count++;
952 }
953 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600954 }
955
956 if (count > maxSubdirs) {
957 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100958 return -1;
959 }
960
961 return 0;
962}
963
964/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700965 * Checks whether a path points to a system app (.apk file). Returns 0
966 * if it is a system app or -1 if it is not.
967 */
968int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600969 std::string path_ = path;
970 for (const auto& dir : android_system_dirs) {
971 if (validate_path(dir, path, 1) == 0) {
972 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700973 }
974 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700975 return -1;
976}
977
Calin Juravle114f0812017-03-08 19:05:07 -0800978bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -0700979 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -0800980 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
981
Calin Juravle3760ad32017-07-27 16:31:55 -0700982 // Empty paths are not allowed.
983 if (dex_path.empty()) { return false; }
984 // First character should always be '/'. No relative paths.
985 if (dex_path[0] != '/') { return false; }
986 // The last character should not be '/'.
987 if (dex_path[dex_path.size() - 1] == '/') { return false; }
988 // There should be no '.' after the directory marker.
989 if (dex_path.find("/.") != std::string::npos) { return false; }
990 // The path should be at most PKG_PATH_MAX long.
991 if (dex_path.size() > PKG_PATH_MAX) { return false; }
992
Calin Juravle7d765462017-09-04 15:57:10 -0700993 // The dex_path should be under the app data directory.
994 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -0700995 ? create_data_user_ce_package_path(
996 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
997 : create_data_user_de_package_path(
998 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -0700999
Calin Juravle7d765462017-09-04 15:57:10 -07001000 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1001 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1002 // If that's the case, attempt to validate against the user data link.
1003 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1004 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1005 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1006 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -07001007 return false;
1008 }
Calin Juravle42451c02017-01-17 14:43:25 -08001009 }
Calin Juravle3760ad32017-07-27 16:31:55 -07001010
1011 // If we got here we have a valid path.
1012 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001013}
1014
Mike Lockwood94afecf2012-10-24 10:45:23 -07001015/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001016 * Check whether path points to a valid path for an APK file. The path must
1017 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1018 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1019 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001020 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001021static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1022 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001023 return 0;
shafikb43faa92019-02-19 12:19:48 +00001024 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1025 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001026 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001027 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001028 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001029 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001030 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001031 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001032 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1033 // Rewrite the path as if it were on internal storage, and test that
1034 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1035 if (end != std::string::npos) {
1036 auto modified = path;
1037 modified.replace(0, end + 1, android_data_dir);
1038 return validate_apk_path_internal(modified, maxSubdirs);
1039 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001040 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001041 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001042}
1043
Narayan Kamathd845c962015-06-04 13:20:27 +01001044int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001045 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001046}
1047
1048int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001049 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001050}
1051
Robin Lee095c7632014-04-25 15:05:19 +01001052int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001053 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001054 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1055 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001056
1057 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001058 auto path = create_data_misc_legacy_path(userid);
1059 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001060}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001061
1062int wait_child(pid_t pid)
1063{
1064 int status;
1065 pid_t got_pid;
1066
1067 while (1) {
1068 got_pid = waitpid(pid, &status, 0);
1069 if (got_pid == -1 && errno == EINTR) {
1070 printf("waitpid interrupted, retrying\n");
1071 } else {
1072 break;
1073 }
1074 }
1075 if (got_pid != pid) {
1076 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1077 (int) pid, (int) got_pid, strerror(errno));
1078 return 1;
1079 }
1080
1081 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1082 return 0;
1083 } else {
1084 return status; /* always nonzero */
1085 }
1086}
1087
Calin Juravle42451c02017-01-17 14:43:25 -08001088/**
1089 * Prepare an app cache directory, which offers to fix-up the GID and
1090 * directory mode flags during a platform upgrade.
1091 * The app cache directory path will be 'parent'/'name'.
1092 */
1093int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1094 uid_t uid, gid_t gid) {
1095 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1096 struct stat st;
1097 if (stat(path.c_str(), &st) != 0) {
1098 if (errno == ENOENT) {
1099 // This is fine, just create it
1100 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1101 PLOG(ERROR) << "Failed to prepare " << path;
1102 return -1;
1103 } else {
1104 return 0;
1105 }
1106 } else {
1107 PLOG(ERROR) << "Failed to stat " << path;
1108 return -1;
1109 }
1110 }
1111
1112 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1113 if (st.st_uid != uid) {
1114 // Mismatched UID is real trouble; we can't recover
1115 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1116 << " but expected " << uid;
1117 return -1;
1118 } else if (st.st_gid == gid && actual_mode == target_mode) {
1119 // Everything looks good!
1120 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001121 } else {
1122 // Mismatched GID/mode is recoverable; fall through to update
1123 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001124 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001125 }
1126
1127 // Directory is owned correctly, but GID or mode mismatch means it's
1128 // probably a platform upgrade so we need to fix them
1129 FTS *fts;
1130 FTSENT *p;
1131 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001132 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001133 PLOG(ERROR) << "Failed to fts_open " << path;
1134 return -1;
1135 }
Yi Kong954cf642018-07-17 16:16:24 -07001136 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001137 switch (p->fts_info) {
1138 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001139 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001140 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1141 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001142 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001143 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001144 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001145 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1146 }
1147 break;
1148 case FTS_SL:
1149 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001150 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001151 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1152 }
1153 break;
1154 }
1155 }
1156 fts_close(fts);
1157 return 0;
1158}
1159
Martijn Coenen771cc342020-02-19 23:26:56 +01001160static const char* kProcFilesystems = "/proc/filesystems";
1161bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001162 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1163 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001164 std::string supported;
1165 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1166 PLOG(ERROR) << "Failed to read supported filesystems";
1167 return false;
1168 }
1169 return supported.find("sdcardfs\n") != std::string::npos;
1170}
1171
1172int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1173 static const bool supportsSdcardFs = supports_sdcardfs();
1174
1175 if (supportsSdcardFs) {
1176 int extGid = multiuser_get_ext_gid(userId, appId);
1177
1178 if (extGid == -1) {
1179 return -1;
1180 }
1181
1182 return GetOccupiedSpaceForGid(uuid, extGid);
1183 } else {
1184 uid_t uid = multiuser_get_uid(userId, appId);
1185 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1186 return GetOccupiedSpaceForProjectId(uuid, projectId);
1187 }
1188}
1189int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1190 static const bool supportsSdcardFs = supports_sdcardfs();
1191
1192 if (supportsSdcardFs) {
1193 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1194
1195 if (extCacheGid == -1) {
1196 return -1;
1197 }
1198
1199 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1200 } else {
1201 uid_t uid = multiuser_get_uid(userId, appId);
1202 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1203 return GetOccupiedSpaceForProjectId(uuid, projectId);
1204 }
1205}
1206
Calin Juravlee61189e2018-01-23 19:54:11 -08001207// Collect all non empty profiles from the given directory and puts then into profile_paths.
1208// The profiles are identified based on PROFILE_EXT extension.
1209// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1210// It returns true if there were no errors at all, and false otherwise.
1211static bool collect_profiles(DIR* d,
1212 const std::string& current_path,
1213 std::vector<std::string>* profiles_paths) {
1214 int32_t dir_fd = dirfd(d);
1215 if (dir_fd < 0) {
1216 return false;
1217 }
1218
1219 bool result = true;
1220 struct dirent* dir_entry;
1221 while ((dir_entry = readdir(d))) {
1222 std::string name = dir_entry->d_name;
1223 std::string local_path = current_path + "/" + name;
1224
1225 if (dir_entry->d_type == DT_REG) {
1226 // Check if this is a non empty profile file.
1227 if (EndsWith(name, PROFILE_EXT)) {
1228 struct stat st;
1229 if (stat(local_path.c_str(), &st) != 0) {
1230 PLOG(WARNING) << "Cannot stat local path " << local_path;
1231 result = false;
1232 continue;
1233 } else if (st.st_size > 0) {
1234 profiles_paths->push_back(local_path);
1235 }
1236 }
1237 } else if (dir_entry->d_type == DT_DIR) {
1238 // always skip "." and ".."
1239 if (name == "." || name == "..") {
1240 continue;
1241 }
1242
1243 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1244 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1245 if (subdir_fd < 0) {
1246 PLOG(WARNING) << "Could not open dir path " << local_path;
1247 result = false;
1248 continue;
1249 }
1250
Mathieu Chartier89883e32018-11-01 11:39:00 -07001251 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001252 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001253 PLOG(WARNING) << "Could not open dir path " << local_path;
1254 result = false;
1255 continue;
1256 }
1257 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1258 result = result && new_result;
1259 if (closedir(subdir) != 0) {
1260 PLOG(WARNING) << "Could not close dir path " << local_path;
1261 }
1262 }
1263 }
1264
1265 return result;
1266}
1267
1268bool collect_profiles(std::vector<std::string>* profiles_paths) {
1269 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001270 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001271 return false;
1272 } else {
1273 return collect_profiles(d, android_profiles_dir, profiles_paths);
1274 }
1275}
1276
Eric Holk2af5e6a2019-01-09 18:17:27 -08001277void drop_capabilities(uid_t uid) {
1278 if (setgid(uid) != 0) {
1279 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1280 exit(DexoptReturnCodes::kSetGid);
1281 }
1282 if (setuid(uid) != 0) {
1283 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1284 exit(DexoptReturnCodes::kSetUid);
1285 }
1286 // drop capabilities
1287 struct __user_cap_header_struct capheader;
1288 struct __user_cap_data_struct capdata[2];
1289 memset(&capheader, 0, sizeof(capheader));
1290 memset(&capdata, 0, sizeof(capdata));
1291 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1292 if (capset(&capheader, &capdata[0]) < 0) {
1293 PLOG(ERROR) << "capset failed";
1294 exit(DexoptReturnCodes::kCapSet);
1295 }
1296}
1297
Andreas Gampe02d0de52015-11-11 20:43:16 -08001298} // namespace installd
1299} // namespace android