blob: fd4d7bd3603fb623c6b44f22a94f1e8112a7751f [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>
Shikha Malhotra7fa4f882022-01-12 21:05:31 +000040#include <linux/fs.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070041#include <log/log.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080042#include <private/android_filesystem_config.h>
Martijn Coenen771cc342020-02-19 23:26:56 +010043#include <private/android_projectid_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070044
Eric Holk2af5e6a2019-01-09 18:17:27 -080045#include "dexopt_return_codes.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080046#include "globals.h" // extern variables.
Martijn Coenen771cc342020-02-19 23:26:56 +010047#include "QuotaUtils.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080048
49#ifndef LOG_TAG
50#define LOG_TAG "installd"
51#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060052
Jeff Sharkey9a998f42016-07-14 18:16:22 -060053#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070054
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080055using android::base::Dirname;
Calin Juravlee61189e2018-01-23 19:54:11 -080056using android::base::EndsWith;
Mathieu Chartier89883e32018-11-01 11:39:00 -070057using android::base::Fdopendir;
Jeff Sharkeyc03de092015-04-07 18:14:05 -070058using android::base::StringPrintf;
Calin Juravlee61189e2018-01-23 19:54:11 -080059using android::base::unique_fd;
Mike Lockwood94afecf2012-10-24 10:45:23 -070060
Andreas Gampe02d0de52015-11-11 20:43:16 -080061namespace android {
62namespace installd {
63
Alex Buynytskyy038a19b2022-02-09 19:51:52 -080064using namespace std::literals;
65
66static constexpr auto deletedSuffix = "==deleted=="sv;
67
Jeff Sharkeyc03de092015-04-07 18:14:05 -070068/**
69 * Check that given string is valid filename, and that it attempts no
70 * parent or child directory traversal.
71 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070072bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070073 if (name.empty() || (name == ".") || (name == "..")
74 || (name.find('/') != std::string::npos)) {
75 return false;
76 } else {
77 return true;
78 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070079}
80
Calin Juravle6a1648e2016-02-01 12:12:16 +000081static void check_package_name(const char* package_name) {
82 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070083 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000084}
85
Nikita Ioffe8755f792019-01-25 13:54:43 +000086static std::string resolve_ce_path_by_inode_or_fallback(const std::string& root_path,
87 ino_t ce_data_inode, const std::string& fallback) {
88 if (ce_data_inode != 0) {
89 DIR* dir = opendir(root_path.c_str());
90 if (dir == nullptr) {
91 PLOG(ERROR) << "Failed to opendir " << root_path;
92 return fallback;
93 }
94
95 struct dirent* ent;
96 while ((ent = readdir(dir))) {
97 if (ent->d_ino == ce_data_inode) {
98 auto resolved = StringPrintf("%s/%s", root_path.c_str(), ent->d_name);
99 if (resolved != fallback) {
100 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
101 << " instead of " << fallback;
102 }
103 closedir(dir);
104 return resolved;
105 }
106 }
107 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
108 closedir(dir);
109 return fallback;
110 } else {
111 return fallback;
112 }
113}
114
Mike Lockwood94afecf2012-10-24 10:45:23 -0700115/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700116 * Create the path name where package data should be stored for the given
117 * volume UUID, package name, and user ID. An empty UUID is assumed to be
118 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700119 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600120std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700121 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000122 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700123 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600124 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
125}
126
Calin Juravle7d765462017-09-04 15:57:10 -0700127/**
128 * Create the path name where package data should be stored for the given
129 * volume UUID, package name, and user ID. An empty UUID is assumed to be
130 * internal storage.
131 * Compared to create_data_user_ce_package_path this method always return the
132 * ".../user/..." directory.
133 */
134std::string create_data_user_ce_package_path_as_user_link(
135 const char* volume_uuid, userid_t userid, const char* package_name) {
136 check_package_name(package_name);
137 std::string data(create_data_path(volume_uuid));
138 return StringPrintf("%s/user/%u/%s", data.c_str(), userid, package_name);
139}
140
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600141std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
142 const char* package_name, ino_t ce_data_inode) {
143 // For testing purposes, rely on the inode when defined; this could be
144 // optimized to use access() in the future.
145 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000146 auto user_path = create_data_user_ce_path(volume_uuid, user);
147 return resolve_ce_path_by_inode_or_fallback(user_path, ce_data_inode, fallback);
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700148}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700149
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800150std::string create_data_user_de_package_path(const char* volume_uuid,
151 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000152 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800153 return StringPrintf("%s/%s",
154 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
155}
156
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700157std::string create_data_path(const char* volume_uuid) {
158 if (volume_uuid == nullptr) {
159 return "/data";
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700160 } else if (!strcmp(volume_uuid, "TEST")) {
161 CHECK(property_get_bool("ro.debuggable", false));
162 return "/data/local/tmp";
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700163 } else {
164 CHECK(is_valid_filename(volume_uuid));
165 return StringPrintf("/mnt/expand/%s", volume_uuid);
166 }
167}
168
Mike Lockwood94afecf2012-10-24 10:45:23 -0700169/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700170 * Create the path name for app data.
171 */
172std::string create_data_app_path(const char* volume_uuid) {
173 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
174}
175
176/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700177 * Create the path name for user data for a certain userid.
cjbao75d4e572017-04-12 00:12:24 +0800178 * Keep same implementation as vold to minimize path walking overhead
Mike Lockwood94afecf2012-10-24 10:45:23 -0700179 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600180std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700181 std::string data(create_data_path(volume_uuid));
cjbao75d4e572017-04-12 00:12:24 +0800182 if (volume_uuid == nullptr && userid == 0) {
183 std::string legacy = StringPrintf("%s/data", data.c_str());
184 struct stat sb;
185 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
186 /* /data/data is dir, return /data/data for legacy system */
187 return legacy;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700188 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700189 }
cjbao75d4e572017-04-12 00:12:24 +0800190 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700191}
192
193/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800194 * Create the path name for device encrypted user data for a certain userid.
195 */
196std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
197 std::string data(create_data_path(volume_uuid));
198 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
199}
200
Samiul Islamb911bc62022-01-14 16:24:48 +0000201/**
Nikita Ioffe9c3e8f52022-02-21 19:02:05 +0000202 * Create the path name where sdk_sandbox data for all apps will be stored.
203 * E.g. /data/misc_ce/0/sdksandbox
Samiul Islamb911bc62022-01-14 16:24:48 +0000204 */
Nikita Ioffe9c3e8f52022-02-21 19:02:05 +0000205std::string create_data_misc_sdk_sandbox_path(const char* uuid, bool isCeData, userid_t user) {
Samiul Islamb911bc62022-01-14 16:24:48 +0000206 std::string data(create_data_path(uuid));
207 if (isCeData) {
Nikita Ioffe9c3e8f52022-02-21 19:02:05 +0000208 return StringPrintf("%s/misc_ce/%d/sdksandbox", data.c_str(), user);
Samiul Islamb911bc62022-01-14 16:24:48 +0000209 } else {
Nikita Ioffe9c3e8f52022-02-21 19:02:05 +0000210 return StringPrintf("%s/misc_de/%d/sdksandbox", data.c_str(), user);
Samiul Islamb911bc62022-01-14 16:24:48 +0000211 }
212}
213
214/**
215 * Create the path name where code data for all codes in a particular app will be stored.
Samiul Islamb9e96bf2022-02-03 12:45:51 +0000216 * E.g. /data/misc_ce/0/sdksandbox/<package-name>
Samiul Islamb911bc62022-01-14 16:24:48 +0000217 */
Nikita Ioffe9c3e8f52022-02-21 19:02:05 +0000218std::string create_data_misc_sdk_sandbox_package_path(const char* volume_uuid, bool isCeData,
219 userid_t user, const char* package_name) {
Samiul Islamb911bc62022-01-14 16:24:48 +0000220 check_package_name(package_name);
221 return StringPrintf("%s/%s",
Nikita Ioffe9c3e8f52022-02-21 19:02:05 +0000222 create_data_misc_sdk_sandbox_path(volume_uuid, isCeData, user).c_str(),
Samiul Islamb911bc62022-01-14 16:24:48 +0000223 package_name);
224}
225
226/**
227 * Create the path name where shared code data for a particular app will be stored.
Samiul Islamb9e96bf2022-02-03 12:45:51 +0000228 * E.g. /data/misc_ce/0/sdksandbox/<package-name>/shared
Samiul Islamb911bc62022-01-14 16:24:48 +0000229 */
Nikita Ioffe9c3e8f52022-02-21 19:02:05 +0000230std::string create_data_misc_sdk_sandbox_shared_path(const char* volume_uuid, bool isCeData,
231 userid_t user, const char* package_name) {
Samiul Islamb911bc62022-01-14 16:24:48 +0000232 return StringPrintf("%s/shared",
Nikita Ioffe9c3e8f52022-02-21 19:02:05 +0000233 create_data_misc_sdk_sandbox_package_path(volume_uuid, isCeData, user,
234 package_name)
Samiul Islamb911bc62022-01-14 16:24:48 +0000235 .c_str());
236}
237
Samiul Islamb9e96bf2022-02-03 12:45:51 +0000238/**
239 * Create the path name where per-code level data for a particular app will be stored.
240 * E.g. /data/misc_ce/0/sdksandbox/<package-name>/<sdk-name>-<random-suffix>
241 */
242std::string create_data_misc_sdk_sandbox_sdk_path(const char* volume_uuid, bool isCeData,
243 userid_t user, const char* package_name,
244 const char* sdk_name, const char* randomSuffix) {
245 check_package_name(sdk_name);
246 auto package_path =
247 create_data_misc_sdk_sandbox_package_path(volume_uuid, isCeData, user, package_name);
248 return StringPrintf("%s/%s@%s", package_path.c_str(), sdk_name, randomSuffix);
249}
250
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000251std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000252 return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
253}
254
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000255std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000256 return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
257}
258
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000259std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
260 int32_t snapshot_id) {
261 return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
262 snapshot_id);
263}
264
265std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
266 int32_t snapshot_id) {
267 return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
268 snapshot_id);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000269}
270
Nikita Ioffe8755f792019-01-25 13:54:43 +0000271std::string create_data_misc_ce_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) {
273 return StringPrintf("%s/%s",
274 create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
275}
276
277std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
278 userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
279 auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
280 package_name);
281 auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000282 return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
283}
284
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000285std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000286 userid_t user, int32_t snapshot_id, const char* package_name) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000287 return StringPrintf("%s/%s",
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000288 create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000289}
290
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800291/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700292 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700293 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700294std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
295 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700296}
297
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700298std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
299 const char* data_type, const char* package_name) {
300 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
301 data_type, package_name);
302}
303
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600304std::string create_data_misc_legacy_path(userid_t userid) {
305 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
306}
307
Calin Juravle114f0812017-03-08 19:05:07 -0800308std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600309 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000310}
311
Calin Juravle114f0812017-03-08 19:05:07 -0800312std::string create_primary_current_profile_package_dir_path(userid_t user,
313 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800314 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800315 return StringPrintf("%s/%s",
316 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700317}
318
Calin Juravle114f0812017-03-08 19:05:07 -0800319std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600320 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000321}
322
Calin Juravle114f0812017-03-08 19:05:07 -0800323std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800324 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600325 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000326}
327
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700328std::string create_data_dalvik_cache_path() {
329 return "/data/dalvik-cache";
330}
331
Felka Chang2a0a2462019-11-20 14:20:40 +0800332std::string create_system_user_ce_path(userid_t userId) {
333 return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
334}
335
336std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
337 check_package_name(package_name);
338 return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
339}
340
Calin Juravle114f0812017-03-08 19:05:07 -0800341// Keep profile paths in sync with ActivityThread and LoadedApk.
342const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700343const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800344const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700345
Calin Juravle3760ad32017-07-27 16:31:55 -0700346// Gets the parent directory and the file name for the given secondary dex path.
347// Returns true on success, false on failure (if the dex_path does not have the expected
348// structure).
349static bool get_secondary_dex_location(const std::string& dex_path,
350 std::string* out_dir_name, std::string* out_file_name) {
351 size_t dirIndex = dex_path.rfind('/');
352 if (dirIndex == std::string::npos) {
353 return false;
354 }
355 if (dirIndex == dex_path.size() - 1) {
356 return false;
357 }
358 *out_dir_name = dex_path.substr(0, dirIndex);
359 *out_file_name = dex_path.substr(dirIndex + 1);
360
361 return true;
362}
363
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800364std::string create_current_profile_path(userid_t user, const std::string& package_name,
365 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800366 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700367 // Secondary dex current profiles are stored next to the dex files under the oat folder.
368 std::string dex_dir;
369 std::string dex_name;
370 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
371 << "Unexpected dir structure for secondary dex " << location;
372 return StringPrintf("%s/oat/%s%s%s",
373 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
374 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800375 } else {
376 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800377 std::string profile_dir = create_primary_current_profile_package_dir_path(
378 user, package_name);
379 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800380 }
381}
382
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800383std::string create_reference_profile_path(const std::string& package_name,
384 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800385 if (is_secondary_dex) {
386 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700387 std::string dex_dir;
388 std::string dex_name;
389 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800390 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800391 return StringPrintf("%s/oat/%s%s",
392 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
393 } else {
394 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800395 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
396 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800397 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700398}
399
Calin Juravle29591732017-11-20 17:46:19 -0800400std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800401 const std::string& profile_name) {
402 std::string ref_profile = create_reference_profile_path(package, profile_name,
403 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800404 return ref_profile + SNAPSHOT_PROFILE_EXT;
405}
406
Jeff Sharkeye3637242015-04-08 20:56:42 -0700407std::vector<userid_t> get_known_users(const char* volume_uuid) {
408 std::vector<userid_t> users;
409
410 // We always have an owner
411 users.push_back(0);
412
413 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
414 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700415 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700416 // Unable to discover other users, but at least return owner
417 PLOG(ERROR) << "Failed to opendir " << path;
418 return users;
419 }
420
421 struct dirent* ent;
422 while ((ent = readdir(dir))) {
423 if (ent->d_type != DT_DIR) {
424 continue;
425 }
426
427 char* end;
428 userid_t user = strtol(ent->d_name, &end, 10);
429 if (*end == '\0' && user != 0) {
430 LOG(DEBUG) << "Found valid user " << user;
431 users.push_back(user);
432 }
433 }
434 closedir(dir);
435
436 return users;
437}
Shikha Malhotra7fa4f882022-01-12 21:05:31 +0000438long get_project_id(uid_t uid, long start_project_id_range) {
439 return uid - AID_APP_START + start_project_id_range;
440}
Jeff Sharkeye3637242015-04-08 20:56:42 -0700441
Shikha Malhotra7fa4f882022-01-12 21:05:31 +0000442int set_quota_project_id(const std::string& path, long project_id, bool set_inherit) {
443 struct fsxattr fsx;
444 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
445 if (fd == -1) {
446 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
447 return -1;
448 }
449
450 if (ioctl(fd, FS_IOC_FSGETXATTR, &fsx) == -1) {
451 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
452 return -1;
453 }
454
455 fsx.fsx_projid = project_id;
456 if (ioctl(fd, FS_IOC_FSSETXATTR, &fsx) == -1) {
457 PLOG(ERROR) << "Failed to set project id on " << path;
458 return -1;
459 }
460 if (set_inherit) {
461 unsigned int flags;
462 if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1) {
463 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
464 return -1;
465 }
466
467 flags |= FS_PROJINHERIT_FL;
468
469 if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == -1) {
470 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
471 return -1;
472 }
473 }
474 return 0;
475}
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700476int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700477 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700478 FTS *fts;
479 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700480 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700481 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700482 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700483 if (errno != ENOENT) {
484 PLOG(ERROR) << "Failed to fts_open " << path;
485 }
486 return -1;
487 }
Yi Kong954cf642018-07-17 16:16:24 -0700488 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700489 switch (p->fts_info) {
490 case FTS_D:
491 case FTS_DEFAULT:
492 case FTS_F:
493 case FTS_SL:
494 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700495 int32_t uid = p->fts_statp->st_uid;
496 int32_t gid = p->fts_statp->st_gid;
497 int32_t user_uid = multiuser_get_app_id(uid);
498 int32_t user_gid = multiuser_get_app_id(gid);
499 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
500 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
501 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
502 // Don't traverse inside or measure
503 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700504 break;
505 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700506 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700507 break;
508 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700509 if (exclude_gid != -1 && gid == exclude_gid) {
510 break;
511 }
512 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700513 break;
514 }
515 }
516 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700517#if MEASURE_DEBUG
518 if ((include_gid == -1) && (exclude_gid == -1)) {
519 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
520 } else {
521 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
522 << " exclude " << exclude_gid;
523 }
524#endif
525 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700526 return 0;
527}
528
Mike Lockwood94afecf2012-10-24 10:45:23 -0700529/**
530 * Checks whether the package name is valid. Returns -1 on error and
531 * 0 on success.
532 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700533bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700534 // This logic is borrowed from PackageParser.java
535 bool hasSep = false;
536 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700537
Jeff Sharkey367ace22017-03-07 22:12:03 -0700538 auto it = packageName.begin();
539 for (; it != packageName.end() && *it != '-'; it++) {
540 char c = *it;
541 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
542 front = false;
543 continue;
544 }
545 if (!front) {
546 if ((c >= '0' && c <= '9') || c == '_') {
547 continue;
548 }
549 }
550 if (c == '.') {
551 hasSep = true;
552 front = true;
553 continue;
554 }
555 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700556 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700557 }
558
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700559 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700560 LOG(WARNING) << "Missing separator in " << packageName;
561 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700562 }
563
Jeff Sharkey367ace22017-03-07 22:12:03 -0700564 for (; it != packageName.end(); it++) {
565 char c = *it;
566 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
567 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
568 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
569 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700570 }
571
Jeff Sharkey423e7462016-12-09 18:18:43 -0700572 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700573}
574
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100575static int _delete_dir_contents(DIR *d,
576 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700577{
578 int result = 0;
579 struct dirent *de;
580 int dfd;
581
582 dfd = dirfd(d);
583
584 if (dfd < 0) return -1;
585
586 while ((de = readdir(d))) {
587 const char *name = de->d_name;
588
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100589 /* check using the exclusion predicate, if provided */
590 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
591 continue;
592 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700593
594 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700595 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700596 DIR *subdir;
597
598 /* always skip "." and ".." */
599 if (name[0] == '.') {
600 if (name[1] == 0) continue;
601 if ((name[1] == '.') && (name[2] == 0)) continue;
602 }
603
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700604 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700605 if (subfd < 0) {
606 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
607 result = -1;
608 continue;
609 }
610 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700611 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700612 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
613 close(subfd);
614 result = -1;
615 continue;
616 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100617 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700618 result = -1;
619 }
620 closedir(subdir);
621 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
622 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
623 result = -1;
624 }
625 } else {
626 if (unlinkat(dfd, name, 0) < 0) {
627 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
628 result = -1;
629 }
630 }
631 }
632
633 return result;
634}
635
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000636int create_dir_if_needed(const std::string& pathname, mode_t perms) {
637 struct stat st;
638
639 int rc;
640 if ((rc = stat(pathname.c_str(), &st)) != 0) {
641 if (errno == ENOENT) {
642 return mkdir(pathname.c_str(), perms);
643 } else {
644 return rc;
645 }
646 } else if (!S_ISDIR(st.st_mode)) {
647 LOG(DEBUG) << pathname << " is not a folder";
648 return -1;
649 }
650
651 mode_t actual_perms = st.st_mode & ALLPERMS;
652 if (actual_perms != perms) {
653 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
654 return -1;
655 }
656
657 return 0;
658}
659
Calin Juravleb06f98a2016-03-28 15:11:01 +0100660int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700661 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700662}
663
Calin Juravleb06f98a2016-03-28 15:11:01 +0100664int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700665 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700666}
667
Mike Lockwood94afecf2012-10-24 10:45:23 -0700668int delete_dir_contents(const char *pathname,
669 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100670 int (*exclusion_predicate)(const char*, const int),
671 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700672{
673 int res = 0;
674 DIR *d;
675
676 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700677 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100678 if (ignore_if_missing && (errno == ENOENT)) {
679 return 0;
680 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700681 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
682 return -errno;
683 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100684 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700685 closedir(d);
686 if (also_delete_dir) {
687 if (rmdir(pathname)) {
688 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
689 res = -1;
690 }
691 }
692 return res;
693}
694
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800695static std::string make_unique_name(std::string_view suffix) {
696 static constexpr auto uuidStringSize = 36;
697
698 uuid_t guid;
699 uuid_generate(guid);
700
701 std::string name;
702 const auto suffixSize = suffix.size();
703 name.reserve(uuidStringSize + suffixSize);
704
705 name.resize(uuidStringSize);
706 uuid_unparse(guid, name.data());
707 name.append(suffix);
708
709 return name;
710}
711
712static int rename_delete_dir_contents(const std::string& pathname,
713 int (*exclusion_predicate)(const char*, const int),
714 bool ignore_if_missing) {
715 auto temp_dir_name = make_unique_name(deletedSuffix);
716 auto temp_dir_path =
717 base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
718
719 if (::rename(pathname.c_str(), temp_dir_path.c_str())) {
720 if (ignore_if_missing && (errno == ENOENT)) {
721 return 0;
722 }
723 ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), temp_dir_path.c_str(),
724 strerror(errno));
725 return -errno;
726 }
727
728 return delete_dir_contents(temp_dir_path.c_str(), 1, exclusion_predicate, ignore_if_missing);
729}
730
Alex Buynytskyy4ab5d532022-02-17 21:20:10 +0000731bool is_renamed_deleted_dir(const std::string& path) {
732 if (path.size() < deletedSuffix.size()) {
733 return false;
734 }
735 std::string_view pathSuffix{path.c_str() + path.size() - deletedSuffix.size()};
736 return pathSuffix == deletedSuffix;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800737}
738
739int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
740 return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
741}
742
743static auto open_dir(const char* dir) {
744 struct DirCloser {
745 void operator()(DIR* d) const noexcept { ::closedir(d); }
746 };
747 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
748}
749
Samiul Islamb9e96bf2022-02-03 12:45:51 +0000750// Collects filename of subdirectories of given directory and passes it to the function
751int foreach_subdir(const std::string& pathname, const std::function<void(const std::string&)> fn) {
752 auto dir = open_dir(pathname.c_str());
753 if (!dir) return -1;
754
755 int dfd = dirfd(dir.get());
756 if (dfd < 0) {
757 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
758 return -1;
759 }
760
761 struct dirent* de;
762 while ((de = readdir(dir.get()))) {
763 if (de->d_type != DT_DIR) {
764 continue;
765 }
766
767 std::string name{de->d_name};
768 // always skip "." and ".."
769 if (name == "." || name == "..") {
770 continue;
771 }
772 fn(name);
773 }
774
775 return 0;
776}
777
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800778void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800779 auto dir = open_dir(pathname.c_str());
780 if (!dir) {
781 return;
782 }
783 int dfd = dirfd(dir.get());
784 if (dfd < 0) {
785 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
786 return;
787 }
788
789 struct dirent* de;
790 while ((de = readdir(dir.get()))) {
791 if (de->d_type != DT_DIR) {
792 continue;
793 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800794
795 std::string name{de->d_name};
796 // always skip "." and ".."
797 if (name == "." || name == "..") {
798 continue;
799 }
800
801 if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
802 !is_valid_package_name(name)) {
803 ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800804 // Deleting the content.
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800805 delete_dir_contents_fd(dfd, name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800806 // Deleting the directory
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800807 if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
808 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800809 }
810 }
811 }
812}
813
Mike Lockwood94afecf2012-10-24 10:45:23 -0700814int delete_dir_contents_fd(int dfd, const char *name)
815{
816 int fd, res;
817 DIR *d;
818
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700819 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700820 if (fd < 0) {
821 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
822 return -1;
823 }
824 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700825 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700826 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
827 close(fd);
828 return -1;
829 }
Yi Kong954cf642018-07-17 16:16:24 -0700830 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700831 closedir(d);
832 return res;
833}
834
Robin Lee60fd3fe2014-10-07 16:55:02 +0100835static int _copy_owner_permissions(int srcfd, int dstfd)
836{
837 struct stat st;
838 if (fstat(srcfd, &st) != 0) {
839 return -1;
840 }
841 if (fchmod(dstfd, st.st_mode) != 0) {
842 return -1;
843 }
844 return 0;
845}
846
847static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
848{
849 int result = 0;
850 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
851 ALOGE("_copy_dir_files failed to copy dir permissions\n");
852 }
853 if (fchown(ddfd, owner, group) != 0) {
854 ALOGE("_copy_dir_files failed to change dir owner\n");
855 }
856
857 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700858 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100859 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
860 return -1;
861 }
862 struct dirent *de;
863 while ((de = readdir(ds))) {
864 if (de->d_type != DT_REG) {
865 continue;
866 }
867
868 const char *name = de->d_name;
869 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
870 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
871 if (fsfd == -1 || fdfd == -1) {
872 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
873 } else {
874 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
875 ALOGE("Failed to change file permissions\n");
876 }
877 if (fchown(fdfd, owner, group) != 0) {
878 ALOGE("Failed to change file owner\n");
879 }
880
881 char buf[8192];
882 ssize_t size;
883 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
884 write(fdfd, buf, size);
885 }
886 if (size < 0) {
887 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
888 result = -1;
889 }
890 }
891 close(fdfd);
892 close(fsfd);
893 }
894
895 return result;
896}
897
898int copy_dir_files(const char *srcname,
899 const char *dstname,
900 uid_t owner,
901 uid_t group)
902{
903 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700904 DIR *ds = nullptr;
905 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100906
907 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700908 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100909 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
910 return -errno;
911 }
912
913 mkdir(dstname, 0600);
914 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700915 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100916 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
917 closedir(ds);
918 return -errno;
919 }
920
921 int sdfd = dirfd(ds);
922 int ddfd = dirfd(dd);
923 if (sdfd != -1 && ddfd != -1) {
924 res = _copy_dir_files(sdfd, ddfd, owner, group);
925 } else {
926 res = -errno;
927 }
928 closedir(dd);
929 closedir(ds);
930 return res;
931}
932
Jeff Sharkeya836c472017-04-02 23:29:30 -0600933int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600934 struct statvfs sfs;
935 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600936 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700937 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600938 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700939 return -1;
940 }
941}
942
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600943int get_path_inode(const std::string& path, ino_t *inode) {
944 struct stat buf;
945 memset(&buf, 0, sizeof(buf));
946 if (stat(path.c_str(), &buf) != 0) {
947 PLOG(WARNING) << "Failed to stat " << path;
948 return -1;
949 } else {
950 *inode = buf.st_ino;
951 return 0;
952 }
953}
954
955/**
956 * Write the inode of a specific child file into the given xattr on the
957 * parent directory. This allows you to find the child later, even if its
958 * name is encrypted.
959 */
960int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
961 ino_t inode = 0;
962 uint64_t inode_raw = 0;
963 auto path = StringPrintf("%s/%s", parent.c_str(), name);
964
965 if (get_path_inode(path, &inode) != 0) {
966 // Path probably doesn't exist yet; ignore
967 return 0;
968 }
969
970 // Check to see if already set correctly
971 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
972 if (inode_raw == inode) {
973 // Already set correctly; skip writing
974 return 0;
975 } else {
976 PLOG(WARNING) << "Mismatched inode value; found " << inode
977 << " on disk but marked value was " << inode_raw << "; overwriting";
978 }
979 }
980
981 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600982 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600983 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
984 return -1;
985 } else {
986 return 0;
987 }
988}
989
990/**
991 * Read the inode of a specific child file from the given xattr on the
992 * parent directory. Returns a currently valid path for that child, which
993 * might have an encrypted name.
994 */
995std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
996 ino_t inode = 0;
997 uint64_t inode_raw = 0;
998 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
999
1000 // Lookup the inode value written earlier
1001 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
1002 inode = inode_raw;
1003 }
1004
1005 // For testing purposes, rely on the inode when defined; this could be
1006 // optimized to use access() in the future.
1007 if (inode != 0) {
1008 DIR* dir = opendir(parent.c_str());
1009 if (dir == nullptr) {
1010 PLOG(ERROR) << "Failed to opendir " << parent;
1011 return fallback;
1012 }
1013
1014 struct dirent* ent;
1015 while ((ent = readdir(dir))) {
1016 if (ent->d_ino == inode) {
1017 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
1018#if DEBUG_XATTRS
1019 if (resolved != fallback) {
1020 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
1021 << " instead of " << fallback;
1022 }
1023#endif
1024 closedir(dir);
1025 return resolved;
1026 }
1027 }
1028 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
1029 closedir(dir);
1030 return fallback;
1031 } else {
1032 return fallback;
1033 }
1034}
1035
Ryuki Nakamurac7342f82017-09-30 11:57:00 +09001036void remove_path_xattr(const std::string& path, const char* inode_xattr) {
1037 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
1038 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
1039 }
1040}
1041
Mike Lockwood94afecf2012-10-24 10:45:23 -07001042/**
Calin Juravlec597b6d2014-08-19 17:43:05 +01001043 * Validate that the path is valid in the context of the provided directory.
1044 * The path is allowed to have at most one subdirectory and no indirections
1045 * to top level directories (i.e. have "..").
1046 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001047static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +00001048 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001049 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
1050 || dir.find("..") != std::string::npos) {
1051 LOG(ERROR) << "Invalid directory " << dir;
1052 return -1;
1053 }
1054 if (path.find("..") != std::string::npos) {
1055 LOG(ERROR) << "Invalid path " << path;
1056 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +01001057 }
1058
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001059 if (path.compare(0, dir.size(), dir) != 0) {
1060 // Common case, path isn't under directory
1061 return -1;
1062 }
1063
1064 // Count number of subdirectories
1065 auto pos = path.find('/', dir.size());
1066 int count = 0;
1067 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -06001068 auto next = path.find('/', pos + 1);
1069 if (next > pos + 1) {
1070 count++;
1071 }
1072 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001073 }
1074
1075 if (count > maxSubdirs) {
1076 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +01001077 return -1;
1078 }
1079
1080 return 0;
1081}
1082
1083/**
Mike Lockwood94afecf2012-10-24 10:45:23 -07001084 * Checks whether a path points to a system app (.apk file). Returns 0
1085 * if it is a system app or -1 if it is not.
1086 */
1087int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001088 std::string path_ = path;
1089 for (const auto& dir : android_system_dirs) {
1090 if (validate_path(dir, path, 1) == 0) {
1091 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001092 }
1093 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001094 return -1;
1095}
1096
Calin Juravle114f0812017-03-08 19:05:07 -08001097bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -07001098 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -08001099 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1100
Calin Juravle3760ad32017-07-27 16:31:55 -07001101 // Empty paths are not allowed.
1102 if (dex_path.empty()) { return false; }
1103 // First character should always be '/'. No relative paths.
1104 if (dex_path[0] != '/') { return false; }
1105 // The last character should not be '/'.
1106 if (dex_path[dex_path.size() - 1] == '/') { return false; }
1107 // There should be no '.' after the directory marker.
1108 if (dex_path.find("/.") != std::string::npos) { return false; }
1109 // The path should be at most PKG_PATH_MAX long.
1110 if (dex_path.size() > PKG_PATH_MAX) { return false; }
1111
Calin Juravle7d765462017-09-04 15:57:10 -07001112 // The dex_path should be under the app data directory.
1113 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -07001114 ? create_data_user_ce_package_path(
1115 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1116 : create_data_user_de_package_path(
1117 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -07001118
Calin Juravle7d765462017-09-04 15:57:10 -07001119 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1120 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1121 // If that's the case, attempt to validate against the user data link.
1122 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1123 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1124 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1125 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -07001126 return false;
1127 }
Calin Juravle42451c02017-01-17 14:43:25 -08001128 }
Calin Juravle3760ad32017-07-27 16:31:55 -07001129
1130 // If we got here we have a valid path.
1131 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001132}
1133
Mike Lockwood94afecf2012-10-24 10:45:23 -07001134/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001135 * Check whether path points to a valid path for an APK file. The path must
1136 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1137 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1138 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001139 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001140static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1141 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001142 return 0;
shafikb43faa92019-02-19 12:19:48 +00001143 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1144 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001145 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001146 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001147 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001148 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001149 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001150 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001151 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1152 // Rewrite the path as if it were on internal storage, and test that
1153 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1154 if (end != std::string::npos) {
1155 auto modified = path;
1156 modified.replace(0, end + 1, android_data_dir);
1157 return validate_apk_path_internal(modified, maxSubdirs);
1158 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001159 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001160 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001161}
1162
Narayan Kamathd845c962015-06-04 13:20:27 +01001163int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001164 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001165}
1166
1167int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001168 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001169}
1170
Robin Lee095c7632014-04-25 15:05:19 +01001171int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001172 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001173 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1174 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001175
1176 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001177 auto path = create_data_misc_legacy_path(userid);
1178 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001179}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001180
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001181static int wait_child(pid_t pid) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001182 int status;
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001183 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, /*options=*/0));
Andreas Gampe02d0de52015-11-11 20:43:16 -08001184
Andreas Gampe02d0de52015-11-11 20:43:16 -08001185 if (got_pid != pid) {
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001186 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
1187 return W_EXITCODE(/*exit_code=*/255, /*signal_number=*/0);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001188 }
1189
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001190 return status;
1191}
1192
1193int wait_child_with_timeout(pid_t pid, int timeout_ms) {
1194 int pidfd = pidfd_open(pid, /*flags=*/0);
1195 if (pidfd < 0) {
1196 PLOG(ERROR) << "pidfd_open failed for pid " << pid;
1197 kill(pid, SIGKILL);
1198 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001199 }
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001200
1201 struct pollfd pfd;
1202 pfd.fd = pidfd;
1203 pfd.events = POLLIN;
1204 int poll_ret = TEMP_FAILURE_RETRY(poll(&pfd, /*nfds=*/1, timeout_ms));
1205
1206 close(pidfd);
1207
1208 if (poll_ret < 0) {
1209 PLOG(ERROR) << "poll failed for pid " << pid;
1210 kill(pid, SIGKILL);
1211 return wait_child(pid);
1212 }
1213 if (poll_ret == 0) {
1214 LOG(WARNING) << "Child process " << pid << " timed out after " << timeout_ms
1215 << "ms. Killing it";
1216 kill(pid, SIGKILL);
1217 return wait_child(pid);
1218 }
1219 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001220}
1221
Calin Juravle42451c02017-01-17 14:43:25 -08001222/**
1223 * Prepare an app cache directory, which offers to fix-up the GID and
1224 * directory mode flags during a platform upgrade.
1225 * The app cache directory path will be 'parent'/'name'.
1226 */
1227int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1228 uid_t uid, gid_t gid) {
1229 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1230 struct stat st;
1231 if (stat(path.c_str(), &st) != 0) {
1232 if (errno == ENOENT) {
1233 // This is fine, just create it
1234 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1235 PLOG(ERROR) << "Failed to prepare " << path;
1236 return -1;
1237 } else {
1238 return 0;
1239 }
1240 } else {
1241 PLOG(ERROR) << "Failed to stat " << path;
1242 return -1;
1243 }
1244 }
1245
1246 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1247 if (st.st_uid != uid) {
1248 // Mismatched UID is real trouble; we can't recover
1249 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1250 << " but expected " << uid;
1251 return -1;
1252 } else if (st.st_gid == gid && actual_mode == target_mode) {
1253 // Everything looks good!
1254 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001255 } else {
1256 // Mismatched GID/mode is recoverable; fall through to update
1257 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001258 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001259 }
1260
1261 // Directory is owned correctly, but GID or mode mismatch means it's
1262 // probably a platform upgrade so we need to fix them
1263 FTS *fts;
1264 FTSENT *p;
1265 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001266 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001267 PLOG(ERROR) << "Failed to fts_open " << path;
1268 return -1;
1269 }
Yi Kong954cf642018-07-17 16:16:24 -07001270 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001271 switch (p->fts_info) {
1272 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001273 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001274 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1275 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001276 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001277 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001278 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001279 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1280 }
1281 break;
1282 case FTS_SL:
1283 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001284 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001285 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1286 }
1287 break;
1288 }
1289 }
1290 fts_close(fts);
1291 return 0;
1292}
1293
Martijn Coenen771cc342020-02-19 23:26:56 +01001294static const char* kProcFilesystems = "/proc/filesystems";
1295bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001296 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1297 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001298 std::string supported;
1299 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1300 PLOG(ERROR) << "Failed to read supported filesystems";
1301 return false;
1302 }
1303 return supported.find("sdcardfs\n") != std::string::npos;
1304}
1305
1306int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1307 static const bool supportsSdcardFs = supports_sdcardfs();
1308
1309 if (supportsSdcardFs) {
1310 int extGid = multiuser_get_ext_gid(userId, appId);
1311
1312 if (extGid == -1) {
1313 return -1;
1314 }
1315
1316 return GetOccupiedSpaceForGid(uuid, extGid);
1317 } else {
1318 uid_t uid = multiuser_get_uid(userId, appId);
1319 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1320 return GetOccupiedSpaceForProjectId(uuid, projectId);
1321 }
1322}
1323int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1324 static const bool supportsSdcardFs = supports_sdcardfs();
1325
1326 if (supportsSdcardFs) {
1327 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1328
1329 if (extCacheGid == -1) {
1330 return -1;
1331 }
1332
1333 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1334 } else {
1335 uid_t uid = multiuser_get_uid(userId, appId);
1336 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1337 return GetOccupiedSpaceForProjectId(uuid, projectId);
1338 }
1339}
1340
Calin Juravlee61189e2018-01-23 19:54:11 -08001341// Collect all non empty profiles from the given directory and puts then into profile_paths.
1342// The profiles are identified based on PROFILE_EXT extension.
1343// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1344// It returns true if there were no errors at all, and false otherwise.
1345static bool collect_profiles(DIR* d,
1346 const std::string& current_path,
1347 std::vector<std::string>* profiles_paths) {
1348 int32_t dir_fd = dirfd(d);
1349 if (dir_fd < 0) {
1350 return false;
1351 }
1352
1353 bool result = true;
1354 struct dirent* dir_entry;
1355 while ((dir_entry = readdir(d))) {
1356 std::string name = dir_entry->d_name;
1357 std::string local_path = current_path + "/" + name;
1358
1359 if (dir_entry->d_type == DT_REG) {
1360 // Check if this is a non empty profile file.
1361 if (EndsWith(name, PROFILE_EXT)) {
1362 struct stat st;
1363 if (stat(local_path.c_str(), &st) != 0) {
1364 PLOG(WARNING) << "Cannot stat local path " << local_path;
1365 result = false;
1366 continue;
1367 } else if (st.st_size > 0) {
1368 profiles_paths->push_back(local_path);
1369 }
1370 }
1371 } else if (dir_entry->d_type == DT_DIR) {
1372 // always skip "." and ".."
1373 if (name == "." || name == "..") {
1374 continue;
1375 }
1376
1377 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1378 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1379 if (subdir_fd < 0) {
1380 PLOG(WARNING) << "Could not open dir path " << local_path;
1381 result = false;
1382 continue;
1383 }
1384
Mathieu Chartier89883e32018-11-01 11:39:00 -07001385 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001386 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001387 PLOG(WARNING) << "Could not open dir path " << local_path;
1388 result = false;
1389 continue;
1390 }
1391 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1392 result = result && new_result;
1393 if (closedir(subdir) != 0) {
1394 PLOG(WARNING) << "Could not close dir path " << local_path;
1395 }
1396 }
1397 }
1398
1399 return result;
1400}
1401
1402bool collect_profiles(std::vector<std::string>* profiles_paths) {
1403 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001404 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001405 return false;
1406 } else {
1407 return collect_profiles(d, android_profiles_dir, profiles_paths);
1408 }
1409}
1410
Eric Holk2af5e6a2019-01-09 18:17:27 -08001411void drop_capabilities(uid_t uid) {
1412 if (setgid(uid) != 0) {
1413 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1414 exit(DexoptReturnCodes::kSetGid);
1415 }
1416 if (setuid(uid) != 0) {
1417 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1418 exit(DexoptReturnCodes::kSetUid);
1419 }
1420 // drop capabilities
1421 struct __user_cap_header_struct capheader;
1422 struct __user_cap_data_struct capdata[2];
1423 memset(&capheader, 0, sizeof(capheader));
1424 memset(&capdata, 0, sizeof(capdata));
1425 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1426 if (capset(&capheader, &capdata[0]) < 0) {
1427 PLOG(ERROR) << "capset failed";
1428 exit(DexoptReturnCodes::kCapSet);
1429 }
1430}
1431
Jiakai Zhang0a7603c2022-02-21 19:38:14 +00001432bool remove_file_at_fd(int fd, /*out*/ std::string* path) {
1433 char path_buffer[PATH_MAX + 1];
1434 std::string proc_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
1435 ssize_t len = readlink(proc_path.c_str(), path_buffer, PATH_MAX);
1436 if (len < 0) {
1437 PLOG(WARNING) << "Could not remove file at fd " << fd << ": Failed to get file path";
1438 return false;
1439 }
1440 path_buffer[len] = '\0';
1441 if (path != nullptr) {
1442 *path = path_buffer;
1443 }
1444 if (unlink(path_buffer) != 0) {
1445 if (errno == ENOENT) {
1446 return true;
1447 }
1448 PLOG(WARNING) << "Could not remove file at path " << path_buffer;
1449 return false;
1450 }
1451 return true;
1452}
1453
Andreas Gampe02d0de52015-11-11 20:43:16 -08001454} // namespace installd
1455} // namespace android