blob: 123e3d418163ddaab8f4e6a1644e088f9733a3fe [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/**
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000226 * Create the path name where sdk data for a particular sdk will be stored.
227 * E.g. /data/misc_ce/0/sdksandbox/<package-name>/com.foo@randomstrings
Samiul Islam92f5cf02022-02-03 12:45:51 +0000228 */
229std::string create_data_misc_sdk_sandbox_sdk_path(const char* volume_uuid, bool isCeData,
230 userid_t user, const char* package_name,
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000231 const char* sub_dir_name) {
232 return StringPrintf("%s/%s",
233 create_data_misc_sdk_sandbox_package_path(volume_uuid, isCeData, user,
234 package_name)
235 .c_str(),
236 sub_dir_name);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000237}
238
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000239std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000240 return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
241}
242
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000243std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000244 return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
245}
246
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000247std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
248 int32_t snapshot_id) {
249 return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
250 snapshot_id);
251}
252
253std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
254 int32_t snapshot_id) {
255 return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
256 snapshot_id);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000257}
258
Nikita Ioffe8755f792019-01-25 13:54:43 +0000259std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000260 userid_t user, int32_t snapshot_id, const char* package_name) {
261 return StringPrintf("%s/%s",
262 create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
263}
264
265std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
266 userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
267 auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
268 package_name);
269 auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000270 return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
271}
272
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000273std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000274 userid_t user, int32_t snapshot_id, const char* package_name) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000275 return StringPrintf("%s/%s",
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000276 create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000277}
278
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800279/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700280 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700281 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700282std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
283 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700284}
285
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700286std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
287 const char* data_type, const char* package_name) {
288 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
289 data_type, package_name);
290}
291
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600292std::string create_data_misc_legacy_path(userid_t userid) {
293 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
294}
295
Calin Juravle114f0812017-03-08 19:05:07 -0800296std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600297 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000298}
299
Calin Juravle114f0812017-03-08 19:05:07 -0800300std::string create_primary_current_profile_package_dir_path(userid_t user,
301 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800302 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800303 return StringPrintf("%s/%s",
304 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700305}
306
Calin Juravle114f0812017-03-08 19:05:07 -0800307std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600308 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000309}
310
Calin Juravle114f0812017-03-08 19:05:07 -0800311std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800312 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600313 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000314}
315
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700316std::string create_data_dalvik_cache_path() {
317 return "/data/dalvik-cache";
318}
319
Felka Chang2a0a2462019-11-20 14:20:40 +0800320std::string create_system_user_ce_path(userid_t userId) {
321 return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
322}
323
324std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
325 check_package_name(package_name);
326 return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
327}
328
Calin Juravle114f0812017-03-08 19:05:07 -0800329// Keep profile paths in sync with ActivityThread and LoadedApk.
330const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700331const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800332const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700333
Calin Juravle3760ad32017-07-27 16:31:55 -0700334// Gets the parent directory and the file name for the given secondary dex path.
335// Returns true on success, false on failure (if the dex_path does not have the expected
336// structure).
337static bool get_secondary_dex_location(const std::string& dex_path,
338 std::string* out_dir_name, std::string* out_file_name) {
339 size_t dirIndex = dex_path.rfind('/');
340 if (dirIndex == std::string::npos) {
341 return false;
342 }
343 if (dirIndex == dex_path.size() - 1) {
344 return false;
345 }
346 *out_dir_name = dex_path.substr(0, dirIndex);
347 *out_file_name = dex_path.substr(dirIndex + 1);
348
349 return true;
350}
351
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800352std::string create_current_profile_path(userid_t user, const std::string& package_name,
353 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800354 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700355 // Secondary dex current profiles are stored next to the dex files under the oat folder.
356 std::string dex_dir;
357 std::string dex_name;
358 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
359 << "Unexpected dir structure for secondary dex " << location;
360 return StringPrintf("%s/oat/%s%s%s",
361 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
362 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800363 } else {
364 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800365 std::string profile_dir = create_primary_current_profile_package_dir_path(
366 user, package_name);
367 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800368 }
369}
370
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800371std::string create_reference_profile_path(const std::string& package_name,
372 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800373 if (is_secondary_dex) {
374 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700375 std::string dex_dir;
376 std::string dex_name;
377 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800378 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800379 return StringPrintf("%s/oat/%s%s",
380 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
381 } else {
382 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800383 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
384 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800385 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700386}
387
Calin Juravle29591732017-11-20 17:46:19 -0800388std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800389 const std::string& profile_name) {
390 std::string ref_profile = create_reference_profile_path(package, profile_name,
391 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800392 return ref_profile + SNAPSHOT_PROFILE_EXT;
393}
394
Jeff Sharkeye3637242015-04-08 20:56:42 -0700395std::vector<userid_t> get_known_users(const char* volume_uuid) {
396 std::vector<userid_t> users;
397
398 // We always have an owner
399 users.push_back(0);
400
401 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
402 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700403 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700404 // Unable to discover other users, but at least return owner
405 PLOG(ERROR) << "Failed to opendir " << path;
406 return users;
407 }
408
409 struct dirent* ent;
410 while ((ent = readdir(dir))) {
411 if (ent->d_type != DT_DIR) {
412 continue;
413 }
414
415 char* end;
416 userid_t user = strtol(ent->d_name, &end, 10);
417 if (*end == '\0' && user != 0) {
418 LOG(DEBUG) << "Found valid user " << user;
419 users.push_back(user);
420 }
421 }
422 closedir(dir);
423
424 return users;
425}
426
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700427int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700428 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700429 FTS *fts;
430 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700431 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700432 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700433 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700434 if (errno != ENOENT) {
435 PLOG(ERROR) << "Failed to fts_open " << path;
436 }
437 return -1;
438 }
Yi Kong954cf642018-07-17 16:16:24 -0700439 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700440 switch (p->fts_info) {
441 case FTS_D:
442 case FTS_DEFAULT:
443 case FTS_F:
444 case FTS_SL:
445 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700446 int32_t uid = p->fts_statp->st_uid;
447 int32_t gid = p->fts_statp->st_gid;
448 int32_t user_uid = multiuser_get_app_id(uid);
449 int32_t user_gid = multiuser_get_app_id(gid);
450 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
451 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
452 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
453 // Don't traverse inside or measure
454 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700455 break;
456 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700457 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700458 break;
459 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700460 if (exclude_gid != -1 && gid == exclude_gid) {
461 break;
462 }
463 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700464 break;
465 }
466 }
467 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700468#if MEASURE_DEBUG
469 if ((include_gid == -1) && (exclude_gid == -1)) {
470 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
471 } else {
472 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
473 << " exclude " << exclude_gid;
474 }
475#endif
476 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700477 return 0;
478}
479
Mike Lockwood94afecf2012-10-24 10:45:23 -0700480/**
481 * Checks whether the package name is valid. Returns -1 on error and
482 * 0 on success.
483 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700484bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700485 // This logic is borrowed from PackageParser.java
486 bool hasSep = false;
487 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700488
Jeff Sharkey367ace22017-03-07 22:12:03 -0700489 auto it = packageName.begin();
490 for (; it != packageName.end() && *it != '-'; it++) {
491 char c = *it;
492 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
493 front = false;
494 continue;
495 }
496 if (!front) {
497 if ((c >= '0' && c <= '9') || c == '_') {
498 continue;
499 }
500 }
501 if (c == '.') {
502 hasSep = true;
503 front = true;
504 continue;
505 }
506 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700507 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700508 }
509
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700510 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700511 LOG(WARNING) << "Missing separator in " << packageName;
512 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700513 }
514
Jeff Sharkey367ace22017-03-07 22:12:03 -0700515 for (; it != packageName.end(); it++) {
516 char c = *it;
517 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
518 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
519 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
520 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700521 }
522
Jeff Sharkey423e7462016-12-09 18:18:43 -0700523 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700524}
525
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100526static int _delete_dir_contents(DIR *d,
527 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700528{
529 int result = 0;
530 struct dirent *de;
531 int dfd;
532
533 dfd = dirfd(d);
534
535 if (dfd < 0) return -1;
536
537 while ((de = readdir(d))) {
538 const char *name = de->d_name;
539
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100540 /* check using the exclusion predicate, if provided */
541 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
542 continue;
543 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700544
545 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700546 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700547 DIR *subdir;
548
549 /* always skip "." and ".." */
550 if (name[0] == '.') {
551 if (name[1] == 0) continue;
552 if ((name[1] == '.') && (name[2] == 0)) continue;
553 }
554
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700555 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700556 if (subfd < 0) {
557 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
558 result = -1;
559 continue;
560 }
561 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700562 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700563 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
564 close(subfd);
565 result = -1;
566 continue;
567 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100568 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700569 result = -1;
570 }
571 closedir(subdir);
572 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
573 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
574 result = -1;
575 }
576 } else {
577 if (unlinkat(dfd, name, 0) < 0) {
578 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
579 result = -1;
580 }
581 }
582 }
583
584 return result;
585}
586
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000587int create_dir_if_needed(const std::string& pathname, mode_t perms) {
588 struct stat st;
589
590 int rc;
591 if ((rc = stat(pathname.c_str(), &st)) != 0) {
592 if (errno == ENOENT) {
593 return mkdir(pathname.c_str(), perms);
594 } else {
595 return rc;
596 }
597 } else if (!S_ISDIR(st.st_mode)) {
598 LOG(DEBUG) << pathname << " is not a folder";
599 return -1;
600 }
601
602 mode_t actual_perms = st.st_mode & ALLPERMS;
603 if (actual_perms != perms) {
604 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
605 return -1;
606 }
607
608 return 0;
609}
610
Calin Juravleb06f98a2016-03-28 15:11:01 +0100611int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700612 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700613}
614
Calin Juravleb06f98a2016-03-28 15:11:01 +0100615int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700616 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700617}
618
Mike Lockwood94afecf2012-10-24 10:45:23 -0700619int delete_dir_contents(const char *pathname,
620 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100621 int (*exclusion_predicate)(const char*, const int),
622 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700623{
624 int res = 0;
625 DIR *d;
626
627 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700628 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100629 if (ignore_if_missing && (errno == ENOENT)) {
630 return 0;
631 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700632 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
633 return -errno;
634 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100635 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700636 closedir(d);
637 if (also_delete_dir) {
638 if (rmdir(pathname)) {
639 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
640 res = -1;
641 }
642 }
643 return res;
644}
645
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800646static std::string make_unique_name(std::string_view suffix) {
647 static constexpr auto uuidStringSize = 36;
648
649 uuid_t guid;
650 uuid_generate(guid);
651
652 std::string name;
653 const auto suffixSize = suffix.size();
654 name.reserve(uuidStringSize + suffixSize);
655
656 name.resize(uuidStringSize);
657 uuid_unparse(guid, name.data());
658 name.append(suffix);
659
660 return name;
661}
662
663static int rename_delete_dir_contents(const std::string& pathname,
664 int (*exclusion_predicate)(const char*, const int),
665 bool ignore_if_missing) {
666 auto temp_dir_name = make_unique_name(deletedSuffix);
667 auto temp_dir_path =
668 base::StringPrintf("%s/%s", Dirname(pathname).c_str(), temp_dir_name.c_str());
669
670 if (::rename(pathname.c_str(), temp_dir_path.c_str())) {
671 if (ignore_if_missing && (errno == ENOENT)) {
672 return 0;
673 }
674 ALOGE("Couldn't rename %s -> %s: %s \n", pathname.c_str(), temp_dir_path.c_str(),
675 strerror(errno));
676 return -errno;
677 }
678
679 return delete_dir_contents(temp_dir_path.c_str(), 1, exclusion_predicate, ignore_if_missing);
680}
681
Alex Buynytskyy4ab5d532022-02-17 21:20:10 +0000682bool is_renamed_deleted_dir(const std::string& path) {
683 if (path.size() < deletedSuffix.size()) {
684 return false;
685 }
686 std::string_view pathSuffix{path.c_str() + path.size() - deletedSuffix.size()};
687 return pathSuffix == deletedSuffix;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800688}
689
690int rename_delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
691 return rename_delete_dir_contents(pathname, nullptr, ignore_if_missing);
692}
693
694static auto open_dir(const char* dir) {
695 struct DirCloser {
696 void operator()(DIR* d) const noexcept { ::closedir(d); }
697 };
698 return std::unique_ptr<DIR, DirCloser>(::opendir(dir));
699}
700
Samiul Islam92f5cf02022-02-03 12:45:51 +0000701// Collects filename of subdirectories of given directory and passes it to the function
702int foreach_subdir(const std::string& pathname, const std::function<void(const std::string&)> fn) {
703 auto dir = open_dir(pathname.c_str());
704 if (!dir) return -1;
705
706 int dfd = dirfd(dir.get());
707 if (dfd < 0) {
708 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
709 return -1;
710 }
711
712 struct dirent* de;
713 while ((de = readdir(dir.get()))) {
714 if (de->d_type != DT_DIR) {
715 continue;
716 }
717
718 std::string name{de->d_name};
719 // always skip "." and ".."
720 if (name == "." || name == "..") {
721 continue;
722 }
723 fn(name);
724 }
725
726 return 0;
727}
728
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800729void cleanup_invalid_package_dirs_under_path(const std::string& pathname) {
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800730 auto dir = open_dir(pathname.c_str());
731 if (!dir) {
732 return;
733 }
734 int dfd = dirfd(dir.get());
735 if (dfd < 0) {
736 ALOGE("Couldn't dirfd %s: %s\n", pathname.c_str(), strerror(errno));
737 return;
738 }
739
740 struct dirent* de;
741 while ((de = readdir(dir.get()))) {
742 if (de->d_type != DT_DIR) {
743 continue;
744 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800745
746 std::string name{de->d_name};
747 // always skip "." and ".."
748 if (name == "." || name == "..") {
749 continue;
750 }
751
752 if (is_renamed_deleted_dir(name) || !is_valid_filename(name) ||
753 !is_valid_package_name(name)) {
754 ALOGI("Deleting renamed or invalid data directory: %s\n", name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800755 // Deleting the content.
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800756 delete_dir_contents_fd(dfd, name.c_str());
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800757 // Deleting the directory
Alex Buynytskyy58a73092022-02-14 13:15:53 -0800758 if (unlinkat(dfd, name.c_str(), AT_REMOVEDIR) < 0) {
759 ALOGE("Couldn't unlinkat %s: %s\n", name.c_str(), strerror(errno));
Alex Buynytskyy038a19b2022-02-09 19:51:52 -0800760 }
761 }
762 }
763}
764
Mike Lockwood94afecf2012-10-24 10:45:23 -0700765int delete_dir_contents_fd(int dfd, const char *name)
766{
767 int fd, res;
768 DIR *d;
769
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700770 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700771 if (fd < 0) {
772 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
773 return -1;
774 }
775 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700776 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700777 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
778 close(fd);
779 return -1;
780 }
Yi Kong954cf642018-07-17 16:16:24 -0700781 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700782 closedir(d);
783 return res;
784}
785
Robin Lee60fd3fe2014-10-07 16:55:02 +0100786static int _copy_owner_permissions(int srcfd, int dstfd)
787{
788 struct stat st;
789 if (fstat(srcfd, &st) != 0) {
790 return -1;
791 }
792 if (fchmod(dstfd, st.st_mode) != 0) {
793 return -1;
794 }
795 return 0;
796}
797
798static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
799{
800 int result = 0;
801 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
802 ALOGE("_copy_dir_files failed to copy dir permissions\n");
803 }
804 if (fchown(ddfd, owner, group) != 0) {
805 ALOGE("_copy_dir_files failed to change dir owner\n");
806 }
807
808 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700809 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100810 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
811 return -1;
812 }
813 struct dirent *de;
814 while ((de = readdir(ds))) {
815 if (de->d_type != DT_REG) {
816 continue;
817 }
818
819 const char *name = de->d_name;
820 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
821 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
822 if (fsfd == -1 || fdfd == -1) {
823 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
824 } else {
825 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
826 ALOGE("Failed to change file permissions\n");
827 }
828 if (fchown(fdfd, owner, group) != 0) {
829 ALOGE("Failed to change file owner\n");
830 }
831
832 char buf[8192];
833 ssize_t size;
834 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
835 write(fdfd, buf, size);
836 }
837 if (size < 0) {
838 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
839 result = -1;
840 }
841 }
842 close(fdfd);
843 close(fsfd);
844 }
845
846 return result;
847}
848
849int copy_dir_files(const char *srcname,
850 const char *dstname,
851 uid_t owner,
852 uid_t group)
853{
854 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700855 DIR *ds = nullptr;
856 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100857
858 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700859 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100860 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
861 return -errno;
862 }
863
864 mkdir(dstname, 0600);
865 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700866 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100867 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
868 closedir(ds);
869 return -errno;
870 }
871
872 int sdfd = dirfd(ds);
873 int ddfd = dirfd(dd);
874 if (sdfd != -1 && ddfd != -1) {
875 res = _copy_dir_files(sdfd, ddfd, owner, group);
876 } else {
877 res = -errno;
878 }
879 closedir(dd);
880 closedir(ds);
881 return res;
882}
883
Jeff Sharkeya836c472017-04-02 23:29:30 -0600884int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600885 struct statvfs sfs;
886 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600887 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700888 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600889 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700890 return -1;
891 }
892}
893
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600894int get_path_inode(const std::string& path, ino_t *inode) {
895 struct stat buf;
896 memset(&buf, 0, sizeof(buf));
897 if (stat(path.c_str(), &buf) != 0) {
898 PLOG(WARNING) << "Failed to stat " << path;
899 return -1;
900 } else {
901 *inode = buf.st_ino;
902 return 0;
903 }
904}
905
906/**
907 * Write the inode of a specific child file into the given xattr on the
908 * parent directory. This allows you to find the child later, even if its
909 * name is encrypted.
910 */
911int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
912 ino_t inode = 0;
913 uint64_t inode_raw = 0;
914 auto path = StringPrintf("%s/%s", parent.c_str(), name);
915
916 if (get_path_inode(path, &inode) != 0) {
917 // Path probably doesn't exist yet; ignore
918 return 0;
919 }
920
921 // Check to see if already set correctly
922 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
923 if (inode_raw == inode) {
924 // Already set correctly; skip writing
925 return 0;
926 } else {
927 PLOG(WARNING) << "Mismatched inode value; found " << inode
928 << " on disk but marked value was " << inode_raw << "; overwriting";
929 }
930 }
931
932 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600933 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600934 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
935 return -1;
936 } else {
937 return 0;
938 }
939}
940
941/**
942 * Read the inode of a specific child file from the given xattr on the
943 * parent directory. Returns a currently valid path for that child, which
944 * might have an encrypted name.
945 */
946std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
947 ino_t inode = 0;
948 uint64_t inode_raw = 0;
949 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
950
951 // Lookup the inode value written earlier
952 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
953 inode = inode_raw;
954 }
955
956 // For testing purposes, rely on the inode when defined; this could be
957 // optimized to use access() in the future.
958 if (inode != 0) {
959 DIR* dir = opendir(parent.c_str());
960 if (dir == nullptr) {
961 PLOG(ERROR) << "Failed to opendir " << parent;
962 return fallback;
963 }
964
965 struct dirent* ent;
966 while ((ent = readdir(dir))) {
967 if (ent->d_ino == inode) {
968 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
969#if DEBUG_XATTRS
970 if (resolved != fallback) {
971 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
972 << " instead of " << fallback;
973 }
974#endif
975 closedir(dir);
976 return resolved;
977 }
978 }
979 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
980 closedir(dir);
981 return fallback;
982 } else {
983 return fallback;
984 }
985}
986
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900987void remove_path_xattr(const std::string& path, const char* inode_xattr) {
988 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
989 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
990 }
991}
992
Mike Lockwood94afecf2012-10-24 10:45:23 -0700993/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100994 * Validate that the path is valid in the context of the provided directory.
995 * The path is allowed to have at most one subdirectory and no indirections
996 * to top level directories (i.e. have "..").
997 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600998static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
Hanna Nizhnikavab35b8722022-01-21 16:59:56 +0000999 // Argument check
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001000 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
1001 || dir.find("..") != std::string::npos) {
1002 LOG(ERROR) << "Invalid directory " << dir;
1003 return -1;
1004 }
1005 if (path.find("..") != std::string::npos) {
1006 LOG(ERROR) << "Invalid path " << path;
1007 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +01001008 }
1009
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001010 if (path.compare(0, dir.size(), dir) != 0) {
1011 // Common case, path isn't under directory
1012 return -1;
1013 }
1014
1015 // Count number of subdirectories
1016 auto pos = path.find('/', dir.size());
1017 int count = 0;
1018 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -06001019 auto next = path.find('/', pos + 1);
1020 if (next > pos + 1) {
1021 count++;
1022 }
1023 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001024 }
1025
1026 if (count > maxSubdirs) {
1027 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +01001028 return -1;
1029 }
1030
1031 return 0;
1032}
1033
1034/**
Mike Lockwood94afecf2012-10-24 10:45:23 -07001035 * Checks whether a path points to a system app (.apk file). Returns 0
1036 * if it is a system app or -1 if it is not.
1037 */
1038int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001039 std::string path_ = path;
1040 for (const auto& dir : android_system_dirs) {
1041 if (validate_path(dir, path, 1) == 0) {
1042 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001043 }
1044 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001045 return -1;
1046}
1047
Calin Juravle114f0812017-03-08 19:05:07 -08001048bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -07001049 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -08001050 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
1051
Calin Juravle3760ad32017-07-27 16:31:55 -07001052 // Empty paths are not allowed.
1053 if (dex_path.empty()) { return false; }
1054 // First character should always be '/'. No relative paths.
1055 if (dex_path[0] != '/') { return false; }
1056 // The last character should not be '/'.
1057 if (dex_path[dex_path.size() - 1] == '/') { return false; }
1058 // There should be no '.' after the directory marker.
1059 if (dex_path.find("/.") != std::string::npos) { return false; }
1060 // The path should be at most PKG_PATH_MAX long.
1061 if (dex_path.size() > PKG_PATH_MAX) { return false; }
1062
Calin Juravle7d765462017-09-04 15:57:10 -07001063 // The dex_path should be under the app data directory.
1064 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -07001065 ? create_data_user_ce_package_path(
1066 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
1067 : create_data_user_de_package_path(
1068 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -07001069
Calin Juravle7d765462017-09-04 15:57:10 -07001070 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
1071 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
1072 // If that's the case, attempt to validate against the user data link.
1073 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
1074 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
1075 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
1076 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -07001077 return false;
1078 }
Calin Juravle42451c02017-01-17 14:43:25 -08001079 }
Calin Juravle3760ad32017-07-27 16:31:55 -07001080
1081 // If we got here we have a valid path.
1082 return true;
Calin Juravle42451c02017-01-17 14:43:25 -08001083}
1084
Mike Lockwood94afecf2012-10-24 10:45:23 -07001085/**
Narayan Kamathd845c962015-06-04 13:20:27 +01001086 * Check whether path points to a valid path for an APK file. The path must
1087 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
1088 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
1089 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -07001090 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001091static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
1092 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001093 return 0;
shafikb43faa92019-02-19 12:19:48 +00001094 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
1095 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001096 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001097 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001098 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001099 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001100 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -06001101 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001102 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
1103 // Rewrite the path as if it were on internal storage, and test that
1104 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
1105 if (end != std::string::npos) {
1106 auto modified = path;
1107 modified.replace(0, end + 1, android_data_dir);
1108 return validate_apk_path_internal(modified, maxSubdirs);
1109 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001110 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -06001111 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001112}
1113
Narayan Kamathd845c962015-06-04 13:20:27 +01001114int validate_apk_path(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001115 return validate_apk_path_internal(path, 2 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001116}
1117
1118int validate_apk_path_subdirs(const char* path) {
Songchun Fan29556092020-01-23 14:51:45 -08001119 return validate_apk_path_internal(path, 4 /* maxSubdirs */);
Narayan Kamathd845c962015-06-04 13:20:27 +01001120}
1121
Robin Lee095c7632014-04-25 15:05:19 +01001122int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +01001123 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +01001124 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
1125 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +01001126
1127 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001128 auto path = create_data_misc_legacy_path(userid);
1129 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +01001130}
Andreas Gampe02d0de52015-11-11 20:43:16 -08001131
Jiakai Zhang495142a2022-02-21 19:38:14 +00001132static int wait_child(pid_t pid) {
Andreas Gampe02d0de52015-11-11 20:43:16 -08001133 int status;
Jiakai Zhang495142a2022-02-21 19:38:14 +00001134 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, /*options=*/0));
Andreas Gampe02d0de52015-11-11 20:43:16 -08001135
Andreas Gampe02d0de52015-11-11 20:43:16 -08001136 if (got_pid != pid) {
Jiakai Zhang495142a2022-02-21 19:38:14 +00001137 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
1138 return W_EXITCODE(/*exit_code=*/255, /*signal_number=*/0);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001139 }
1140
Jiakai Zhang495142a2022-02-21 19:38:14 +00001141 return status;
1142}
1143
1144int wait_child_with_timeout(pid_t pid, int timeout_ms) {
1145 int pidfd = pidfd_open(pid, /*flags=*/0);
1146 if (pidfd < 0) {
1147 PLOG(ERROR) << "pidfd_open failed for pid " << pid;
1148 kill(pid, SIGKILL);
1149 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001150 }
Jiakai Zhang495142a2022-02-21 19:38:14 +00001151
1152 struct pollfd pfd;
1153 pfd.fd = pidfd;
1154 pfd.events = POLLIN;
1155 int poll_ret = TEMP_FAILURE_RETRY(poll(&pfd, /*nfds=*/1, timeout_ms));
1156
1157 close(pidfd);
1158
1159 if (poll_ret < 0) {
1160 PLOG(ERROR) << "poll failed for pid " << pid;
1161 kill(pid, SIGKILL);
1162 return wait_child(pid);
1163 }
1164 if (poll_ret == 0) {
1165 LOG(WARNING) << "Child process " << pid << " timed out after " << timeout_ms
1166 << "ms. Killing it";
1167 kill(pid, SIGKILL);
1168 return wait_child(pid);
1169 }
1170 return wait_child(pid);
Andreas Gampe02d0de52015-11-11 20:43:16 -08001171}
1172
Calin Juravle42451c02017-01-17 14:43:25 -08001173/**
1174 * Prepare an app cache directory, which offers to fix-up the GID and
1175 * directory mode flags during a platform upgrade.
1176 * The app cache directory path will be 'parent'/'name'.
1177 */
1178int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1179 uid_t uid, gid_t gid) {
1180 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1181 struct stat st;
1182 if (stat(path.c_str(), &st) != 0) {
1183 if (errno == ENOENT) {
1184 // This is fine, just create it
1185 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1186 PLOG(ERROR) << "Failed to prepare " << path;
1187 return -1;
1188 } else {
1189 return 0;
1190 }
1191 } else {
1192 PLOG(ERROR) << "Failed to stat " << path;
1193 return -1;
1194 }
1195 }
1196
1197 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1198 if (st.st_uid != uid) {
1199 // Mismatched UID is real trouble; we can't recover
1200 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1201 << " but expected " << uid;
1202 return -1;
1203 } else if (st.st_gid == gid && actual_mode == target_mode) {
1204 // Everything looks good!
1205 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001206 } else {
1207 // Mismatched GID/mode is recoverable; fall through to update
1208 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001209 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001210 }
1211
1212 // Directory is owned correctly, but GID or mode mismatch means it's
1213 // probably a platform upgrade so we need to fix them
1214 FTS *fts;
1215 FTSENT *p;
1216 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001217 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001218 PLOG(ERROR) << "Failed to fts_open " << path;
1219 return -1;
1220 }
Yi Kong954cf642018-07-17 16:16:24 -07001221 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001222 switch (p->fts_info) {
1223 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001224 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001225 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1226 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001227 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001228 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001229 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001230 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1231 }
1232 break;
1233 case FTS_SL:
1234 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001235 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001236 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1237 }
1238 break;
1239 }
1240 }
1241 fts_close(fts);
1242 return 0;
1243}
1244
Martijn Coenen771cc342020-02-19 23:26:56 +01001245static const char* kProcFilesystems = "/proc/filesystems";
1246bool supports_sdcardfs() {
Daniel Rosenbergf6184432020-07-23 00:01:23 -07001247 if (!property_get_bool("external_storage.sdcardfs.enabled", true))
1248 return false;
Martijn Coenen771cc342020-02-19 23:26:56 +01001249 std::string supported;
1250 if (!android::base::ReadFileToString(kProcFilesystems, &supported)) {
1251 PLOG(ERROR) << "Failed to read supported filesystems";
1252 return false;
1253 }
1254 return supported.find("sdcardfs\n") != std::string::npos;
1255}
1256
1257int64_t get_occupied_app_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1258 static const bool supportsSdcardFs = supports_sdcardfs();
1259
1260 if (supportsSdcardFs) {
1261 int extGid = multiuser_get_ext_gid(userId, appId);
1262
1263 if (extGid == -1) {
1264 return -1;
1265 }
1266
1267 return GetOccupiedSpaceForGid(uuid, extGid);
1268 } else {
1269 uid_t uid = multiuser_get_uid(userId, appId);
1270 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
1271 return GetOccupiedSpaceForProjectId(uuid, projectId);
1272 }
1273}
1274int64_t get_occupied_app_cache_space_external(const std::string& uuid, int32_t userId, int32_t appId) {
1275 static const bool supportsSdcardFs = supports_sdcardfs();
1276
1277 if (supportsSdcardFs) {
1278 int extCacheGid = multiuser_get_ext_cache_gid(userId, appId);
1279
1280 if (extCacheGid == -1) {
1281 return -1;
1282 }
1283
1284 return GetOccupiedSpaceForGid(uuid, extCacheGid);
1285 } else {
1286 uid_t uid = multiuser_get_uid(userId, appId);
1287 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
1288 return GetOccupiedSpaceForProjectId(uuid, projectId);
1289 }
1290}
1291
Calin Juravlee61189e2018-01-23 19:54:11 -08001292// Collect all non empty profiles from the given directory and puts then into profile_paths.
1293// The profiles are identified based on PROFILE_EXT extension.
1294// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1295// It returns true if there were no errors at all, and false otherwise.
1296static bool collect_profiles(DIR* d,
1297 const std::string& current_path,
1298 std::vector<std::string>* profiles_paths) {
1299 int32_t dir_fd = dirfd(d);
1300 if (dir_fd < 0) {
1301 return false;
1302 }
1303
1304 bool result = true;
1305 struct dirent* dir_entry;
1306 while ((dir_entry = readdir(d))) {
1307 std::string name = dir_entry->d_name;
1308 std::string local_path = current_path + "/" + name;
1309
1310 if (dir_entry->d_type == DT_REG) {
1311 // Check if this is a non empty profile file.
1312 if (EndsWith(name, PROFILE_EXT)) {
1313 struct stat st;
1314 if (stat(local_path.c_str(), &st) != 0) {
1315 PLOG(WARNING) << "Cannot stat local path " << local_path;
1316 result = false;
1317 continue;
1318 } else if (st.st_size > 0) {
1319 profiles_paths->push_back(local_path);
1320 }
1321 }
1322 } else if (dir_entry->d_type == DT_DIR) {
1323 // always skip "." and ".."
1324 if (name == "." || name == "..") {
1325 continue;
1326 }
1327
1328 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1329 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1330 if (subdir_fd < 0) {
1331 PLOG(WARNING) << "Could not open dir path " << local_path;
1332 result = false;
1333 continue;
1334 }
1335
Mathieu Chartier89883e32018-11-01 11:39:00 -07001336 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001337 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001338 PLOG(WARNING) << "Could not open dir path " << local_path;
1339 result = false;
1340 continue;
1341 }
1342 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1343 result = result && new_result;
1344 if (closedir(subdir) != 0) {
1345 PLOG(WARNING) << "Could not close dir path " << local_path;
1346 }
1347 }
1348 }
1349
1350 return result;
1351}
1352
1353bool collect_profiles(std::vector<std::string>* profiles_paths) {
1354 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001355 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001356 return false;
1357 } else {
1358 return collect_profiles(d, android_profiles_dir, profiles_paths);
1359 }
1360}
1361
Eric Holk2af5e6a2019-01-09 18:17:27 -08001362void drop_capabilities(uid_t uid) {
1363 if (setgid(uid) != 0) {
1364 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1365 exit(DexoptReturnCodes::kSetGid);
1366 }
1367 if (setuid(uid) != 0) {
1368 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1369 exit(DexoptReturnCodes::kSetUid);
1370 }
1371 // drop capabilities
1372 struct __user_cap_header_struct capheader;
1373 struct __user_cap_data_struct capdata[2];
1374 memset(&capheader, 0, sizeof(capheader));
1375 memset(&capdata, 0, sizeof(capdata));
1376 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1377 if (capset(&capheader, &capdata[0]) < 0) {
1378 PLOG(ERROR) << "capset failed";
1379 exit(DexoptReturnCodes::kCapSet);
1380 }
1381}
1382
Jiakai Zhang495142a2022-02-21 19:38:14 +00001383bool remove_file_at_fd(int fd, /*out*/ std::string* path) {
1384 char path_buffer[PATH_MAX + 1];
1385 std::string proc_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
1386 ssize_t len = readlink(proc_path.c_str(), path_buffer, PATH_MAX);
1387 if (len < 0) {
1388 PLOG(WARNING) << "Could not remove file at fd " << fd << ": Failed to get file path";
1389 return false;
1390 }
1391 path_buffer[len] = '\0';
1392 if (path != nullptr) {
1393 *path = path_buffer;
1394 }
1395 if (unlink(path_buffer) != 0) {
1396 if (errno == ENOENT) {
1397 return true;
1398 }
1399 PLOG(WARNING) << "Could not remove file at path " << path_buffer;
1400 return false;
1401 }
1402 return true;
1403}
1404
Andreas Gampe02d0de52015-11-11 20:43:16 -08001405} // namespace installd
1406} // namespace android