blob: f04ee337d9db4f0f0fa2fa5367fa4869b3fe202f [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>
Jiakai Zhang0a7603c2022-02-21 19:38:14 +000022#include <poll.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080023#include <stdlib.h>
Eric Holk2af5e6a2019-01-09 18:17:27 -080024#include <sys/capability.h>
Jiakai Zhang0a7603c2022-02-21 19:38:14 +000025#include <sys/pidfd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026#include <sys/stat.h>
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080027#include <sys/statvfs.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028#include <sys/wait.h>
Jeff Sharkey9a998f42016-07-14 18:16:22 -060029#include <sys/xattr.h>
Jiakai Zhang0a7603c2022-02-21 19:38:14 +000030#include <unistd.h>
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080031#include <uuid/uuid.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080032
Martijn Coenen771cc342020-02-19 23:26:56 +010033#include <android-base/file.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080034#include <android-base/logging.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080035#include <android-base/stringprintf.h>
Jiakai Zhang0a7603c2022-02-21 19:38:14 +000036#include <android-base/strings.h>
Calin Juravlee61189e2018-01-23 19:54:11 -080037#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080038#include <cutils/fs.h>
Jeff Sharkey871a8f22017-02-21 18:30:28 -070039#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070040#include <log/log.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080041#include <private/android_filesystem_config.h>
Martijn Coenen771cc342020-02-19 23:26:56 +010042#include <private/android_projectid_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070043
Eric Holk2af5e6a2019-01-09 18:17:27 -080044#include "dexopt_return_codes.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080045#include "globals.h" // extern variables.
Martijn Coenen771cc342020-02-19 23:26:56 +010046#include "QuotaUtils.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080047
48#ifndef LOG_TAG
49#define LOG_TAG "installd"
50#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060051
Jeff Sharkey9a998f42016-07-14 18:16:22 -060052#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070053
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080054using android::base::Dirname;
Calin Juravlee61189e2018-01-23 19:54:11 -080055using android::base::EndsWith;
Mathieu Chartier89883e32018-11-01 11:39:00 -070056using android::base::Fdopendir;
Jeff Sharkeyc03de092015-04-07 18:14:05 -070057using android::base::StringPrintf;
Calin Juravlee61189e2018-01-23 19:54:11 -080058using android::base::unique_fd;
Mike Lockwood94afecf2012-10-24 10:45:23 -070059
Andreas Gampe02d0de52015-11-11 20:43:16 -080060namespace android {
61namespace installd {
62
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080063using namespace std::literals;
64
65static constexpr auto deletedSuffix = "==deleted=="sv;
66
Jeff Sharkeyc03de092015-04-07 18:14:05 -070067/**
68 * Check that given string is valid filename, and that it attempts no
69 * parent or child directory traversal.
70 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070071bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070072 if (name.empty() || (name == ".") || (name == "..")
73 || (name.find('/') != std::string::npos)) {
74 return false;
75 } else {
76 return true;
77 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070078}
79
Calin Juravle6a1648e2016-02-01 12:12:16 +000080static void check_package_name(const char* package_name) {
81 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070082 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000083}
84
Nikita Ioffe8755f792019-01-25 13:54:43 +000085static std::string resolve_ce_path_by_inode_or_fallback(const std::string& root_path,
86 ino_t ce_data_inode, const std::string& fallback) {
87 if (ce_data_inode != 0) {
88 DIR* dir = opendir(root_path.c_str());
89 if (dir == nullptr) {
90 PLOG(ERROR) << "Failed to opendir " << root_path;
91 return fallback;
92 }
93
94 struct dirent* ent;
95 while ((ent = readdir(dir))) {
96 if (ent->d_ino == ce_data_inode) {
97 auto resolved = StringPrintf("%s/%s", root_path.c_str(), ent->d_name);
98 if (resolved != fallback) {
99 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
100 << " instead of " << fallback;
101 }
102 closedir(dir);
103 return resolved;
104 }
105 }
106 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
107 closedir(dir);
108 return fallback;
109 } else {
110 return fallback;
111 }
112}
113
Mike Lockwood94afecf2012-10-24 10:45:23 -0700114/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700115 * Create the path name where package data should be stored for the given
116 * volume UUID, package name, and user ID. An empty UUID is assumed to be
117 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700118 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600119std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700120 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000121 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700122 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600123 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
124}
125
Calin Juravle7d765462017-09-04 15:57:10 -0700126/**
127 * Create the path name where package data should be stored for the given
128 * volume UUID, package name, and user ID. An empty UUID is assumed to be
129 * internal storage.
130 * Compared to create_data_user_ce_package_path this method always return the
131 * ".../user/..." directory.
132 */
133std::string create_data_user_ce_package_path_as_user_link(
134 const char* volume_uuid, userid_t userid, const char* package_name) {
135 check_package_name(package_name);
136 std::string data(create_data_path(volume_uuid));
137 return StringPrintf("%s/user/%u/%s", data.c_str(), userid, package_name);
138}
139
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600140std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
141 const char* package_name, ino_t ce_data_inode) {
142 // For testing purposes, rely on the inode when defined; this could be
143 // optimized to use access() in the future.
144 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000145 auto user_path = create_data_user_ce_path(volume_uuid, user);
146 return resolve_ce_path_by_inode_or_fallback(user_path, ce_data_inode, fallback);
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700147}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700148
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800149std::string create_data_user_de_package_path(const char* volume_uuid,
150 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000151 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800152 return StringPrintf("%s/%s",
153 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
154}
155
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700156std::string create_data_path(const char* volume_uuid) {
157 if (volume_uuid == nullptr) {
158 return "/data";
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700159 } else if (!strcmp(volume_uuid, "TEST")) {
160 CHECK(property_get_bool("ro.debuggable", false));
161 return "/data/local/tmp";
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700162 } else {
163 CHECK(is_valid_filename(volume_uuid));
164 return StringPrintf("/mnt/expand/%s", volume_uuid);
165 }
166}
167
Mike Lockwood94afecf2012-10-24 10:45:23 -0700168/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700169 * Create the path name for app data.
170 */
171std::string create_data_app_path(const char* volume_uuid) {
172 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
173}
174
175/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700176 * Create the path name for user data for a certain userid.
cjbao75d4e572017-04-12 00:12:24 +0800177 * Keep same implementation as vold to minimize path walking overhead
Mike Lockwood94afecf2012-10-24 10:45:23 -0700178 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600179std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700180 std::string data(create_data_path(volume_uuid));
cjbao75d4e572017-04-12 00:12:24 +0800181 if (volume_uuid == nullptr && userid == 0) {
182 std::string legacy = StringPrintf("%s/data", data.c_str());
183 struct stat sb;
184 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
185 /* /data/data is dir, return /data/data for legacy system */
186 return legacy;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700187 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700188 }
cjbao75d4e572017-04-12 00:12:24 +0800189 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700190}
191
192/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800193 * Create the path name for device encrypted user data for a certain userid.
194 */
195std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
196 std::string data(create_data_path(volume_uuid));
197 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
198}
199
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000200std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000201 return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
202}
203
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000204std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000205 return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
206}
207
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000208std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
209 int32_t snapshot_id) {
210 return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
211 snapshot_id);
212}
213
214std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
215 int32_t snapshot_id) {
216 return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
217 snapshot_id);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000218}
219
Nikita Ioffe8755f792019-01-25 13:54:43 +0000220std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000221 userid_t user, int32_t snapshot_id, const char* package_name) {
222 return StringPrintf("%s/%s",
223 create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
224}
225
226std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
227 userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
228 auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
229 package_name);
230 auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000231 return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
232}
233
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000234std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000235 userid_t user, int32_t snapshot_id, const char* package_name) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000236 return StringPrintf("%s/%s",
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000237 create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000238}
239
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800240/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700241 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700242 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700243std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
244 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700245}
246
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700247std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
248 const char* data_type, const char* package_name) {
249 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
250 data_type, package_name);
251}
252
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600253std::string create_data_misc_legacy_path(userid_t userid) {
254 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
255}
256
Calin Juravle114f0812017-03-08 19:05:07 -0800257std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600258 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000259}
260
Calin Juravle114f0812017-03-08 19:05:07 -0800261std::string create_primary_current_profile_package_dir_path(userid_t user,
262 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800263 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800264 return StringPrintf("%s/%s",
265 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700266}
267
Calin Juravle114f0812017-03-08 19:05:07 -0800268std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600269 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000270}
271
Calin Juravle114f0812017-03-08 19:05:07 -0800272std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800273 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600274 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000275}
276
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700277std::string create_data_dalvik_cache_path() {
278 return "/data/dalvik-cache";
279}
280
Felka Chang2a0a2462019-11-20 14:20:40 +0800281std::string create_system_user_ce_path(userid_t userId) {
282 return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
283}
284
285std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
286 check_package_name(package_name);
287 return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
288}
289
Calin Juravle114f0812017-03-08 19:05:07 -0800290// Keep profile paths in sync with ActivityThread and LoadedApk.
291const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700292const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800293const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700294
Calin Juravle3760ad32017-07-27 16:31:55 -0700295// Gets the parent directory and the file name for the given secondary dex path.
296// Returns true on success, false on failure (if the dex_path does not have the expected
297// structure).
298static bool get_secondary_dex_location(const std::string& dex_path,
299 std::string* out_dir_name, std::string* out_file_name) {
300 size_t dirIndex = dex_path.rfind('/');
301 if (dirIndex == std::string::npos) {
302 return false;
303 }
304 if (dirIndex == dex_path.size() - 1) {
305 return false;
306 }
307 *out_dir_name = dex_path.substr(0, dirIndex);
308 *out_file_name = dex_path.substr(dirIndex + 1);
309
310 return true;
311}
312
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800313std::string create_current_profile_path(userid_t user, const std::string& package_name,
314 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800315 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700316 // Secondary dex current profiles are stored next to the dex files under the oat folder.
317 std::string dex_dir;
318 std::string dex_name;
319 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
320 << "Unexpected dir structure for secondary dex " << location;
321 return StringPrintf("%s/oat/%s%s%s",
322 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
323 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800324 } else {
325 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800326 std::string profile_dir = create_primary_current_profile_package_dir_path(
327 user, package_name);
328 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800329 }
330}
331
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800332std::string create_reference_profile_path(const std::string& package_name,
333 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800334 if (is_secondary_dex) {
335 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700336 std::string dex_dir;
337 std::string dex_name;
338 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800339 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800340 return StringPrintf("%s/oat/%s%s",
341 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
342 } else {
343 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800344 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
345 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800346 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700347}
348
Calin Juravle29591732017-11-20 17:46:19 -0800349std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800350 const std::string& profile_name) {
351 std::string ref_profile = create_reference_profile_path(package, profile_name,
352 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800353 return ref_profile + SNAPSHOT_PROFILE_EXT;
354}
355
Jeff Sharkeye3637242015-04-08 20:56:42 -0700356std::vector<userid_t> get_known_users(const char* volume_uuid) {
357 std::vector<userid_t> users;
358
359 // We always have an owner
360 users.push_back(0);
361
362 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
363 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700364 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700365 // Unable to discover other users, but at least return owner
366 PLOG(ERROR) << "Failed to opendir " << path;
367 return users;
368 }
369
370 struct dirent* ent;
371 while ((ent = readdir(dir))) {
372 if (ent->d_type != DT_DIR) {
373 continue;
374 }
375
376 char* end;
377 userid_t user = strtol(ent->d_name, &end, 10);
378 if (*end == '\0' && user != 0) {
379 LOG(DEBUG) << "Found valid user " << user;
380 users.push_back(user);
381 }
382 }
383 closedir(dir);
384
385 return users;
386}
387
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700388int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700389 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700390 FTS *fts;
391 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700392 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700393 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700394 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700395 if (errno != ENOENT) {
396 PLOG(ERROR) << "Failed to fts_open " << path;
397 }
398 return -1;
399 }
Yi Kong954cf642018-07-17 16:16:24 -0700400 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700401 switch (p->fts_info) {
402 case FTS_D:
403 case FTS_DEFAULT:
404 case FTS_F:
405 case FTS_SL:
406 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700407 int32_t uid = p->fts_statp->st_uid;
408 int32_t gid = p->fts_statp->st_gid;
409 int32_t user_uid = multiuser_get_app_id(uid);
410 int32_t user_gid = multiuser_get_app_id(gid);
411 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
412 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
413 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
414 // Don't traverse inside or measure
415 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700416 break;
417 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700418 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700419 break;
420 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700421 if (exclude_gid != -1 && gid == exclude_gid) {
422 break;
423 }
424 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700425 break;
426 }
427 }
428 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700429#if MEASURE_DEBUG
430 if ((include_gid == -1) && (exclude_gid == -1)) {
431 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
432 } else {
433 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
434 << " exclude " << exclude_gid;
435 }
436#endif
437 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700438 return 0;
439}
440
Mike Lockwood94afecf2012-10-24 10:45:23 -0700441/**
442 * Checks whether the package name is valid. Returns -1 on error and
443 * 0 on success.
444 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700445bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700446 // This logic is borrowed from PackageParser.java
447 bool hasSep = false;
448 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700449
Jeff Sharkey367ace22017-03-07 22:12:03 -0700450 auto it = packageName.begin();
451 for (; it != packageName.end() && *it != '-'; it++) {
452 char c = *it;
453 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
454 front = false;
455 continue;
456 }
457 if (!front) {
458 if ((c >= '0' && c <= '9') || c == '_') {
459 continue;
460 }
461 }
462 if (c == '.') {
463 hasSep = true;
464 front = true;
465 continue;
466 }
467 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700468 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700469 }
470
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700471 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700472 LOG(WARNING) << "Missing separator in " << packageName;
473 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700474 }
475
Jeff Sharkey367ace22017-03-07 22:12:03 -0700476 for (; it != packageName.end(); it++) {
477 char c = *it;
478 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
479 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
480 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
481 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700482 }
483
Jeff Sharkey423e7462016-12-09 18:18:43 -0700484 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700485}
486
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100487static int _delete_dir_contents(DIR *d,
488 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700489{
490 int result = 0;
491 struct dirent *de;
492 int dfd;
493
494 dfd = dirfd(d);
495
496 if (dfd < 0) return -1;
497
498 while ((de = readdir(d))) {
499 const char *name = de->d_name;
500
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100501 /* check using the exclusion predicate, if provided */
502 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
503 continue;
504 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700505
506 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700507 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700508 DIR *subdir;
509
510 /* always skip "." and ".." */
511 if (name[0] == '.') {
512 if (name[1] == 0) continue;
513 if ((name[1] == '.') && (name[2] == 0)) continue;
514 }
515
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700516 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700517 if (subfd < 0) {
518 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
519 result = -1;
520 continue;
521 }
522 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700523 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700524 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
525 close(subfd);
526 result = -1;
527 continue;
528 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100529 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700530 result = -1;
531 }
532 closedir(subdir);
533 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
534 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
535 result = -1;
536 }
537 } else {
538 if (unlinkat(dfd, name, 0) < 0) {
539 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
540 result = -1;
541 }
542 }
543 }
544
545 return result;
546}
547
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000548int create_dir_if_needed(const std::string& pathname, mode_t perms) {
549 struct stat st;
550
551 int rc;
552 if ((rc = stat(pathname.c_str(), &st)) != 0) {
553 if (errno == ENOENT) {
554 return mkdir(pathname.c_str(), perms);
555 } else {
556 return rc;
557 }
558 } else if (!S_ISDIR(st.st_mode)) {
559 LOG(DEBUG) << pathname << " is not a folder";
560 return -1;
561 }
562
563 mode_t actual_perms = st.st_mode & ALLPERMS;
564 if (actual_perms != perms) {
565 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
566 return -1;
567 }
568
569 return 0;
570}
571
Calin Juravleb06f98a2016-03-28 15:11:01 +0100572int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700573 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700574}
575
Calin Juravleb06f98a2016-03-28 15:11:01 +0100576int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700577 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700578}
579
Mike Lockwood94afecf2012-10-24 10:45:23 -0700580int delete_dir_contents(const char *pathname,
581 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100582 int (*exclusion_predicate)(const char*, const int),
583 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700584{
585 int res = 0;
586 DIR *d;
587
588 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700589 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100590 if (ignore_if_missing && (errno == ENOENT)) {
591 return 0;
592 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700593 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
594 return -errno;
595 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100596 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700597 closedir(d);
598 if (also_delete_dir) {
599 if (rmdir(pathname)) {
600 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
601 res = -1;
602 }
603 }
604 return res;
605}
606
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800607static std::string make_unique_name(std::string_view suffix) {
608 static constexpr auto uuidStringSize = 36;
609
610 uuid_t guid;
611 uuid_generate(guid);
612
613 std::string name;
614 const auto suffixSize = suffix.size();
615 name.reserve(uuidStringSize + suffixSize);
616
617 name.resize(uuidStringSize);
618 uuid_unparse(guid, name.data());
619 name.append(suffix);
620
621 return name;
622}
623
624static int rename_delete_dir_contents(const std::string& pathname,
625 int (*exclusion_predicate)(const char*, const int),
626 bool ignore_if_missing) {
627 auto temp_dir_name = make_unique_name(deletedSuffix);
628 auto temp_dir_path =
629 base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
630
631 if (::rename(pathname.c_str(), temp_dir_path.c_str())) {
632 if (ignore_if_missing && (errno == ENOENT)) {
633 return 0;
634 }
635 ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), temp_dir_path.c_str(),
636 strerror(errno));
637 return -errno;
638 }
639
640 return delete_dir_contents(temp_dir_path.c_str(), 1, exclusion_predicate, ignore_if_missing);
641}
642
Alex Buynytskyy4ab5d532022-02-17 21:20:10 +0000643bool is_renamed_deleted_dir(const std::string& path) {
644 if (path.size() < deletedSuffix.size()) {
645 return false;
646 }
647 std::string_view pathSuffix{path.c_str() + path.size() - deletedSuffix.size()};
648 return pathSuffix == deletedSuffix;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800649}
650
651int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
652 return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
653}
654
655static auto open_dir(const char* dir) {
656 struct DirCloser {
657 void operator()(DIR* d) const noexcept { ::closedir(d); }
658 };
659 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
660}
661
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800662void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800663 auto dir = open_dir(pathname.c_str());
664 if (!dir) {
665 return;
666 }
667 int dfd = dirfd(dir.get());
668 if (dfd < 0) {
669 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
670 return;
671 }
672
673 struct dirent* de;
674 while ((de = readdir(dir.get()))) {
675 if (de->d_type != DT_DIR) {
676 continue;
677 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800678
679 std::string name{de->d_name};
680 // always skip "." and ".."
681 if (name == "." || name == "..") {
682 continue;
683 }
684
685 if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
686 !is_valid_package_name(name)) {
687 ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800688 // Deleting the content.
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800689 delete_dir_contents_fd(dfd, name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800690 // Deleting the directory
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800691 if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
692 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800693 }
694 }
695 }
696}
697
Mike Lockwood94afecf2012-10-24 10:45:23 -0700698int delete_dir_contents_fd(int dfd, const char *name)
699{
700 int fd, res;
701 DIR *d;
702
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700703 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700704 if (fd < 0) {
705 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
706 return -1;
707 }
708 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700709 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700710 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
711 close(fd);
712 return -1;
713 }
Yi Kong954cf642018-07-17 16:16:24 -0700714 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700715 closedir(d);
716 return res;
717}
718
Robin Lee60fd3fe2014-10-07 16:55:02 +0100719static int _copy_owner_permissions(int srcfd, int dstfd)
720{
721 struct stat st;
722 if (fstat(srcfd, &st) != 0) {
723 return -1;
724 }
725 if (fchmod(dstfd, st.st_mode) != 0) {
726 return -1;
727 }
728 return 0;
729}
730
731static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
732{
733 int result = 0;
734 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
735 ALOGE("_copy_dir_files failed to copy dir permissions\n");
736 }
737 if (fchown(ddfd, owner, group) != 0) {
738 ALOGE("_copy_dir_files failed to change dir owner\n");
739 }
740
741 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700742 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100743 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
744 return -1;
745 }
746 struct dirent *de;
747 while ((de = readdir(ds))) {
748 if (de->d_type != DT_REG) {
749 continue;
750 }
751
752 const char *name = de->d_name;
753 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
754 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
755 if (fsfd == -1 || fdfd == -1) {
756 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
757 } else {
758 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
759 ALOGE("Failed to change file permissions\n");
760 }
761 if (fchown(fdfd, owner, group) != 0) {
762 ALOGE("Failed to change file owner\n");
763 }
764
765 char buf[8192];
766 ssize_t size;
767 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
768 write(fdfd, buf, size);
769 }
770 if (size < 0) {
771 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
772 result = -1;
773 }
774 }
775 close(fdfd);
776 close(fsfd);
777 }
778
779 return result;
780}
781
782int copy_dir_files(const char *srcname,
783 const char *dstname,
784 uid_t owner,
785 uid_t group)
786{
787 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700788 DIR *ds = nullptr;
789 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100790
791 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700792 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100793 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
794 return -errno;
795 }
796
797 mkdir(dstname, 0600);
798 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700799 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100800 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
801 closedir(ds);
802 return -errno;
803 }
804
805 int sdfd = dirfd(ds);
806 int ddfd = dirfd(dd);
807 if (sdfd != -1 && ddfd != -1) {
808 res = _copy_dir_files(sdfd, ddfd, owner, group);
809 } else {
810 res = -errno;
811 }
812 closedir(dd);
813 closedir(ds);
814 return res;
815}
816
Jeff Sharkeya836c472017-04-02 23:29:30 -0600817int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600818 struct statvfs sfs;
819 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600820 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700821 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600822 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700823 return -1;
824 }
825}
826
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600827int get_path_inode(const std::string& path, ino_t *inode) {
828 struct stat buf;
829 memset(&buf, 0, sizeof(buf));
830 if (stat(path.c_str(), &buf) != 0) {
831 PLOG(WARNING) << "Failed to stat " << path;
832 return -1;
833 } else {
834 *inode = buf.st_ino;
835 return 0;
836 }
837}
838
839/**
840 * Write the inode of a specific child file into the given xattr on the
841 * parent directory. This allows you to find the child later, even if its
842 * name is encrypted.
843 */
844int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
845 ino_t inode = 0;
846 uint64_t inode_raw = 0;
847 auto path = StringPrintf("%s/%s", parent.c_str(), name);
848
849 if (get_path_inode(path, &inode) != 0) {
850 // Path probably doesn't exist yet; ignore
851 return 0;
852 }
853
854 // Check to see if already set correctly
855 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
856 if (inode_raw == inode) {
857 // Already set correctly; skip writing
858 return 0;
859 } else {
860 PLOG(WARNING) << "Mismatched inode value; found " << inode
861 << " on disk but marked value was " << inode_raw << "; overwriting";
862 }
863 }
864
865 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600866 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600867 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
868 return -1;
869 } else {
870 return 0;
871 }
872}
873
874/**
875 * Read the inode of a specific child file from the given xattr on the
876 * parent directory. Returns a currently valid path for that child, which
877 * might have an encrypted name.
878 */
879std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
880 ino_t inode = 0;
881 uint64_t inode_raw = 0;
882 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
883
884 // Lookup the inode value written earlier
885 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
886 inode = inode_raw;
887 }
888
889 // For testing purposes, rely on the inode when defined; this could be
890 // optimized to use access() in the future.
891 if (inode != 0) {
892 DIR* dir = opendir(parent.c_str());
893 if (dir == nullptr) {
894 PLOG(ERROR) << "Failed to opendir " << parent;
895 return fallback;
896 }
897
898 struct dirent* ent;
899 while ((ent = readdir(dir))) {
900 if (ent->d_ino == inode) {
901 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
902#if DEBUG_XATTRS
903 if (resolved != fallback) {
904 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
905 << " instead of " << fallback;
906 }
907#endif
908 closedir(dir);
909 return resolved;
910 }
911 }
912 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
913 closedir(dir);
914 return fallback;
915 } else {
916 return fallback;
917 }
918}
919
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900920void remove_path_xattr(const std::string& path, const char* inode_xattr) {
921 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
922 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
923 }
924}
925
Mike Lockwood94afecf2012-10-24 10:45:23 -0700926/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100927 * Validate that the path is valid in the context of the provided directory.
928 * The path is allowed to have at most one subdirectory and no indirections
929 * to top level directories (i.e. have "..").
930 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600931static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000932 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600933 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
934 || dir.find("..") != std::string::npos) {
935 LOG(ERROR) << "Invalid directory " << dir;
936 return -1;
937 }
938 if (path.find("..") != std::string::npos) {
939 LOG(ERROR) << "Invalid path " << path;
940 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100941 }
942
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600943 if (path.compare(0, dir.size(), dir) != 0) {
944 // Common case, path isn't under directory
945 return -1;
946 }
947
948 // Count number of subdirectories
949 auto pos = path.find('/', dir.size());
950 int count = 0;
951 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600952 auto next = path.find('/', pos + 1);
953 if (next > pos + 1) {
954 count++;
955 }
956 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600957 }
958
959 if (count > maxSubdirs) {
960 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100961 return -1;
962 }
963
964 return 0;
965}
966
967/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700968 * Checks whether a path points to a system app (.apk file). Returns 0
969 * if it is a system app or -1 if it is not.
970 */
971int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600972 std::string path_ = path;
973 for (const auto& dir : android_system_dirs) {
974 if (validate_path(dir, path, 1) == 0) {
975 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700976 }
977 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700978 return -1;
979}
980
Calin Juravle114f0812017-03-08 19:05:07 -0800981bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -0700982 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -0800983 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
984
Calin Juravle3760ad32017-07-27 16:31:55 -0700985 // Empty paths are not allowed.
986 if (dex_path.empty()) { return false; }
987 // First character should always be '/'. No relative paths.
988 if (dex_path[0] != '/') { return false; }
989 // The last character should not be '/'.
990 if (dex_path[dex_path.size() - 1] == '/') { return false; }
991 // There should be no '.' after the directory marker.
992 if (dex_path.find("/.") != std::string::npos) { return false; }
993 // The path should be at most PKG_PATH_MAX long.
994 if (dex_path.size() > PKG_PATH_MAX) { return false; }
995
Calin Juravle7d765462017-09-04 15:57:10 -0700996 // The dex_path should be under the app data directory.
997 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -0700998 ? create_data_user_ce_package_path(
999 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1000 : create_data_user_de_package_path(
1001 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -07001002
Calin Juravle7d765462017-09-04 15:57:10 -07001003 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1004 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1005 // If that's the case, attempt to validate against the user data link.
1006 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1007 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1008 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1009 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -07001010 return false;
1011 }
Calin Juravle42451c02017-01-17 14:43:25 -08001012 }
Calin Juravle3760ad32017-07-27 16:31:55 -07001013
1014 // If we got here we have a valid path.
1015 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001016}
1017
Mike Lockwood94afecf2012-10-24 10:45:23 -07001018/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001019 * Check whether path points to a valid path for an APK file. The path must
1020 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1021 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1022 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001023 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001024static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1025 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001026 return 0;
shafikb43faa92019-02-19 12:19:48 +00001027 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1028 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001029 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001030 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001031 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001032 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001033 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001034 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001035 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1036 // Rewrite the path as if it were on internal storage, and test that
1037 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1038 if (end != std::string::npos) {
1039 auto modified = path;
1040 modified.replace(0, end + 1, android_data_dir);
1041 return validate_apk_path_internal(modified, maxSubdirs);
1042 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001043 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001044 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001045}
1046
Narayan Kamathd845c962015-06-04 13:20:27 +01001047int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001048 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001049}
1050
1051int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001052 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001053}
1054
Robin Lee095c7632014-04-25 15:05:19 +01001055int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001056 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001057 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1058 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001059
1060 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001061 auto path = create_data_misc_legacy_path(userid);
1062 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001063}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001064
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001065static int wait_child(pid_t pid) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001066 int status;
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001067 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, /*options=*/0));
Andreas Gampe02d0de52015-11-11 20:43:16 -08001068
Andreas Gampe02d0de52015-11-11 20:43:16 -08001069 if (got_pid != pid) {
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001070 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
1071 return W_EXITCODE(/*exit_code=*/255, /*signal_number=*/0);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001072 }
1073
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001074 return status;
1075}
1076
1077int wait_child_with_timeout(pid_t pid, int timeout_ms) {
1078 int pidfd = pidfd_open(pid, /*flags=*/0);
1079 if (pidfd < 0) {
1080 PLOG(ERROR) << "pidfd_open failed for pid " << pid;
1081 kill(pid, SIGKILL);
1082 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001083 }
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001084
1085 struct pollfd pfd;
1086 pfd.fd = pidfd;
1087 pfd.events = POLLIN;
1088 int poll_ret = TEMP_FAILURE_RETRY(poll(&pfd, /*nfds=*/1, timeout_ms));
1089
1090 close(pidfd);
1091
1092 if (poll_ret < 0) {
1093 PLOG(ERROR) << "poll failed for pid " << pid;
1094 kill(pid, SIGKILL);
1095 return wait_child(pid);
1096 }
1097 if (poll_ret == 0) {
1098 LOG(WARNING) << "Child process " << pid << " timed out after " << timeout_ms
1099 << "ms. Killing it";
1100 kill(pid, SIGKILL);
1101 return wait_child(pid);
1102 }
1103 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001104}
1105
Calin Juravle42451c02017-01-17 14:43:25 -08001106/**
1107 * Prepare an app cache directory, which offers to fix-up the GID and
1108 * directory mode flags during a platform upgrade.
1109 * The app cache directory path will be 'parent'/'name'.
1110 */
1111int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1112 uid_t uid, gid_t gid) {
1113 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1114 struct stat st;
1115 if (stat(path.c_str(), &st) != 0) {
1116 if (errno == ENOENT) {
1117 // This is fine, just create it
1118 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1119 PLOG(ERROR) << "Failed to prepare " << path;
1120 return -1;
1121 } else {
1122 return 0;
1123 }
1124 } else {
1125 PLOG(ERROR) << "Failed to stat " << path;
1126 return -1;
1127 }
1128 }
1129
1130 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1131 if (st.st_uid != uid) {
1132 // Mismatched UID is real trouble; we can't recover
1133 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1134 << " but expected " << uid;
1135 return -1;
1136 } else if (st.st_gid == gid && actual_mode == target_mode) {
1137 // Everything looks good!
1138 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001139 } else {
1140 // Mismatched GID/mode is recoverable; fall through to update
1141 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001142 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001143 }
1144
1145 // Directory is owned correctly, but GID or mode mismatch means it's
1146 // probably a platform upgrade so we need to fix them
1147 FTS *fts;
1148 FTSENT *p;
1149 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001150 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001151 PLOG(ERROR) << "Failed to fts_open " << path;
1152 return -1;
1153 }
Yi Kong954cf642018-07-17 16:16:24 -07001154 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001155 switch (p->fts_info) {
1156 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001157 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001158 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1159 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001160 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001161 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001162 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001163 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1164 }
1165 break;
1166 case FTS_SL:
1167 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001168 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001169 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1170 }
1171 break;
1172 }
1173 }
1174 fts_close(fts);
1175 return 0;
1176}
1177
Martijn Coenen771cc342020-02-19 23:26:56 +01001178static const char* kProcFilesystems = "/proc/filesystems";
1179bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001180 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1181 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001182 std::string supported;
1183 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1184 PLOG(ERROR) << "Failed to read supported filesystems";
1185 return false;
1186 }
1187 return supported.find("sdcardfs\n") != std::string::npos;
1188}
1189
1190int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1191 static const bool supportsSdcardFs = supports_sdcardfs();
1192
1193 if (supportsSdcardFs) {
1194 int extGid = multiuser_get_ext_gid(userId, appId);
1195
1196 if (extGid == -1) {
1197 return -1;
1198 }
1199
1200 return GetOccupiedSpaceForGid(uuid, extGid);
1201 } else {
1202 uid_t uid = multiuser_get_uid(userId, appId);
1203 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1204 return GetOccupiedSpaceForProjectId(uuid, projectId);
1205 }
1206}
1207int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1208 static const bool supportsSdcardFs = supports_sdcardfs();
1209
1210 if (supportsSdcardFs) {
1211 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1212
1213 if (extCacheGid == -1) {
1214 return -1;
1215 }
1216
1217 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1218 } else {
1219 uid_t uid = multiuser_get_uid(userId, appId);
1220 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1221 return GetOccupiedSpaceForProjectId(uuid, projectId);
1222 }
1223}
1224
Calin Juravlee61189e2018-01-23 19:54:11 -08001225// Collect all non empty profiles from the given directory and puts then into profile_paths.
1226// The profiles are identified based on PROFILE_EXT extension.
1227// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1228// It returns true if there were no errors at all, and false otherwise.
1229static bool collect_profiles(DIR* d,
1230 const std::string& current_path,
1231 std::vector<std::string>* profiles_paths) {
1232 int32_t dir_fd = dirfd(d);
1233 if (dir_fd < 0) {
1234 return false;
1235 }
1236
1237 bool result = true;
1238 struct dirent* dir_entry;
1239 while ((dir_entry = readdir(d))) {
1240 std::string name = dir_entry->d_name;
1241 std::string local_path = current_path + "/" + name;
1242
1243 if (dir_entry->d_type == DT_REG) {
1244 // Check if this is a non empty profile file.
1245 if (EndsWith(name, PROFILE_EXT)) {
1246 struct stat st;
1247 if (stat(local_path.c_str(), &st) != 0) {
1248 PLOG(WARNING) << "Cannot stat local path " << local_path;
1249 result = false;
1250 continue;
1251 } else if (st.st_size > 0) {
1252 profiles_paths->push_back(local_path);
1253 }
1254 }
1255 } else if (dir_entry->d_type == DT_DIR) {
1256 // always skip "." and ".."
1257 if (name == "." || name == "..") {
1258 continue;
1259 }
1260
1261 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1262 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1263 if (subdir_fd < 0) {
1264 PLOG(WARNING) << "Could not open dir path " << local_path;
1265 result = false;
1266 continue;
1267 }
1268
Mathieu Chartier89883e32018-11-01 11:39:00 -07001269 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001270 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001271 PLOG(WARNING) << "Could not open dir path " << local_path;
1272 result = false;
1273 continue;
1274 }
1275 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1276 result = result && new_result;
1277 if (closedir(subdir) != 0) {
1278 PLOG(WARNING) << "Could not close dir path " << local_path;
1279 }
1280 }
1281 }
1282
1283 return result;
1284}
1285
1286bool collect_profiles(std::vector<std::string>* profiles_paths) {
1287 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001288 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001289 return false;
1290 } else {
1291 return collect_profiles(d, android_profiles_dir, profiles_paths);
1292 }
1293}
1294
Eric Holk2af5e6a2019-01-09 18:17:27 -08001295void drop_capabilities(uid_t uid) {
1296 if (setgid(uid) != 0) {
1297 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1298 exit(DexoptReturnCodes::kSetGid);
1299 }
1300 if (setuid(uid) != 0) {
1301 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1302 exit(DexoptReturnCodes::kSetUid);
1303 }
1304 // drop capabilities
1305 struct __user_cap_header_struct capheader;
1306 struct __user_cap_data_struct capdata[2];
1307 memset(&capheader, 0, sizeof(capheader));
1308 memset(&capdata, 0, sizeof(capdata));
1309 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1310 if (capset(&capheader, &capdata[0]) < 0) {
1311 PLOG(ERROR) << "capset failed";
1312 exit(DexoptReturnCodes::kCapSet);
1313 }
1314}
1315
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001316bool remove_file_at_fd(int fd, /*out*/ std::string* path) {
1317 char path_buffer[PATH_MAX + 1];
1318 std::string proc_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
1319 ssize_t len = readlink(proc_path.c_str(), path_buffer, PATH_MAX);
1320 if (len < 0) {
1321 PLOG(WARNING) << "Could not remove file at fd " << fd << ": Failed to get file path";
1322 return false;
1323 }
1324 path_buffer[len] = '\0';
1325 if (path != nullptr) {
1326 *path = path_buffer;
1327 }
1328 if (unlink(path_buffer) != 0) {
1329 if (errno == ENOENT) {
1330 return true;
1331 }
1332 PLOG(WARNING) << "Could not remove file at path " << path_buffer;
1333 return false;
1334 }
1335 return true;
1336}
1337
Andreas Gampe02d0de52015-11-11 20:43:16 -08001338} // namespace installd
1339} // namespace android