blob: 52ca0df121b61a30694b616777e5d0fea47cd7d9 [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 Sharkeydf2d7542017-01-07 09:19:35 -0700247std::string create_data_media_obb_path(const char* volume_uuid, const char* package_name) {
248 return StringPrintf("%s/media/obb/%s", create_data_path(volume_uuid).c_str(), package_name);
249}
250
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700251std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
252 const char* data_type, const char* package_name) {
253 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
254 data_type, package_name);
255}
256
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600257std::string create_data_misc_legacy_path(userid_t userid) {
258 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
259}
260
Calin Juravle114f0812017-03-08 19:05:07 -0800261std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600262 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000263}
264
Calin Juravle114f0812017-03-08 19:05:07 -0800265std::string create_primary_current_profile_package_dir_path(userid_t user,
266 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800267 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800268 return StringPrintf("%s/%s",
269 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700270}
271
Calin Juravle114f0812017-03-08 19:05:07 -0800272std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600273 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000274}
275
Calin Juravle114f0812017-03-08 19:05:07 -0800276std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800277 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600278 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000279}
280
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700281std::string create_data_dalvik_cache_path() {
282 return "/data/dalvik-cache";
283}
284
Calin Juravle114f0812017-03-08 19:05:07 -0800285// Keep profile paths in sync with ActivityThread and LoadedApk.
286const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700287const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800288const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700289
Calin Juravle3760ad32017-07-27 16:31:55 -0700290// Gets the parent directory and the file name for the given secondary dex path.
291// Returns true on success, false on failure (if the dex_path does not have the expected
292// structure).
293static bool get_secondary_dex_location(const std::string& dex_path,
294 std::string* out_dir_name, std::string* out_file_name) {
295 size_t dirIndex = dex_path.rfind('/');
296 if (dirIndex == std::string::npos) {
297 return false;
298 }
299 if (dirIndex == dex_path.size() - 1) {
300 return false;
301 }
302 *out_dir_name = dex_path.substr(0, dirIndex);
303 *out_file_name = dex_path.substr(dirIndex + 1);
304
305 return true;
306}
307
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800308std::string create_current_profile_path(userid_t user, const std::string& package_name,
309 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800310 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700311 // Secondary dex current profiles are stored next to the dex files under the oat folder.
312 std::string dex_dir;
313 std::string dex_name;
314 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
315 << "Unexpected dir structure for secondary dex " << location;
316 return StringPrintf("%s/oat/%s%s%s",
317 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
318 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800319 } else {
320 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800321 std::string profile_dir = create_primary_current_profile_package_dir_path(
322 user, package_name);
323 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800324 }
325}
326
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800327std::string create_reference_profile_path(const std::string& package_name,
328 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800329 if (is_secondary_dex) {
330 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700331 std::string dex_dir;
332 std::string dex_name;
333 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800334 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800335 return StringPrintf("%s/oat/%s%s",
336 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
337 } else {
338 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800339 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
340 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800341 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700342}
343
Calin Juravle29591732017-11-20 17:46:19 -0800344std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800345 const std::string& profile_name) {
346 std::string ref_profile = create_reference_profile_path(package, profile_name,
347 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800348 return ref_profile + SNAPSHOT_PROFILE_EXT;
349}
350
Jeff Sharkeye3637242015-04-08 20:56:42 -0700351std::vector<userid_t> get_known_users(const char* volume_uuid) {
352 std::vector<userid_t> users;
353
354 // We always have an owner
355 users.push_back(0);
356
357 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
358 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700359 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700360 // Unable to discover other users, but at least return owner
361 PLOG(ERROR) << "Failed to opendir " << path;
362 return users;
363 }
364
365 struct dirent* ent;
366 while ((ent = readdir(dir))) {
367 if (ent->d_type != DT_DIR) {
368 continue;
369 }
370
371 char* end;
372 userid_t user = strtol(ent->d_name, &end, 10);
373 if (*end == '\0' && user != 0) {
374 LOG(DEBUG) << "Found valid user " << user;
375 users.push_back(user);
376 }
377 }
378 closedir(dir);
379
380 return users;
381}
382
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700383int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700384 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700385 FTS *fts;
386 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700387 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700388 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700389 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700390 if (errno != ENOENT) {
391 PLOG(ERROR) << "Failed to fts_open " << path;
392 }
393 return -1;
394 }
Yi Kong954cf642018-07-17 16:16:24 -0700395 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700396 switch (p->fts_info) {
397 case FTS_D:
398 case FTS_DEFAULT:
399 case FTS_F:
400 case FTS_SL:
401 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700402 int32_t uid = p->fts_statp->st_uid;
403 int32_t gid = p->fts_statp->st_gid;
404 int32_t user_uid = multiuser_get_app_id(uid);
405 int32_t user_gid = multiuser_get_app_id(gid);
406 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
407 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
408 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
409 // Don't traverse inside or measure
410 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700411 break;
412 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700413 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700414 break;
415 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700416 if (exclude_gid != -1 && gid == exclude_gid) {
417 break;
418 }
419 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700420 break;
421 }
422 }
423 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700424#if MEASURE_DEBUG
425 if ((include_gid == -1) && (exclude_gid == -1)) {
426 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
427 } else {
428 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
429 << " exclude " << exclude_gid;
430 }
431#endif
432 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700433 return 0;
434}
435
Mike Lockwood94afecf2012-10-24 10:45:23 -0700436/**
437 * Checks whether the package name is valid. Returns -1 on error and
438 * 0 on success.
439 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700440bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700441 // This logic is borrowed from PackageParser.java
442 bool hasSep = false;
443 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700444
Jeff Sharkey367ace22017-03-07 22:12:03 -0700445 auto it = packageName.begin();
446 for (; it != packageName.end() && *it != '-'; it++) {
447 char c = *it;
448 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
449 front = false;
450 continue;
451 }
452 if (!front) {
453 if ((c >= '0' && c <= '9') || c == '_') {
454 continue;
455 }
456 }
457 if (c == '.') {
458 hasSep = true;
459 front = true;
460 continue;
461 }
462 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700463 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700464 }
465
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700466 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700467 LOG(WARNING) << "Missing separator in " << packageName;
468 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700469 }
470
Jeff Sharkey367ace22017-03-07 22:12:03 -0700471 for (; it != packageName.end(); it++) {
472 char c = *it;
473 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
474 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
475 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
476 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700477 }
478
Jeff Sharkey423e7462016-12-09 18:18:43 -0700479 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700480}
481
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100482static int _delete_dir_contents(DIR *d,
483 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700484{
485 int result = 0;
486 struct dirent *de;
487 int dfd;
488
489 dfd = dirfd(d);
490
491 if (dfd < 0) return -1;
492
493 while ((de = readdir(d))) {
494 const char *name = de->d_name;
495
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100496 /* check using the exclusion predicate, if provided */
497 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
498 continue;
499 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700500
501 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700502 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700503 DIR *subdir;
504
505 /* always skip "." and ".." */
506 if (name[0] == '.') {
507 if (name[1] == 0) continue;
508 if ((name[1] == '.') && (name[2] == 0)) continue;
509 }
510
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700511 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700512 if (subfd < 0) {
513 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
514 result = -1;
515 continue;
516 }
517 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700518 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700519 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
520 close(subfd);
521 result = -1;
522 continue;
523 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100524 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700525 result = -1;
526 }
527 closedir(subdir);
528 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
529 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
530 result = -1;
531 }
532 } else {
533 if (unlinkat(dfd, name, 0) < 0) {
534 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
535 result = -1;
536 }
537 }
538 }
539
540 return result;
541}
542
Nikita Ioffead5da1e2019-02-04 11:06:37 +0000543int create_dir_if_needed(const std::string& pathname, mode_t perms) {
544 struct stat st;
545
546 int rc;
547 if ((rc = stat(pathname.c_str(), &st)) != 0) {
548 if (errno == ENOENT) {
549 return mkdir(pathname.c_str(), perms);
550 } else {
551 return rc;
552 }
553 } else if (!S_ISDIR(st.st_mode)) {
554 LOG(DEBUG) << pathname << " is not a folder";
555 return -1;
556 }
557
558 mode_t actual_perms = st.st_mode & ALLPERMS;
559 if (actual_perms != perms) {
560 LOG(WARNING) << pathname << " permissions " << actual_perms << " expected " << perms;
561 return -1;
562 }
563
564 return 0;
565}
566
Calin Juravleb06f98a2016-03-28 15:11:01 +0100567int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700568 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700569}
570
Calin Juravleb06f98a2016-03-28 15:11:01 +0100571int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700572 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700573}
574
Mike Lockwood94afecf2012-10-24 10:45:23 -0700575int delete_dir_contents(const char *pathname,
576 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100577 int (*exclusion_predicate)(const char*, const int),
578 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700579{
580 int res = 0;
581 DIR *d;
582
583 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700584 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100585 if (ignore_if_missing && (errno == ENOENT)) {
586 return 0;
587 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700588 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
589 return -errno;
590 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100591 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700592 closedir(d);
593 if (also_delete_dir) {
594 if (rmdir(pathname)) {
595 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
596 res = -1;
597 }
598 }
599 return res;
600}
601
602int delete_dir_contents_fd(int dfd, const char *name)
603{
604 int fd, res;
605 DIR *d;
606
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700607 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700608 if (fd < 0) {
609 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
610 return -1;
611 }
612 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700613 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700614 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
615 close(fd);
616 return -1;
617 }
Yi Kong954cf642018-07-17 16:16:24 -0700618 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700619 closedir(d);
620 return res;
621}
622
Robin Lee60fd3fe2014-10-07 16:55:02 +0100623static int _copy_owner_permissions(int srcfd, int dstfd)
624{
625 struct stat st;
626 if (fstat(srcfd, &st) != 0) {
627 return -1;
628 }
629 if (fchmod(dstfd, st.st_mode) != 0) {
630 return -1;
631 }
632 return 0;
633}
634
635static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
636{
637 int result = 0;
638 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
639 ALOGE("_copy_dir_files failed to copy dir permissions\n");
640 }
641 if (fchown(ddfd, owner, group) != 0) {
642 ALOGE("_copy_dir_files failed to change dir owner\n");
643 }
644
645 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700646 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100647 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
648 return -1;
649 }
650 struct dirent *de;
651 while ((de = readdir(ds))) {
652 if (de->d_type != DT_REG) {
653 continue;
654 }
655
656 const char *name = de->d_name;
657 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
658 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
659 if (fsfd == -1 || fdfd == -1) {
660 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
661 } else {
662 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
663 ALOGE("Failed to change file permissions\n");
664 }
665 if (fchown(fdfd, owner, group) != 0) {
666 ALOGE("Failed to change file owner\n");
667 }
668
669 char buf[8192];
670 ssize_t size;
671 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
672 write(fdfd, buf, size);
673 }
674 if (size < 0) {
675 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
676 result = -1;
677 }
678 }
679 close(fdfd);
680 close(fsfd);
681 }
682
683 return result;
684}
685
686int copy_dir_files(const char *srcname,
687 const char *dstname,
688 uid_t owner,
689 uid_t group)
690{
691 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700692 DIR *ds = nullptr;
693 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100694
695 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700696 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100697 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
698 return -errno;
699 }
700
701 mkdir(dstname, 0600);
702 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700703 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100704 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
705 closedir(ds);
706 return -errno;
707 }
708
709 int sdfd = dirfd(ds);
710 int ddfd = dirfd(dd);
711 if (sdfd != -1 && ddfd != -1) {
712 res = _copy_dir_files(sdfd, ddfd, owner, group);
713 } else {
714 res = -errno;
715 }
716 closedir(dd);
717 closedir(ds);
718 return res;
719}
720
Jeff Sharkeya836c472017-04-02 23:29:30 -0600721int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600722 struct statvfs sfs;
723 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600724 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700725 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600726 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700727 return -1;
728 }
729}
730
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600731int get_path_inode(const std::string& path, ino_t *inode) {
732 struct stat buf;
733 memset(&buf, 0, sizeof(buf));
734 if (stat(path.c_str(), &buf) != 0) {
735 PLOG(WARNING) << "Failed to stat " << path;
736 return -1;
737 } else {
738 *inode = buf.st_ino;
739 return 0;
740 }
741}
742
743/**
744 * Write the inode of a specific child file into the given xattr on the
745 * parent directory. This allows you to find the child later, even if its
746 * name is encrypted.
747 */
748int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
749 ino_t inode = 0;
750 uint64_t inode_raw = 0;
751 auto path = StringPrintf("%s/%s", parent.c_str(), name);
752
753 if (get_path_inode(path, &inode) != 0) {
754 // Path probably doesn't exist yet; ignore
755 return 0;
756 }
757
758 // Check to see if already set correctly
759 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
760 if (inode_raw == inode) {
761 // Already set correctly; skip writing
762 return 0;
763 } else {
764 PLOG(WARNING) << "Mismatched inode value; found " << inode
765 << " on disk but marked value was " << inode_raw << "; overwriting";
766 }
767 }
768
769 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600770 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600771 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
772 return -1;
773 } else {
774 return 0;
775 }
776}
777
778/**
779 * Read the inode of a specific child file from the given xattr on the
780 * parent directory. Returns a currently valid path for that child, which
781 * might have an encrypted name.
782 */
783std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
784 ino_t inode = 0;
785 uint64_t inode_raw = 0;
786 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
787
788 // Lookup the inode value written earlier
789 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
790 inode = inode_raw;
791 }
792
793 // For testing purposes, rely on the inode when defined; this could be
794 // optimized to use access() in the future.
795 if (inode != 0) {
796 DIR* dir = opendir(parent.c_str());
797 if (dir == nullptr) {
798 PLOG(ERROR) << "Failed to opendir " << parent;
799 return fallback;
800 }
801
802 struct dirent* ent;
803 while ((ent = readdir(dir))) {
804 if (ent->d_ino == inode) {
805 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
806#if DEBUG_XATTRS
807 if (resolved != fallback) {
808 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
809 << " instead of " << fallback;
810 }
811#endif
812 closedir(dir);
813 return resolved;
814 }
815 }
816 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
817 closedir(dir);
818 return fallback;
819 } else {
820 return fallback;
821 }
822}
823
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900824void remove_path_xattr(const std::string& path, const char* inode_xattr) {
825 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
826 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
827 }
828}
829
Mike Lockwood94afecf2012-10-24 10:45:23 -0700830/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100831 * Validate that the path is valid in the context of the provided directory.
832 * The path is allowed to have at most one subdirectory and no indirections
833 * to top level directories (i.e. have "..").
834 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600835static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
836 // Argument sanity checking
837 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
838 || dir.find("..") != std::string::npos) {
839 LOG(ERROR) << "Invalid directory " << dir;
840 return -1;
841 }
842 if (path.find("..") != std::string::npos) {
843 LOG(ERROR) << "Invalid path " << path;
844 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100845 }
846
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600847 if (path.compare(0, dir.size(), dir) != 0) {
848 // Common case, path isn't under directory
849 return -1;
850 }
851
852 // Count number of subdirectories
853 auto pos = path.find('/', dir.size());
854 int count = 0;
855 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600856 auto next = path.find('/', pos + 1);
857 if (next > pos + 1) {
858 count++;
859 }
860 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600861 }
862
863 if (count > maxSubdirs) {
864 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100865 return -1;
866 }
867
868 return 0;
869}
870
871/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700872 * Checks whether a path points to a system app (.apk file). Returns 0
873 * if it is a system app or -1 if it is not.
874 */
875int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600876 std::string path_ = path;
877 for (const auto& dir : android_system_dirs) {
878 if (validate_path(dir, path, 1) == 0) {
879 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700880 }
881 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700882 return -1;
883}
884
Calin Juravle114f0812017-03-08 19:05:07 -0800885bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -0700886 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -0800887 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
888
Calin Juravle3760ad32017-07-27 16:31:55 -0700889 // Empty paths are not allowed.
890 if (dex_path.empty()) { return false; }
891 // First character should always be '/'. No relative paths.
892 if (dex_path[0] != '/') { return false; }
893 // The last character should not be '/'.
894 if (dex_path[dex_path.size() - 1] == '/') { return false; }
895 // There should be no '.' after the directory marker.
896 if (dex_path.find("/.") != std::string::npos) { return false; }
897 // The path should be at most PKG_PATH_MAX long.
898 if (dex_path.size() > PKG_PATH_MAX) { return false; }
899
Calin Juravle7d765462017-09-04 15:57:10 -0700900 // The dex_path should be under the app data directory.
901 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -0700902 ? create_data_user_ce_package_path(
903 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
904 : create_data_user_de_package_path(
905 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -0700906
Calin Juravle7d765462017-09-04 15:57:10 -0700907 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
908 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
909 // If that's the case, attempt to validate against the user data link.
910 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
911 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
912 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
913 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -0700914 return false;
915 }
Calin Juravle42451c02017-01-17 14:43:25 -0800916 }
Calin Juravle3760ad32017-07-27 16:31:55 -0700917
918 // If we got here we have a valid path.
919 return true;
Calin Juravle42451c02017-01-17 14:43:25 -0800920}
921
Mike Lockwood94afecf2012-10-24 10:45:23 -0700922/**
Narayan Kamathd845c962015-06-04 13:20:27 +0100923 * Check whether path points to a valid path for an APK file. The path must
924 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
925 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
926 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700927 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600928static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
929 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600930 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600931 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600932 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600933 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600934 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600935 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600936 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600937 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
938 // Rewrite the path as if it were on internal storage, and test that
939 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
940 if (end != std::string::npos) {
941 auto modified = path;
942 modified.replace(0, end + 1, android_data_dir);
943 return validate_apk_path_internal(modified, maxSubdirs);
944 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700945 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600946 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700947}
948
Narayan Kamathd845c962015-06-04 13:20:27 +0100949int validate_apk_path(const char* path) {
950 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
951}
952
953int validate_apk_path_subdirs(const char* path) {
954 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
955}
956
Robin Lee095c7632014-04-25 15:05:19 +0100957int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +0100958 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +0100959 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
960 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +0100961
962 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600963 auto path = create_data_misc_legacy_path(userid);
964 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +0100965}
Andreas Gampe02d0de52015-11-11 20:43:16 -0800966
967int wait_child(pid_t pid)
968{
969 int status;
970 pid_t got_pid;
971
972 while (1) {
973 got_pid = waitpid(pid, &status, 0);
974 if (got_pid == -1 && errno == EINTR) {
975 printf("waitpid interrupted, retrying\n");
976 } else {
977 break;
978 }
979 }
980 if (got_pid != pid) {
981 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
982 (int) pid, (int) got_pid, strerror(errno));
983 return 1;
984 }
985
986 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
987 return 0;
988 } else {
989 return status; /* always nonzero */
990 }
991}
992
Calin Juravle42451c02017-01-17 14:43:25 -0800993/**
994 * Prepare an app cache directory, which offers to fix-up the GID and
995 * directory mode flags during a platform upgrade.
996 * The app cache directory path will be 'parent'/'name'.
997 */
998int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
999 uid_t uid, gid_t gid) {
1000 auto path = StringPrintf("%s/%s", parent.c_str(), name);
1001 struct stat st;
1002 if (stat(path.c_str(), &st) != 0) {
1003 if (errno == ENOENT) {
1004 // This is fine, just create it
1005 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
1006 PLOG(ERROR) << "Failed to prepare " << path;
1007 return -1;
1008 } else {
1009 return 0;
1010 }
1011 } else {
1012 PLOG(ERROR) << "Failed to stat " << path;
1013 return -1;
1014 }
1015 }
1016
1017 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
1018 if (st.st_uid != uid) {
1019 // Mismatched UID is real trouble; we can't recover
1020 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
1021 << " but expected " << uid;
1022 return -1;
1023 } else if (st.st_gid == gid && actual_mode == target_mode) {
1024 // Everything looks good!
1025 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001026 } else {
1027 // Mismatched GID/mode is recoverable; fall through to update
1028 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -07001029 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -08001030 }
1031
1032 // Directory is owned correctly, but GID or mode mismatch means it's
1033 // probably a platform upgrade so we need to fix them
1034 FTS *fts;
1035 FTSENT *p;
1036 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -07001037 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -08001038 PLOG(ERROR) << "Failed to fts_open " << path;
1039 return -1;
1040 }
Yi Kong954cf642018-07-17 16:16:24 -07001041 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -08001042 switch (p->fts_info) {
1043 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001044 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001045 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1046 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001047 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -08001048 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001049 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001050 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1051 }
1052 break;
1053 case FTS_SL:
1054 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001055 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -08001056 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1057 }
1058 break;
1059 }
1060 }
1061 fts_close(fts);
1062 return 0;
1063}
1064
Calin Juravlee61189e2018-01-23 19:54:11 -08001065// Collect all non empty profiles from the given directory and puts then into profile_paths.
1066// The profiles are identified based on PROFILE_EXT extension.
1067// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1068// It returns true if there were no errors at all, and false otherwise.
1069static bool collect_profiles(DIR* d,
1070 const std::string& current_path,
1071 std::vector<std::string>* profiles_paths) {
1072 int32_t dir_fd = dirfd(d);
1073 if (dir_fd < 0) {
1074 return false;
1075 }
1076
1077 bool result = true;
1078 struct dirent* dir_entry;
1079 while ((dir_entry = readdir(d))) {
1080 std::string name = dir_entry->d_name;
1081 std::string local_path = current_path + "/" + name;
1082
1083 if (dir_entry->d_type == DT_REG) {
1084 // Check if this is a non empty profile file.
1085 if (EndsWith(name, PROFILE_EXT)) {
1086 struct stat st;
1087 if (stat(local_path.c_str(), &st) != 0) {
1088 PLOG(WARNING) << "Cannot stat local path " << local_path;
1089 result = false;
1090 continue;
1091 } else if (st.st_size > 0) {
1092 profiles_paths->push_back(local_path);
1093 }
1094 }
1095 } else if (dir_entry->d_type == DT_DIR) {
1096 // always skip "." and ".."
1097 if (name == "." || name == "..") {
1098 continue;
1099 }
1100
1101 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1102 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1103 if (subdir_fd < 0) {
1104 PLOG(WARNING) << "Could not open dir path " << local_path;
1105 result = false;
1106 continue;
1107 }
1108
Mathieu Chartier89883e32018-11-01 11:39:00 -07001109 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001110 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001111 PLOG(WARNING) << "Could not open dir path " << local_path;
1112 result = false;
1113 continue;
1114 }
1115 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1116 result = result && new_result;
1117 if (closedir(subdir) != 0) {
1118 PLOG(WARNING) << "Could not close dir path " << local_path;
1119 }
1120 }
1121 }
1122
1123 return result;
1124}
1125
1126bool collect_profiles(std::vector<std::string>* profiles_paths) {
1127 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001128 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001129 return false;
1130 } else {
1131 return collect_profiles(d, android_profiles_dir, profiles_paths);
1132 }
1133}
1134
Eric Holk2af5e6a2019-01-09 18:17:27 -08001135void drop_capabilities(uid_t uid) {
1136 if (setgid(uid) != 0) {
1137 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1138 exit(DexoptReturnCodes::kSetGid);
1139 }
1140 if (setuid(uid) != 0) {
1141 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1142 exit(DexoptReturnCodes::kSetUid);
1143 }
1144 // drop capabilities
1145 struct __user_cap_header_struct capheader;
1146 struct __user_cap_data_struct capdata[2];
1147 memset(&capheader, 0, sizeof(capheader));
1148 memset(&capdata, 0, sizeof(capdata));
1149 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1150 if (capset(&capheader, &capdata[0]) < 0) {
1151 PLOG(ERROR) << "capset failed";
1152 exit(DexoptReturnCodes::kCapSet);
1153 }
1154}
1155
Andreas Gampe02d0de52015-11-11 20:43:16 -08001156} // namespace installd
1157} // namespace android