blob: 6012822f69bbfb6a86bbd5473c897e4f0c89909a [file] [log] [blame]
Mike Lockwood94afecf2012-10-24 10:45:23 -07001/*
2** Copyright 2008, The Android Open Source Project
3**
Dave Allisond9370732014-01-30 14:19:23 -08004** Licensed under the Apache License, Version 2.0 (the "License");
5** you may not use this file except in compliance with the License.
6** You may obtain a copy of the License at
Mike Lockwood94afecf2012-10-24 10:45:23 -07007**
Dave Allisond9370732014-01-30 14:19:23 -08008** http://www.apache.org/licenses/LICENSE-2.0
Mike Lockwood94afecf2012-10-24 10:45:23 -07009**
Dave Allisond9370732014-01-30 14:19:23 -080010** Unless required by applicable law or agreed to in writing, software
11** distributed under the License is distributed on an "AS IS" BASIS,
12** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13** See the License for the specific language governing permissions and
Mike Lockwood94afecf2012-10-24 10:45:23 -070014** limitations under the License.
15*/
16
Andreas Gampe02d0de52015-11-11 20:43:16 -080017#include "utils.h"
Mike Lockwood94afecf2012-10-24 10:45:23 -070018
Andreas Gampe02d0de52015-11-11 20:43:16 -080019#include <errno.h>
20#include <fcntl.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070021#include <fts.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080022#include <stdlib.h>
Eric Holk2af5e6a2019-01-09 18:17:27 -080023#include <sys/capability.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080024#include <sys/stat.h>
25#include <sys/wait.h>
Jeff Sharkey9a998f42016-07-14 18:16:22 -060026#include <sys/xattr.h>
Jeff Sharkeyed909ae2017-03-22 21:27:40 -060027#include <sys/statvfs.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080028
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080029#include <android-base/logging.h>
Calin Juravlecfcd6aa2018-01-18 20:23:17 -080030#include <android-base/strings.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080031#include <android-base/stringprintf.h>
Calin Juravlee61189e2018-01-23 19:54:11 -080032#include <android-base/unique_fd.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080033#include <cutils/fs.h>
Jeff Sharkey871a8f22017-02-21 18:30:28 -070034#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070035#include <log/log.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080036#include <private/android_filesystem_config.h>
Jeff Sharkeyc03de092015-04-07 18:14:05 -070037
Eric Holk2af5e6a2019-01-09 18:17:27 -080038#include "dexopt_return_codes.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080039#include "globals.h" // extern variables.
40
41#ifndef LOG_TAG
42#define LOG_TAG "installd"
43#endif
Jeff Sharkey9a998f42016-07-14 18:16:22 -060044
Jeff Sharkey9a998f42016-07-14 18:16:22 -060045#define DEBUG_XATTRS 0
Mike Lockwood94afecf2012-10-24 10:45:23 -070046
Calin Juravlee61189e2018-01-23 19:54:11 -080047using android::base::EndsWith;
Mathieu Chartier89883e32018-11-01 11:39:00 -070048using android::base::Fdopendir;
Jeff Sharkeyc03de092015-04-07 18:14:05 -070049using android::base::StringPrintf;
Calin Juravlee61189e2018-01-23 19:54:11 -080050using android::base::unique_fd;
Mike Lockwood94afecf2012-10-24 10:45:23 -070051
Andreas Gampe02d0de52015-11-11 20:43:16 -080052namespace android {
53namespace installd {
54
Jeff Sharkeyc03de092015-04-07 18:14:05 -070055/**
56 * Check that given string is valid filename, and that it attempts no
57 * parent or child directory traversal.
58 */
Jeff Sharkey423e7462016-12-09 18:18:43 -070059bool is_valid_filename(const std::string& name) {
Jeff Sharkeyc03de092015-04-07 18:14:05 -070060 if (name.empty() || (name == ".") || (name == "..")
61 || (name.find('/') != std::string::npos)) {
62 return false;
63 } else {
64 return true;
65 }
Mike Lockwood94afecf2012-10-24 10:45:23 -070066}
67
Calin Juravle6a1648e2016-02-01 12:12:16 +000068static void check_package_name(const char* package_name) {
69 CHECK(is_valid_filename(package_name));
Jeff Sharkey423e7462016-12-09 18:18:43 -070070 CHECK(is_valid_package_name(package_name));
Calin Juravle6a1648e2016-02-01 12:12:16 +000071}
72
Nikita Ioffe8755f792019-01-25 13:54:43 +000073static std::string resolve_ce_path_by_inode_or_fallback(const std::string& root_path,
74 ino_t ce_data_inode, const std::string& fallback) {
75 if (ce_data_inode != 0) {
76 DIR* dir = opendir(root_path.c_str());
77 if (dir == nullptr) {
78 PLOG(ERROR) << "Failed to opendir " << root_path;
79 return fallback;
80 }
81
82 struct dirent* ent;
83 while ((ent = readdir(dir))) {
84 if (ent->d_ino == ce_data_inode) {
85 auto resolved = StringPrintf("%s/%s", root_path.c_str(), ent->d_name);
86 if (resolved != fallback) {
87 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
88 << " instead of " << fallback;
89 }
90 closedir(dir);
91 return resolved;
92 }
93 }
94 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
95 closedir(dir);
96 return fallback;
97 } else {
98 return fallback;
99 }
100}
101
Mike Lockwood94afecf2012-10-24 10:45:23 -0700102/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700103 * Create the path name where package app contents should be stored for
104 * the given volume UUID and package name. An empty UUID is assumed to
105 * be internal storage.
106 */
107std::string create_data_app_package_path(const char* volume_uuid,
108 const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000109 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700110 return StringPrintf("%s/%s",
111 create_data_app_path(volume_uuid).c_str(), package_name);
112}
113
114/**
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
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000200std::string create_data_misc_ce_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000201 return StringPrintf("%s/misc_ce/%u/rollback", create_data_path(volume_uuid).c_str(), user);
202}
203
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000204std::string create_data_misc_de_rollback_base_path(const char* volume_uuid, userid_t user) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000205 return StringPrintf("%s/misc_de/%u/rollback", create_data_path(volume_uuid).c_str(), user);
206}
207
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000208std::string create_data_misc_ce_rollback_path(const char* volume_uuid, userid_t user,
209 int32_t snapshot_id) {
210 return StringPrintf("%s/%d", create_data_misc_ce_rollback_base_path(volume_uuid, user).c_str(),
211 snapshot_id);
212}
213
214std::string create_data_misc_de_rollback_path(const char* volume_uuid, userid_t user,
215 int32_t snapshot_id) {
216 return StringPrintf("%s/%d", create_data_misc_de_rollback_base_path(volume_uuid, user).c_str(),
217 snapshot_id);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000218}
219
Nikita Ioffe8755f792019-01-25 13:54:43 +0000220std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000221 userid_t user, int32_t snapshot_id, const char* package_name) {
222 return StringPrintf("%s/%s",
223 create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
224}
225
226std::string create_data_misc_ce_rollback_package_path(const char* volume_uuid,
227 userid_t user, int32_t snapshot_id, const char* package_name, ino_t ce_rollback_inode) {
228 auto fallback = create_data_misc_ce_rollback_package_path(volume_uuid, user, snapshot_id,
229 package_name);
230 auto user_path = create_data_misc_ce_rollback_path(volume_uuid, user, snapshot_id);
Nikita Ioffe8755f792019-01-25 13:54:43 +0000231 return resolve_ce_path_by_inode_or_fallback(user_path, ce_rollback_inode, fallback);
232}
233
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000234std::string create_data_misc_de_rollback_package_path(const char* volume_uuid,
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000235 userid_t user, int32_t snapshot_id, const char* package_name) {
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000236 return StringPrintf("%s/%s",
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000237 create_data_misc_de_rollback_path(volume_uuid, user, snapshot_id).c_str(), package_name);
Narayan Kamathdfdfb792019-01-14 15:21:52 +0000238}
239
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800240/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700241 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700242 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700243std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
244 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700245}
246
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700247std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
248 const char* data_type, const char* package_name) {
249 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
250 data_type, package_name);
251}
252
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600253std::string create_data_misc_legacy_path(userid_t userid) {
254 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
255}
256
Calin Juravle114f0812017-03-08 19:05:07 -0800257std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600258 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000259}
260
Calin Juravle114f0812017-03-08 19:05:07 -0800261std::string create_primary_current_profile_package_dir_path(userid_t user,
262 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800263 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800264 return StringPrintf("%s/%s",
265 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700266}
267
Calin Juravle114f0812017-03-08 19:05:07 -0800268std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600269 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000270}
271
Calin Juravle114f0812017-03-08 19:05:07 -0800272std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800273 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600274 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000275}
276
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700277std::string create_data_dalvik_cache_path() {
278 return "/data/dalvik-cache";
279}
280
Felka Chang2a0a2462019-11-20 14:20:40 +0800281std::string create_system_user_ce_path(userid_t userId) {
282 return StringPrintf("%s/system_ce/%u", create_data_path(nullptr).c_str(), userId);
283}
284
285std::string create_system_user_ce_package_path(userid_t userId, const char* package_name) {
286 check_package_name(package_name);
287 return StringPrintf("%s/%s", create_system_user_ce_path(userId).c_str(), package_name);
288}
289
Calin Juravle114f0812017-03-08 19:05:07 -0800290// Keep profile paths in sync with ActivityThread and LoadedApk.
291const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700292const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800293const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700294
Calin Juravle3760ad32017-07-27 16:31:55 -0700295// Gets the parent directory and the file name for the given secondary dex path.
296// Returns true on success, false on failure (if the dex_path does not have the expected
297// structure).
298static bool get_secondary_dex_location(const std::string& dex_path,
299 std::string* out_dir_name, std::string* out_file_name) {
300 size_t dirIndex = dex_path.rfind('/');
301 if (dirIndex == std::string::npos) {
302 return false;
303 }
304 if (dirIndex == dex_path.size() - 1) {
305 return false;
306 }
307 *out_dir_name = dex_path.substr(0, dirIndex);
308 *out_file_name = dex_path.substr(dirIndex + 1);
309
310 return true;
311}
312
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800313std::string create_current_profile_path(userid_t user, const std::string& package_name,
314 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800315 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700316 // Secondary dex current profiles are stored next to the dex files under the oat folder.
317 std::string dex_dir;
318 std::string dex_name;
319 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
320 << "Unexpected dir structure for secondary dex " << location;
321 return StringPrintf("%s/oat/%s%s%s",
322 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
323 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800324 } else {
325 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800326 std::string profile_dir = create_primary_current_profile_package_dir_path(
327 user, package_name);
328 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800329 }
330}
331
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800332std::string create_reference_profile_path(const std::string& package_name,
333 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800334 if (is_secondary_dex) {
335 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700336 std::string dex_dir;
337 std::string dex_name;
338 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800339 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800340 return StringPrintf("%s/oat/%s%s",
341 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
342 } else {
343 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800344 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
345 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800346 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700347}
348
Calin Juravle29591732017-11-20 17:46:19 -0800349std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800350 const std::string& profile_name) {
351 std::string ref_profile = create_reference_profile_path(package, profile_name,
352 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800353 return ref_profile + SNAPSHOT_PROFILE_EXT;
354}
355
Jeff Sharkeye3637242015-04-08 20:56:42 -0700356std::vector<userid_t> get_known_users(const char* volume_uuid) {
357 std::vector<userid_t> users;
358
359 // We always have an owner
360 users.push_back(0);
361
362 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
363 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700364 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700365 // Unable to discover other users, but at least return owner
366 PLOG(ERROR) << "Failed to opendir " << path;
367 return users;
368 }
369
370 struct dirent* ent;
371 while ((ent = readdir(dir))) {
372 if (ent->d_type != DT_DIR) {
373 continue;
374 }
375
376 char* end;
377 userid_t user = strtol(ent->d_name, &end, 10);
378 if (*end == '\0' && user != 0) {
379 LOG(DEBUG) << "Found valid user " << user;
380 users.push_back(user);
381 }
382 }
383 closedir(dir);
384
385 return users;
386}
387
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700388int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700389 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700390 FTS *fts;
391 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700392 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700393 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700394 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700395 if (errno != ENOENT) {
396 PLOG(ERROR) << "Failed to fts_open " << path;
397 }
398 return -1;
399 }
Yi Kong954cf642018-07-17 16:16:24 -0700400 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700401 switch (p->fts_info) {
402 case FTS_D:
403 case FTS_DEFAULT:
404 case FTS_F:
405 case FTS_SL:
406 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700407 int32_t uid = p->fts_statp->st_uid;
408 int32_t gid = p->fts_statp->st_gid;
409 int32_t user_uid = multiuser_get_app_id(uid);
410 int32_t user_gid = multiuser_get_app_id(gid);
411 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
412 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
413 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
414 // Don't traverse inside or measure
415 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700416 break;
417 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700418 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700419 break;
420 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700421 if (exclude_gid != -1 && gid == exclude_gid) {
422 break;
423 }
424 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700425 break;
426 }
427 }
428 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700429#if MEASURE_DEBUG
430 if ((include_gid == -1) && (exclude_gid == -1)) {
431 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
432 } else {
433 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
434 << " exclude " << exclude_gid;
435 }
436#endif
437 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700438 return 0;
439}
440
Mike Lockwood94afecf2012-10-24 10:45:23 -0700441/**
442 * Checks whether the package name is valid. Returns -1 on error and
443 * 0 on success.
444 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700445bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700446 // This logic is borrowed from PackageParser.java
447 bool hasSep = false;
448 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700449
Jeff Sharkey367ace22017-03-07 22:12:03 -0700450 auto it = packageName.begin();
451 for (; it != packageName.end() && *it != '-'; it++) {
452 char c = *it;
453 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
454 front = false;
455 continue;
456 }
457 if (!front) {
458 if ((c >= '0' && c <= '9') || c == '_') {
459 continue;
460 }
461 }
462 if (c == '.') {
463 hasSep = true;
464 front = true;
465 continue;
466 }
467 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700468 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700469 }
470
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700471 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700472 LOG(WARNING) << "Missing separator in " << packageName;
473 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700474 }
475
Jeff Sharkey367ace22017-03-07 22:12:03 -0700476 for (; it != packageName.end(); it++) {
477 char c = *it;
478 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
479 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
480 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
481 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700482 }
483
Jeff Sharkey423e7462016-12-09 18:18:43 -0700484 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700485}
486
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100487static int _delete_dir_contents(DIR *d,
488 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700489{
490 int result = 0;
491 struct dirent *de;
492 int dfd;
493
494 dfd = dirfd(d);
495
496 if (dfd < 0) return -1;
497
498 while ((de = readdir(d))) {
499 const char *name = de->d_name;
500
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100501 /* check using the exclusion predicate, if provided */
502 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
503 continue;
504 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700505
506 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700507 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700508 DIR *subdir;
509
510 /* always skip "." and ".." */
511 if (name[0] == '.') {
512 if (name[1] == 0) continue;
513 if ((name[1] == '.') && (name[2] == 0)) continue;
514 }
515
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700516 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700517 if (subfd < 0) {
518 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
519 result = -1;
520 continue;
521 }
522 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700523 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700524 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
525 close(subfd);
526 result = -1;
527 continue;
528 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100529 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700530 result = -1;
531 }
532 closedir(subdir);
533 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
534 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
535 result = -1;
536 }
537 } else {
538 if (unlinkat(dfd, name, 0) < 0) {
539 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
540 result = -1;
541 }
542 }
543 }
544
545 return result;
546}
547
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000548int create_dir_if_needed(const std::string& pathname, mode_t perms) {
549 struct stat st;
550
551 int rc;
552 if ((rc = stat(pathname.c_str(), &st)) != 0) {
553 if (errno == ENOENT) {
554 return mkdir(pathname.c_str(), perms);
555 } else {
556 return rc;
557 }
558 } else if (!S_ISDIR(st.st_mode)) {
559 LOG(DEBUG) << pathname << " is not a folder";
560 return -1;
561 }
562
563 mode_t actual_perms = st.st_mode & ALLPERMS;
564 if (actual_perms != perms) {
565 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
566 return -1;
567 }
568
569 return 0;
570}
571
Calin Juravleb06f98a2016-03-28 15:11:01 +0100572int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700573 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700574}
575
Calin Juravleb06f98a2016-03-28 15:11:01 +0100576int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700577 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700578}
579
Mike Lockwood94afecf2012-10-24 10:45:23 -0700580int delete_dir_contents(const char *pathname,
581 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100582 int (*exclusion_predicate)(const char*, const int),
583 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700584{
585 int res = 0;
586 DIR *d;
587
588 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700589 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100590 if (ignore_if_missing && (errno == ENOENT)) {
591 return 0;
592 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700593 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
594 return -errno;
595 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100596 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700597 closedir(d);
598 if (also_delete_dir) {
599 if (rmdir(pathname)) {
600 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
601 res = -1;
602 }
603 }
604 return res;
605}
606
607int delete_dir_contents_fd(int dfd, const char *name)
608{
609 int fd, res;
610 DIR *d;
611
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700612 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700613 if (fd < 0) {
614 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
615 return -1;
616 }
617 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700618 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700619 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
620 close(fd);
621 return -1;
622 }
Yi Kong954cf642018-07-17 16:16:24 -0700623 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700624 closedir(d);
625 return res;
626}
627
Robin Lee60fd3fe2014-10-07 16:55:02 +0100628static int _copy_owner_permissions(int srcfd, int dstfd)
629{
630 struct stat st;
631 if (fstat(srcfd, &st) != 0) {
632 return -1;
633 }
634 if (fchmod(dstfd, st.st_mode) != 0) {
635 return -1;
636 }
637 return 0;
638}
639
640static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
641{
642 int result = 0;
643 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
644 ALOGE("_copy_dir_files failed to copy dir permissions\n");
645 }
646 if (fchown(ddfd, owner, group) != 0) {
647 ALOGE("_copy_dir_files failed to change dir owner\n");
648 }
649
650 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700651 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100652 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
653 return -1;
654 }
655 struct dirent *de;
656 while ((de = readdir(ds))) {
657 if (de->d_type != DT_REG) {
658 continue;
659 }
660
661 const char *name = de->d_name;
662 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
663 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
664 if (fsfd == -1 || fdfd == -1) {
665 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
666 } else {
667 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
668 ALOGE("Failed to change file permissions\n");
669 }
670 if (fchown(fdfd, owner, group) != 0) {
671 ALOGE("Failed to change file owner\n");
672 }
673
674 char buf[8192];
675 ssize_t size;
676 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
677 write(fdfd, buf, size);
678 }
679 if (size < 0) {
680 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
681 result = -1;
682 }
683 }
684 close(fdfd);
685 close(fsfd);
686 }
687
688 return result;
689}
690
691int copy_dir_files(const char *srcname,
692 const char *dstname,
693 uid_t owner,
694 uid_t group)
695{
696 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700697 DIR *ds = nullptr;
698 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100699
700 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700701 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100702 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
703 return -errno;
704 }
705
706 mkdir(dstname, 0600);
707 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700708 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100709 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
710 closedir(ds);
711 return -errno;
712 }
713
714 int sdfd = dirfd(ds);
715 int ddfd = dirfd(dd);
716 if (sdfd != -1 && ddfd != -1) {
717 res = _copy_dir_files(sdfd, ddfd, owner, group);
718 } else {
719 res = -errno;
720 }
721 closedir(dd);
722 closedir(ds);
723 return res;
724}
725
Jeff Sharkeya836c472017-04-02 23:29:30 -0600726int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600727 struct statvfs sfs;
728 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600729 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700730 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600731 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700732 return -1;
733 }
734}
735
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600736int get_path_inode(const std::string& path, ino_t *inode) {
737 struct stat buf;
738 memset(&buf, 0, sizeof(buf));
739 if (stat(path.c_str(), &buf) != 0) {
740 PLOG(WARNING) << "Failed to stat " << path;
741 return -1;
742 } else {
743 *inode = buf.st_ino;
744 return 0;
745 }
746}
747
748/**
749 * Write the inode of a specific child file into the given xattr on the
750 * parent directory. This allows you to find the child later, even if its
751 * name is encrypted.
752 */
753int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
754 ino_t inode = 0;
755 uint64_t inode_raw = 0;
756 auto path = StringPrintf("%s/%s", parent.c_str(), name);
757
758 if (get_path_inode(path, &inode) != 0) {
759 // Path probably doesn't exist yet; ignore
760 return 0;
761 }
762
763 // Check to see if already set correctly
764 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
765 if (inode_raw == inode) {
766 // Already set correctly; skip writing
767 return 0;
768 } else {
769 PLOG(WARNING) << "Mismatched inode value; found " << inode
770 << " on disk but marked value was " << inode_raw << "; overwriting";
771 }
772 }
773
774 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600775 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600776 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
777 return -1;
778 } else {
779 return 0;
780 }
781}
782
783/**
784 * Read the inode of a specific child file from the given xattr on the
785 * parent directory. Returns a currently valid path for that child, which
786 * might have an encrypted name.
787 */
788std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
789 ino_t inode = 0;
790 uint64_t inode_raw = 0;
791 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
792
793 // Lookup the inode value written earlier
794 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
795 inode = inode_raw;
796 }
797
798 // For testing purposes, rely on the inode when defined; this could be
799 // optimized to use access() in the future.
800 if (inode != 0) {
801 DIR* dir = opendir(parent.c_str());
802 if (dir == nullptr) {
803 PLOG(ERROR) << "Failed to opendir " << parent;
804 return fallback;
805 }
806
807 struct dirent* ent;
808 while ((ent = readdir(dir))) {
809 if (ent->d_ino == inode) {
810 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
811#if DEBUG_XATTRS
812 if (resolved != fallback) {
813 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
814 << " instead of " << fallback;
815 }
816#endif
817 closedir(dir);
818 return resolved;
819 }
820 }
821 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
822 closedir(dir);
823 return fallback;
824 } else {
825 return fallback;
826 }
827}
828
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900829void remove_path_xattr(const std::string& path, const char* inode_xattr) {
830 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
831 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
832 }
833}
834
Mike Lockwood94afecf2012-10-24 10:45:23 -0700835/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100836 * Validate that the path is valid in the context of the provided directory.
837 * The path is allowed to have at most one subdirectory and no indirections
838 * to top level directories (i.e. have "..").
839 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600840static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
841 // Argument sanity checking
842 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
843 || dir.find("..") != std::string::npos) {
844 LOG(ERROR) << "Invalid directory " << dir;
845 return -1;
846 }
847 if (path.find("..") != std::string::npos) {
848 LOG(ERROR) << "Invalid path " << path;
849 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100850 }
851
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600852 if (path.compare(0, dir.size(), dir) != 0) {
853 // Common case, path isn't under directory
854 return -1;
855 }
856
857 // Count number of subdirectories
858 auto pos = path.find('/', dir.size());
859 int count = 0;
860 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600861 auto next = path.find('/', pos + 1);
862 if (next > pos + 1) {
863 count++;
864 }
865 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600866 }
867
868 if (count > maxSubdirs) {
869 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100870 return -1;
871 }
872
873 return 0;
874}
875
876/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700877 * Checks whether a path points to a system app (.apk file). Returns 0
878 * if it is a system app or -1 if it is not.
879 */
880int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600881 std::string path_ = path;
882 for (const auto& dir : android_system_dirs) {
883 if (validate_path(dir, path, 1) == 0) {
884 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700885 }
886 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700887 return -1;
888}
889
Calin Juravle114f0812017-03-08 19:05:07 -0800890bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -0700891 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -0800892 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
893
Calin Juravle3760ad32017-07-27 16:31:55 -0700894 // Empty paths are not allowed.
895 if (dex_path.empty()) { return false; }
896 // First character should always be '/'. No relative paths.
897 if (dex_path[0] != '/') { return false; }
898 // The last character should not be '/'.
899 if (dex_path[dex_path.size() - 1] == '/') { return false; }
900 // There should be no '.' after the directory marker.
901 if (dex_path.find("/.") != std::string::npos) { return false; }
902 // The path should be at most PKG_PATH_MAX long.
903 if (dex_path.size() > PKG_PATH_MAX) { return false; }
904
Calin Juravle7d765462017-09-04 15:57:10 -0700905 // The dex_path should be under the app data directory.
906 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -0700907 ? create_data_user_ce_package_path(
908 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
909 : create_data_user_de_package_path(
910 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -0700911
Calin Juravle7d765462017-09-04 15:57:10 -0700912 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
913 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
914 // If that's the case, attempt to validate against the user data link.
915 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
916 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
917 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
918 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -0700919 return false;
920 }
Calin Juravle42451c02017-01-17 14:43:25 -0800921 }
Calin Juravle3760ad32017-07-27 16:31:55 -0700922
923 // If we got here we have a valid path.
924 return true;
Calin Juravle42451c02017-01-17 14:43:25 -0800925}
926
Mike Lockwood94afecf2012-10-24 10:45:23 -0700927/**
Narayan Kamathd845c962015-06-04 13:20:27 +0100928 * Check whether path points to a valid path for an APK file. The path must
929 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
930 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
931 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700932 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600933static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
934 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600935 return 0;
shafikb43faa92019-02-19 12:19:48 +0000936 } else if (validate_path(android_staging_dir, path, maxSubdirs) == 0) {
937 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600938 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600939 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600940 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600941 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600942 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600943 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600944 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
945 // Rewrite the path as if it were on internal storage, and test that
946 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
947 if (end != std::string::npos) {
948 auto modified = path;
949 modified.replace(0, end + 1, android_data_dir);
950 return validate_apk_path_internal(modified, maxSubdirs);
951 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700952 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600953 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700954}
955
Narayan Kamathd845c962015-06-04 13:20:27 +0100956int validate_apk_path(const char* path) {
957 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
958}
959
960int validate_apk_path_subdirs(const char* path) {
961 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
962}
963
Robin Lee095c7632014-04-25 15:05:19 +0100964int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +0100965 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +0100966 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
967 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +0100968
969 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600970 auto path = create_data_misc_legacy_path(userid);
971 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +0100972}
Andreas Gampe02d0de52015-11-11 20:43:16 -0800973
974int wait_child(pid_t pid)
975{
976 int status;
977 pid_t got_pid;
978
979 while (1) {
980 got_pid = waitpid(pid, &status, 0);
981 if (got_pid == -1 && errno == EINTR) {
982 printf("waitpid interrupted, retrying\n");
983 } else {
984 break;
985 }
986 }
987 if (got_pid != pid) {
988 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
989 (int) pid, (int) got_pid, strerror(errno));
990 return 1;
991 }
992
993 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
994 return 0;
995 } else {
996 return status; /* always nonzero */
997 }
998}
999
Calin Juravle42451c02017-01-17 14:43:25 -08001000/**
1001 * Prepare an app cache directory, which offers to fix-up the GID and
1002 * directory mode flags during a platform upgrade.
1003 * The app cache directory path will be 'parent'/'name'.
1004 */
1005int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
1006 uid_t uid, gid_t gid) {
1007 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1008 struct stat st;
1009 if (stat(path.c_str(), &st) != 0) {
1010 if (errno == ENOENT) {
1011 // This is fine, just create it
1012 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1013 PLOG(ERROR) << "Failed to prepare " << path;
1014 return -1;
1015 } else {
1016 return 0;
1017 }
1018 } else {
1019 PLOG(ERROR) << "Failed to stat " << path;
1020 return -1;
1021 }
1022 }
1023
1024 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1025 if (st.st_uid != uid) {
1026 // Mismatched UID is real trouble; we can't recover
1027 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1028 << " but expected " << uid;
1029 return -1;
1030 } else if (st.st_gid == gid && actual_mode == target_mode) {
1031 // Everything looks good!
1032 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001033 } else {
1034 // Mismatched GID/mode is recoverable; fall through to update
1035 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001036 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001037 }
1038
1039 // Directory is owned correctly, but GID or mode mismatch means it's
1040 // probably a platform upgrade so we need to fix them
1041 FTS *fts;
1042 FTSENT *p;
1043 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001044 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001045 PLOG(ERROR) << "Failed to fts_open " << path;
1046 return -1;
1047 }
Yi Kong954cf642018-07-17 16:16:24 -07001048 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001049 switch (p->fts_info) {
1050 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001051 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001052 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1053 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001054 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001055 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001056 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001057 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1058 }
1059 break;
1060 case FTS_SL:
1061 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001062 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001063 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1064 }
1065 break;
1066 }
1067 }
1068 fts_close(fts);
1069 return 0;
1070}
1071
Calin Juravlee61189e2018-01-23 19:54:11 -08001072// Collect all non empty profiles from the given directory and puts then into profile_paths.
1073// The profiles are identified based on PROFILE_EXT extension.
1074// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1075// It returns true if there were no errors at all, and false otherwise.
1076static bool collect_profiles(DIR* d,
1077 const std::string& current_path,
1078 std::vector<std::string>* profiles_paths) {
1079 int32_t dir_fd = dirfd(d);
1080 if (dir_fd < 0) {
1081 return false;
1082 }
1083
1084 bool result = true;
1085 struct dirent* dir_entry;
1086 while ((dir_entry = readdir(d))) {
1087 std::string name = dir_entry->d_name;
1088 std::string local_path = current_path + "/" + name;
1089
1090 if (dir_entry->d_type == DT_REG) {
1091 // Check if this is a non empty profile file.
1092 if (EndsWith(name, PROFILE_EXT)) {
1093 struct stat st;
1094 if (stat(local_path.c_str(), &st) != 0) {
1095 PLOG(WARNING) << "Cannot stat local path " << local_path;
1096 result = false;
1097 continue;
1098 } else if (st.st_size > 0) {
1099 profiles_paths->push_back(local_path);
1100 }
1101 }
1102 } else if (dir_entry->d_type == DT_DIR) {
1103 // always skip "." and ".."
1104 if (name == "." || name == "..") {
1105 continue;
1106 }
1107
1108 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1109 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1110 if (subdir_fd < 0) {
1111 PLOG(WARNING) << "Could not open dir path " << local_path;
1112 result = false;
1113 continue;
1114 }
1115
Mathieu Chartier89883e32018-11-01 11:39:00 -07001116 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001117 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001118 PLOG(WARNING) << "Could not open dir path " << local_path;
1119 result = false;
1120 continue;
1121 }
1122 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1123 result = result && new_result;
1124 if (closedir(subdir) != 0) {
1125 PLOG(WARNING) << "Could not close dir path " << local_path;
1126 }
1127 }
1128 }
1129
1130 return result;
1131}
1132
1133bool collect_profiles(std::vector<std::string>* profiles_paths) {
1134 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001135 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001136 return false;
1137 } else {
1138 return collect_profiles(d, android_profiles_dir, profiles_paths);
1139 }
1140}
1141
Eric Holk2af5e6a2019-01-09 18:17:27 -08001142void drop_capabilities(uid_t uid) {
1143 if (setgid(uid) != 0) {
1144 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1145 exit(DexoptReturnCodes::kSetGid);
1146 }
1147 if (setuid(uid) != 0) {
1148 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1149 exit(DexoptReturnCodes::kSetUid);
1150 }
1151 // drop capabilities
1152 struct __user_cap_header_struct capheader;
1153 struct __user_cap_data_struct capdata[2];
1154 memset(&capheader, 0, sizeof(capheader));
1155 memset(&capdata, 0, sizeof(capdata));
1156 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1157 if (capset(&capheader, &capdata[0]) < 0) {
1158 PLOG(ERROR) << "capset failed";
1159 exit(DexoptReturnCodes::kCapSet);
1160 }
1161}
1162
Andreas Gampe02d0de52015-11-11 20:43:16 -08001163} // namespace installd
1164} // namespace android