blob: bbf14cb5f766d236c0e873dd326621fc4f46ad82 [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
Mike Lockwood94afecf2012-10-24 10:45:23 -070073/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -070074 * Create the path name where package app contents should be stored for
75 * the given volume UUID and package name. An empty UUID is assumed to
76 * be internal storage.
77 */
78std::string create_data_app_package_path(const char* volume_uuid,
79 const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000080 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070081 return StringPrintf("%s/%s",
82 create_data_app_path(volume_uuid).c_str(), package_name);
83}
84
85/**
Jeff Sharkeyc03de092015-04-07 18:14:05 -070086 * Create the path name where package data should be stored for the given
87 * volume UUID, package name, and user ID. An empty UUID is assumed to be
88 * internal storage.
Mike Lockwood94afecf2012-10-24 10:45:23 -070089 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -060090std::string create_data_user_ce_package_path(const char* volume_uuid,
Jeff Sharkeyd7921182015-04-30 15:58:19 -070091 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +000092 check_package_name(package_name);
Jeff Sharkeyd7921182015-04-30 15:58:19 -070093 return StringPrintf("%s/%s",
Jeff Sharkey2f720f72016-04-10 20:51:40 -060094 create_data_user_ce_path(volume_uuid, user).c_str(), package_name);
95}
96
Calin Juravle7d765462017-09-04 15:57:10 -070097/**
98 * Create the path name where package data should be stored for the given
99 * volume UUID, package name, and user ID. An empty UUID is assumed to be
100 * internal storage.
101 * Compared to create_data_user_ce_package_path this method always return the
102 * ".../user/..." directory.
103 */
104std::string create_data_user_ce_package_path_as_user_link(
105 const char* volume_uuid, userid_t userid, const char* package_name) {
106 check_package_name(package_name);
107 std::string data(create_data_path(volume_uuid));
108 return StringPrintf("%s/user/%u/%s", data.c_str(), userid, package_name);
109}
110
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600111std::string create_data_user_ce_package_path(const char* volume_uuid, userid_t user,
112 const char* package_name, ino_t ce_data_inode) {
113 // For testing purposes, rely on the inode when defined; this could be
114 // optimized to use access() in the future.
115 auto fallback = create_data_user_ce_package_path(volume_uuid, user, package_name);
116 if (ce_data_inode != 0) {
117 auto user_path = create_data_user_ce_path(volume_uuid, user);
118 DIR* dir = opendir(user_path.c_str());
119 if (dir == nullptr) {
120 PLOG(ERROR) << "Failed to opendir " << user_path;
121 return fallback;
122 }
123
124 struct dirent* ent;
125 while ((ent = readdir(dir))) {
126 if (ent->d_ino == ce_data_inode) {
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600127 auto resolved = StringPrintf("%s/%s", user_path.c_str(), ent->d_name);
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600128#if DEBUG_XATTRS
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600129 if (resolved != fallback) {
130 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << ce_data_inode
131 << " instead of " << fallback;
132 }
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600133#endif
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600134 closedir(dir);
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600135 return resolved;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600136 }
137 }
Jeff Sharkey1d992f92016-04-13 13:45:47 -0600138 LOG(WARNING) << "Failed to resolve inode " << ce_data_inode << "; using " << fallback;
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600139 closedir(dir);
140 return fallback;
141 } else {
142 return fallback;
143 }
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700144}
Mike Lockwood94afecf2012-10-24 10:45:23 -0700145
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800146std::string create_data_user_de_package_path(const char* volume_uuid,
147 userid_t user, const char* package_name) {
Calin Juravle6a1648e2016-02-01 12:12:16 +0000148 check_package_name(package_name);
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800149 return StringPrintf("%s/%s",
150 create_data_user_de_path(volume_uuid, user).c_str(), package_name);
151}
152
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700153std::string create_data_path(const char* volume_uuid) {
154 if (volume_uuid == nullptr) {
155 return "/data";
Jeff Sharkey871a8f22017-02-21 18:30:28 -0700156 } else if (!strcmp(volume_uuid, "TEST")) {
157 CHECK(property_get_bool("ro.debuggable", false));
158 return "/data/local/tmp";
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700159 } else {
160 CHECK(is_valid_filename(volume_uuid));
161 return StringPrintf("/mnt/expand/%s", volume_uuid);
162 }
163}
164
Mike Lockwood94afecf2012-10-24 10:45:23 -0700165/**
Jeff Sharkeyd7921182015-04-30 15:58:19 -0700166 * Create the path name for app data.
167 */
168std::string create_data_app_path(const char* volume_uuid) {
169 return StringPrintf("%s/app", create_data_path(volume_uuid).c_str());
170}
171
172/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700173 * Create the path name for user data for a certain userid.
cjbao75d4e572017-04-12 00:12:24 +0800174 * Keep same implementation as vold to minimize path walking overhead
Mike Lockwood94afecf2012-10-24 10:45:23 -0700175 */
Jeff Sharkey2f720f72016-04-10 20:51:40 -0600176std::string create_data_user_ce_path(const char* volume_uuid, userid_t userid) {
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700177 std::string data(create_data_path(volume_uuid));
cjbao75d4e572017-04-12 00:12:24 +0800178 if (volume_uuid == nullptr && userid == 0) {
179 std::string legacy = StringPrintf("%s/data", data.c_str());
180 struct stat sb;
181 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
182 /* /data/data is dir, return /data/data for legacy system */
183 return legacy;
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700184 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700185 }
cjbao75d4e572017-04-12 00:12:24 +0800186 return StringPrintf("%s/user/%u", data.c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700187}
188
189/**
Jeff Sharkey63ec2d62015-11-09 13:10:36 -0800190 * Create the path name for device encrypted user data for a certain userid.
191 */
192std::string create_data_user_de_path(const char* volume_uuid, userid_t userid) {
193 std::string data(create_data_path(volume_uuid));
194 return StringPrintf("%s/user_de/%u", data.c_str(), userid);
195}
196
197/**
Jeff Sharkeyabe4fe52013-07-10 16:55:46 -0700198 * Create the path name for media for a certain userid.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700199 */
Jeff Sharkey41ea4242015-04-09 11:34:03 -0700200std::string create_data_media_path(const char* volume_uuid, userid_t userid) {
201 return StringPrintf("%s/media/%u", create_data_path(volume_uuid).c_str(), userid);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700202}
203
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700204std::string create_data_media_obb_path(const char* volume_uuid, const char* package_name) {
205 return StringPrintf("%s/media/obb/%s", create_data_path(volume_uuid).c_str(), package_name);
206}
207
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700208std::string create_data_media_package_path(const char* volume_uuid, userid_t userid,
209 const char* data_type, const char* package_name) {
210 return StringPrintf("%s/Android/%s/%s", create_data_media_path(volume_uuid, userid).c_str(),
211 data_type, package_name);
212}
213
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600214std::string create_data_misc_legacy_path(userid_t userid) {
215 return StringPrintf("%s/misc/user/%u", create_data_path(nullptr).c_str(), userid);
216}
217
Calin Juravle114f0812017-03-08 19:05:07 -0800218std::string create_primary_cur_profile_dir_path(userid_t userid) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600219 return StringPrintf("%s/cur/%u", android_profiles_dir.c_str(), userid);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000220}
221
Calin Juravle114f0812017-03-08 19:05:07 -0800222std::string create_primary_current_profile_package_dir_path(userid_t user,
223 const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800224 check_package_name(package_name.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800225 return StringPrintf("%s/%s",
226 create_primary_cur_profile_dir_path(user).c_str(), package_name.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700227}
228
Calin Juravle114f0812017-03-08 19:05:07 -0800229std::string create_primary_ref_profile_dir_path() {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600230 return StringPrintf("%s/ref", android_profiles_dir.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000231}
232
Calin Juravle114f0812017-03-08 19:05:07 -0800233std::string create_primary_reference_profile_package_dir_path(const std::string& package_name) {
Calin Juravle76268c52017-03-09 13:19:42 -0800234 check_package_name(package_name.c_str());
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600235 return StringPrintf("%s/ref/%s", android_profiles_dir.c_str(), package_name.c_str());
Calin Juravle6a1648e2016-02-01 12:12:16 +0000236}
237
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700238std::string create_data_dalvik_cache_path() {
239 return "/data/dalvik-cache";
240}
241
Calin Juravle114f0812017-03-08 19:05:07 -0800242// Keep profile paths in sync with ActivityThread and LoadedApk.
243const std::string PROFILE_EXT = ".prof";
Calin Juravle3760ad32017-07-27 16:31:55 -0700244const std::string CURRENT_PROFILE_EXT = ".cur";
Calin Juravle29591732017-11-20 17:46:19 -0800245const std::string SNAPSHOT_PROFILE_EXT = ".snapshot";
Jeff Sharkey90aff262016-12-12 14:28:24 -0700246
Calin Juravle3760ad32017-07-27 16:31:55 -0700247// Gets the parent directory and the file name for the given secondary dex path.
248// Returns true on success, false on failure (if the dex_path does not have the expected
249// structure).
250static bool get_secondary_dex_location(const std::string& dex_path,
251 std::string* out_dir_name, std::string* out_file_name) {
252 size_t dirIndex = dex_path.rfind('/');
253 if (dirIndex == std::string::npos) {
254 return false;
255 }
256 if (dirIndex == dex_path.size() - 1) {
257 return false;
258 }
259 *out_dir_name = dex_path.substr(0, dirIndex);
260 *out_file_name = dex_path.substr(dirIndex + 1);
261
262 return true;
263}
264
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800265std::string create_current_profile_path(userid_t user, const std::string& package_name,
266 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800267 if (is_secondary_dex) {
Calin Juravle3760ad32017-07-27 16:31:55 -0700268 // Secondary dex current profiles are stored next to the dex files under the oat folder.
269 std::string dex_dir;
270 std::string dex_name;
271 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
272 << "Unexpected dir structure for secondary dex " << location;
273 return StringPrintf("%s/oat/%s%s%s",
274 dex_dir.c_str(), dex_name.c_str(), CURRENT_PROFILE_EXT.c_str(),
275 PROFILE_EXT.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800276 } else {
277 // Profiles for primary apks are under /data/misc/profiles/cur.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800278 std::string profile_dir = create_primary_current_profile_package_dir_path(
279 user, package_name);
280 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800281 }
282}
283
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800284std::string create_reference_profile_path(const std::string& package_name,
285 const std::string& location, bool is_secondary_dex) {
Calin Juravle114f0812017-03-08 19:05:07 -0800286 if (is_secondary_dex) {
287 // Secondary dex reference profiles are stored next to the dex files under the oat folder.
Calin Juravle3760ad32017-07-27 16:31:55 -0700288 std::string dex_dir;
289 std::string dex_name;
290 CHECK(get_secondary_dex_location(location, &dex_dir, &dex_name))
Calin Juravle114f0812017-03-08 19:05:07 -0800291 << "Unexpected dir structure for secondary dex " << location;
Calin Juravle114f0812017-03-08 19:05:07 -0800292 return StringPrintf("%s/oat/%s%s",
293 dex_dir.c_str(), dex_name.c_str(), PROFILE_EXT.c_str());
294 } else {
295 // Reference profiles for primary apks are stored in /data/misc/profile/ref.
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800296 std::string profile_dir = create_primary_reference_profile_package_dir_path(package_name);
297 return StringPrintf("%s/%s", profile_dir.c_str(), location.c_str());
Calin Juravle114f0812017-03-08 19:05:07 -0800298 }
Jeff Sharkey90aff262016-12-12 14:28:24 -0700299}
300
Calin Juravle29591732017-11-20 17:46:19 -0800301std::string create_snapshot_profile_path(const std::string& package,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800302 const std::string& profile_name) {
303 std::string ref_profile = create_reference_profile_path(package, profile_name,
304 /*is_secondary_dex*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800305 return ref_profile + SNAPSHOT_PROFILE_EXT;
306}
307
Jeff Sharkeye3637242015-04-08 20:56:42 -0700308std::vector<userid_t> get_known_users(const char* volume_uuid) {
309 std::vector<userid_t> users;
310
311 // We always have an owner
312 users.push_back(0);
313
314 std::string path(create_data_path(volume_uuid) + "/" + SECONDARY_USER_PREFIX);
315 DIR* dir = opendir(path.c_str());
Yi Kong954cf642018-07-17 16:16:24 -0700316 if (dir == nullptr) {
Jeff Sharkeye3637242015-04-08 20:56:42 -0700317 // Unable to discover other users, but at least return owner
318 PLOG(ERROR) << "Failed to opendir " << path;
319 return users;
320 }
321
322 struct dirent* ent;
323 while ((ent = readdir(dir))) {
324 if (ent->d_type != DT_DIR) {
325 continue;
326 }
327
328 char* end;
329 userid_t user = strtol(ent->d_name, &end, 10);
330 if (*end == '\0' && user != 0) {
331 LOG(DEBUG) << "Found valid user " << user;
332 users.push_back(user);
333 }
334 }
335 closedir(dir);
336
337 return users;
338}
339
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700340int calculate_tree_size(const std::string& path, int64_t* size,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700341 int32_t include_gid, int32_t exclude_gid, bool exclude_apps) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700342 FTS *fts;
343 FTSENT *p;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700344 int64_t matchedSize = 0;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700345 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700346 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700347 if (errno != ENOENT) {
348 PLOG(ERROR) << "Failed to fts_open " << path;
349 }
350 return -1;
351 }
Yi Kong954cf642018-07-17 16:16:24 -0700352 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700353 switch (p->fts_info) {
354 case FTS_D:
355 case FTS_DEFAULT:
356 case FTS_F:
357 case FTS_SL:
358 case FTS_SLNONE:
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700359 int32_t uid = p->fts_statp->st_uid;
360 int32_t gid = p->fts_statp->st_gid;
361 int32_t user_uid = multiuser_get_app_id(uid);
362 int32_t user_gid = multiuser_get_app_id(gid);
363 if (exclude_apps && ((user_uid >= AID_APP_START && user_uid <= AID_APP_END)
364 || (user_gid >= AID_CACHE_GID_START && user_gid <= AID_CACHE_GID_END)
365 || (user_gid >= AID_SHARED_GID_START && user_gid <= AID_SHARED_GID_END))) {
366 // Don't traverse inside or measure
367 fts_set(fts, p, FTS_SKIP);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700368 break;
369 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700370 if (include_gid != -1 && gid != include_gid) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700371 break;
372 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700373 if (exclude_gid != -1 && gid == exclude_gid) {
374 break;
375 }
376 matchedSize += (p->fts_statp->st_blocks * 512);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700377 break;
378 }
379 }
380 fts_close(fts);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -0700381#if MEASURE_DEBUG
382 if ((include_gid == -1) && (exclude_gid == -1)) {
383 LOG(DEBUG) << "Measured " << path << " size " << matchedSize;
384 } else {
385 LOG(DEBUG) << "Measured " << path << " size " << matchedSize << "; include " << include_gid
386 << " exclude " << exclude_gid;
387 }
388#endif
389 *size += matchedSize;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700390 return 0;
391}
392
Mike Lockwood94afecf2012-10-24 10:45:23 -0700393/**
394 * Checks whether the package name is valid. Returns -1 on error and
395 * 0 on success.
396 */
Jeff Sharkey423e7462016-12-09 18:18:43 -0700397bool is_valid_package_name(const std::string& packageName) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700398 // This logic is borrowed from PackageParser.java
399 bool hasSep = false;
400 bool front = true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700401
Jeff Sharkey367ace22017-03-07 22:12:03 -0700402 auto it = packageName.begin();
403 for (; it != packageName.end() && *it != '-'; it++) {
404 char c = *it;
405 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
406 front = false;
407 continue;
408 }
409 if (!front) {
410 if ((c >= '0' && c <= '9') || c == '_') {
411 continue;
412 }
413 }
414 if (c == '.') {
415 hasSep = true;
416 front = true;
417 continue;
418 }
419 LOG(WARNING) << "Bad package character " << c << " in " << packageName;
Jeff Sharkey423e7462016-12-09 18:18:43 -0700420 return false;
Jeff Sharkeyc03de092015-04-07 18:14:05 -0700421 }
422
Jeff Sharkeyab7ac8d2017-03-08 12:39:46 -0700423 if (front) {
Jeff Sharkey367ace22017-03-07 22:12:03 -0700424 LOG(WARNING) << "Missing separator in " << packageName;
425 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700426 }
427
Jeff Sharkey367ace22017-03-07 22:12:03 -0700428 for (; it != packageName.end(); it++) {
429 char c = *it;
430 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
431 if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
432 LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
433 return false;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700434 }
435
Jeff Sharkey423e7462016-12-09 18:18:43 -0700436 return true;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700437}
438
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100439static int _delete_dir_contents(DIR *d,
440 int (*exclusion_predicate)(const char *name, const int is_dir))
Mike Lockwood94afecf2012-10-24 10:45:23 -0700441{
442 int result = 0;
443 struct dirent *de;
444 int dfd;
445
446 dfd = dirfd(d);
447
448 if (dfd < 0) return -1;
449
450 while ((de = readdir(d))) {
451 const char *name = de->d_name;
452
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100453 /* check using the exclusion predicate, if provided */
454 if (exclusion_predicate && exclusion_predicate(name, (de->d_type == DT_DIR))) {
455 continue;
456 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700457
458 if (de->d_type == DT_DIR) {
Chih-Hung Hsieh99d9fb12014-09-11 14:44:46 -0700459 int subfd;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700460 DIR *subdir;
461
462 /* always skip "." and ".." */
463 if (name[0] == '.') {
464 if (name[1] == 0) continue;
465 if ((name[1] == '.') && (name[2] == 0)) continue;
466 }
467
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700468 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700469 if (subfd < 0) {
470 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
471 result = -1;
472 continue;
473 }
474 subdir = fdopendir(subfd);
Yi Kong954cf642018-07-17 16:16:24 -0700475 if (subdir == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700476 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
477 close(subfd);
478 result = -1;
479 continue;
480 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100481 if (_delete_dir_contents(subdir, exclusion_predicate)) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700482 result = -1;
483 }
484 closedir(subdir);
485 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
486 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
487 result = -1;
488 }
489 } else {
490 if (unlinkat(dfd, name, 0) < 0) {
491 ALOGE("Couldn't unlinkat %s: %s\n", name, strerror(errno));
492 result = -1;
493 }
494 }
495 }
496
497 return result;
498}
499
Calin Juravleb06f98a2016-03-28 15:11:01 +0100500int delete_dir_contents(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700501 return delete_dir_contents(pathname.c_str(), 0, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700502}
503
Calin Juravleb06f98a2016-03-28 15:11:01 +0100504int delete_dir_contents_and_dir(const std::string& pathname, bool ignore_if_missing) {
Yi Kong954cf642018-07-17 16:16:24 -0700505 return delete_dir_contents(pathname.c_str(), 1, nullptr, ignore_if_missing);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -0700506}
507
Mike Lockwood94afecf2012-10-24 10:45:23 -0700508int delete_dir_contents(const char *pathname,
509 int also_delete_dir,
Calin Juravleb06f98a2016-03-28 15:11:01 +0100510 int (*exclusion_predicate)(const char*, const int),
511 bool ignore_if_missing)
Mike Lockwood94afecf2012-10-24 10:45:23 -0700512{
513 int res = 0;
514 DIR *d;
515
516 d = opendir(pathname);
Yi Kong954cf642018-07-17 16:16:24 -0700517 if (d == nullptr) {
Calin Juravleb06f98a2016-03-28 15:11:01 +0100518 if (ignore_if_missing && (errno == ENOENT)) {
519 return 0;
520 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700521 ALOGE("Couldn't opendir %s: %s\n", pathname, strerror(errno));
522 return -errno;
523 }
Narayan Kamath3aee2c52014-06-10 13:16:47 +0100524 res = _delete_dir_contents(d, exclusion_predicate);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700525 closedir(d);
526 if (also_delete_dir) {
527 if (rmdir(pathname)) {
528 ALOGE("Couldn't rmdir %s: %s\n", pathname, strerror(errno));
529 res = -1;
530 }
531 }
532 return res;
533}
534
535int delete_dir_contents_fd(int dfd, const char *name)
536{
537 int fd, res;
538 DIR *d;
539
Nick Kralevich8b7acac2015-08-10 13:43:00 -0700540 fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700541 if (fd < 0) {
542 ALOGE("Couldn't openat %s: %s\n", name, strerror(errno));
543 return -1;
544 }
545 d = fdopendir(fd);
Yi Kong954cf642018-07-17 16:16:24 -0700546 if (d == nullptr) {
Mike Lockwood94afecf2012-10-24 10:45:23 -0700547 ALOGE("Couldn't fdopendir %s: %s\n", name, strerror(errno));
548 close(fd);
549 return -1;
550 }
Yi Kong954cf642018-07-17 16:16:24 -0700551 res = _delete_dir_contents(d, nullptr);
Mike Lockwood94afecf2012-10-24 10:45:23 -0700552 closedir(d);
553 return res;
554}
555
Robin Lee60fd3fe2014-10-07 16:55:02 +0100556static int _copy_owner_permissions(int srcfd, int dstfd)
557{
558 struct stat st;
559 if (fstat(srcfd, &st) != 0) {
560 return -1;
561 }
562 if (fchmod(dstfd, st.st_mode) != 0) {
563 return -1;
564 }
565 return 0;
566}
567
568static int _copy_dir_files(int sdfd, int ddfd, uid_t owner, gid_t group)
569{
570 int result = 0;
571 if (_copy_owner_permissions(sdfd, ddfd) != 0) {
572 ALOGE("_copy_dir_files failed to copy dir permissions\n");
573 }
574 if (fchown(ddfd, owner, group) != 0) {
575 ALOGE("_copy_dir_files failed to change dir owner\n");
576 }
577
578 DIR *ds = fdopendir(sdfd);
Yi Kong954cf642018-07-17 16:16:24 -0700579 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100580 ALOGE("Couldn't fdopendir: %s\n", strerror(errno));
581 return -1;
582 }
583 struct dirent *de;
584 while ((de = readdir(ds))) {
585 if (de->d_type != DT_REG) {
586 continue;
587 }
588
589 const char *name = de->d_name;
590 int fsfd = openat(sdfd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
591 int fdfd = openat(ddfd, name, O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_CREAT, 0600);
592 if (fsfd == -1 || fdfd == -1) {
593 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
594 } else {
595 if (_copy_owner_permissions(fsfd, fdfd) != 0) {
596 ALOGE("Failed to change file permissions\n");
597 }
598 if (fchown(fdfd, owner, group) != 0) {
599 ALOGE("Failed to change file owner\n");
600 }
601
602 char buf[8192];
603 ssize_t size;
604 while ((size = read(fsfd, buf, sizeof(buf))) > 0) {
605 write(fdfd, buf, size);
606 }
607 if (size < 0) {
608 ALOGW("Couldn't copy %s: %s\n", name, strerror(errno));
609 result = -1;
610 }
611 }
612 close(fdfd);
613 close(fsfd);
614 }
615
616 return result;
617}
618
619int copy_dir_files(const char *srcname,
620 const char *dstname,
621 uid_t owner,
622 uid_t group)
623{
624 int res = 0;
Yi Kong954cf642018-07-17 16:16:24 -0700625 DIR *ds = nullptr;
626 DIR *dd = nullptr;
Robin Lee60fd3fe2014-10-07 16:55:02 +0100627
628 ds = opendir(srcname);
Yi Kong954cf642018-07-17 16:16:24 -0700629 if (ds == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100630 ALOGE("Couldn't opendir %s: %s\n", srcname, strerror(errno));
631 return -errno;
632 }
633
634 mkdir(dstname, 0600);
635 dd = opendir(dstname);
Yi Kong954cf642018-07-17 16:16:24 -0700636 if (dd == nullptr) {
Robin Lee60fd3fe2014-10-07 16:55:02 +0100637 ALOGE("Couldn't opendir %s: %s\n", dstname, strerror(errno));
638 closedir(ds);
639 return -errno;
640 }
641
642 int sdfd = dirfd(ds);
643 int ddfd = dirfd(dd);
644 if (sdfd != -1 && ddfd != -1) {
645 res = _copy_dir_files(sdfd, ddfd, owner, group);
646 } else {
647 res = -errno;
648 }
649 closedir(dd);
650 closedir(ds);
651 return res;
652}
653
Jeff Sharkeya836c472017-04-02 23:29:30 -0600654int64_t data_disk_free(const std::string& data_path) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600655 struct statvfs sfs;
656 if (statvfs(data_path.c_str(), &sfs) == 0) {
Jeff Sharkey4f7be172017-08-11 15:13:31 -0600657 return static_cast<int64_t>(sfs.f_bavail) * sfs.f_frsize;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700658 } else {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -0600659 PLOG(ERROR) << "Couldn't statvfs " << data_path;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700660 return -1;
661 }
662}
663
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600664int get_path_inode(const std::string& path, ino_t *inode) {
665 struct stat buf;
666 memset(&buf, 0, sizeof(buf));
667 if (stat(path.c_str(), &buf) != 0) {
668 PLOG(WARNING) << "Failed to stat " << path;
669 return -1;
670 } else {
671 *inode = buf.st_ino;
672 return 0;
673 }
674}
675
676/**
677 * Write the inode of a specific child file into the given xattr on the
678 * parent directory. This allows you to find the child later, even if its
679 * name is encrypted.
680 */
681int write_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
682 ino_t inode = 0;
683 uint64_t inode_raw = 0;
684 auto path = StringPrintf("%s/%s", parent.c_str(), name);
685
686 if (get_path_inode(path, &inode) != 0) {
687 // Path probably doesn't exist yet; ignore
688 return 0;
689 }
690
691 // Check to see if already set correctly
692 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
693 if (inode_raw == inode) {
694 // Already set correctly; skip writing
695 return 0;
696 } else {
697 PLOG(WARNING) << "Mismatched inode value; found " << inode
698 << " on disk but marked value was " << inode_raw << "; overwriting";
699 }
700 }
701
702 inode_raw = inode;
Jeff Sharkey4ed65072016-07-22 11:38:54 -0600703 if (setxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw), 0) != 0 && errno != EOPNOTSUPP) {
Jeff Sharkey9a998f42016-07-14 18:16:22 -0600704 PLOG(ERROR) << "Failed to write xattr " << inode_xattr << " at " << parent;
705 return -1;
706 } else {
707 return 0;
708 }
709}
710
711/**
712 * Read the inode of a specific child file from the given xattr on the
713 * parent directory. Returns a currently valid path for that child, which
714 * might have an encrypted name.
715 */
716std::string read_path_inode(const std::string& parent, const char* name, const char* inode_xattr) {
717 ino_t inode = 0;
718 uint64_t inode_raw = 0;
719 auto fallback = StringPrintf("%s/%s", parent.c_str(), name);
720
721 // Lookup the inode value written earlier
722 if (getxattr(parent.c_str(), inode_xattr, &inode_raw, sizeof(inode_raw)) == sizeof(inode_raw)) {
723 inode = inode_raw;
724 }
725
726 // For testing purposes, rely on the inode when defined; this could be
727 // optimized to use access() in the future.
728 if (inode != 0) {
729 DIR* dir = opendir(parent.c_str());
730 if (dir == nullptr) {
731 PLOG(ERROR) << "Failed to opendir " << parent;
732 return fallback;
733 }
734
735 struct dirent* ent;
736 while ((ent = readdir(dir))) {
737 if (ent->d_ino == inode) {
738 auto resolved = StringPrintf("%s/%s", parent.c_str(), ent->d_name);
739#if DEBUG_XATTRS
740 if (resolved != fallback) {
741 LOG(DEBUG) << "Resolved path " << resolved << " for inode " << inode
742 << " instead of " << fallback;
743 }
744#endif
745 closedir(dir);
746 return resolved;
747 }
748 }
749 LOG(WARNING) << "Failed to resolve inode " << inode << "; using " << fallback;
750 closedir(dir);
751 return fallback;
752 } else {
753 return fallback;
754 }
755}
756
Ryuki Nakamurac7342f82017-09-30 11:57:00 +0900757void remove_path_xattr(const std::string& path, const char* inode_xattr) {
758 if (removexattr(path.c_str(), inode_xattr) && errno != ENODATA) {
759 PLOG(ERROR) << "Failed to remove xattr " << inode_xattr << " at " << path;
760 }
761}
762
Mike Lockwood94afecf2012-10-24 10:45:23 -0700763/**
Calin Juravlec597b6d2014-08-19 17:43:05 +0100764 * Validate that the path is valid in the context of the provided directory.
765 * The path is allowed to have at most one subdirectory and no indirections
766 * to top level directories (i.e. have "..").
767 */
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600768static int validate_path(const std::string& dir, const std::string& path, int maxSubdirs) {
769 // Argument sanity checking
770 if (dir.find('/') != 0 || dir.rfind('/') != dir.size() - 1
771 || dir.find("..") != std::string::npos) {
772 LOG(ERROR) << "Invalid directory " << dir;
773 return -1;
774 }
775 if (path.find("..") != std::string::npos) {
776 LOG(ERROR) << "Invalid path " << path;
777 return -1;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100778 }
779
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600780 if (path.compare(0, dir.size(), dir) != 0) {
781 // Common case, path isn't under directory
782 return -1;
783 }
784
785 // Count number of subdirectories
786 auto pos = path.find('/', dir.size());
787 int count = 0;
788 while (pos != std::string::npos) {
Jeff Sharkey172fac02017-10-06 13:09:46 -0600789 auto next = path.find('/', pos + 1);
790 if (next > pos + 1) {
791 count++;
792 }
793 pos = next;
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600794 }
795
796 if (count > maxSubdirs) {
797 LOG(ERROR) << "Invalid path depth " << path << " when tested against " << dir;
Calin Juravlec597b6d2014-08-19 17:43:05 +0100798 return -1;
799 }
800
801 return 0;
802}
803
804/**
Mike Lockwood94afecf2012-10-24 10:45:23 -0700805 * Checks whether a path points to a system app (.apk file). Returns 0
806 * if it is a system app or -1 if it is not.
807 */
808int validate_system_app_path(const char* path) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600809 std::string path_ = path;
810 for (const auto& dir : android_system_dirs) {
811 if (validate_path(dir, path, 1) == 0) {
812 return 0;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700813 }
814 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700815 return -1;
816}
817
Calin Juravle114f0812017-03-08 19:05:07 -0800818bool validate_secondary_dex_path(const std::string& pkgname, const std::string& dex_path,
Calin Juravle7d765462017-09-04 15:57:10 -0700819 const char* volume_uuid, int uid, int storage_flag) {
Calin Juravle42451c02017-01-17 14:43:25 -0800820 CHECK(storage_flag == FLAG_STORAGE_CE || storage_flag == FLAG_STORAGE_DE);
821
Calin Juravle3760ad32017-07-27 16:31:55 -0700822 // Empty paths are not allowed.
823 if (dex_path.empty()) { return false; }
824 // First character should always be '/'. No relative paths.
825 if (dex_path[0] != '/') { return false; }
826 // The last character should not be '/'.
827 if (dex_path[dex_path.size() - 1] == '/') { return false; }
828 // There should be no '.' after the directory marker.
829 if (dex_path.find("/.") != std::string::npos) { return false; }
830 // The path should be at most PKG_PATH_MAX long.
831 if (dex_path.size() > PKG_PATH_MAX) { return false; }
832
Calin Juravle7d765462017-09-04 15:57:10 -0700833 // The dex_path should be under the app data directory.
834 std::string app_private_dir = storage_flag == FLAG_STORAGE_CE
Calin Juravledd42e272017-09-11 11:50:36 -0700835 ? create_data_user_ce_package_path(
836 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str())
837 : create_data_user_de_package_path(
838 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
Calin Juravle3760ad32017-07-27 16:31:55 -0700839
Calin Juravle7d765462017-09-04 15:57:10 -0700840 if (strncmp(dex_path.c_str(), app_private_dir.c_str(), app_private_dir.size()) != 0) {
841 // The check above might fail if the dex file is accessed via the /data/user/0 symlink.
842 // If that's the case, attempt to validate against the user data link.
843 std::string app_private_dir_symlink = create_data_user_ce_package_path_as_user_link(
844 volume_uuid, multiuser_get_user_id(uid), pkgname.c_str());
845 if (strncmp(dex_path.c_str(), app_private_dir_symlink.c_str(),
846 app_private_dir_symlink.size()) != 0) {
Calin Juravledd42e272017-09-11 11:50:36 -0700847 return false;
848 }
Calin Juravle42451c02017-01-17 14:43:25 -0800849 }
Calin Juravle3760ad32017-07-27 16:31:55 -0700850
851 // If we got here we have a valid path.
852 return true;
Calin Juravle42451c02017-01-17 14:43:25 -0800853}
854
Mike Lockwood94afecf2012-10-24 10:45:23 -0700855/**
Narayan Kamathd845c962015-06-04 13:20:27 +0100856 * Check whether path points to a valid path for an APK file. The path must
857 * begin with a whitelisted prefix path and must be no deeper than |maxSubdirs| within
858 * that path. Returns -1 when an invalid path is encountered and 0 when a valid path
859 * is encountered.
Mike Lockwood94afecf2012-10-24 10:45:23 -0700860 */
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600861static int validate_apk_path_internal(const std::string& path, int maxSubdirs) {
862 if (validate_path(android_app_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600863 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600864 } else if (validate_path(android_app_private_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600865 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600866 } else if (validate_path(android_app_ephemeral_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600867 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600868 } else if (validate_path(android_asec_dir, path, maxSubdirs) == 0) {
Jeff Sharkeyc1149c92017-09-21 14:51:09 -0600869 return 0;
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600870 } else if (android::base::StartsWith(path, android_mnt_expand_dir)) {
871 // Rewrite the path as if it were on internal storage, and test that
872 size_t end = path.find('/', android_mnt_expand_dir.size() + 1);
873 if (end != std::string::npos) {
874 auto modified = path;
875 modified.replace(0, end + 1, android_data_dir);
876 return validate_apk_path_internal(modified, maxSubdirs);
877 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700878 }
Jeff Sharkey8fa803a2018-04-09 18:46:45 -0600879 return -1;
Mike Lockwood94afecf2012-10-24 10:45:23 -0700880}
881
Narayan Kamathd845c962015-06-04 13:20:27 +0100882int validate_apk_path(const char* path) {
883 return validate_apk_path_internal(path, 1 /* maxSubdirs */);
884}
885
886int validate_apk_path_subdirs(const char* path) {
887 return validate_apk_path_internal(path, 3 /* maxSubdirs */);
888}
889
Robin Lee095c7632014-04-25 15:05:19 +0100890int ensure_config_user_dirs(userid_t userid) {
Robin Lee095c7632014-04-25 15:05:19 +0100891 // writable by system, readable by any app within the same user
Robin Lee60fd3fe2014-10-07 16:55:02 +0100892 const int uid = multiuser_get_uid(userid, AID_SYSTEM);
893 const int gid = multiuser_get_uid(userid, AID_EVERYBODY);
Robin Lee095c7632014-04-25 15:05:19 +0100894
895 // Ensure /data/misc/user/<userid> exists
Jeff Sharkey379a12b2016-04-14 20:45:06 -0600896 auto path = create_data_misc_legacy_path(userid);
897 return fs_prepare_dir(path.c_str(), 0750, uid, gid);
Robin Lee095c7632014-04-25 15:05:19 +0100898}
Andreas Gampe02d0de52015-11-11 20:43:16 -0800899
900int wait_child(pid_t pid)
901{
902 int status;
903 pid_t got_pid;
904
905 while (1) {
906 got_pid = waitpid(pid, &status, 0);
907 if (got_pid == -1 && errno == EINTR) {
908 printf("waitpid interrupted, retrying\n");
909 } else {
910 break;
911 }
912 }
913 if (got_pid != pid) {
914 ALOGW("waitpid failed: wanted %d, got %d: %s\n",
915 (int) pid, (int) got_pid, strerror(errno));
916 return 1;
917 }
918
919 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
920 return 0;
921 } else {
922 return status; /* always nonzero */
923 }
924}
925
Calin Juravle42451c02017-01-17 14:43:25 -0800926/**
927 * Prepare an app cache directory, which offers to fix-up the GID and
928 * directory mode flags during a platform upgrade.
929 * The app cache directory path will be 'parent'/'name'.
930 */
931int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
932 uid_t uid, gid_t gid) {
933 auto path = StringPrintf("%s/%s", parent.c_str(), name);
934 struct stat st;
935 if (stat(path.c_str(), &st) != 0) {
936 if (errno == ENOENT) {
937 // This is fine, just create it
938 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
939 PLOG(ERROR) << "Failed to prepare " << path;
940 return -1;
941 } else {
942 return 0;
943 }
944 } else {
945 PLOG(ERROR) << "Failed to stat " << path;
946 return -1;
947 }
948 }
949
950 mode_t actual_mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISGID);
951 if (st.st_uid != uid) {
952 // Mismatched UID is real trouble; we can't recover
953 LOG(ERROR) << "Mismatched UID at " << path << ": found " << st.st_uid
954 << " but expected " << uid;
955 return -1;
956 } else if (st.st_gid == gid && actual_mode == target_mode) {
957 // Everything looks good!
958 return 0;
Jeff Sharkeye59c85c2017-04-02 21:53:14 -0600959 } else {
960 // Mismatched GID/mode is recoverable; fall through to update
961 LOG(DEBUG) << "Mismatched cache GID/mode at " << path << ": found " << st.st_gid
Shubham Ajmeraec0afbf2017-09-14 11:07:33 -0700962 << "/" << actual_mode << " but expected " << gid << "/" << target_mode;
Calin Juravle42451c02017-01-17 14:43:25 -0800963 }
964
965 // Directory is owned correctly, but GID or mode mismatch means it's
966 // probably a platform upgrade so we need to fix them
967 FTS *fts;
968 FTSENT *p;
969 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Kong954cf642018-07-17 16:16:24 -0700970 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Calin Juravle42451c02017-01-17 14:43:25 -0800971 PLOG(ERROR) << "Failed to fts_open " << path;
972 return -1;
973 }
Yi Kong954cf642018-07-17 16:16:24 -0700974 while ((p = fts_read(fts)) != nullptr) {
Calin Juravle42451c02017-01-17 14:43:25 -0800975 switch (p->fts_info) {
976 case FTS_DP:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600977 if (chmod(p->fts_path, target_mode) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800978 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
979 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -0700980 [[fallthrough]]; // to also set GID
Calin Juravle42451c02017-01-17 14:43:25 -0800981 case FTS_F:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600982 if (chown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800983 PLOG(WARNING) << "Failed to chown " << p->fts_path;
984 }
985 break;
986 case FTS_SL:
987 case FTS_SLNONE:
Jeff Sharkeye12d5962017-04-03 16:41:02 -0600988 if (lchown(p->fts_path, -1, gid) != 0) {
Calin Juravle42451c02017-01-17 14:43:25 -0800989 PLOG(WARNING) << "Failed to chown " << p->fts_path;
990 }
991 break;
992 }
993 }
994 fts_close(fts);
995 return 0;
996}
997
Calin Juravlee61189e2018-01-23 19:54:11 -0800998// Collect all non empty profiles from the given directory and puts then into profile_paths.
999// The profiles are identified based on PROFILE_EXT extension.
1000// If a subdirectory or profile file cannot be opened the method logs a warning and moves on.
1001// It returns true if there were no errors at all, and false otherwise.
1002static bool collect_profiles(DIR* d,
1003 const std::string& current_path,
1004 std::vector<std::string>* profiles_paths) {
1005 int32_t dir_fd = dirfd(d);
1006 if (dir_fd < 0) {
1007 return false;
1008 }
1009
1010 bool result = true;
1011 struct dirent* dir_entry;
1012 while ((dir_entry = readdir(d))) {
1013 std::string name = dir_entry->d_name;
1014 std::string local_path = current_path + "/" + name;
1015
1016 if (dir_entry->d_type == DT_REG) {
1017 // Check if this is a non empty profile file.
1018 if (EndsWith(name, PROFILE_EXT)) {
1019 struct stat st;
1020 if (stat(local_path.c_str(), &st) != 0) {
1021 PLOG(WARNING) << "Cannot stat local path " << local_path;
1022 result = false;
1023 continue;
1024 } else if (st.st_size > 0) {
1025 profiles_paths->push_back(local_path);
1026 }
1027 }
1028 } else if (dir_entry->d_type == DT_DIR) {
1029 // always skip "." and ".."
1030 if (name == "." || name == "..") {
1031 continue;
1032 }
1033
1034 unique_fd subdir_fd(openat(dir_fd, name.c_str(),
1035 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1036 if (subdir_fd < 0) {
1037 PLOG(WARNING) << "Could not open dir path " << local_path;
1038 result = false;
1039 continue;
1040 }
1041
Mathieu Chartier89883e32018-11-01 11:39:00 -07001042 DIR* subdir = Fdopendir(std::move(subdir_fd));
Yi Kong954cf642018-07-17 16:16:24 -07001043 if (subdir == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001044 PLOG(WARNING) << "Could not open dir path " << local_path;
1045 result = false;
1046 continue;
1047 }
1048 bool new_result = collect_profiles(subdir, local_path, profiles_paths);
1049 result = result && new_result;
1050 if (closedir(subdir) != 0) {
1051 PLOG(WARNING) << "Could not close dir path " << local_path;
1052 }
1053 }
1054 }
1055
1056 return result;
1057}
1058
1059bool collect_profiles(std::vector<std::string>* profiles_paths) {
1060 DIR* d = opendir(android_profiles_dir.c_str());
Yi Kong954cf642018-07-17 16:16:24 -07001061 if (d == nullptr) {
Calin Juravlee61189e2018-01-23 19:54:11 -08001062 return false;
1063 } else {
1064 return collect_profiles(d, android_profiles_dir, profiles_paths);
1065 }
1066}
1067
Eric Holk2af5e6a2019-01-09 18:17:27 -08001068void drop_capabilities(uid_t uid) {
1069 if (setgid(uid) != 0) {
1070 PLOG(ERROR) << "setgid(" << uid << ") failed in installd during dexopt";
1071 exit(DexoptReturnCodes::kSetGid);
1072 }
1073 if (setuid(uid) != 0) {
1074 PLOG(ERROR) << "setuid(" << uid << ") failed in installd during dexopt";
1075 exit(DexoptReturnCodes::kSetUid);
1076 }
1077 // drop capabilities
1078 struct __user_cap_header_struct capheader;
1079 struct __user_cap_data_struct capdata[2];
1080 memset(&capheader, 0, sizeof(capheader));
1081 memset(&capdata, 0, sizeof(capdata));
1082 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1083 if (capset(&capheader, &capdata[0]) < 0) {
1084 PLOG(ERROR) << "capset failed";
1085 exit(DexoptReturnCodes::kCapSet);
1086 }
1087}
1088
Andreas Gampe02d0de52015-11-11 20:43:16 -08001089} // namespace installd
1090} // namespace android