blob: 8cfd12313bee3bae0f680e354a1c3f406c9946a5 [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 Zhang495142a2022-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 Zhang495142a2022-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 Zhang495142a2022-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 Zhang495142a2022-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 Islamc40dff52022-01-14 16:24:48 +0000200/**
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000201 * Create the path name where sdk_sandbox data for all apps will be stored.
202 * E.g. /data/misc_ce/0/sdksandbox
Samiul Islamc40dff52022-01-14 16:24:48 +0000203 */
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000204std::string create_data_misc_sdk_sandbox_path(const char* uuid, bool isCeData, userid_t user) {
Samiul Islamc40dff52022-01-14 16:24:48 +0000205 std::string data(create_data_path(uuid));
206 if (isCeData) {
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000207 return StringPrintf("%s/misc_ce/%d/sdksandbox", data.c_str(), user);
Samiul Islamc40dff52022-01-14 16:24:48 +0000208 } else {
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000209 return StringPrintf("%s/misc_de/%d/sdksandbox", data.c_str(), user);
Samiul Islamc40dff52022-01-14 16:24:48 +0000210 }
211}
212
213/**
214 * Create the path name where code data for all codes in a particular app will be stored.
Samiul Islam92f5cf02022-02-03 12:45:51 +0000215 * E.g. /data/misc_ce/0/sdksandbox/<package-name>
Samiul Islamc40dff52022-01-14 16:24:48 +0000216 */
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000217std::string create_data_misc_sdk_sandbox_package_path(const char* volume_uuid, bool isCeData,
218 userid_t user, const char* package_name) {
Samiul Islamc40dff52022-01-14 16:24:48 +0000219 check_package_name(package_name);
220 return StringPrintf("%s/%s",
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000221 create_data_misc_sdk_sandbox_path(volume_uuid, isCeData, user).c_str(),
Samiul Islamc40dff52022-01-14 16:24:48 +0000222 package_name);
223}
224
225/**
226 * Create the path name where shared code data for a particular app will be stored.
Samiul Islam92f5cf02022-02-03 12:45:51 +0000227 * E.g. /data/misc_ce/0/sdksandbox/<package-name>/shared
Samiul Islamc40dff52022-01-14 16:24:48 +0000228 */
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000229std::string create_data_misc_sdk_sandbox_shared_path(const char* volume_uuid, bool isCeData,
230 userid_t user, const char* package_name) {
Samiul Islamc40dff52022-01-14 16:24:48 +0000231 return StringPrintf("%s/shared",
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000232 create_data_misc_sdk_sandbox_package_path(volume_uuid, isCeData, user,
233 package_name)
Samiul Islamc40dff52022-01-14 16:24:48 +0000234 .c_str());
235}
236
Samiul Islam92f5cf02022-02-03 12:45:51 +0000237/**
238 * Create the path name where per-code level data for a particular app will be stored.
239 * E.g. /data/misc_ce/0/sdksandbox/<package-name>/<sdk-name>-<random-suffix>
240 */
241std::string create_data_misc_sdk_sandbox_sdk_path(const char* volume_uuid, bool isCeData,
242 userid_t user, const char* package_name,
243 const char* sdk_name, const char* randomSuffix) {
244 check_package_name(sdk_name);
245 auto package_path =
246 create_data_misc_sdk_sandbox_package_path(volume_uuid, isCeData, user, package_name);
247 return StringPrintf("%s/%s@%s", package_path.c_str(), sdk_name, randomSuffix);
248}
249
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000250std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000251 return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
252}
253
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000254std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000255 return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
256}
257
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000258std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
259 int32_t snapshot_id) {
260 return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
261 snapshot_id);
262}
263
264std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
265 int32_t snapshot_id) {
266 return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
267 snapshot_id);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000268}
269
Nikita Ioffe8755f792019-01-25 13:54:43 +0000270std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000271 userid_t user, int32_t snapshot_id, const char* package_name) {
272 return StringPrintf("%s/%s",
273 create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
274}
275
276std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
277 userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
278 auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
279 package_name);
280 auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000281 return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
282}
283
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000284std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000285 userid_t user, int32_t snapshot_id, const char* package_name) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000286 return StringPrintf("%s/%s",
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000287 create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000288}
289
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800290/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700291 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700292 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700293std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
294 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700295}
296
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700297std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
298 const char* data_type, const char* package_name) {
299 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
300 data_type, package_name);
301}
302
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600303std::string create_data_misc_legacy_path(userid_t userid) {
304 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
305}
306
Calin Juravle114f0812017-03-08 19:05:07 -0800307std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600308 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000309}
310
Calin Juravle114f0812017-03-08 19:05:07 -0800311std::string create_primary_current_profile_package_dir_path(userid_t user,
312 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800313 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800314 return StringPrintf("%s/%s",
315 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700316}
317
Calin Juravle114f0812017-03-08 19:05:07 -0800318std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600319 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000320}
321
Calin Juravle114f0812017-03-08 19:05:07 -0800322std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800323 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600324 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000325}
326
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700327std::string create_data_dalvik_cache_path() {
328 return "/data/dalvik-cache";
329}
330
Felka Chang2a0a2462019-11-20 14:20:40 +0800331std::string create_system_user_ce_path(userid_t userId) {
332 return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
333}
334
335std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
336 check_package_name(package_name);
337 return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
338}
339
Calin Juravle114f0812017-03-08 19:05:07 -0800340// Keep profile paths in sync with ActivityThread and LoadedApk.
341const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700342const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800343const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700344
Calin Juravle3760ad32017-07-27 16:31:55 -0700345// Gets the parent directory and the file name for the given secondary dex path.
346// Returns true on success, false on failure (if the dex_path does not have the expected
347// structure).
348static bool get_secondary_dex_location(const std::string& dex_path,
349 std::string* out_dir_name, std::string* out_file_name) {
350 size_t dirIndex = dex_path.rfind('/');
351 if (dirIndex == std::string::npos) {
352 return false;
353 }
354 if (dirIndex == dex_path.size() - 1) {
355 return false;
356 }
357 *out_dir_name = dex_path.substr(0, dirIndex);
358 *out_file_name = dex_path.substr(dirIndex + 1);
359
360 return true;
361}
362
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800363std::string create_current_profile_path(userid_t user, const std::string& package_name,
364 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800365 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700366 // Secondary dex current profiles are stored next to the dex files under the oat folder.
367 std::string dex_dir;
368 std::string dex_name;
369 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
370 << "Unexpected dir structure for secondary dex " << location;
371 return StringPrintf("%s/oat/%s%s%s",
372 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
373 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800374 } else {
375 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800376 std::string profile_dir = create_primary_current_profile_package_dir_path(
377 user, package_name);
378 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800379 }
380}
381
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800382std::string create_reference_profile_path(const std::string& package_name,
383 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800384 if (is_secondary_dex) {
385 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700386 std::string dex_dir;
387 std::string dex_name;
388 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800389 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800390 return StringPrintf("%s/oat/%s%s",
391 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
392 } else {
393 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800394 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
395 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800396 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700397}
398
Calin Juravle29591732017-11-20 17:46:19 -0800399std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800400 const std::string& profile_name) {
401 std::string ref_profile = create_reference_profile_path(package, profile_name,
402 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800403 return ref_profile + SNAPSHOT_PROFILE_EXT;
404}
405
Jeff Sharkeye3637242015-04-08 20:56:42 -0700406std::vector<userid_t> get_known_users(const char* volume_uuid) {
407 std::vector<userid_t> users;
408
409 // We always have an owner
410 users.push_back(0);
411
412 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
413 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700414 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700415 // Unable to discover other users, but at least return owner
416 PLOG(ERROR) << "Failed to opendir " << path;
417 return users;
418 }
419
420 struct dirent* ent;
421 while ((ent = readdir(dir))) {
422 if (ent->d_type != DT_DIR) {
423 continue;
424 }
425
426 char* end;
427 userid_t user = strtol(ent->d_name, &end, 10);
428 if (*end == '\0' && user != 0) {
429 LOG(DEBUG) << "Found valid user " << user;
430 users.push_back(user);
431 }
432 }
433 closedir(dir);
434
435 return users;
436}
437
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700438int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700439 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700440 FTS *fts;
441 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700442 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700443 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700444 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700445 if (errno != ENOENT) {
446 PLOG(ERROR) << "Failed to fts_open " << path;
447 }
448 return -1;
449 }
Yi Kong954cf642018-07-17 16:16:24 -0700450 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700451 switch (p->fts_info) {
452 case FTS_D:
453 case FTS_DEFAULT:
454 case FTS_F:
455 case FTS_SL:
456 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700457 int32_t uid = p->fts_statp->st_uid;
458 int32_t gid = p->fts_statp->st_gid;
459 int32_t user_uid = multiuser_get_app_id(uid);
460 int32_t user_gid = multiuser_get_app_id(gid);
461 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
462 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
463 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
464 // Don't traverse inside or measure
465 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700466 break;
467 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700468 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700469 break;
470 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700471 if (exclude_gid != -1 && gid == exclude_gid) {
472 break;
473 }
474 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700475 break;
476 }
477 }
478 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700479#if MEASURE_DEBUG
480 if ((include_gid == -1) && (exclude_gid == -1)) {
481 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
482 } else {
483 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
484 << " exclude " << exclude_gid;
485 }
486#endif
487 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700488 return 0;
489}
490
Mike Lockwood94afecf2012-10-24 10:45:23 -0700491/**
492 * Checks whether the package name is valid. Returns -1 on error and
493 * 0 on success.
494 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700495bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700496 // This logic is borrowed from PackageParser.java
497 bool hasSep = false;
498 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700499
Jeff Sharkey367ace22017-03-07 22:12:03 -0700500 auto it = packageName.begin();
501 for (; it != packageName.end() && *it != '-'; it++) {
502 char c = *it;
503 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
504 front = false;
505 continue;
506 }
507 if (!front) {
508 if ((c >= '0' && c <= '9') || c == '_') {
509 continue;
510 }
511 }
512 if (c == '.') {
513 hasSep = true;
514 front = true;
515 continue;
516 }
517 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700518 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700519 }
520
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700521 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700522 LOG(WARNING) << "Missing separator in " << packageName;
523 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700524 }
525
Jeff Sharkey367ace22017-03-07 22:12:03 -0700526 for (; it != packageName.end(); it++) {
527 char c = *it;
528 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
529 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
530 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
531 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700532 }
533
Jeff Sharkey423e7462016-12-09 18:18:43 -0700534 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700535}
536
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100537static int _delete_dir_contents(DIR *d,
538 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700539{
540 int result = 0;
541 struct dirent *de;
542 int dfd;
543
544 dfd = dirfd(d);
545
546 if (dfd < 0) return -1;
547
548 while ((de = readdir(d))) {
549 const char *name = de->d_name;
550
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100551 /* check using the exclusion predicate, if provided */
552 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
553 continue;
554 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700555
556 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700557 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700558 DIR *subdir;
559
560 /* always skip "." and ".." */
561 if (name[0] == '.') {
562 if (name[1] == 0) continue;
563 if ((name[1] == '.') && (name[2] == 0)) continue;
564 }
565
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700566 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700567 if (subfd < 0) {
568 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
569 result = -1;
570 continue;
571 }
572 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700573 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700574 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
575 close(subfd);
576 result = -1;
577 continue;
578 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100579 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700580 result = -1;
581 }
582 closedir(subdir);
583 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
584 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
585 result = -1;
586 }
587 } else {
588 if (unlinkat(dfd, name, 0) < 0) {
589 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
590 result = -1;
591 }
592 }
593 }
594
595 return result;
596}
597
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000598int create_dir_if_needed(const std::string& pathname, mode_t perms) {
599 struct stat st;
600
601 int rc;
602 if ((rc = stat(pathname.c_str(), &st)) != 0) {
603 if (errno == ENOENT) {
604 return mkdir(pathname.c_str(), perms);
605 } else {
606 return rc;
607 }
608 } else if (!S_ISDIR(st.st_mode)) {
609 LOG(DEBUG) << pathname << " is not a folder";
610 return -1;
611 }
612
613 mode_t actual_perms = st.st_mode & ALLPERMS;
614 if (actual_perms != perms) {
615 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
616 return -1;
617 }
618
619 return 0;
620}
621
Calin Juravleb06f98a2016-03-28 15:11:01 +0100622int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700623 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700624}
625
Calin Juravleb06f98a2016-03-28 15:11:01 +0100626int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700627 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700628}
629
Mike Lockwood94afecf2012-10-24 10:45:23 -0700630int delete_dir_contents(const char *pathname,
631 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100632 int (*exclusion_predicate)(const char*, const int),
633 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700634{
635 int res = 0;
636 DIR *d;
637
638 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700639 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100640 if (ignore_if_missing && (errno == ENOENT)) {
641 return 0;
642 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700643 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
644 return -errno;
645 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100646 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700647 closedir(d);
648 if (also_delete_dir) {
649 if (rmdir(pathname)) {
650 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
651 res = -1;
652 }
653 }
654 return res;
655}
656
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800657static std::string make_unique_name(std::string_view suffix) {
658 static constexpr auto uuidStringSize = 36;
659
660 uuid_t guid;
661 uuid_generate(guid);
662
663 std::string name;
664 const auto suffixSize = suffix.size();
665 name.reserve(uuidStringSize + suffixSize);
666
667 name.resize(uuidStringSize);
668 uuid_unparse(guid, name.data());
669 name.append(suffix);
670
671 return name;
672}
673
674static int rename_delete_dir_contents(const std::string& pathname,
675 int (*exclusion_predicate)(const char*, const int),
676 bool ignore_if_missing) {
677 auto temp_dir_name = make_unique_name(deletedSuffix);
678 auto temp_dir_path =
679 base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
680
681 if (::rename(pathname.c_str(), temp_dir_path.c_str())) {
682 if (ignore_if_missing && (errno == ENOENT)) {
683 return 0;
684 }
685 ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), temp_dir_path.c_str(),
686 strerror(errno));
687 return -errno;
688 }
689
690 return delete_dir_contents(temp_dir_path.c_str(), 1, exclusion_predicate, ignore_if_missing);
691}
692
Alex Buynytskyy4ab5d532022-02-17 21:20:10 +0000693bool is_renamed_deleted_dir(const std::string& path) {
694 if (path.size() < deletedSuffix.size()) {
695 return false;
696 }
697 std::string_view pathSuffix{path.c_str() + path.size() - deletedSuffix.size()};
698 return pathSuffix == deletedSuffix;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800699}
700
701int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
702 return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
703}
704
705static auto open_dir(const char* dir) {
706 struct DirCloser {
707 void operator()(DIR* d) const noexcept { ::closedir(d); }
708 };
709 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
710}
711
Samiul Islam92f5cf02022-02-03 12:45:51 +0000712// Collects filename of subdirectories of given directory and passes it to the function
713int foreach_subdir(const std::string& pathname, const std::function<void(const std::string&)> fn) {
714 auto dir = open_dir(pathname.c_str());
715 if (!dir) return -1;
716
717 int dfd = dirfd(dir.get());
718 if (dfd < 0) {
719 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
720 return -1;
721 }
722
723 struct dirent* de;
724 while ((de = readdir(dir.get()))) {
725 if (de->d_type != DT_DIR) {
726 continue;
727 }
728
729 std::string name{de->d_name};
730 // always skip "." and ".."
731 if (name == "." || name == "..") {
732 continue;
733 }
734 fn(name);
735 }
736
737 return 0;
738}
739
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800740void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800741 auto dir = open_dir(pathname.c_str());
742 if (!dir) {
743 return;
744 }
745 int dfd = dirfd(dir.get());
746 if (dfd < 0) {
747 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
748 return;
749 }
750
751 struct dirent* de;
752 while ((de = readdir(dir.get()))) {
753 if (de->d_type != DT_DIR) {
754 continue;
755 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800756
757 std::string name{de->d_name};
758 // always skip "." and ".."
759 if (name == "." || name == "..") {
760 continue;
761 }
762
763 if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
764 !is_valid_package_name(name)) {
765 ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800766 // Deleting the content.
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800767 delete_dir_contents_fd(dfd, name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800768 // Deleting the directory
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800769 if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
770 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800771 }
772 }
773 }
774}
775
Mike Lockwood94afecf2012-10-24 10:45:23 -0700776int delete_dir_contents_fd(int dfd, const char *name)
777{
778 int fd, res;
779 DIR *d;
780
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700781 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700782 if (fd < 0) {
783 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
784 return -1;
785 }
786 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700787 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700788 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
789 close(fd);
790 return -1;
791 }
Yi Kong954cf642018-07-17 16:16:24 -0700792 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700793 closedir(d);
794 return res;
795}
796
Robin Lee60fd3fe2014-10-07 16:55:02 +0100797static int _copy_owner_permissions(int srcfd, int dstfd)
798{
799 struct stat st;
800 if (fstat(srcfd, &st) != 0) {
801 return -1;
802 }
803 if (fchmod(dstfd, st.st_mode) != 0) {
804 return -1;
805 }
806 return 0;
807}
808
809static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
810{
811 int result = 0;
812 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
813 ALOGE("_copy_dir_files failed to copy dir permissions\n");
814 }
815 if (fchown(ddfd, owner, group) != 0) {
816 ALOGE("_copy_dir_files failed to change dir owner\n");
817 }
818
819 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700820 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100821 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
822 return -1;
823 }
824 struct dirent *de;
825 while ((de = readdir(ds))) {
826 if (de->d_type != DT_REG) {
827 continue;
828 }
829
830 const char *name = de->d_name;
831 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
832 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
833 if (fsfd == -1 || fdfd == -1) {
834 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
835 } else {
836 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
837 ALOGE("Failed to change file permissions\n");
838 }
839 if (fchown(fdfd, owner, group) != 0) {
840 ALOGE("Failed to change file owner\n");
841 }
842
843 char buf[8192];
844 ssize_t size;
845 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
846 write(fdfd, buf, size);
847 }
848 if (size < 0) {
849 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
850 result = -1;
851 }
852 }
853 close(fdfd);
854 close(fsfd);
855 }
856
857 return result;
858}
859
860int copy_dir_files(const char *srcname,
861 const char *dstname,
862 uid_t owner,
863 uid_t group)
864{
865 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700866 DIR *ds = nullptr;
867 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100868
869 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700870 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100871 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
872 return -errno;
873 }
874
875 mkdir(dstname, 0600);
876 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700877 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100878 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
879 closedir(ds);
880 return -errno;
881 }
882
883 int sdfd = dirfd(ds);
884 int ddfd = dirfd(dd);
885 if (sdfd != -1 && ddfd != -1) {
886 res = _copy_dir_files(sdfd, ddfd, owner, group);
887 } else {
888 res = -errno;
889 }
890 closedir(dd);
891 closedir(ds);
892 return res;
893}
894
Jeff Sharkeya836c472017-04-02 23:29:30 -0600895int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600896 struct statvfs sfs;
897 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600898 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700899 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600900 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700901 return -1;
902 }
903}
904
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600905int get_path_inode(const std::string& path, ino_t *inode) {
906 struct stat buf;
907 memset(&buf, 0, sizeof(buf));
908 if (stat(path.c_str(), &buf) != 0) {
909 PLOG(WARNING) << "Failed to stat " << path;
910 return -1;
911 } else {
912 *inode = buf.st_ino;
913 return 0;
914 }
915}
916
917/**
918 * Write the inode of a specific child file into the given xattr on the
919 * parent directory. This allows you to find the child later, even if its
920 * name is encrypted.
921 */
922int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
923 ino_t inode = 0;
924 uint64_t inode_raw = 0;
925 auto path = StringPrintf("%s/%s", parent.c_str(), name);
926
927 if (get_path_inode(path, &inode) != 0) {
928 // Path probably doesn't exist yet; ignore
929 return 0;
930 }
931
932 // Check to see if already set correctly
933 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
934 if (inode_raw == inode) {
935 // Already set correctly; skip writing
936 return 0;
937 } else {
938 PLOG(WARNING) << "Mismatched inode value; found " << inode
939 << " on disk but marked value was " << inode_raw << "; overwriting";
940 }
941 }
942
943 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600944 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600945 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
946 return -1;
947 } else {
948 return 0;
949 }
950}
951
952/**
953 * Read the inode of a specific child file from the given xattr on the
954 * parent directory. Returns a currently valid path for that child, which
955 * might have an encrypted name.
956 */
957std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
958 ino_t inode = 0;
959 uint64_t inode_raw = 0;
960 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
961
962 // Lookup the inode value written earlier
963 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
964 inode = inode_raw;
965 }
966
967 // For testing purposes, rely on the inode when defined; this could be
968 // optimized to use access() in the future.
969 if (inode != 0) {
970 DIR* dir = opendir(parent.c_str());
971 if (dir == nullptr) {
972 PLOG(ERROR) << "Failed to opendir " << parent;
973 return fallback;
974 }
975
976 struct dirent* ent;
977 while ((ent = readdir(dir))) {
978 if (ent->d_ino == inode) {
979 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
980#if DEBUG_XATTRS
981 if (resolved != fallback) {
982 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
983 << " instead of " << fallback;
984 }
985#endif
986 closedir(dir);
987 return resolved;
988 }
989 }
990 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
991 closedir(dir);
992 return fallback;
993 } else {
994 return fallback;
995 }
996}
997
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900998void remove_path_xattr(const std::string& path, const char* inode_xattr) {
999 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
1000 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
1001 }
1002}
1003
Mike Lockwood94afecf2012-10-24 10:45:23 -07001004/**
Calin Juravlec597b6d2014-08-19 17:43:05 +01001005 * Validate that the path is valid in the context of the provided directory.
1006 * The path is allowed to have at most one subdirectory and no indirections
1007 * to top level directories (i.e. have "..").
1008 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001009static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +00001010 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001011 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
1012 || dir.find("..") != std::string::npos) {
1013 LOG(ERROR) << "Invalid directory " << dir;
1014 return -1;
1015 }
1016 if (path.find("..") != std::string::npos) {
1017 LOG(ERROR) << "Invalid path " << path;
1018 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +01001019 }
1020
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001021 if (path.compare(0, dir.size(), dir) != 0) {
1022 // Common case, path isn't under directory
1023 return -1;
1024 }
1025
1026 // Count number of subdirectories
1027 auto pos = path.find('/', dir.size());
1028 int count = 0;
1029 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -06001030 auto next = path.find('/', pos + 1);
1031 if (next > pos + 1) {
1032 count++;
1033 }
1034 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001035 }
1036
1037 if (count > maxSubdirs) {
1038 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +01001039 return -1;
1040 }
1041
1042 return 0;
1043}
1044
1045/**
Mike Lockwood94afecf2012-10-24 10:45:23 -07001046 * Checks whether a path points to a system app (.apk file). Returns 0
1047 * if it is a system app or -1 if it is not.
1048 */
1049int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001050 std::string path_ = path;
1051 for (const auto& dir : android_system_dirs) {
1052 if (validate_path(dir, path, 1) == 0) {
1053 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001054 }
1055 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001056 return -1;
1057}
1058
Calin Juravle114f0812017-03-08 19:05:07 -08001059bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -07001060 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -08001061 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1062
Calin Juravle3760ad32017-07-27 16:31:55 -07001063 // Empty paths are not allowed.
1064 if (dex_path.empty()) { return false; }
1065 // First character should always be '/'. No relative paths.
1066 if (dex_path[0] != '/') { return false; }
1067 // The last character should not be '/'.
1068 if (dex_path[dex_path.size() - 1] == '/') { return false; }
1069 // There should be no '.' after the directory marker.
1070 if (dex_path.find("/.") != std::string::npos) { return false; }
1071 // The path should be at most PKG_PATH_MAX long.
1072 if (dex_path.size() > PKG_PATH_MAX) { return false; }
1073
Calin Juravle7d765462017-09-04 15:57:10 -07001074 // The dex_path should be under the app data directory.
1075 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -07001076 ? create_data_user_ce_package_path(
1077 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1078 : create_data_user_de_package_path(
1079 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -07001080
Calin Juravle7d765462017-09-04 15:57:10 -07001081 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1082 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1083 // If that's the case, attempt to validate against the user data link.
1084 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1085 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1086 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1087 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -07001088 return false;
1089 }
Calin Juravle42451c02017-01-17 14:43:25 -08001090 }
Calin Juravle3760ad32017-07-27 16:31:55 -07001091
1092 // If we got here we have a valid path.
1093 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001094}
1095
Mike Lockwood94afecf2012-10-24 10:45:23 -07001096/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001097 * Check whether path points to a valid path for an APK file. The path must
1098 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1099 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1100 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001101 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001102static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1103 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001104 return 0;
shafikb43faa92019-02-19 12:19:48 +00001105 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1106 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001107 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001108 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001109 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001110 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001111 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001112 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001113 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1114 // Rewrite the path as if it were on internal storage, and test that
1115 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1116 if (end != std::string::npos) {
1117 auto modified = path;
1118 modified.replace(0, end + 1, android_data_dir);
1119 return validate_apk_path_internal(modified, maxSubdirs);
1120 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001121 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001122 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001123}
1124
Narayan Kamathd845c962015-06-04 13:20:27 +01001125int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001126 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001127}
1128
1129int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001130 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001131}
1132
Robin Lee095c7632014-04-25 15:05:19 +01001133int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001134 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001135 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1136 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001137
1138 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001139 auto path = create_data_misc_legacy_path(userid);
1140 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001141}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001142
Jiakai Zhang495142a2022-02-21 19:38:14 +00001143static int wait_child(pid_t pid) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001144 int status;
Jiakai Zhang495142a2022-02-21 19:38:14 +00001145 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, /*options=*/0));
Andreas Gampe02d0de52015-11-11 20:43:16 -08001146
Andreas Gampe02d0de52015-11-11 20:43:16 -08001147 if (got_pid != pid) {
Jiakai Zhang495142a2022-02-21 19:38:14 +00001148 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
1149 return W_EXITCODE(/*exit_code=*/255, /*signal_number=*/0);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001150 }
1151
Jiakai Zhang495142a2022-02-21 19:38:14 +00001152 return status;
1153}
1154
1155int wait_child_with_timeout(pid_t pid, int timeout_ms) {
1156 int pidfd = pidfd_open(pid, /*flags=*/0);
1157 if (pidfd < 0) {
1158 PLOG(ERROR) << "pidfd_open failed for pid " << pid;
1159 kill(pid, SIGKILL);
1160 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001161 }
Jiakai Zhang495142a2022-02-21 19:38:14 +00001162
1163 struct pollfd pfd;
1164 pfd.fd = pidfd;
1165 pfd.events = POLLIN;
1166 int poll_ret = TEMP_FAILURE_RETRY(poll(&pfd, /*nfds=*/1, timeout_ms));
1167
1168 close(pidfd);
1169
1170 if (poll_ret < 0) {
1171 PLOG(ERROR) << "poll failed for pid " << pid;
1172 kill(pid, SIGKILL);
1173 return wait_child(pid);
1174 }
1175 if (poll_ret == 0) {
1176 LOG(WARNING) << "Child process " << pid << " timed out after " << timeout_ms
1177 << "ms. Killing it";
1178 kill(pid, SIGKILL);
1179 return wait_child(pid);
1180 }
1181 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001182}
1183
Calin Juravle42451c02017-01-17 14:43:25 -08001184/**
1185 * Prepare an app cache directory, which offers to fix-up the GID and
1186 * directory mode flags during a platform upgrade.
1187 * The app cache directory path will be 'parent'/'name'.
1188 */
1189int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1190 uid_t uid, gid_t gid) {
1191 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1192 struct stat st;
1193 if (stat(path.c_str(), &st) != 0) {
1194 if (errno == ENOENT) {
1195 // This is fine, just create it
1196 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1197 PLOG(ERROR) << "Failed to prepare " << path;
1198 return -1;
1199 } else {
1200 return 0;
1201 }
1202 } else {
1203 PLOG(ERROR) << "Failed to stat " << path;
1204 return -1;
1205 }
1206 }
1207
1208 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1209 if (st.st_uid != uid) {
1210 // Mismatched UID is real trouble; we can't recover
1211 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1212 << " but expected " << uid;
1213 return -1;
1214 } else if (st.st_gid == gid && actual_mode == target_mode) {
1215 // Everything looks good!
1216 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001217 } else {
1218 // Mismatched GID/mode is recoverable; fall through to update
1219 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001220 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001221 }
1222
1223 // Directory is owned correctly, but GID or mode mismatch means it's
1224 // probably a platform upgrade so we need to fix them
1225 FTS *fts;
1226 FTSENT *p;
1227 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001228 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001229 PLOG(ERROR) << "Failed to fts_open " << path;
1230 return -1;
1231 }
Yi Kong954cf642018-07-17 16:16:24 -07001232 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001233 switch (p->fts_info) {
1234 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001235 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001236 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1237 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001238 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001239 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001240 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001241 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1242 }
1243 break;
1244 case FTS_SL:
1245 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001246 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001247 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1248 }
1249 break;
1250 }
1251 }
1252 fts_close(fts);
1253 return 0;
1254}
1255
Martijn Coenen771cc342020-02-19 23:26:56 +01001256static const char* kProcFilesystems = "/proc/filesystems";
1257bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001258 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1259 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001260 std::string supported;
1261 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1262 PLOG(ERROR) << "Failed to read supported filesystems";
1263 return false;
1264 }
1265 return supported.find("sdcardfs\n") != std::string::npos;
1266}
1267
1268int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1269 static const bool supportsSdcardFs = supports_sdcardfs();
1270
1271 if (supportsSdcardFs) {
1272 int extGid = multiuser_get_ext_gid(userId, appId);
1273
1274 if (extGid == -1) {
1275 return -1;
1276 }
1277
1278 return GetOccupiedSpaceForGid(uuid, extGid);
1279 } else {
1280 uid_t uid = multiuser_get_uid(userId, appId);
1281 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1282 return GetOccupiedSpaceForProjectId(uuid, projectId);
1283 }
1284}
1285int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1286 static const bool supportsSdcardFs = supports_sdcardfs();
1287
1288 if (supportsSdcardFs) {
1289 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1290
1291 if (extCacheGid == -1) {
1292 return -1;
1293 }
1294
1295 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1296 } else {
1297 uid_t uid = multiuser_get_uid(userId, appId);
1298 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1299 return GetOccupiedSpaceForProjectId(uuid, projectId);
1300 }
1301}
1302
Calin Juravlee61189e2018-01-23 19:54:11 -08001303// Collect all non empty profiles from the given directory and puts then into profile_paths.
1304// The profiles are identified based on PROFILE_EXT extension.
1305// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1306// It returns true if there were no errors at all, and false otherwise.
1307static bool collect_profiles(DIR* d,
1308 const std::string& current_path,
1309 std::vector<std::string>* profiles_paths) {
1310 int32_t dir_fd = dirfd(d);
1311 if (dir_fd < 0) {
1312 return false;
1313 }
1314
1315 bool result = true;
1316 struct dirent* dir_entry;
1317 while ((dir_entry = readdir(d))) {
1318 std::string name = dir_entry->d_name;
1319 std::string local_path = current_path + "/" + name;
1320
1321 if (dir_entry->d_type == DT_REG) {
1322 // Check if this is a non empty profile file.
1323 if (EndsWith(name, PROFILE_EXT)) {
1324 struct stat st;
1325 if (stat(local_path.c_str(), &st) != 0) {
1326 PLOG(WARNING) << "Cannot stat local path " << local_path;
1327 result = false;
1328 continue;
1329 } else if (st.st_size > 0) {
1330 profiles_paths->push_back(local_path);
1331 }
1332 }
1333 } else if (dir_entry->d_type == DT_DIR) {
1334 // always skip "." and ".."
1335 if (name == "." || name == "..") {
1336 continue;
1337 }
1338
1339 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1340 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1341 if (subdir_fd < 0) {
1342 PLOG(WARNING) << "Could not open dir path " << local_path;
1343 result = false;
1344 continue;
1345 }
1346
Mathieu Chartier89883e32018-11-01 11:39:00 -07001347 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001348 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001349 PLOG(WARNING) << "Could not open dir path " << local_path;
1350 result = false;
1351 continue;
1352 }
1353 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1354 result = result && new_result;
1355 if (closedir(subdir) != 0) {
1356 PLOG(WARNING) << "Could not close dir path " << local_path;
1357 }
1358 }
1359 }
1360
1361 return result;
1362}
1363
1364bool collect_profiles(std::vector<std::string>* profiles_paths) {
1365 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001366 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001367 return false;
1368 } else {
1369 return collect_profiles(d, android_profiles_dir, profiles_paths);
1370 }
1371}
1372
Eric Holk2af5e6a2019-01-09 18:17:27 -08001373void drop_capabilities(uid_t uid) {
1374 if (setgid(uid) != 0) {
1375 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1376 exit(DexoptReturnCodes::kSetGid);
1377 }
1378 if (setuid(uid) != 0) {
1379 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1380 exit(DexoptReturnCodes::kSetUid);
1381 }
1382 // drop capabilities
1383 struct __user_cap_header_struct capheader;
1384 struct __user_cap_data_struct capdata[2];
1385 memset(&capheader, 0, sizeof(capheader));
1386 memset(&capdata, 0, sizeof(capdata));
1387 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1388 if (capset(&capheader, &capdata[0]) < 0) {
1389 PLOG(ERROR) << "capset failed";
1390 exit(DexoptReturnCodes::kCapSet);
1391 }
1392}
1393
Jiakai Zhang495142a2022-02-21 19:38:14 +00001394bool remove_file_at_fd(int fd, /*out*/ std::string* path) {
1395 char path_buffer[PATH_MAX + 1];
1396 std::string proc_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
1397 ssize_t len = readlink(proc_path.c_str(), path_buffer, PATH_MAX);
1398 if (len < 0) {
1399 PLOG(WARNING) << "Could not remove file at fd " << fd << ": Failed to get file path";
1400 return false;
1401 }
1402 path_buffer[len] = '\0';
1403 if (path != nullptr) {
1404 *path = path_buffer;
1405 }
1406 if (unlink(path_buffer) != 0) {
1407 if (errno == ENOENT) {
1408 return true;
1409 }
1410 PLOG(WARNING) << "Could not remove file at path " << path_buffer;
1411 return false;
1412 }
1413 return true;
1414}
1415
Andreas Gampe02d0de52015-11-11 20:43:16 -08001416} // namespace installd
1417} // namespace android