blob: a4a21b720c35a5070526d215cf797a1862eddbfa [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
640bool is_renamed_deleted_dir(std::string_view path) {
641 return path.ends_with(deletedSuffix);
642}
643
644int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
645 return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
646}
647
648static auto open_dir(const char* dir) {
649 struct DirCloser {
650 void operator()(DIR* d) const noexcept { ::closedir(d); }
651 };
652 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
653}
654
655void find_and_delete_renamed_deleted_dirs_under_path(const std::string& pathname) {
656 auto dir = open_dir(pathname.c_str());
657 if (!dir) {
658 return;
659 }
660 int dfd = dirfd(dir.get());
661 if (dfd < 0) {
662 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
663 return;
664 }
665
666 struct dirent* de;
667 while ((de = readdir(dir.get()))) {
668 if (de->d_type != DT_DIR) {
669 continue;
670 }
671 const char* name = de->d_name;
672 if (is_renamed_deleted_dir({name})) {
673 LOG(INFO) << "Deleting renamed data directory: " << name;
674 // Deleting the content.
675 delete_dir_contents_fd(dfd, name);
676 // Deleting the directory
677 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
678 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
679 }
680 }
681 }
682}
683
Mike Lockwood94afecf2012-10-24 10:45:23 -0700684int delete_dir_contents_fd(int dfd, const char *name)
685{
686 int fd, res;
687 DIR *d;
688
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700689 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700690 if (fd < 0) {
691 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
692 return -1;
693 }
694 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700695 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700696 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
697 close(fd);
698 return -1;
699 }
Yi Kong954cf642018-07-17 16:16:24 -0700700 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700701 closedir(d);
702 return res;
703}
704
Robin Lee60fd3fe2014-10-07 16:55:02 +0100705static int _copy_owner_permissions(int srcfd, int dstfd)
706{
707 struct stat st;
708 if (fstat(srcfd, &st) != 0) {
709 return -1;
710 }
711 if (fchmod(dstfd, st.st_mode) != 0) {
712 return -1;
713 }
714 return 0;
715}
716
717static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
718{
719 int result = 0;
720 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
721 ALOGE("_copy_dir_files failed to copy dir permissions\n");
722 }
723 if (fchown(ddfd, owner, group) != 0) {
724 ALOGE("_copy_dir_files failed to change dir owner\n");
725 }
726
727 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700728 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100729 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
730 return -1;
731 }
732 struct dirent *de;
733 while ((de = readdir(ds))) {
734 if (de->d_type != DT_REG) {
735 continue;
736 }
737
738 const char *name = de->d_name;
739 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
740 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
741 if (fsfd == -1 || fdfd == -1) {
742 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
743 } else {
744 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
745 ALOGE("Failed to change file permissions\n");
746 }
747 if (fchown(fdfd, owner, group) != 0) {
748 ALOGE("Failed to change file owner\n");
749 }
750
751 char buf[8192];
752 ssize_t size;
753 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
754 write(fdfd, buf, size);
755 }
756 if (size < 0) {
757 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
758 result = -1;
759 }
760 }
761 close(fdfd);
762 close(fsfd);
763 }
764
765 return result;
766}
767
768int copy_dir_files(const char *srcname,
769 const char *dstname,
770 uid_t owner,
771 uid_t group)
772{
773 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700774 DIR *ds = nullptr;
775 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100776
777 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700778 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100779 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
780 return -errno;
781 }
782
783 mkdir(dstname, 0600);
784 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700785 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100786 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
787 closedir(ds);
788 return -errno;
789 }
790
791 int sdfd = dirfd(ds);
792 int ddfd = dirfd(dd);
793 if (sdfd != -1 && ddfd != -1) {
794 res = _copy_dir_files(sdfd, ddfd, owner, group);
795 } else {
796 res = -errno;
797 }
798 closedir(dd);
799 closedir(ds);
800 return res;
801}
802
Jeff Sharkeya836c472017-04-02 23:29:30 -0600803int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600804 struct statvfs sfs;
805 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600806 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700807 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600808 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700809 return -1;
810 }
811}
812
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600813int get_path_inode(const std::string& path, ino_t *inode) {
814 struct stat buf;
815 memset(&buf, 0, sizeof(buf));
816 if (stat(path.c_str(), &buf) != 0) {
817 PLOG(WARNING) << "Failed to stat " << path;
818 return -1;
819 } else {
820 *inode = buf.st_ino;
821 return 0;
822 }
823}
824
825/**
826 * Write the inode of a specific child file into the given xattr on the
827 * parent directory. This allows you to find the child later, even if its
828 * name is encrypted.
829 */
830int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
831 ino_t inode = 0;
832 uint64_t inode_raw = 0;
833 auto path = StringPrintf("%s/%s", parent.c_str(), name);
834
835 if (get_path_inode(path, &inode) != 0) {
836 // Path probably doesn't exist yet; ignore
837 return 0;
838 }
839
840 // Check to see if already set correctly
841 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
842 if (inode_raw == inode) {
843 // Already set correctly; skip writing
844 return 0;
845 } else {
846 PLOG(WARNING) << "Mismatched inode value; found " << inode
847 << " on disk but marked value was " << inode_raw << "; overwriting";
848 }
849 }
850
851 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600852 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600853 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
854 return -1;
855 } else {
856 return 0;
857 }
858}
859
860/**
861 * Read the inode of a specific child file from the given xattr on the
862 * parent directory. Returns a currently valid path for that child, which
863 * might have an encrypted name.
864 */
865std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
866 ino_t inode = 0;
867 uint64_t inode_raw = 0;
868 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
869
870 // Lookup the inode value written earlier
871 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
872 inode = inode_raw;
873 }
874
875 // For testing purposes, rely on the inode when defined; this could be
876 // optimized to use access() in the future.
877 if (inode != 0) {
878 DIR* dir = opendir(parent.c_str());
879 if (dir == nullptr) {
880 PLOG(ERROR) << "Failed to opendir " << parent;
881 return fallback;
882 }
883
884 struct dirent* ent;
885 while ((ent = readdir(dir))) {
886 if (ent->d_ino == inode) {
887 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
888#if DEBUG_XATTRS
889 if (resolved != fallback) {
890 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
891 << " instead of " << fallback;
892 }
893#endif
894 closedir(dir);
895 return resolved;
896 }
897 }
898 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
899 closedir(dir);
900 return fallback;
901 } else {
902 return fallback;
903 }
904}
905
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900906void remove_path_xattr(const std::string& path, const char* inode_xattr) {
907 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
908 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
909 }
910}
911
Mike Lockwood94afecf2012-10-24 10:45:23 -0700912/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100913 * Validate that the path is valid in the context of the provided directory.
914 * The path is allowed to have at most one subdirectory and no indirections
915 * to top level directories (i.e. have "..").
916 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600917static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000918 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600919 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
920 || dir.find("..") != std::string::npos) {
921 LOG(ERROR) << "Invalid directory " << dir;
922 return -1;
923 }
924 if (path.find("..") != std::string::npos) {
925 LOG(ERROR) << "Invalid path " << path;
926 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100927 }
928
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600929 if (path.compare(0, dir.size(), dir) != 0) {
930 // Common case, path isn't under directory
931 return -1;
932 }
933
934 // Count number of subdirectories
935 auto pos = path.find('/', dir.size());
936 int count = 0;
937 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600938 auto next = path.find('/', pos + 1);
939 if (next > pos + 1) {
940 count++;
941 }
942 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600943 }
944
945 if (count > maxSubdirs) {
946 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100947 return -1;
948 }
949
950 return 0;
951}
952
953/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700954 * Checks whether a path points to a system app (.apk file). Returns 0
955 * if it is a system app or -1 if it is not.
956 */
957int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600958 std::string path_ = path;
959 for (const auto& dir : android_system_dirs) {
960 if (validate_path(dir, path, 1) == 0) {
961 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700962 }
963 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700964 return -1;
965}
966
Calin Juravle114f0812017-03-08 19:05:07 -0800967bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -0700968 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -0800969 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
970
Calin Juravle3760ad32017-07-27 16:31:55 -0700971 // Empty paths are not allowed.
972 if (dex_path.empty()) { return false; }
973 // First character should always be '/'. No relative paths.
974 if (dex_path[0] != '/') { return false; }
975 // The last character should not be '/'.
976 if (dex_path[dex_path.size() - 1] == '/') { return false; }
977 // There should be no '.' after the directory marker.
978 if (dex_path.find("/.") != std::string::npos) { return false; }
979 // The path should be at most PKG_PATH_MAX long.
980 if (dex_path.size() > PKG_PATH_MAX) { return false; }
981
Calin Juravle7d765462017-09-04 15:57:10 -0700982 // The dex_path should be under the app data directory.
983 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -0700984 ? create_data_user_ce_package_path(
985 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
986 : create_data_user_de_package_path(
987 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -0700988
Calin Juravle7d765462017-09-04 15:57:10 -0700989 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
990 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
991 // If that's the case, attempt to validate against the user data link.
992 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
993 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
994 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
995 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -0700996 return false;
997 }
Calin Juravle42451c02017-01-17 14:43:25 -0800998 }
Calin Juravle3760ad32017-07-27 16:31:55 -0700999
1000 // If we got here we have a valid path.
1001 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001002}
1003
Mike Lockwood94afecf2012-10-24 10:45:23 -07001004/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001005 * Check whether path points to a valid path for an APK file. The path must
1006 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1007 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1008 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001009 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001010static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1011 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001012 return 0;
shafikb43faa92019-02-19 12:19:48 +00001013 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1014 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001015 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001016 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001017 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001018 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001019 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001020 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001021 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1022 // Rewrite the path as if it were on internal storage, and test that
1023 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1024 if (end != std::string::npos) {
1025 auto modified = path;
1026 modified.replace(0, end + 1, android_data_dir);
1027 return validate_apk_path_internal(modified, maxSubdirs);
1028 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001029 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001030 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001031}
1032
Narayan Kamathd845c962015-06-04 13:20:27 +01001033int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001034 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001035}
1036
1037int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001038 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001039}
1040
Robin Lee095c7632014-04-25 15:05:19 +01001041int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001042 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001043 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1044 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001045
1046 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001047 auto path = create_data_misc_legacy_path(userid);
1048 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001049}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001050
1051int wait_child(pid_t pid)
1052{
1053 int status;
1054 pid_t got_pid;
1055
1056 while (1) {
1057 got_pid = waitpid(pid, &status, 0);
1058 if (got_pid == -1 && errno == EINTR) {
1059 printf("waitpid interrupted, retrying\n");
1060 } else {
1061 break;
1062 }
1063 }
1064 if (got_pid != pid) {
1065 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1066 (int) pid, (int) got_pid, strerror(errno));
1067 return 1;
1068 }
1069
1070 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1071 return 0;
1072 } else {
1073 return status; /* always nonzero */
1074 }
1075}
1076
Calin Juravle42451c02017-01-17 14:43:25 -08001077/**
1078 * Prepare an app cache directory, which offers to fix-up the GID and
1079 * directory mode flags during a platform upgrade.
1080 * The app cache directory path will be 'parent'/'name'.
1081 */
1082int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1083 uid_t uid, gid_t gid) {
1084 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1085 struct stat st;
1086 if (stat(path.c_str(), &st) != 0) {
1087 if (errno == ENOENT) {
1088 // This is fine, just create it
1089 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1090 PLOG(ERROR) << "Failed to prepare " << path;
1091 return -1;
1092 } else {
1093 return 0;
1094 }
1095 } else {
1096 PLOG(ERROR) << "Failed to stat " << path;
1097 return -1;
1098 }
1099 }
1100
1101 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1102 if (st.st_uid != uid) {
1103 // Mismatched UID is real trouble; we can't recover
1104 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1105 << " but expected " << uid;
1106 return -1;
1107 } else if (st.st_gid == gid && actual_mode == target_mode) {
1108 // Everything looks good!
1109 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001110 } else {
1111 // Mismatched GID/mode is recoverable; fall through to update
1112 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001113 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001114 }
1115
1116 // Directory is owned correctly, but GID or mode mismatch means it's
1117 // probably a platform upgrade so we need to fix them
1118 FTS *fts;
1119 FTSENT *p;
1120 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001121 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001122 PLOG(ERROR) << "Failed to fts_open " << path;
1123 return -1;
1124 }
Yi Kong954cf642018-07-17 16:16:24 -07001125 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001126 switch (p->fts_info) {
1127 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001128 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001129 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1130 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001131 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001132 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001133 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001134 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1135 }
1136 break;
1137 case FTS_SL:
1138 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001139 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001140 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1141 }
1142 break;
1143 }
1144 }
1145 fts_close(fts);
1146 return 0;
1147}
1148
Martijn Coenen771cc342020-02-19 23:26:56 +01001149static const char* kProcFilesystems = "/proc/filesystems";
1150bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001151 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1152 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001153 std::string supported;
1154 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1155 PLOG(ERROR) << "Failed to read supported filesystems";
1156 return false;
1157 }
1158 return supported.find("sdcardfs\n") != std::string::npos;
1159}
1160
1161int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1162 static const bool supportsSdcardFs = supports_sdcardfs();
1163
1164 if (supportsSdcardFs) {
1165 int extGid = multiuser_get_ext_gid(userId, appId);
1166
1167 if (extGid == -1) {
1168 return -1;
1169 }
1170
1171 return GetOccupiedSpaceForGid(uuid, extGid);
1172 } else {
1173 uid_t uid = multiuser_get_uid(userId, appId);
1174 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1175 return GetOccupiedSpaceForProjectId(uuid, projectId);
1176 }
1177}
1178int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1179 static const bool supportsSdcardFs = supports_sdcardfs();
1180
1181 if (supportsSdcardFs) {
1182 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1183
1184 if (extCacheGid == -1) {
1185 return -1;
1186 }
1187
1188 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1189 } else {
1190 uid_t uid = multiuser_get_uid(userId, appId);
1191 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1192 return GetOccupiedSpaceForProjectId(uuid, projectId);
1193 }
1194}
1195
Calin Juravlee61189e2018-01-23 19:54:11 -08001196// Collect all non empty profiles from the given directory and puts then into profile_paths.
1197// The profiles are identified based on PROFILE_EXT extension.
1198// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1199// It returns true if there were no errors at all, and false otherwise.
1200static bool collect_profiles(DIR* d,
1201 const std::string& current_path,
1202 std::vector<std::string>* profiles_paths) {
1203 int32_t dir_fd = dirfd(d);
1204 if (dir_fd < 0) {
1205 return false;
1206 }
1207
1208 bool result = true;
1209 struct dirent* dir_entry;
1210 while ((dir_entry = readdir(d))) {
1211 std::string name = dir_entry->d_name;
1212 std::string local_path = current_path + "/" + name;
1213
1214 if (dir_entry->d_type == DT_REG) {
1215 // Check if this is a non empty profile file.
1216 if (EndsWith(name, PROFILE_EXT)) {
1217 struct stat st;
1218 if (stat(local_path.c_str(), &st) != 0) {
1219 PLOG(WARNING) << "Cannot stat local path " << local_path;
1220 result = false;
1221 continue;
1222 } else if (st.st_size > 0) {
1223 profiles_paths->push_back(local_path);
1224 }
1225 }
1226 } else if (dir_entry->d_type == DT_DIR) {
1227 // always skip "." and ".."
1228 if (name == "." || name == "..") {
1229 continue;
1230 }
1231
1232 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1233 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1234 if (subdir_fd < 0) {
1235 PLOG(WARNING) << "Could not open dir path " << local_path;
1236 result = false;
1237 continue;
1238 }
1239
Mathieu Chartier89883e32018-11-01 11:39:00 -07001240 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001241 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001242 PLOG(WARNING) << "Could not open dir path " << local_path;
1243 result = false;
1244 continue;
1245 }
1246 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1247 result = result && new_result;
1248 if (closedir(subdir) != 0) {
1249 PLOG(WARNING) << "Could not close dir path " << local_path;
1250 }
1251 }
1252 }
1253
1254 return result;
1255}
1256
1257bool collect_profiles(std::vector<std::string>* profiles_paths) {
1258 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001259 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001260 return false;
1261 } else {
1262 return collect_profiles(d, android_profiles_dir, profiles_paths);
1263 }
1264}
1265
Eric Holk2af5e6a2019-01-09 18:17:27 -08001266void drop_capabilities(uid_t uid) {
1267 if (setgid(uid) != 0) {
1268 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1269 exit(DexoptReturnCodes::kSetGid);
1270 }
1271 if (setuid(uid) != 0) {
1272 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1273 exit(DexoptReturnCodes::kSetUid);
1274 }
1275 // drop capabilities
1276 struct __user_cap_header_struct capheader;
1277 struct __user_cap_data_struct capdata[2];
1278 memset(&capheader, 0, sizeof(capheader));
1279 memset(&capdata, 0, sizeof(capdata));
1280 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1281 if (capset(&capheader, &capdata[0]) < 0) {
1282 PLOG(ERROR) << "capset failed";
1283 exit(DexoptReturnCodes::kCapSet);
1284 }
1285}
1286
Andreas Gampe02d0de52015-11-11 20:43:16 -08001287} // namespace installd
1288} // namespace android