blob: 1afac576f9e76ba4f5daa005d67f8dc7763add37 [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
Samiul Islamc40dff52022-01-14 16:24:48 +0000197/**
198 * Create the path name where supplemental data for all apps will be stored.
199 * E.g. /data/misc_ce/0/supplemental
200 */
201std::string create_data_misc_supplemental_path(const char* uuid, bool isCeData, userid_t user) {
202 std::string data(create_data_path(uuid));
203 if (isCeData) {
204 return StringPrintf("%s/misc_ce/%d/supplemental", data.c_str(), user);
205 } else {
206 return StringPrintf("%s/misc_de/%d/supplemental", data.c_str(), user);
207 }
208}
209
210/**
211 * Create the path name where code data for all codes in a particular app will be stored.
212 * E.g. /data/misc_ce/0/supplemental/<app-name>
213 */
214std::string create_data_misc_supplemental_package_path(const char* volume_uuid, bool isCeData,
215 userid_t user, const char* package_name) {
216 check_package_name(package_name);
217 return StringPrintf("%s/%s",
218 create_data_misc_supplemental_path(volume_uuid, isCeData, user).c_str(),
219 package_name);
220}
221
222/**
223 * Create the path name where shared code data for a particular app will be stored.
224 * E.g. /data/misc_ce/0/supplemental/<app-name>/shared
225 */
226std::string create_data_misc_supplemental_shared_path(const char* volume_uuid, bool isCeData,
227 userid_t user, const char* package_name) {
228 return StringPrintf("%s/shared",
229 create_data_misc_supplemental_package_path(volume_uuid, isCeData, user,
230 package_name)
231 .c_str());
232}
233
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000234std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000235 return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
236}
237
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000238std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000239 return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
240}
241
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000242std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
243 int32_t snapshot_id) {
244 return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
245 snapshot_id);
246}
247
248std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
249 int32_t snapshot_id) {
250 return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
251 snapshot_id);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000252}
253
Nikita Ioffe8755f792019-01-25 13:54:43 +0000254std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000255 userid_t user, int32_t snapshot_id, const char* package_name) {
256 return StringPrintf("%s/%s",
257 create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
258}
259
260std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
261 userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
262 auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
263 package_name);
264 auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000265 return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
266}
267
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000268std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000269 userid_t user, int32_t snapshot_id, const char* package_name) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000270 return StringPrintf("%s/%s",
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000271 create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000272}
273
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800274/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700275 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700276 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700277std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
278 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700279}
280
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700281std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
282 const char* data_type, const char* package_name) {
283 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
284 data_type, package_name);
285}
286
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600287std::string create_data_misc_legacy_path(userid_t userid) {
288 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
289}
290
Calin Juravle114f0812017-03-08 19:05:07 -0800291std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600292 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000293}
294
Calin Juravle114f0812017-03-08 19:05:07 -0800295std::string create_primary_current_profile_package_dir_path(userid_t user,
296 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800297 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800298 return StringPrintf("%s/%s",
299 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700300}
301
Calin Juravle114f0812017-03-08 19:05:07 -0800302std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600303 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000304}
305
Calin Juravle114f0812017-03-08 19:05:07 -0800306std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800307 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600308 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000309}
310
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700311std::string create_data_dalvik_cache_path() {
312 return "/data/dalvik-cache";
313}
314
Felka Chang2a0a2462019-11-20 14:20:40 +0800315std::string create_system_user_ce_path(userid_t userId) {
316 return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
317}
318
319std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
320 check_package_name(package_name);
321 return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
322}
323
Calin Juravle114f0812017-03-08 19:05:07 -0800324// Keep profile paths in sync with ActivityThread and LoadedApk.
325const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700326const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800327const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700328
Calin Juravle3760ad32017-07-27 16:31:55 -0700329// Gets the parent directory and the file name for the given secondary dex path.
330// Returns true on success, false on failure (if the dex_path does not have the expected
331// structure).
332static bool get_secondary_dex_location(const std::string& dex_path,
333 std::string* out_dir_name, std::string* out_file_name) {
334 size_t dirIndex = dex_path.rfind('/');
335 if (dirIndex == std::string::npos) {
336 return false;
337 }
338 if (dirIndex == dex_path.size() - 1) {
339 return false;
340 }
341 *out_dir_name = dex_path.substr(0, dirIndex);
342 *out_file_name = dex_path.substr(dirIndex + 1);
343
344 return true;
345}
346
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800347std::string create_current_profile_path(userid_t user, const std::string& package_name,
348 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800349 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700350 // Secondary dex current profiles are stored next to the dex files under the oat folder.
351 std::string dex_dir;
352 std::string dex_name;
353 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
354 << "Unexpected dir structure for secondary dex " << location;
355 return StringPrintf("%s/oat/%s%s%s",
356 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
357 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800358 } else {
359 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800360 std::string profile_dir = create_primary_current_profile_package_dir_path(
361 user, package_name);
362 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800363 }
364}
365
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800366std::string create_reference_profile_path(const std::string& package_name,
367 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800368 if (is_secondary_dex) {
369 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700370 std::string dex_dir;
371 std::string dex_name;
372 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800373 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800374 return StringPrintf("%s/oat/%s%s",
375 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
376 } else {
377 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800378 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
379 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800380 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700381}
382
Calin Juravle29591732017-11-20 17:46:19 -0800383std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800384 const std::string& profile_name) {
385 std::string ref_profile = create_reference_profile_path(package, profile_name,
386 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800387 return ref_profile + SNAPSHOT_PROFILE_EXT;
388}
389
Jeff Sharkeye3637242015-04-08 20:56:42 -0700390std::vector<userid_t> get_known_users(const char* volume_uuid) {
391 std::vector<userid_t> users;
392
393 // We always have an owner
394 users.push_back(0);
395
396 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
397 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700398 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700399 // Unable to discover other users, but at least return owner
400 PLOG(ERROR) << "Failed to opendir " << path;
401 return users;
402 }
403
404 struct dirent* ent;
405 while ((ent = readdir(dir))) {
406 if (ent->d_type != DT_DIR) {
407 continue;
408 }
409
410 char* end;
411 userid_t user = strtol(ent->d_name, &end, 10);
412 if (*end == '\0' && user != 0) {
413 LOG(DEBUG) << "Found valid user " << user;
414 users.push_back(user);
415 }
416 }
417 closedir(dir);
418
419 return users;
420}
421
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700422int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700423 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700424 FTS *fts;
425 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700426 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700427 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700428 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700429 if (errno != ENOENT) {
430 PLOG(ERROR) << "Failed to fts_open " << path;
431 }
432 return -1;
433 }
Yi Kong954cf642018-07-17 16:16:24 -0700434 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700435 switch (p->fts_info) {
436 case FTS_D:
437 case FTS_DEFAULT:
438 case FTS_F:
439 case FTS_SL:
440 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700441 int32_t uid = p->fts_statp->st_uid;
442 int32_t gid = p->fts_statp->st_gid;
443 int32_t user_uid = multiuser_get_app_id(uid);
444 int32_t user_gid = multiuser_get_app_id(gid);
445 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
446 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
447 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
448 // Don't traverse inside or measure
449 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700450 break;
451 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700452 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700453 break;
454 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700455 if (exclude_gid != -1 && gid == exclude_gid) {
456 break;
457 }
458 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700459 break;
460 }
461 }
462 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700463#if MEASURE_DEBUG
464 if ((include_gid == -1) && (exclude_gid == -1)) {
465 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
466 } else {
467 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
468 << " exclude " << exclude_gid;
469 }
470#endif
471 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700472 return 0;
473}
474
Mike Lockwood94afecf2012-10-24 10:45:23 -0700475/**
476 * Checks whether the package name is valid. Returns -1 on error and
477 * 0 on success.
478 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700479bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700480 // This logic is borrowed from PackageParser.java
481 bool hasSep = false;
482 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700483
Jeff Sharkey367ace22017-03-07 22:12:03 -0700484 auto it = packageName.begin();
485 for (; it != packageName.end() && *it != '-'; it++) {
486 char c = *it;
487 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
488 front = false;
489 continue;
490 }
491 if (!front) {
492 if ((c >= '0' && c <= '9') || c == '_') {
493 continue;
494 }
495 }
496 if (c == '.') {
497 hasSep = true;
498 front = true;
499 continue;
500 }
501 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700502 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700503 }
504
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700505 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700506 LOG(WARNING) << "Missing separator in " << packageName;
507 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700508 }
509
Jeff Sharkey367ace22017-03-07 22:12:03 -0700510 for (; it != packageName.end(); it++) {
511 char c = *it;
512 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
513 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
514 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
515 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700516 }
517
Jeff Sharkey423e7462016-12-09 18:18:43 -0700518 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700519}
520
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100521static int _delete_dir_contents(DIR *d,
522 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700523{
524 int result = 0;
525 struct dirent *de;
526 int dfd;
527
528 dfd = dirfd(d);
529
530 if (dfd < 0) return -1;
531
532 while ((de = readdir(d))) {
533 const char *name = de->d_name;
534
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100535 /* check using the exclusion predicate, if provided */
536 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
537 continue;
538 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700539
540 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700541 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700542 DIR *subdir;
543
544 /* always skip "." and ".." */
545 if (name[0] == '.') {
546 if (name[1] == 0) continue;
547 if ((name[1] == '.') && (name[2] == 0)) continue;
548 }
549
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700550 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700551 if (subfd < 0) {
552 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
553 result = -1;
554 continue;
555 }
556 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700557 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700558 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
559 close(subfd);
560 result = -1;
561 continue;
562 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100563 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700564 result = -1;
565 }
566 closedir(subdir);
567 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
568 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
569 result = -1;
570 }
571 } else {
572 if (unlinkat(dfd, name, 0) < 0) {
573 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
574 result = -1;
575 }
576 }
577 }
578
579 return result;
580}
581
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000582int create_dir_if_needed(const std::string& pathname, mode_t perms) {
583 struct stat st;
584
585 int rc;
586 if ((rc = stat(pathname.c_str(), &st)) != 0) {
587 if (errno == ENOENT) {
588 return mkdir(pathname.c_str(), perms);
589 } else {
590 return rc;
591 }
592 } else if (!S_ISDIR(st.st_mode)) {
593 LOG(DEBUG) << pathname << " is not a folder";
594 return -1;
595 }
596
597 mode_t actual_perms = st.st_mode & ALLPERMS;
598 if (actual_perms != perms) {
599 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
600 return -1;
601 }
602
603 return 0;
604}
605
Calin Juravleb06f98a2016-03-28 15:11:01 +0100606int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700607 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700608}
609
Calin Juravleb06f98a2016-03-28 15:11:01 +0100610int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700611 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700612}
613
Mike Lockwood94afecf2012-10-24 10:45:23 -0700614int delete_dir_contents(const char *pathname,
615 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100616 int (*exclusion_predicate)(const char*, const int),
617 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700618{
619 int res = 0;
620 DIR *d;
621
622 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700623 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100624 if (ignore_if_missing && (errno == ENOENT)) {
625 return 0;
626 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700627 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
628 return -errno;
629 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100630 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700631 closedir(d);
632 if (also_delete_dir) {
633 if (rmdir(pathname)) {
634 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
635 res = -1;
636 }
637 }
638 return res;
639}
640
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800641static std::string make_unique_name(std::string_view suffix) {
642 static constexpr auto uuidStringSize = 36;
643
644 uuid_t guid;
645 uuid_generate(guid);
646
647 std::string name;
648 const auto suffixSize = suffix.size();
649 name.reserve(uuidStringSize + suffixSize);
650
651 name.resize(uuidStringSize);
652 uuid_unparse(guid, name.data());
653 name.append(suffix);
654
655 return name;
656}
657
658static int rename_delete_dir_contents(const std::string& pathname,
659 int (*exclusion_predicate)(const char*, const int),
660 bool ignore_if_missing) {
661 auto temp_dir_name = make_unique_name(deletedSuffix);
662 auto temp_dir_path =
663 base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
664
665 if (::rename(pathname.c_str(), temp_dir_path.c_str())) {
666 if (ignore_if_missing && (errno == ENOENT)) {
667 return 0;
668 }
669 ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), temp_dir_path.c_str(),
670 strerror(errno));
671 return -errno;
672 }
673
674 return delete_dir_contents(temp_dir_path.c_str(), 1, exclusion_predicate, ignore_if_missing);
675}
676
677bool is_renamed_deleted_dir(std::string_view path) {
678 return path.ends_with(deletedSuffix);
679}
680
681int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
682 return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
683}
684
685static auto open_dir(const char* dir) {
686 struct DirCloser {
687 void operator()(DIR* d) const noexcept { ::closedir(d); }
688 };
689 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
690}
691
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800692void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800693 auto dir = open_dir(pathname.c_str());
694 if (!dir) {
695 return;
696 }
697 int dfd = dirfd(dir.get());
698 if (dfd < 0) {
699 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
700 return;
701 }
702
703 struct dirent* de;
704 while ((de = readdir(dir.get()))) {
705 if (de->d_type != DT_DIR) {
706 continue;
707 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800708
709 std::string name{de->d_name};
710 // always skip "." and ".."
711 if (name == "." || name == "..") {
712 continue;
713 }
714
715 if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
716 !is_valid_package_name(name)) {
717 ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800718 // Deleting the content.
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800719 delete_dir_contents_fd(dfd, name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800720 // Deleting the directory
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800721 if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
722 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800723 }
724 }
725 }
726}
727
Mike Lockwood94afecf2012-10-24 10:45:23 -0700728int delete_dir_contents_fd(int dfd, const char *name)
729{
730 int fd, res;
731 DIR *d;
732
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700733 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700734 if (fd < 0) {
735 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
736 return -1;
737 }
738 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700739 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700740 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
741 close(fd);
742 return -1;
743 }
Yi Kong954cf642018-07-17 16:16:24 -0700744 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700745 closedir(d);
746 return res;
747}
748
Robin Lee60fd3fe2014-10-07 16:55:02 +0100749static int _copy_owner_permissions(int srcfd, int dstfd)
750{
751 struct stat st;
752 if (fstat(srcfd, &st) != 0) {
753 return -1;
754 }
755 if (fchmod(dstfd, st.st_mode) != 0) {
756 return -1;
757 }
758 return 0;
759}
760
761static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
762{
763 int result = 0;
764 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
765 ALOGE("_copy_dir_files failed to copy dir permissions\n");
766 }
767 if (fchown(ddfd, owner, group) != 0) {
768 ALOGE("_copy_dir_files failed to change dir owner\n");
769 }
770
771 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700772 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100773 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
774 return -1;
775 }
776 struct dirent *de;
777 while ((de = readdir(ds))) {
778 if (de->d_type != DT_REG) {
779 continue;
780 }
781
782 const char *name = de->d_name;
783 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
784 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
785 if (fsfd == -1 || fdfd == -1) {
786 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
787 } else {
788 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
789 ALOGE("Failed to change file permissions\n");
790 }
791 if (fchown(fdfd, owner, group) != 0) {
792 ALOGE("Failed to change file owner\n");
793 }
794
795 char buf[8192];
796 ssize_t size;
797 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
798 write(fdfd, buf, size);
799 }
800 if (size < 0) {
801 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
802 result = -1;
803 }
804 }
805 close(fdfd);
806 close(fsfd);
807 }
808
809 return result;
810}
811
812int copy_dir_files(const char *srcname,
813 const char *dstname,
814 uid_t owner,
815 uid_t group)
816{
817 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700818 DIR *ds = nullptr;
819 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100820
821 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700822 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100823 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
824 return -errno;
825 }
826
827 mkdir(dstname, 0600);
828 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700829 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100830 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
831 closedir(ds);
832 return -errno;
833 }
834
835 int sdfd = dirfd(ds);
836 int ddfd = dirfd(dd);
837 if (sdfd != -1 && ddfd != -1) {
838 res = _copy_dir_files(sdfd, ddfd, owner, group);
839 } else {
840 res = -errno;
841 }
842 closedir(dd);
843 closedir(ds);
844 return res;
845}
846
Jeff Sharkeya836c472017-04-02 23:29:30 -0600847int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600848 struct statvfs sfs;
849 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600850 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700851 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600852 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700853 return -1;
854 }
855}
856
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600857int get_path_inode(const std::string& path, ino_t *inode) {
858 struct stat buf;
859 memset(&buf, 0, sizeof(buf));
860 if (stat(path.c_str(), &buf) != 0) {
861 PLOG(WARNING) << "Failed to stat " << path;
862 return -1;
863 } else {
864 *inode = buf.st_ino;
865 return 0;
866 }
867}
868
869/**
870 * Write the inode of a specific child file into the given xattr on the
871 * parent directory. This allows you to find the child later, even if its
872 * name is encrypted.
873 */
874int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
875 ino_t inode = 0;
876 uint64_t inode_raw = 0;
877 auto path = StringPrintf("%s/%s", parent.c_str(), name);
878
879 if (get_path_inode(path, &inode) != 0) {
880 // Path probably doesn't exist yet; ignore
881 return 0;
882 }
883
884 // Check to see if already set correctly
885 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
886 if (inode_raw == inode) {
887 // Already set correctly; skip writing
888 return 0;
889 } else {
890 PLOG(WARNING) << "Mismatched inode value; found " << inode
891 << " on disk but marked value was " << inode_raw << "; overwriting";
892 }
893 }
894
895 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600896 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600897 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
898 return -1;
899 } else {
900 return 0;
901 }
902}
903
904/**
905 * Read the inode of a specific child file from the given xattr on the
906 * parent directory. Returns a currently valid path for that child, which
907 * might have an encrypted name.
908 */
909std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
910 ino_t inode = 0;
911 uint64_t inode_raw = 0;
912 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
913
914 // Lookup the inode value written earlier
915 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
916 inode = inode_raw;
917 }
918
919 // For testing purposes, rely on the inode when defined; this could be
920 // optimized to use access() in the future.
921 if (inode != 0) {
922 DIR* dir = opendir(parent.c_str());
923 if (dir == nullptr) {
924 PLOG(ERROR) << "Failed to opendir " << parent;
925 return fallback;
926 }
927
928 struct dirent* ent;
929 while ((ent = readdir(dir))) {
930 if (ent->d_ino == inode) {
931 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
932#if DEBUG_XATTRS
933 if (resolved != fallback) {
934 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
935 << " instead of " << fallback;
936 }
937#endif
938 closedir(dir);
939 return resolved;
940 }
941 }
942 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
943 closedir(dir);
944 return fallback;
945 } else {
946 return fallback;
947 }
948}
949
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900950void remove_path_xattr(const std::string& path, const char* inode_xattr) {
951 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
952 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
953 }
954}
955
Mike Lockwood94afecf2012-10-24 10:45:23 -0700956/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100957 * Validate that the path is valid in the context of the provided directory.
958 * The path is allowed to have at most one subdirectory and no indirections
959 * to top level directories (i.e. have "..").
960 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600961static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000962 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600963 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
964 || dir.find("..") != std::string::npos) {
965 LOG(ERROR) << "Invalid directory " << dir;
966 return -1;
967 }
968 if (path.find("..") != std::string::npos) {
969 LOG(ERROR) << "Invalid path " << path;
970 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100971 }
972
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600973 if (path.compare(0, dir.size(), dir) != 0) {
974 // Common case, path isn't under directory
975 return -1;
976 }
977
978 // Count number of subdirectories
979 auto pos = path.find('/', dir.size());
980 int count = 0;
981 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600982 auto next = path.find('/', pos + 1);
983 if (next > pos + 1) {
984 count++;
985 }
986 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600987 }
988
989 if (count > maxSubdirs) {
990 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100991 return -1;
992 }
993
994 return 0;
995}
996
997/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700998 * Checks whether a path points to a system app (.apk file). Returns 0
999 * if it is a system app or -1 if it is not.
1000 */
1001int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001002 std::string path_ = path;
1003 for (const auto& dir : android_system_dirs) {
1004 if (validate_path(dir, path, 1) == 0) {
1005 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001006 }
1007 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001008 return -1;
1009}
1010
Calin Juravle114f0812017-03-08 19:05:07 -08001011bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -07001012 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -08001013 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1014
Calin Juravle3760ad32017-07-27 16:31:55 -07001015 // Empty paths are not allowed.
1016 if (dex_path.empty()) { return false; }
1017 // First character should always be '/'. No relative paths.
1018 if (dex_path[0] != '/') { return false; }
1019 // The last character should not be '/'.
1020 if (dex_path[dex_path.size() - 1] == '/') { return false; }
1021 // There should be no '.' after the directory marker.
1022 if (dex_path.find("/.") != std::string::npos) { return false; }
1023 // The path should be at most PKG_PATH_MAX long.
1024 if (dex_path.size() > PKG_PATH_MAX) { return false; }
1025
Calin Juravle7d765462017-09-04 15:57:10 -07001026 // The dex_path should be under the app data directory.
1027 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -07001028 ? create_data_user_ce_package_path(
1029 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1030 : create_data_user_de_package_path(
1031 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -07001032
Calin Juravle7d765462017-09-04 15:57:10 -07001033 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1034 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1035 // If that's the case, attempt to validate against the user data link.
1036 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1037 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1038 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1039 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -07001040 return false;
1041 }
Calin Juravle42451c02017-01-17 14:43:25 -08001042 }
Calin Juravle3760ad32017-07-27 16:31:55 -07001043
1044 // If we got here we have a valid path.
1045 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001046}
1047
Mike Lockwood94afecf2012-10-24 10:45:23 -07001048/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001049 * Check whether path points to a valid path for an APK file. The path must
1050 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1051 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1052 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001053 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001054static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1055 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001056 return 0;
shafikb43faa92019-02-19 12:19:48 +00001057 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1058 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001059 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001060 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001061 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001062 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001063 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001064 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001065 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1066 // Rewrite the path as if it were on internal storage, and test that
1067 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1068 if (end != std::string::npos) {
1069 auto modified = path;
1070 modified.replace(0, end + 1, android_data_dir);
1071 return validate_apk_path_internal(modified, maxSubdirs);
1072 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001073 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001074 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001075}
1076
Narayan Kamathd845c962015-06-04 13:20:27 +01001077int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001078 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001079}
1080
1081int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001082 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001083}
1084
Robin Lee095c7632014-04-25 15:05:19 +01001085int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001086 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001087 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1088 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001089
1090 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001091 auto path = create_data_misc_legacy_path(userid);
1092 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001093}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001094
1095int wait_child(pid_t pid)
1096{
1097 int status;
1098 pid_t got_pid;
1099
1100 while (1) {
1101 got_pid = waitpid(pid, &status, 0);
1102 if (got_pid == -1 && errno == EINTR) {
1103 printf("waitpid interrupted, retrying\n");
1104 } else {
1105 break;
1106 }
1107 }
1108 if (got_pid != pid) {
1109 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
1110 (int) pid, (int) got_pid, strerror(errno));
1111 return 1;
1112 }
1113
1114 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1115 return 0;
1116 } else {
1117 return status; /* always nonzero */
1118 }
1119}
1120
Calin Juravle42451c02017-01-17 14:43:25 -08001121/**
1122 * Prepare an app cache directory, which offers to fix-up the GID and
1123 * directory mode flags during a platform upgrade.
1124 * The app cache directory path will be 'parent'/'name'.
1125 */
1126int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1127 uid_t uid, gid_t gid) {
1128 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1129 struct stat st;
1130 if (stat(path.c_str(), &st) != 0) {
1131 if (errno == ENOENT) {
1132 // This is fine, just create it
1133 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1134 PLOG(ERROR) << "Failed to prepare " << path;
1135 return -1;
1136 } else {
1137 return 0;
1138 }
1139 } else {
1140 PLOG(ERROR) << "Failed to stat " << path;
1141 return -1;
1142 }
1143 }
1144
1145 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1146 if (st.st_uid != uid) {
1147 // Mismatched UID is real trouble; we can't recover
1148 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1149 << " but expected " << uid;
1150 return -1;
1151 } else if (st.st_gid == gid && actual_mode == target_mode) {
1152 // Everything looks good!
1153 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001154 } else {
1155 // Mismatched GID/mode is recoverable; fall through to update
1156 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001157 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001158 }
1159
1160 // Directory is owned correctly, but GID or mode mismatch means it's
1161 // probably a platform upgrade so we need to fix them
1162 FTS *fts;
1163 FTSENT *p;
1164 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001165 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001166 PLOG(ERROR) << "Failed to fts_open " << path;
1167 return -1;
1168 }
Yi Kong954cf642018-07-17 16:16:24 -07001169 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001170 switch (p->fts_info) {
1171 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001172 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001173 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1174 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001175 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001176 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001177 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001178 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1179 }
1180 break;
1181 case FTS_SL:
1182 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001183 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001184 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1185 }
1186 break;
1187 }
1188 }
1189 fts_close(fts);
1190 return 0;
1191}
1192
Martijn Coenen771cc342020-02-19 23:26:56 +01001193static const char* kProcFilesystems = "/proc/filesystems";
1194bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001195 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1196 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001197 std::string supported;
1198 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1199 PLOG(ERROR) << "Failed to read supported filesystems";
1200 return false;
1201 }
1202 return supported.find("sdcardfs\n") != std::string::npos;
1203}
1204
1205int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1206 static const bool supportsSdcardFs = supports_sdcardfs();
1207
1208 if (supportsSdcardFs) {
1209 int extGid = multiuser_get_ext_gid(userId, appId);
1210
1211 if (extGid == -1) {
1212 return -1;
1213 }
1214
1215 return GetOccupiedSpaceForGid(uuid, extGid);
1216 } else {
1217 uid_t uid = multiuser_get_uid(userId, appId);
1218 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1219 return GetOccupiedSpaceForProjectId(uuid, projectId);
1220 }
1221}
1222int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1223 static const bool supportsSdcardFs = supports_sdcardfs();
1224
1225 if (supportsSdcardFs) {
1226 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1227
1228 if (extCacheGid == -1) {
1229 return -1;
1230 }
1231
1232 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1233 } else {
1234 uid_t uid = multiuser_get_uid(userId, appId);
1235 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1236 return GetOccupiedSpaceForProjectId(uuid, projectId);
1237 }
1238}
1239
Calin Juravlee61189e2018-01-23 19:54:11 -08001240// Collect all non empty profiles from the given directory and puts then into profile_paths.
1241// The profiles are identified based on PROFILE_EXT extension.
1242// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1243// It returns true if there were no errors at all, and false otherwise.
1244static bool collect_profiles(DIR* d,
1245 const std::string& current_path,
1246 std::vector<std::string>* profiles_paths) {
1247 int32_t dir_fd = dirfd(d);
1248 if (dir_fd < 0) {
1249 return false;
1250 }
1251
1252 bool result = true;
1253 struct dirent* dir_entry;
1254 while ((dir_entry = readdir(d))) {
1255 std::string name = dir_entry->d_name;
1256 std::string local_path = current_path + "/" + name;
1257
1258 if (dir_entry->d_type == DT_REG) {
1259 // Check if this is a non empty profile file.
1260 if (EndsWith(name, PROFILE_EXT)) {
1261 struct stat st;
1262 if (stat(local_path.c_str(), &st) != 0) {
1263 PLOG(WARNING) << "Cannot stat local path " << local_path;
1264 result = false;
1265 continue;
1266 } else if (st.st_size > 0) {
1267 profiles_paths->push_back(local_path);
1268 }
1269 }
1270 } else if (dir_entry->d_type == DT_DIR) {
1271 // always skip "." and ".."
1272 if (name == "." || name == "..") {
1273 continue;
1274 }
1275
1276 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1277 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1278 if (subdir_fd < 0) {
1279 PLOG(WARNING) << "Could not open dir path " << local_path;
1280 result = false;
1281 continue;
1282 }
1283
Mathieu Chartier89883e32018-11-01 11:39:00 -07001284 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001285 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001286 PLOG(WARNING) << "Could not open dir path " << local_path;
1287 result = false;
1288 continue;
1289 }
1290 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1291 result = result && new_result;
1292 if (closedir(subdir) != 0) {
1293 PLOG(WARNING) << "Could not close dir path " << local_path;
1294 }
1295 }
1296 }
1297
1298 return result;
1299}
1300
1301bool collect_profiles(std::vector<std::string>* profiles_paths) {
1302 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001303 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001304 return false;
1305 } else {
1306 return collect_profiles(d, android_profiles_dir, profiles_paths);
1307 }
1308}
1309
Eric Holk2af5e6a2019-01-09 18:17:27 -08001310void drop_capabilities(uid_t uid) {
1311 if (setgid(uid) != 0) {
1312 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1313 exit(DexoptReturnCodes::kSetGid);
1314 }
1315 if (setuid(uid) != 0) {
1316 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1317 exit(DexoptReturnCodes::kSetUid);
1318 }
1319 // drop capabilities
1320 struct __user_cap_header_struct capheader;
1321 struct __user_cap_data_struct capdata[2];
1322 memset(&capheader, 0, sizeof(capheader));
1323 memset(&capdata, 0, sizeof(capdata));
1324 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1325 if (capset(&capheader, &capdata[0]) < 0) {
1326 PLOG(ERROR) << "capset failed";
1327 exit(DexoptReturnCodes::kCapSet);
1328 }
1329}
1330
Andreas Gampe02d0de52015-11-11 20:43:16 -08001331} // namespace installd
1332} // namespace android