blob: 6650b761e1b60b0659da60490ee24aba88e5eb08 [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
Samiul Islamb911bc62022-01-14 16:24:48 +0000200/**
201 * Create the path name where supplemental data for all apps will be stored.
202 * E.g. /data/misc_ce/0/supplemental
203 */
204std::string create_data_misc_supplemental_path(const char* uuid, bool isCeData, userid_t user) {
205 std::string data(create_data_path(uuid));
206 if (isCeData) {
207 return StringPrintf("%s/misc_ce/%d/supplemental", data.c_str(), user);
208 } else {
209 return StringPrintf("%s/misc_de/%d/supplemental", data.c_str(), user);
210 }
211}
212
213/**
214 * Create the path name where code data for all codes in a particular app will be stored.
215 * E.g. /data/misc_ce/0/supplemental/<app-name>
216 */
217std::string create_data_misc_supplemental_package_path(const char* volume_uuid, bool isCeData,
218 userid_t user, const char* package_name) {
219 check_package_name(package_name);
220 return StringPrintf("%s/%s",
221 create_data_misc_supplemental_path(volume_uuid, isCeData, user).c_str(),
222 package_name);
223}
224
225/**
226 * Create the path name where shared code data for a particular app will be stored.
227 * E.g. /data/misc_ce/0/supplemental/<app-name>/shared
228 */
229std::string create_data_misc_supplemental_shared_path(const char* volume_uuid, bool isCeData,
230 userid_t user, const char* package_name) {
231 return StringPrintf("%s/shared",
232 create_data_misc_supplemental_package_path(volume_uuid, isCeData, user,
233 package_name)
234 .c_str());
235}
236
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000237std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000238 return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
239}
240
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000241std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000242 return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
243}
244
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000245std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
246 int32_t snapshot_id) {
247 return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
248 snapshot_id);
249}
250
251std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
252 int32_t snapshot_id) {
253 return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
254 snapshot_id);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000255}
256
Nikita Ioffe8755f792019-01-25 13:54:43 +0000257std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000258 userid_t user, int32_t snapshot_id, const char* package_name) {
259 return StringPrintf("%s/%s",
260 create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
261}
262
263std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
264 userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
265 auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
266 package_name);
267 auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000268 return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
269}
270
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000271std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000272 userid_t user, int32_t snapshot_id, const char* package_name) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000273 return StringPrintf("%s/%s",
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000274 create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000275}
276
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800277/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700278 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700279 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700280std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
281 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700282}
283
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700284std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
285 const char* data_type, const char* package_name) {
286 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
287 data_type, package_name);
288}
289
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600290std::string create_data_misc_legacy_path(userid_t userid) {
291 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
292}
293
Calin Juravle114f0812017-03-08 19:05:07 -0800294std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600295 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000296}
297
Calin Juravle114f0812017-03-08 19:05:07 -0800298std::string create_primary_current_profile_package_dir_path(userid_t user,
299 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800300 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800301 return StringPrintf("%s/%s",
302 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700303}
304
Calin Juravle114f0812017-03-08 19:05:07 -0800305std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600306 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000307}
308
Calin Juravle114f0812017-03-08 19:05:07 -0800309std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800310 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600311 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000312}
313
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700314std::string create_data_dalvik_cache_path() {
315 return "/data/dalvik-cache";
316}
317
Felka Chang2a0a2462019-11-20 14:20:40 +0800318std::string create_system_user_ce_path(userid_t userId) {
319 return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
320}
321
322std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
323 check_package_name(package_name);
324 return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
325}
326
Calin Juravle114f0812017-03-08 19:05:07 -0800327// Keep profile paths in sync with ActivityThread and LoadedApk.
328const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700329const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800330const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700331
Calin Juravle3760ad32017-07-27 16:31:55 -0700332// Gets the parent directory and the file name for the given secondary dex path.
333// Returns true on success, false on failure (if the dex_path does not have the expected
334// structure).
335static bool get_secondary_dex_location(const std::string& dex_path,
336 std::string* out_dir_name, std::string* out_file_name) {
337 size_t dirIndex = dex_path.rfind('/');
338 if (dirIndex == std::string::npos) {
339 return false;
340 }
341 if (dirIndex == dex_path.size() - 1) {
342 return false;
343 }
344 *out_dir_name = dex_path.substr(0, dirIndex);
345 *out_file_name = dex_path.substr(dirIndex + 1);
346
347 return true;
348}
349
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800350std::string create_current_profile_path(userid_t user, const std::string& package_name,
351 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800352 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700353 // Secondary dex current profiles are stored next to the dex files under the oat folder.
354 std::string dex_dir;
355 std::string dex_name;
356 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
357 << "Unexpected dir structure for secondary dex " << location;
358 return StringPrintf("%s/oat/%s%s%s",
359 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
360 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800361 } else {
362 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800363 std::string profile_dir = create_primary_current_profile_package_dir_path(
364 user, package_name);
365 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800366 }
367}
368
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800369std::string create_reference_profile_path(const std::string& package_name,
370 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800371 if (is_secondary_dex) {
372 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700373 std::string dex_dir;
374 std::string dex_name;
375 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800376 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800377 return StringPrintf("%s/oat/%s%s",
378 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
379 } else {
380 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800381 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
382 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800383 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700384}
385
Calin Juravle29591732017-11-20 17:46:19 -0800386std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800387 const std::string& profile_name) {
388 std::string ref_profile = create_reference_profile_path(package, profile_name,
389 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800390 return ref_profile + SNAPSHOT_PROFILE_EXT;
391}
392
Jeff Sharkeye3637242015-04-08 20:56:42 -0700393std::vector<userid_t> get_known_users(const char* volume_uuid) {
394 std::vector<userid_t> users;
395
396 // We always have an owner
397 users.push_back(0);
398
399 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
400 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700401 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700402 // Unable to discover other users, but at least return owner
403 PLOG(ERROR) << "Failed to opendir " << path;
404 return users;
405 }
406
407 struct dirent* ent;
408 while ((ent = readdir(dir))) {
409 if (ent->d_type != DT_DIR) {
410 continue;
411 }
412
413 char* end;
414 userid_t user = strtol(ent->d_name, &end, 10);
415 if (*end == '\0' && user != 0) {
416 LOG(DEBUG) << "Found valid user " << user;
417 users.push_back(user);
418 }
419 }
420 closedir(dir);
421
422 return users;
423}
424
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700425int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700426 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700427 FTS *fts;
428 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700429 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700430 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700431 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700432 if (errno != ENOENT) {
433 PLOG(ERROR) << "Failed to fts_open " << path;
434 }
435 return -1;
436 }
Yi Kong954cf642018-07-17 16:16:24 -0700437 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700438 switch (p->fts_info) {
439 case FTS_D:
440 case FTS_DEFAULT:
441 case FTS_F:
442 case FTS_SL:
443 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700444 int32_t uid = p->fts_statp->st_uid;
445 int32_t gid = p->fts_statp->st_gid;
446 int32_t user_uid = multiuser_get_app_id(uid);
447 int32_t user_gid = multiuser_get_app_id(gid);
448 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
449 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
450 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
451 // Don't traverse inside or measure
452 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700453 break;
454 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700455 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700456 break;
457 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700458 if (exclude_gid != -1 && gid == exclude_gid) {
459 break;
460 }
461 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700462 break;
463 }
464 }
465 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700466#if MEASURE_DEBUG
467 if ((include_gid == -1) && (exclude_gid == -1)) {
468 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
469 } else {
470 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
471 << " exclude " << exclude_gid;
472 }
473#endif
474 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700475 return 0;
476}
477
Mike Lockwood94afecf2012-10-24 10:45:23 -0700478/**
479 * Checks whether the package name is valid. Returns -1 on error and
480 * 0 on success.
481 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700482bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700483 // This logic is borrowed from PackageParser.java
484 bool hasSep = false;
485 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700486
Jeff Sharkey367ace22017-03-07 22:12:03 -0700487 auto it = packageName.begin();
488 for (; it != packageName.end() && *it != '-'; it++) {
489 char c = *it;
490 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
491 front = false;
492 continue;
493 }
494 if (!front) {
495 if ((c >= '0' && c <= '9') || c == '_') {
496 continue;
497 }
498 }
499 if (c == '.') {
500 hasSep = true;
501 front = true;
502 continue;
503 }
504 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700505 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700506 }
507
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700508 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700509 LOG(WARNING) << "Missing separator in " << packageName;
510 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700511 }
512
Jeff Sharkey367ace22017-03-07 22:12:03 -0700513 for (; it != packageName.end(); it++) {
514 char c = *it;
515 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
516 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
517 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
518 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700519 }
520
Jeff Sharkey423e7462016-12-09 18:18:43 -0700521 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700522}
523
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100524static int _delete_dir_contents(DIR *d,
525 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700526{
527 int result = 0;
528 struct dirent *de;
529 int dfd;
530
531 dfd = dirfd(d);
532
533 if (dfd < 0) return -1;
534
535 while ((de = readdir(d))) {
536 const char *name = de->d_name;
537
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100538 /* check using the exclusion predicate, if provided */
539 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
540 continue;
541 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700542
543 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700544 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700545 DIR *subdir;
546
547 /* always skip "." and ".." */
548 if (name[0] == '.') {
549 if (name[1] == 0) continue;
550 if ((name[1] == '.') && (name[2] == 0)) continue;
551 }
552
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700553 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700554 if (subfd < 0) {
555 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
556 result = -1;
557 continue;
558 }
559 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700560 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700561 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
562 close(subfd);
563 result = -1;
564 continue;
565 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100566 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700567 result = -1;
568 }
569 closedir(subdir);
570 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
571 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
572 result = -1;
573 }
574 } else {
575 if (unlinkat(dfd, name, 0) < 0) {
576 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
577 result = -1;
578 }
579 }
580 }
581
582 return result;
583}
584
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000585int create_dir_if_needed(const std::string& pathname, mode_t perms) {
586 struct stat st;
587
588 int rc;
589 if ((rc = stat(pathname.c_str(), &st)) != 0) {
590 if (errno == ENOENT) {
591 return mkdir(pathname.c_str(), perms);
592 } else {
593 return rc;
594 }
595 } else if (!S_ISDIR(st.st_mode)) {
596 LOG(DEBUG) << pathname << " is not a folder";
597 return -1;
598 }
599
600 mode_t actual_perms = st.st_mode & ALLPERMS;
601 if (actual_perms != perms) {
602 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
603 return -1;
604 }
605
606 return 0;
607}
608
Calin Juravleb06f98a2016-03-28 15:11:01 +0100609int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700610 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700611}
612
Calin Juravleb06f98a2016-03-28 15:11:01 +0100613int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700614 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700615}
616
Mike Lockwood94afecf2012-10-24 10:45:23 -0700617int delete_dir_contents(const char *pathname,
618 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100619 int (*exclusion_predicate)(const char*, const int),
620 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700621{
622 int res = 0;
623 DIR *d;
624
625 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700626 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100627 if (ignore_if_missing && (errno == ENOENT)) {
628 return 0;
629 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700630 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
631 return -errno;
632 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100633 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700634 closedir(d);
635 if (also_delete_dir) {
636 if (rmdir(pathname)) {
637 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
638 res = -1;
639 }
640 }
641 return res;
642}
643
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800644static std::string make_unique_name(std::string_view suffix) {
645 static constexpr auto uuidStringSize = 36;
646
647 uuid_t guid;
648 uuid_generate(guid);
649
650 std::string name;
651 const auto suffixSize = suffix.size();
652 name.reserve(uuidStringSize + suffixSize);
653
654 name.resize(uuidStringSize);
655 uuid_unparse(guid, name.data());
656 name.append(suffix);
657
658 return name;
659}
660
661static int rename_delete_dir_contents(const std::string& pathname,
662 int (*exclusion_predicate)(const char*, const int),
663 bool ignore_if_missing) {
664 auto temp_dir_name = make_unique_name(deletedSuffix);
665 auto temp_dir_path =
666 base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
667
668 if (::rename(pathname.c_str(), temp_dir_path.c_str())) {
669 if (ignore_if_missing && (errno == ENOENT)) {
670 return 0;
671 }
672 ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), temp_dir_path.c_str(),
673 strerror(errno));
674 return -errno;
675 }
676
677 return delete_dir_contents(temp_dir_path.c_str(), 1, exclusion_predicate, ignore_if_missing);
678}
679
Alex Buynytskyy4ab5d532022-02-17 21:20:10 +0000680bool is_renamed_deleted_dir(const std::string& path) {
681 if (path.size() < deletedSuffix.size()) {
682 return false;
683 }
684 std::string_view pathSuffix{path.c_str() + path.size() - deletedSuffix.size()};
685 return pathSuffix == deletedSuffix;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800686}
687
688int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
689 return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
690}
691
692static auto open_dir(const char* dir) {
693 struct DirCloser {
694 void operator()(DIR* d) const noexcept { ::closedir(d); }
695 };
696 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
697}
698
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800699void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800700 auto dir = open_dir(pathname.c_str());
701 if (!dir) {
702 return;
703 }
704 int dfd = dirfd(dir.get());
705 if (dfd < 0) {
706 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
707 return;
708 }
709
710 struct dirent* de;
711 while ((de = readdir(dir.get()))) {
712 if (de->d_type != DT_DIR) {
713 continue;
714 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800715
716 std::string name{de->d_name};
717 // always skip "." and ".."
718 if (name == "." || name == "..") {
719 continue;
720 }
721
722 if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
723 !is_valid_package_name(name)) {
724 ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800725 // Deleting the content.
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800726 delete_dir_contents_fd(dfd, name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800727 // Deleting the directory
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800728 if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
729 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800730 }
731 }
732 }
733}
734
Mike Lockwood94afecf2012-10-24 10:45:23 -0700735int delete_dir_contents_fd(int dfd, const char *name)
736{
737 int fd, res;
738 DIR *d;
739
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700740 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700741 if (fd < 0) {
742 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
743 return -1;
744 }
745 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700746 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700747 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
748 close(fd);
749 return -1;
750 }
Yi Kong954cf642018-07-17 16:16:24 -0700751 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700752 closedir(d);
753 return res;
754}
755
Robin Lee60fd3fe2014-10-07 16:55:02 +0100756static int _copy_owner_permissions(int srcfd, int dstfd)
757{
758 struct stat st;
759 if (fstat(srcfd, &st) != 0) {
760 return -1;
761 }
762 if (fchmod(dstfd, st.st_mode) != 0) {
763 return -1;
764 }
765 return 0;
766}
767
768static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
769{
770 int result = 0;
771 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
772 ALOGE("_copy_dir_files failed to copy dir permissions\n");
773 }
774 if (fchown(ddfd, owner, group) != 0) {
775 ALOGE("_copy_dir_files failed to change dir owner\n");
776 }
777
778 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700779 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100780 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
781 return -1;
782 }
783 struct dirent *de;
784 while ((de = readdir(ds))) {
785 if (de->d_type != DT_REG) {
786 continue;
787 }
788
789 const char *name = de->d_name;
790 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
791 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
792 if (fsfd == -1 || fdfd == -1) {
793 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
794 } else {
795 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
796 ALOGE("Failed to change file permissions\n");
797 }
798 if (fchown(fdfd, owner, group) != 0) {
799 ALOGE("Failed to change file owner\n");
800 }
801
802 char buf[8192];
803 ssize_t size;
804 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
805 write(fdfd, buf, size);
806 }
807 if (size < 0) {
808 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
809 result = -1;
810 }
811 }
812 close(fdfd);
813 close(fsfd);
814 }
815
816 return result;
817}
818
819int copy_dir_files(const char *srcname,
820 const char *dstname,
821 uid_t owner,
822 uid_t group)
823{
824 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700825 DIR *ds = nullptr;
826 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100827
828 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700829 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100830 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
831 return -errno;
832 }
833
834 mkdir(dstname, 0600);
835 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700836 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100837 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
838 closedir(ds);
839 return -errno;
840 }
841
842 int sdfd = dirfd(ds);
843 int ddfd = dirfd(dd);
844 if (sdfd != -1 && ddfd != -1) {
845 res = _copy_dir_files(sdfd, ddfd, owner, group);
846 } else {
847 res = -errno;
848 }
849 closedir(dd);
850 closedir(ds);
851 return res;
852}
853
Jeff Sharkeya836c472017-04-02 23:29:30 -0600854int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600855 struct statvfs sfs;
856 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600857 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700858 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600859 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700860 return -1;
861 }
862}
863
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600864int get_path_inode(const std::string& path, ino_t *inode) {
865 struct stat buf;
866 memset(&buf, 0, sizeof(buf));
867 if (stat(path.c_str(), &buf) != 0) {
868 PLOG(WARNING) << "Failed to stat " << path;
869 return -1;
870 } else {
871 *inode = buf.st_ino;
872 return 0;
873 }
874}
875
876/**
877 * Write the inode of a specific child file into the given xattr on the
878 * parent directory. This allows you to find the child later, even if its
879 * name is encrypted.
880 */
881int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
882 ino_t inode = 0;
883 uint64_t inode_raw = 0;
884 auto path = StringPrintf("%s/%s", parent.c_str(), name);
885
886 if (get_path_inode(path, &inode) != 0) {
887 // Path probably doesn't exist yet; ignore
888 return 0;
889 }
890
891 // Check to see if already set correctly
892 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
893 if (inode_raw == inode) {
894 // Already set correctly; skip writing
895 return 0;
896 } else {
897 PLOG(WARNING) << "Mismatched inode value; found " << inode
898 << " on disk but marked value was " << inode_raw << "; overwriting";
899 }
900 }
901
902 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600903 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600904 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
905 return -1;
906 } else {
907 return 0;
908 }
909}
910
911/**
912 * Read the inode of a specific child file from the given xattr on the
913 * parent directory. Returns a currently valid path for that child, which
914 * might have an encrypted name.
915 */
916std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
917 ino_t inode = 0;
918 uint64_t inode_raw = 0;
919 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
920
921 // Lookup the inode value written earlier
922 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
923 inode = inode_raw;
924 }
925
926 // For testing purposes, rely on the inode when defined; this could be
927 // optimized to use access() in the future.
928 if (inode != 0) {
929 DIR* dir = opendir(parent.c_str());
930 if (dir == nullptr) {
931 PLOG(ERROR) << "Failed to opendir " << parent;
932 return fallback;
933 }
934
935 struct dirent* ent;
936 while ((ent = readdir(dir))) {
937 if (ent->d_ino == inode) {
938 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
939#if DEBUG_XATTRS
940 if (resolved != fallback) {
941 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
942 << " instead of " << fallback;
943 }
944#endif
945 closedir(dir);
946 return resolved;
947 }
948 }
949 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
950 closedir(dir);
951 return fallback;
952 } else {
953 return fallback;
954 }
955}
956
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900957void remove_path_xattr(const std::string& path, const char* inode_xattr) {
958 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
959 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
960 }
961}
962
Mike Lockwood94afecf2012-10-24 10:45:23 -0700963/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100964 * Validate that the path is valid in the context of the provided directory.
965 * The path is allowed to have at most one subdirectory and no indirections
966 * to top level directories (i.e. have "..").
967 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600968static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000969 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600970 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
971 || dir.find("..") != std::string::npos) {
972 LOG(ERROR) << "Invalid directory " << dir;
973 return -1;
974 }
975 if (path.find("..") != std::string::npos) {
976 LOG(ERROR) << "Invalid path " << path;
977 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100978 }
979
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600980 if (path.compare(0, dir.size(), dir) != 0) {
981 // Common case, path isn't under directory
982 return -1;
983 }
984
985 // Count number of subdirectories
986 auto pos = path.find('/', dir.size());
987 int count = 0;
988 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600989 auto next = path.find('/', pos + 1);
990 if (next > pos + 1) {
991 count++;
992 }
993 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600994 }
995
996 if (count > maxSubdirs) {
997 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100998 return -1;
999 }
1000
1001 return 0;
1002}
1003
1004/**
Mike Lockwood94afecf2012-10-24 10:45:23 -07001005 * Checks whether a path points to a system app (.apk file). Returns 0
1006 * if it is a system app or -1 if it is not.
1007 */
1008int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001009 std::string path_ = path;
1010 for (const auto& dir : android_system_dirs) {
1011 if (validate_path(dir, path, 1) == 0) {
1012 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001013 }
1014 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001015 return -1;
1016}
1017
Calin Juravle114f0812017-03-08 19:05:07 -08001018bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -07001019 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -08001020 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1021
Calin Juravle3760ad32017-07-27 16:31:55 -07001022 // Empty paths are not allowed.
1023 if (dex_path.empty()) { return false; }
1024 // First character should always be '/'. No relative paths.
1025 if (dex_path[0] != '/') { return false; }
1026 // The last character should not be '/'.
1027 if (dex_path[dex_path.size() - 1] == '/') { return false; }
1028 // There should be no '.' after the directory marker.
1029 if (dex_path.find("/.") != std::string::npos) { return false; }
1030 // The path should be at most PKG_PATH_MAX long.
1031 if (dex_path.size() > PKG_PATH_MAX) { return false; }
1032
Calin Juravle7d765462017-09-04 15:57:10 -07001033 // The dex_path should be under the app data directory.
1034 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -07001035 ? create_data_user_ce_package_path(
1036 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1037 : create_data_user_de_package_path(
1038 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -07001039
Calin Juravle7d765462017-09-04 15:57:10 -07001040 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1041 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1042 // If that's the case, attempt to validate against the user data link.
1043 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1044 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1045 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1046 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -07001047 return false;
1048 }
Calin Juravle42451c02017-01-17 14:43:25 -08001049 }
Calin Juravle3760ad32017-07-27 16:31:55 -07001050
1051 // If we got here we have a valid path.
1052 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001053}
1054
Mike Lockwood94afecf2012-10-24 10:45:23 -07001055/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001056 * Check whether path points to a valid path for an APK file. The path must
1057 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1058 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1059 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001060 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001061static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1062 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001063 return 0;
shafikb43faa92019-02-19 12:19:48 +00001064 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1065 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001066 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001067 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001068 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001069 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001070 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001071 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001072 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1073 // Rewrite the path as if it were on internal storage, and test that
1074 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1075 if (end != std::string::npos) {
1076 auto modified = path;
1077 modified.replace(0, end + 1, android_data_dir);
1078 return validate_apk_path_internal(modified, maxSubdirs);
1079 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001080 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001081 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001082}
1083
Narayan Kamathd845c962015-06-04 13:20:27 +01001084int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001085 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001086}
1087
1088int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001089 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001090}
1091
Robin Lee095c7632014-04-25 15:05:19 +01001092int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001093 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001094 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1095 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001096
1097 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001098 auto path = create_data_misc_legacy_path(userid);
1099 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001100}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001101
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001102static int wait_child(pid_t pid) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001103 int status;
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001104 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, /*options=*/0));
Andreas Gampe02d0de52015-11-11 20:43:16 -08001105
Andreas Gampe02d0de52015-11-11 20:43:16 -08001106 if (got_pid != pid) {
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001107 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
1108 return W_EXITCODE(/*exit_code=*/255, /*signal_number=*/0);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001109 }
1110
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001111 return status;
1112}
1113
1114int wait_child_with_timeout(pid_t pid, int timeout_ms) {
1115 int pidfd = pidfd_open(pid, /*flags=*/0);
1116 if (pidfd < 0) {
1117 PLOG(ERROR) << "pidfd_open failed for pid " << pid;
1118 kill(pid, SIGKILL);
1119 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001120 }
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001121
1122 struct pollfd pfd;
1123 pfd.fd = pidfd;
1124 pfd.events = POLLIN;
1125 int poll_ret = TEMP_FAILURE_RETRY(poll(&pfd, /*nfds=*/1, timeout_ms));
1126
1127 close(pidfd);
1128
1129 if (poll_ret < 0) {
1130 PLOG(ERROR) << "poll failed for pid " << pid;
1131 kill(pid, SIGKILL);
1132 return wait_child(pid);
1133 }
1134 if (poll_ret == 0) {
1135 LOG(WARNING) << "Child process " << pid << " timed out after " << timeout_ms
1136 << "ms. Killing it";
1137 kill(pid, SIGKILL);
1138 return wait_child(pid);
1139 }
1140 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001141}
1142
Calin Juravle42451c02017-01-17 14:43:25 -08001143/**
1144 * Prepare an app cache directory, which offers to fix-up the GID and
1145 * directory mode flags during a platform upgrade.
1146 * The app cache directory path will be 'parent'/'name'.
1147 */
1148int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1149 uid_t uid, gid_t gid) {
1150 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1151 struct stat st;
1152 if (stat(path.c_str(), &st) != 0) {
1153 if (errno == ENOENT) {
1154 // This is fine, just create it
1155 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1156 PLOG(ERROR) << "Failed to prepare " << path;
1157 return -1;
1158 } else {
1159 return 0;
1160 }
1161 } else {
1162 PLOG(ERROR) << "Failed to stat " << path;
1163 return -1;
1164 }
1165 }
1166
1167 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1168 if (st.st_uid != uid) {
1169 // Mismatched UID is real trouble; we can't recover
1170 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1171 << " but expected " << uid;
1172 return -1;
1173 } else if (st.st_gid == gid && actual_mode == target_mode) {
1174 // Everything looks good!
1175 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001176 } else {
1177 // Mismatched GID/mode is recoverable; fall through to update
1178 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001179 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001180 }
1181
1182 // Directory is owned correctly, but GID or mode mismatch means it's
1183 // probably a platform upgrade so we need to fix them
1184 FTS *fts;
1185 FTSENT *p;
1186 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001187 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001188 PLOG(ERROR) << "Failed to fts_open " << path;
1189 return -1;
1190 }
Yi Kong954cf642018-07-17 16:16:24 -07001191 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001192 switch (p->fts_info) {
1193 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001194 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001195 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1196 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001197 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001198 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001199 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001200 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1201 }
1202 break;
1203 case FTS_SL:
1204 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001205 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001206 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1207 }
1208 break;
1209 }
1210 }
1211 fts_close(fts);
1212 return 0;
1213}
1214
Martijn Coenen771cc342020-02-19 23:26:56 +01001215static const char* kProcFilesystems = "/proc/filesystems";
1216bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001217 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1218 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001219 std::string supported;
1220 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1221 PLOG(ERROR) << "Failed to read supported filesystems";
1222 return false;
1223 }
1224 return supported.find("sdcardfs\n") != std::string::npos;
1225}
1226
1227int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1228 static const bool supportsSdcardFs = supports_sdcardfs();
1229
1230 if (supportsSdcardFs) {
1231 int extGid = multiuser_get_ext_gid(userId, appId);
1232
1233 if (extGid == -1) {
1234 return -1;
1235 }
1236
1237 return GetOccupiedSpaceForGid(uuid, extGid);
1238 } else {
1239 uid_t uid = multiuser_get_uid(userId, appId);
1240 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1241 return GetOccupiedSpaceForProjectId(uuid, projectId);
1242 }
1243}
1244int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1245 static const bool supportsSdcardFs = supports_sdcardfs();
1246
1247 if (supportsSdcardFs) {
1248 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1249
1250 if (extCacheGid == -1) {
1251 return -1;
1252 }
1253
1254 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1255 } else {
1256 uid_t uid = multiuser_get_uid(userId, appId);
1257 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1258 return GetOccupiedSpaceForProjectId(uuid, projectId);
1259 }
1260}
1261
Calin Juravlee61189e2018-01-23 19:54:11 -08001262// Collect all non empty profiles from the given directory and puts then into profile_paths.
1263// The profiles are identified based on PROFILE_EXT extension.
1264// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1265// It returns true if there were no errors at all, and false otherwise.
1266static bool collect_profiles(DIR* d,
1267 const std::string& current_path,
1268 std::vector<std::string>* profiles_paths) {
1269 int32_t dir_fd = dirfd(d);
1270 if (dir_fd < 0) {
1271 return false;
1272 }
1273
1274 bool result = true;
1275 struct dirent* dir_entry;
1276 while ((dir_entry = readdir(d))) {
1277 std::string name = dir_entry->d_name;
1278 std::string local_path = current_path + "/" + name;
1279
1280 if (dir_entry->d_type == DT_REG) {
1281 // Check if this is a non empty profile file.
1282 if (EndsWith(name, PROFILE_EXT)) {
1283 struct stat st;
1284 if (stat(local_path.c_str(), &st) != 0) {
1285 PLOG(WARNING) << "Cannot stat local path " << local_path;
1286 result = false;
1287 continue;
1288 } else if (st.st_size > 0) {
1289 profiles_paths->push_back(local_path);
1290 }
1291 }
1292 } else if (dir_entry->d_type == DT_DIR) {
1293 // always skip "." and ".."
1294 if (name == "." || name == "..") {
1295 continue;
1296 }
1297
1298 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1299 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1300 if (subdir_fd < 0) {
1301 PLOG(WARNING) << "Could not open dir path " << local_path;
1302 result = false;
1303 continue;
1304 }
1305
Mathieu Chartier89883e32018-11-01 11:39:00 -07001306 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001307 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001308 PLOG(WARNING) << "Could not open dir path " << local_path;
1309 result = false;
1310 continue;
1311 }
1312 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1313 result = result && new_result;
1314 if (closedir(subdir) != 0) {
1315 PLOG(WARNING) << "Could not close dir path " << local_path;
1316 }
1317 }
1318 }
1319
1320 return result;
1321}
1322
1323bool collect_profiles(std::vector<std::string>* profiles_paths) {
1324 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001325 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001326 return false;
1327 } else {
1328 return collect_profiles(d, android_profiles_dir, profiles_paths);
1329 }
1330}
1331
Eric Holk2af5e6a2019-01-09 18:17:27 -08001332void drop_capabilities(uid_t uid) {
1333 if (setgid(uid) != 0) {
1334 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1335 exit(DexoptReturnCodes::kSetGid);
1336 }
1337 if (setuid(uid) != 0) {
1338 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1339 exit(DexoptReturnCodes::kSetUid);
1340 }
1341 // drop capabilities
1342 struct __user_cap_header_struct capheader;
1343 struct __user_cap_data_struct capdata[2];
1344 memset(&capheader, 0, sizeof(capheader));
1345 memset(&capdata, 0, sizeof(capdata));
1346 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1347 if (capset(&capheader, &capdata[0]) < 0) {
1348 PLOG(ERROR) << "capset failed";
1349 exit(DexoptReturnCodes::kCapSet);
1350 }
1351}
1352
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001353bool remove_file_at_fd(int fd, /*out*/ std::string* path) {
1354 char path_buffer[PATH_MAX + 1];
1355 std::string proc_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
1356 ssize_t len = readlink(proc_path.c_str(), path_buffer, PATH_MAX);
1357 if (len < 0) {
1358 PLOG(WARNING) << "Could not remove file at fd " << fd << ": Failed to get file path";
1359 return false;
1360 }
1361 path_buffer[len] = '\0';
1362 if (path != nullptr) {
1363 *path = path_buffer;
1364 }
1365 if (unlink(path_buffer) != 0) {
1366 if (errno == ENOENT) {
1367 return true;
1368 }
1369 PLOG(WARNING) << "Could not remove file at path " << path_buffer;
1370 return false;
1371 }
1372 return true;
1373}
1374
Andreas Gampe02d0de52015-11-11 20:43:16 -08001375} // namespace installd
1376} // namespace android