blob: 8a00be9193468cf6fed9cbf7bf0b75ce066ca066 [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
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800655void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800656 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 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800671
672 std::string name{de->d_name};
673 // always skip "." and ".."
674 if (name == "." || name == "..") {
675 continue;
676 }
677
678 if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
679 !is_valid_package_name(name)) {
680 ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800681 // Deleting the content.
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800682 delete_dir_contents_fd(dfd, name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800683 // Deleting the directory
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800684 if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
685 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800686 }
687 }
688 }
689}
690
Mike Lockwood94afecf2012-10-24 10:45:23 -0700691int delete_dir_contents_fd(int dfd, const char *name)
692{
693 int fd, res;
694 DIR *d;
695
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700696 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700697 if (fd < 0) {
698 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
699 return -1;
700 }
701 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700702 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700703 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
704 close(fd);
705 return -1;
706 }
Yi Kong954cf642018-07-17 16:16:24 -0700707 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700708 closedir(d);
709 return res;
710}
711
Robin Lee60fd3fe2014-10-07 16:55:02 +0100712static int _copy_owner_permissions(int srcfd, int dstfd)
713{
714 struct stat st;
715 if (fstat(srcfd, &st) != 0) {
716 return -1;
717 }
718 if (fchmod(dstfd, st.st_mode) != 0) {
719 return -1;
720 }
721 return 0;
722}
723
724static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
725{
726 int result = 0;
727 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
728 ALOGE("_copy_dir_files failed to copy dir permissions\n");
729 }
730 if (fchown(ddfd, owner, group) != 0) {
731 ALOGE("_copy_dir_files failed to change dir owner\n");
732 }
733
734 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700735 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100736 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
737 return -1;
738 }
739 struct dirent *de;
740 while ((de = readdir(ds))) {
741 if (de->d_type != DT_REG) {
742 continue;
743 }
744
745 const char *name = de->d_name;
746 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
747 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
748 if (fsfd == -1 || fdfd == -1) {
749 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
750 } else {
751 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
752 ALOGE("Failed to change file permissions\n");
753 }
754 if (fchown(fdfd, owner, group) != 0) {
755 ALOGE("Failed to change file owner\n");
756 }
757
758 char buf[8192];
759 ssize_t size;
760 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
761 write(fdfd, buf, size);
762 }
763 if (size < 0) {
764 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
765 result = -1;
766 }
767 }
768 close(fdfd);
769 close(fsfd);
770 }
771
772 return result;
773}
774
775int copy_dir_files(const char *srcname,
776 const char *dstname,
777 uid_t owner,
778 uid_t group)
779{
780 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700781 DIR *ds = nullptr;
782 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100783
784 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700785 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100786 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
787 return -errno;
788 }
789
790 mkdir(dstname, 0600);
791 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700792 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100793 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
794 closedir(ds);
795 return -errno;
796 }
797
798 int sdfd = dirfd(ds);
799 int ddfd = dirfd(dd);
800 if (sdfd != -1 && ddfd != -1) {
801 res = _copy_dir_files(sdfd, ddfd, owner, group);
802 } else {
803 res = -errno;
804 }
805 closedir(dd);
806 closedir(ds);
807 return res;
808}
809
Jeff Sharkeya836c472017-04-02 23:29:30 -0600810int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600811 struct statvfs sfs;
812 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600813 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700814 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600815 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700816 return -1;
817 }
818}
819
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600820int get_path_inode(const std::string& path, ino_t *inode) {
821 struct stat buf;
822 memset(&buf, 0, sizeof(buf));
823 if (stat(path.c_str(), &buf) != 0) {
824 PLOG(WARNING) << "Failed to stat " << path;
825 return -1;
826 } else {
827 *inode = buf.st_ino;
828 return 0;
829 }
830}
831
832/**
833 * Write the inode of a specific child file into the given xattr on the
834 * parent directory. This allows you to find the child later, even if its
835 * name is encrypted.
836 */
837int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
838 ino_t inode = 0;
839 uint64_t inode_raw = 0;
840 auto path = StringPrintf("%s/%s", parent.c_str(), name);
841
842 if (get_path_inode(path, &inode) != 0) {
843 // Path probably doesn't exist yet; ignore
844 return 0;
845 }
846
847 // Check to see if already set correctly
848 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
849 if (inode_raw == inode) {
850 // Already set correctly; skip writing
851 return 0;
852 } else {
853 PLOG(WARNING) << "Mismatched inode value; found " << inode
854 << " on disk but marked value was " << inode_raw << "; overwriting";
855 }
856 }
857
858 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600859 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600860 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
861 return -1;
862 } else {
863 return 0;
864 }
865}
866
867/**
868 * Read the inode of a specific child file from the given xattr on the
869 * parent directory. Returns a currently valid path for that child, which
870 * might have an encrypted name.
871 */
872std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
873 ino_t inode = 0;
874 uint64_t inode_raw = 0;
875 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
876
877 // Lookup the inode value written earlier
878 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
879 inode = inode_raw;
880 }
881
882 // For testing purposes, rely on the inode when defined; this could be
883 // optimized to use access() in the future.
884 if (inode != 0) {
885 DIR* dir = opendir(parent.c_str());
886 if (dir == nullptr) {
887 PLOG(ERROR) << "Failed to opendir " << parent;
888 return fallback;
889 }
890
891 struct dirent* ent;
892 while ((ent = readdir(dir))) {
893 if (ent->d_ino == inode) {
894 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
895#if DEBUG_XATTRS
896 if (resolved != fallback) {
897 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
898 << " instead of " << fallback;
899 }
900#endif
901 closedir(dir);
902 return resolved;
903 }
904 }
905 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
906 closedir(dir);
907 return fallback;
908 } else {
909 return fallback;
910 }
911}
912
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900913void remove_path_xattr(const std::string& path, const char* inode_xattr) {
914 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
915 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
916 }
917}
918
Mike Lockwood94afecf2012-10-24 10:45:23 -0700919/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100920 * Validate that the path is valid in the context of the provided directory.
921 * The path is allowed to have at most one subdirectory and no indirections
922 * to top level directories (i.e. have "..").
923 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600924static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000925 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600926 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
927 || dir.find("..") != std::string::npos) {
928 LOG(ERROR) << "Invalid directory " << dir;
929 return -1;
930 }
931 if (path.find("..") != std::string::npos) {
932 LOG(ERROR) << "Invalid path " << path;
933 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100934 }
935
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600936 if (path.compare(0, dir.size(), dir) != 0) {
937 // Common case, path isn't under directory
938 return -1;
939 }
940
941 // Count number of subdirectories
942 auto pos = path.find('/', dir.size());
943 int count = 0;
944 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600945 auto next = path.find('/', pos + 1);
946 if (next > pos + 1) {
947 count++;
948 }
949 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600950 }
951
952 if (count > maxSubdirs) {
953 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100954 return -1;
955 }
956
957 return 0;
958}
959
960/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700961 * Checks whether a path points to a system app (.apk file). Returns 0
962 * if it is a system app or -1 if it is not.
963 */
964int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600965 std::string path_ = path;
966 for (const auto& dir : android_system_dirs) {
967 if (validate_path(dir, path, 1) == 0) {
968 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700969 }
970 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700971 return -1;
972}
973
Calin Juravle114f0812017-03-08 19:05:07 -0800974bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -0700975 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -0800976 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
977
Calin Juravle3760ad32017-07-27 16:31:55 -0700978 // Empty paths are not allowed.
979 if (dex_path.empty()) { return false; }
980 // First character should always be '/'. No relative paths.
981 if (dex_path[0] != '/') { return false; }
982 // The last character should not be '/'.
983 if (dex_path[dex_path.size() - 1] == '/') { return false; }
984 // There should be no '.' after the directory marker.
985 if (dex_path.find("/.") != std::string::npos) { return false; }
986 // The path should be at most PKG_PATH_MAX long.
987 if (dex_path.size() > PKG_PATH_MAX) { return false; }
988
Calin Juravle7d765462017-09-04 15:57:10 -0700989 // The dex_path should be under the app data directory.
990 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -0700991 ? create_data_user_ce_package_path(
992 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
993 : create_data_user_de_package_path(
994 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -0700995
Calin Juravle7d765462017-09-04 15:57:10 -0700996 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
997 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
998 // If that's the case, attempt to validate against the user data link.
999 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1000 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1001 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1002 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -07001003 return false;
1004 }
Calin Juravle42451c02017-01-17 14:43:25 -08001005 }
Calin Juravle3760ad32017-07-27 16:31:55 -07001006
1007 // If we got here we have a valid path.
1008 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001009}
1010
Mike Lockwood94afecf2012-10-24 10:45:23 -07001011/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001012 * Check whether path points to a valid path for an APK file. The path must
1013 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1014 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1015 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001016 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001017static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1018 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001019 return 0;
shafikb43faa92019-02-19 12:19:48 +00001020 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1021 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001022 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001023 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001024 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001025 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001026 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001027 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001028 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1029 // Rewrite the path as if it were on internal storage, and test that
1030 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1031 if (end != std::string::npos) {
1032 auto modified = path;
1033 modified.replace(0, end + 1, android_data_dir);
1034 return validate_apk_path_internal(modified, maxSubdirs);
1035 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001036 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001037 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001038}
1039
Narayan Kamathd845c962015-06-04 13:20:27 +01001040int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001041 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001042}
1043
1044int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001045 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001046}
1047
Robin Lee095c7632014-04-25 15:05:19 +01001048int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001049 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001050 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1051 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001052
1053 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001054 auto path = create_data_misc_legacy_path(userid);
1055 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001056}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001057
1058int wait_child(pid_t pid)
1059{
1060 int status;
1061 pid_t got_pid;
1062
1063 while (1) {
1064 got_pid = waitpid(pid, &status, 0);
1065 if (got_pid == -1 && errno == EINTR) {
1066 printf("waitpid interrupted, retrying\n");
1067 } else {
1068 break;
1069 }
1070 }
1071 if (got_pid != pid) {
1072 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1073 (int) pid, (int) got_pid, strerror(errno));
1074 return 1;
1075 }
1076
1077 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1078 return 0;
1079 } else {
1080 return status; /* always nonzero */
1081 }
1082}
1083
Calin Juravle42451c02017-01-17 14:43:25 -08001084/**
1085 * Prepare an app cache directory, which offers to fix-up the GID and
1086 * directory mode flags during a platform upgrade.
1087 * The app cache directory path will be 'parent'/'name'.
1088 */
1089int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1090 uid_t uid, gid_t gid) {
1091 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1092 struct stat st;
1093 if (stat(path.c_str(), &st) != 0) {
1094 if (errno == ENOENT) {
1095 // This is fine, just create it
1096 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1097 PLOG(ERROR) << "Failed to prepare " << path;
1098 return -1;
1099 } else {
1100 return 0;
1101 }
1102 } else {
1103 PLOG(ERROR) << "Failed to stat " << path;
1104 return -1;
1105 }
1106 }
1107
1108 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1109 if (st.st_uid != uid) {
1110 // Mismatched UID is real trouble; we can't recover
1111 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1112 << " but expected " << uid;
1113 return -1;
1114 } else if (st.st_gid == gid && actual_mode == target_mode) {
1115 // Everything looks good!
1116 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001117 } else {
1118 // Mismatched GID/mode is recoverable; fall through to update
1119 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001120 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001121 }
1122
1123 // Directory is owned correctly, but GID or mode mismatch means it's
1124 // probably a platform upgrade so we need to fix them
1125 FTS *fts;
1126 FTSENT *p;
1127 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001128 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001129 PLOG(ERROR) << "Failed to fts_open " << path;
1130 return -1;
1131 }
Yi Kong954cf642018-07-17 16:16:24 -07001132 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001133 switch (p->fts_info) {
1134 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001135 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001136 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1137 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001138 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001139 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001140 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001141 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1142 }
1143 break;
1144 case FTS_SL:
1145 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001146 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001147 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1148 }
1149 break;
1150 }
1151 }
1152 fts_close(fts);
1153 return 0;
1154}
1155
Martijn Coenen771cc342020-02-19 23:26:56 +01001156static const char* kProcFilesystems = "/proc/filesystems";
1157bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001158 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1159 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001160 std::string supported;
1161 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1162 PLOG(ERROR) << "Failed to read supported filesystems";
1163 return false;
1164 }
1165 return supported.find("sdcardfs\n") != std::string::npos;
1166}
1167
1168int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1169 static const bool supportsSdcardFs = supports_sdcardfs();
1170
1171 if (supportsSdcardFs) {
1172 int extGid = multiuser_get_ext_gid(userId, appId);
1173
1174 if (extGid == -1) {
1175 return -1;
1176 }
1177
1178 return GetOccupiedSpaceForGid(uuid, extGid);
1179 } else {
1180 uid_t uid = multiuser_get_uid(userId, appId);
1181 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1182 return GetOccupiedSpaceForProjectId(uuid, projectId);
1183 }
1184}
1185int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1186 static const bool supportsSdcardFs = supports_sdcardfs();
1187
1188 if (supportsSdcardFs) {
1189 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1190
1191 if (extCacheGid == -1) {
1192 return -1;
1193 }
1194
1195 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1196 } else {
1197 uid_t uid = multiuser_get_uid(userId, appId);
1198 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1199 return GetOccupiedSpaceForProjectId(uuid, projectId);
1200 }
1201}
1202
Calin Juravlee61189e2018-01-23 19:54:11 -08001203// Collect all non empty profiles from the given directory and puts then into profile_paths.
1204// The profiles are identified based on PROFILE_EXT extension.
1205// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1206// It returns true if there were no errors at all, and false otherwise.
1207static bool collect_profiles(DIR* d,
1208 const std::string& current_path,
1209 std::vector<std::string>* profiles_paths) {
1210 int32_t dir_fd = dirfd(d);
1211 if (dir_fd < 0) {
1212 return false;
1213 }
1214
1215 bool result = true;
1216 struct dirent* dir_entry;
1217 while ((dir_entry = readdir(d))) {
1218 std::string name = dir_entry->d_name;
1219 std::string local_path = current_path + "/" + name;
1220
1221 if (dir_entry->d_type == DT_REG) {
1222 // Check if this is a non empty profile file.
1223 if (EndsWith(name, PROFILE_EXT)) {
1224 struct stat st;
1225 if (stat(local_path.c_str(), &st) != 0) {
1226 PLOG(WARNING) << "Cannot stat local path " << local_path;
1227 result = false;
1228 continue;
1229 } else if (st.st_size > 0) {
1230 profiles_paths->push_back(local_path);
1231 }
1232 }
1233 } else if (dir_entry->d_type == DT_DIR) {
1234 // always skip "." and ".."
1235 if (name == "." || name == "..") {
1236 continue;
1237 }
1238
1239 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1240 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1241 if (subdir_fd < 0) {
1242 PLOG(WARNING) << "Could not open dir path " << local_path;
1243 result = false;
1244 continue;
1245 }
1246
Mathieu Chartier89883e32018-11-01 11:39:00 -07001247 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001248 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001249 PLOG(WARNING) << "Could not open dir path " << local_path;
1250 result = false;
1251 continue;
1252 }
1253 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1254 result = result && new_result;
1255 if (closedir(subdir) != 0) {
1256 PLOG(WARNING) << "Could not close dir path " << local_path;
1257 }
1258 }
1259 }
1260
1261 return result;
1262}
1263
1264bool collect_profiles(std::vector<std::string>* profiles_paths) {
1265 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001266 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001267 return false;
1268 } else {
1269 return collect_profiles(d, android_profiles_dir, profiles_paths);
1270 }
1271}
1272
Eric Holk2af5e6a2019-01-09 18:17:27 -08001273void drop_capabilities(uid_t uid) {
1274 if (setgid(uid) != 0) {
1275 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1276 exit(DexoptReturnCodes::kSetGid);
1277 }
1278 if (setuid(uid) != 0) {
1279 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1280 exit(DexoptReturnCodes::kSetUid);
1281 }
1282 // drop capabilities
1283 struct __user_cap_header_struct capheader;
1284 struct __user_cap_data_struct capdata[2];
1285 memset(&capheader, 0, sizeof(capheader));
1286 memset(&capdata, 0, sizeof(capdata));
1287 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1288 if (capset(&capheader, &capdata[0]) < 0) {
1289 PLOG(ERROR) << "capset failed";
1290 exit(DexoptReturnCodes::kCapSet);
1291 }
1292}
1293
Andreas Gampe02d0de52015-11-11 20:43:16 -08001294} // namespace installd
1295} // namespace android