blob: b31008cd55854009d0640e1be978686062b3c113 [file] [log] [blame]
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * 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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * 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
14 * limitations under the License.
15 */
16
Jeff Sharkeydeb24052015-03-02 21:01:40 -080017#include "Utils.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070018
Jeff Sharkeydeb24052015-03-02 21:01:40 -080019#include "Process.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070020#include "sehandle.h"
Jeff Sharkeydeb24052015-03-02 21:01:40 -080021
Paul Crowley298fa322018-10-30 15:59:24 -070022#include <android-base/chrono_utils.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080023#include <android-base/file.h>
24#include <android-base/logging.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070025#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080026#include <android-base/stringprintf.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070027#include <android-base/strings.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070028#include <android-base/unique_fd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080029#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070030#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070031#include <private/android_filesystem_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080032
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070033#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080034#include <fcntl.h>
35#include <linux/fs.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010036#include <linux/posix_acl.h>
37#include <linux/posix_acl_xattr.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070038#include <mntent.h>
39#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080040#include <stdlib.h>
41#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080042#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070043#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070044#include <sys/sysmacros.h>
45#include <sys/types.h>
46#include <sys/wait.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010047#include <sys/xattr.h>
Paul Crowley747b4212019-04-05 04:09:57 -070048#include <unistd.h>
Paul Crowley298fa322018-10-30 15:59:24 -070049
Sudheer Shanka89ddf992018-09-25 14:22:07 -070050#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070051#include <mutex>
Martijn Coenen04bb17f2020-02-10 23:48:11 +010052#include <regex>
Paul Crowley298fa322018-10-30 15:59:24 -070053#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080054
55#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070056#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080057#endif
58
Paul Crowley298fa322018-10-30 15:59:24 -070059using namespace std::chrono_literals;
Martijn Coenenba9868b2020-01-31 15:49:24 +010060using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070061using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010062using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070063using android::base::StringPrintf;
64
Jeff Sharkeydeb24052015-03-02 21:01:40 -080065namespace android {
66namespace vold {
67
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070068security_context_t sBlkidContext = nullptr;
69security_context_t sBlkidUntrustedContext = nullptr;
70security_context_t sFsckContext = nullptr;
71security_context_t sFsckUntrustedContext = nullptr;
72
Paul Crowley56292ef2017-10-20 08:07:53 -070073bool sSleepOnUnmount = true;
74
Jeff Sharkey9c484982015-03-31 10:35:33 -070075static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070076static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070077
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070078static const char* kProcFilesystems = "/proc/filesystems";
79
Martijn Coenen04bb17f2020-02-10 23:48:11 +010080static const char* kAndroidDir = "/Android/";
81static const char* kAppDataDir = "/Android/data/";
82static const char* kAppMediaDir = "/Android/media/";
83static const char* kAppObbDir = "/Android/obb/";
84
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060085// Lock used to protect process-level SELinux changes from racing with each
86// other between multiple threads.
87static std::mutex kSecurityLock;
88
Jeff Sharkeydeb24052015-03-02 21:01:40 -080089status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060090 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080091 const char* cpath = path.c_str();
92 status_t res = 0;
93
94 char* secontext = nullptr;
95 if (sehandle) {
96 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
97 setfscreatecon(secontext);
98 }
99 }
100
101 mode_t mode = 0660 | S_IFBLK;
102 if (mknod(cpath, mode, dev) < 0) {
103 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700104 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
105 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800106 res = -errno;
107 }
108 }
109
110 if (secontext) {
111 setfscreatecon(nullptr);
112 freecon(secontext);
113 }
114
115 return res;
116}
117
118status_t DestroyDeviceNode(const std::string& path) {
119 const char* cpath = path.c_str();
120 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
121 return -errno;
122 } else {
123 return OK;
124 }
125}
126
Martijn Coenen879fa802020-02-11 12:37:25 +0100127// Sets a default ACL where the owner and group can read/write/execute.
128// Other users aren't allowed anything.
129int SetDefault770Acl(const std::string& path, uid_t uid, gid_t gid) {
130 if (IsFilesystemSupported("sdcardfs")) {
131 // sdcardfs magically takes care of this
132 return OK;
133 }
134
135 static constexpr size_t size =
136 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
137 auto buf = std::make_unique<uint8_t[]>(size);
138
139 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
140 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
141
142 posix_acl_xattr_entry* entry =
143 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
144
145 entry[0].e_tag = ACL_USER_OBJ;
146 entry[0].e_perm = ACL_READ | ACL_WRITE | ACL_EXECUTE;
147 entry[0].e_id = uid;
148
149 entry[1].e_tag = ACL_GROUP_OBJ;
150 entry[1].e_perm = ACL_READ | ACL_WRITE | ACL_EXECUTE;
151 entry[1].e_id = gid;
152
153 entry[2].e_tag = ACL_OTHER;
154 entry[2].e_perm = 0;
155 entry[2].e_id = 0;
156
157 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
158
159 if (ret != 0) {
160 PLOG(ERROR) << "Failed to set default ACL on " << path;
161 }
162
163 return ret;
164}
165
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100166int SetQuotaInherit(const std::string& path) {
167 unsigned long flags;
168
169 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
170 if (fd == -1) {
171 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
172 return -1;
173 }
174
175 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
176 if (ret == -1) {
177 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
178 return ret;
179 }
180
181 flags |= FS_PROJINHERIT_FL;
182
183 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
184 if (ret == -1) {
185 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
186 return ret;
187 }
188
189 return 0;
190}
191
192int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100193 struct fsxattr fsx;
194
195 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
196 if (fd == -1) {
197 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
198 return -1;
199 }
200
201 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
202 if (ret == -1) {
203 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
204 return ret;
205 }
206
207 fsx.fsx_projid = projectId;
208 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
209}
210
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100211int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
212 long projectId) {
213 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
214
215 if (ret != 0) {
216 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100217 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100218
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100219 if (!IsFilesystemSupported("sdcardfs")) {
220 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100221 }
222
223 return ret;
224}
225
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100226static gid_t getAppDirGid(const std::string& appDir) {
227 gid_t gid = AID_MEDIA_RW;
228 if (!IsFilesystemSupported("sdcardfs")) {
229 if (appDir == android::vold::kAppDataDir) {
230 gid = AID_EXT_DATA_RW;
231 } else if (appDir == android::vold::kAppObbDir) {
232 gid = AID_EXT_OBB_RW;
233 } else if (appDir == android::vold::kAppMediaDir) {
234 gid = AID_MEDIA_RW;
235 } else {
236 gid = AID_MEDIA_RW;
237 }
238 }
239
240 return gid;
241}
242
243int PrepareAppDirFromRoot(std::string path, int appUid) {
244 int ret = 0;
245 // Extract various parts of the path to setup correctly
246 // Sample path:
247 // /data/media/0/Android/data/com.foo/files
248 // [1]: path in which to create app-specific dir, eg. /data/media/0/Android/data/
249 // [2]: the part of [1] starting from /Android, eg. /Android/data/
250 // [3]: the package name part of the path, eg. com.foo
251 // [4]: the directory to create within [3], eg files
252 std::regex re("(^/.*(/Android/(?:data|media|obb|sandbox)/))([^/]+)/([^/]+)?/?");
253
254 std::smatch match;
255 bool is_match = regex_match(path, match, re);
256
257 if (!is_match) {
258 LOG(ERROR) << "Invalid application directory: " << path;
259 return -EINVAL;
260 }
261
262 uid_t uid = appUid;
263 gid_t gid = getAppDirGid(match.str(2));
264 // mode = 770, plus sticky bit on directory to inherit GID when apps
265 // create subdirs
266 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
267 long projectId = uid - AID_APP_START + AID_EXT_GID_START;
268
269 // First, create the package-path
270 std::string package_path = match.str(1) + match.str(3);
271 ret = PrepareDirWithProjectId(package_path, mode, uid, gid, projectId);
272 if (ret) {
273 return ret;
274 }
275
Martijn Coenen879fa802020-02-11 12:37:25 +0100276 // Set the default ACL, to ensure that even if applications run with a
277 // umask of 0077, new directories within these directories will allow the
278 // GID specified here to write; this is necessary for apps like installers
279 // and MTP, that require access here.
280 //
281 // See man (5) acl for more details.
282 ret = SetDefault770Acl(package_path, uid, gid);
283 if (ret) {
284 return ret;
285 }
286
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100287 // Next, create the directory within the package, if needed
288 if (match.size() <= 4) {
289 return OK;
290 }
291
292 if (match.str(4) == "cache") {
293 // All dirs use the "app" project ID, except for the cache dir
294 projectId = uid - AID_APP_START + AID_CACHE_GID_START;
295 }
Greg Kaiser724f0092020-02-12 07:11:09 -0800296 return PrepareDirWithProjectId(path, mode, uid, gid, projectId);
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100297}
298
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700299status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600300 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700301 const char* cpath = path.c_str();
302
303 char* secontext = nullptr;
304 if (sehandle) {
305 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
306 setfscreatecon(secontext);
307 }
308 }
309
310 int res = fs_prepare_dir(cpath, mode, uid, gid);
311
312 if (secontext) {
313 setfscreatecon(nullptr);
314 freecon(secontext);
315 }
316
317 if (res == 0) {
318 return OK;
319 } else {
320 return -errno;
321 }
322}
323
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800324status_t ForceUnmount(const std::string& path) {
325 const char* cpath = path.c_str();
326 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
327 return OK;
328 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700329 // Apps might still be handling eject request, so wait before
330 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700331 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700332
Jeff Sharkey3472e522017-10-06 18:02:53 -0600333 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700334 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700335 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
336 return OK;
337 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700338
Jeff Sharkey3472e522017-10-06 18:02:53 -0600339 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700340 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800341 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
342 return OK;
343 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700344
Jeff Sharkey3472e522017-10-06 18:02:53 -0600345 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700346 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700347 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
348 return OK;
349 }
Zim3623a212019-07-19 16:46:53 +0100350 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800351 return -errno;
352}
353
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700354status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600355 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700356 return OK;
357 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700358 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700359
Jeff Sharkey3472e522017-10-06 18:02:53 -0600360 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700361 return OK;
362 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700363 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700364
Jeff Sharkey3472e522017-10-06 18:02:53 -0600365 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700366 return OK;
367 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700368 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700369
370 // Send SIGKILL a second time to determine if we've
371 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600372 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700373 return OK;
374 }
375 PLOG(ERROR) << "Failed to kill processes using " << path;
376 return -EBUSY;
377}
378
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700379status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800380 if (UnmountTree(target) < 0) {
381 return -errno;
382 }
383 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700384 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
385 return -errno;
386 }
387 return OK;
388}
389
Sudheer Shanka023b5392019-02-06 12:39:19 -0800390status_t Symlink(const std::string& target, const std::string& linkpath) {
391 if (Unlink(linkpath) < 0) {
392 return -errno;
393 }
394 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
395 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
396 return -errno;
397 }
398 return OK;
399}
400
401status_t Unlink(const std::string& linkpath) {
402 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
403 PLOG(ERROR) << "Failed to unlink " << linkpath;
404 return -errno;
405 }
406 return OK;
407}
408
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000409status_t CreateDir(const std::string& dir, mode_t mode) {
410 struct stat sb;
411 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
412 if (S_ISDIR(sb.st_mode)) {
413 return OK;
414 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
415 PLOG(ERROR) << "Failed to unlink " << dir;
416 return -errno;
417 }
418 } else if (errno != ENOENT) {
419 PLOG(ERROR) << "Failed to stat " << dir;
420 return -errno;
421 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800422 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000423 PLOG(ERROR) << "Failed to mkdir " << dir;
424 return -errno;
425 }
426 return OK;
427}
428
Jeff Sharkey3472e522017-10-06 18:02:53 -0600429bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
430 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800431 size_t start = 0;
432 while (true) {
433 start = raw.find(qual, start);
434 if (start == std::string::npos) return false;
435 if (start == 0 || raw[start - 1] == ' ') {
436 break;
437 }
438 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600439 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600440 start += qual.length();
441
442 auto end = raw.find("\"", start);
443 if (end == std::string::npos) return false;
444
445 *value = raw.substr(start, end - start);
446 return true;
447}
448
Paul Crowley14c8c072018-09-18 13:30:21 -0700449static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
450 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600451 fsType->clear();
452 fsUuid->clear();
453 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700454
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700455 std::vector<std::string> cmd;
456 cmd.push_back(kBlkidPath);
457 cmd.push_back("-c");
458 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700459 cmd.push_back("-s");
460 cmd.push_back("TYPE");
461 cmd.push_back("-s");
462 cmd.push_back("UUID");
463 cmd.push_back("-s");
464 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700465 cmd.push_back(path);
466
467 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800468 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700469 if (res != OK) {
470 LOG(WARNING) << "blkid failed to identify " << path;
471 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700472 }
473
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700474 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700475 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600476 FindValue(line, "TYPE", fsType);
477 FindValue(line, "UUID", fsUuid);
478 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700479 }
480
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700481 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700482}
483
Paul Crowley14c8c072018-09-18 13:30:21 -0700484status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
485 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700486 return readMetadata(path, fsType, fsUuid, fsLabel, false);
487}
488
Paul Crowley14c8c072018-09-18 13:30:21 -0700489status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
490 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700491 return readMetadata(path, fsType, fsUuid, fsLabel, true);
492}
493
Paul Crowleyde2d6202018-11-30 11:43:47 -0800494static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
495 std::vector<const char*> argv;
496 argv.reserve(args.size() + 1);
497 for (const auto& arg : args) {
498 if (argv.empty()) {
499 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700500 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800501 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700502 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800503 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700504 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800505 argv.emplace_back(nullptr);
506 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700507}
508
Paul Crowleyde2d6202018-11-30 11:43:47 -0800509static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
510 android::base::unique_fd ufd) {
511 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700512 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800513 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700514 return -errno;
515 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800516 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700517 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800518 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700519 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800520 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700521 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800522 return OK;
523}
524
525status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
526 security_context_t context) {
527 auto argv = ConvertToArgv(args);
528
Paul Crowleye6d76632018-11-30 11:43:47 -0800529 android::base::unique_fd pipe_read, pipe_write;
530 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
531 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800532 return -errno;
533 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800534
535 pid_t pid = fork();
536 if (pid == 0) {
537 if (context) {
538 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800539 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800540 abort();
541 }
542 }
543 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800544 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
545 PLOG(ERROR) << "dup2 in ForkExecvp";
546 _exit(EXIT_FAILURE);
547 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800548 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800549 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800550 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800551 _exit(EXIT_FAILURE);
552 }
553 if (pid == -1) {
554 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700555 return -errno;
556 }
557
Paul Crowleyde2d6202018-11-30 11:43:47 -0800558 pipe_write.reset();
559 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
560 if (st != 0) return st;
561
562 int status;
563 if (waitpid(pid, &status, 0) == -1) {
564 PLOG(ERROR) << "waitpid in ForkExecvp";
565 return -errno;
566 }
567 if (!WIFEXITED(status)) {
568 LOG(ERROR) << "Process did not exit normally, status: " << status;
569 return -ECHILD;
570 }
571 if (WEXITSTATUS(status)) {
572 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
573 return WEXITSTATUS(status);
574 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700575 return OK;
576}
577
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700578pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800579 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700580
581 pid_t pid = fork();
582 if (pid == 0) {
583 close(STDIN_FILENO);
584 close(STDOUT_FILENO);
585 close(STDERR_FILENO);
586
Paul Crowleyde2d6202018-11-30 11:43:47 -0800587 execvp(argv[0], const_cast<char**>(argv.data()));
588 PLOG(ERROR) << "exec in ForkExecvpAsync";
589 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700590 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700591 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800592 PLOG(ERROR) << "fork in ForkExecvpAsync";
593 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700594 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700595 return pid;
596}
597
Jeff Sharkey9c484982015-03-31 10:35:33 -0700598status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100599 out.resize(bytes);
600 return ReadRandomBytes(bytes, &out[0]);
601}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700602
Pavel Grafove2e2d302017-08-01 17:15:53 +0100603status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700604 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
605 if (fd == -1) {
606 return -errno;
607 }
608
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800609 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100610 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700611 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100612 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700613 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700614 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700615
616 if (bytes == 0) {
617 return OK;
618 } else {
619 return -EIO;
620 }
621}
622
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600623status_t GenerateRandomUuid(std::string& out) {
624 status_t res = ReadRandomBytes(16, out);
625 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700626 out[6] &= 0x0f; /* clear version */
627 out[6] |= 0x40; /* set to version 4 */
628 out[8] &= 0x3f; /* clear variant */
629 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600630 }
631 return res;
632}
633
Jeff Sharkey9c484982015-03-31 10:35:33 -0700634status_t HexToStr(const std::string& hex, std::string& str) {
635 str.clear();
636 bool even = true;
637 char cur = 0;
638 for (size_t i = 0; i < hex.size(); i++) {
639 int val = 0;
640 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700641 // clang-format off
642 case ' ': case '-': case ':': continue;
643 case 'f': case 'F': val = 15; break;
644 case 'e': case 'E': val = 14; break;
645 case 'd': case 'D': val = 13; break;
646 case 'c': case 'C': val = 12; break;
647 case 'b': case 'B': val = 11; break;
648 case 'a': case 'A': val = 10; break;
649 case '9': val = 9; break;
650 case '8': val = 8; break;
651 case '7': val = 7; break;
652 case '6': val = 6; break;
653 case '5': val = 5; break;
654 case '4': val = 4; break;
655 case '3': val = 3; break;
656 case '2': val = 2; break;
657 case '1': val = 1; break;
658 case '0': val = 0; break;
659 default: return -EINVAL;
660 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700661 }
662
663 if (even) {
664 cur = val << 4;
665 } else {
666 cur += val;
667 str.push_back(cur);
668 cur = 0;
669 }
670 even = !even;
671 }
672 return even ? OK : -EINVAL;
673}
674
675static const char* kLookup = "0123456789abcdef";
676
677status_t StrToHex(const std::string& str, std::string& hex) {
678 hex.clear();
679 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700680 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700681 hex.push_back(kLookup[str[i] & 0x0F]);
682 }
683 return OK;
684}
685
Pavel Grafove2e2d302017-08-01 17:15:53 +0100686status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
687 hex.clear();
688 for (size_t i = 0; i < str.size(); i++) {
689 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
690 hex.push_back(kLookup[str.data()[i] & 0x0F]);
691 }
692 return OK;
693}
694
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700695status_t NormalizeHex(const std::string& in, std::string& out) {
696 std::string tmp;
697 if (HexToStr(in, tmp)) {
698 return -EINVAL;
699 }
700 return StrToHex(tmp, out);
701}
702
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200703status_t GetBlockDevSize(int fd, uint64_t* size) {
704 if (ioctl(fd, BLKGETSIZE64, size)) {
705 return -errno;
706 }
707
708 return OK;
709}
710
711status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
712 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
713 status_t res = OK;
714
715 if (fd < 0) {
716 return -errno;
717 }
718
719 res = GetBlockDevSize(fd, size);
720
721 close(fd);
722
723 return res;
724}
725
726status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
727 uint64_t size;
728 status_t res = GetBlockDevSize(path, &size);
729
730 if (res != OK) {
731 return res;
732 }
733
734 *nr_sec = size / 512;
735
736 return OK;
737}
738
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700739uint64_t GetFreeBytes(const std::string& path) {
740 struct statvfs sb;
741 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700742 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700743 } else {
744 return -1;
745 }
746}
747
748// TODO: borrowed from frameworks/native/libs/diskusage/ which should
749// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700750static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700751 int64_t blksize = s->st_blksize;
752 // count actual blocks used instead of nominal file size
753 int64_t size = s->st_blocks * 512;
754
755 if (blksize) {
756 /* round up to filesystem block size */
757 size = (size + blksize - 1) & (~(blksize - 1));
758 }
759
760 return size;
761}
762
763// TODO: borrowed from frameworks/native/libs/diskusage/ which should
764// eventually be migrated into system/
765int64_t calculate_dir_size(int dfd) {
766 int64_t size = 0;
767 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700768 DIR* d;
769 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700770
771 d = fdopendir(dfd);
772 if (d == NULL) {
773 close(dfd);
774 return 0;
775 }
776
777 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700778 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700779 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
780 size += stat_size(&s);
781 }
782 if (de->d_type == DT_DIR) {
783 int subfd;
784
785 /* always skip "." and ".." */
786 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700787 if (name[1] == 0) continue;
788 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700789 }
790
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600791 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700792 if (subfd >= 0) {
793 size += calculate_dir_size(subfd);
794 }
795 }
796 }
797 closedir(d);
798 return size;
799}
800
801uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600802 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700803 if (dirfd < 0) {
804 PLOG(WARNING) << "Failed to open " << path;
805 return -1;
806 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700807 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700808 }
809}
810
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700811bool IsFilesystemSupported(const std::string& fsType) {
812 std::string supported;
813 if (!ReadFileToString(kProcFilesystems, &supported)) {
814 PLOG(ERROR) << "Failed to read supported filesystems";
815 return false;
816 }
817 return supported.find(fsType + "\n") != std::string::npos;
818}
819
820status_t WipeBlockDevice(const std::string& path) {
821 status_t res = -1;
822 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200823 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700824
825 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
826 if (fd == -1) {
827 PLOG(ERROR) << "Failed to open " << path;
828 goto done;
829 }
830
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200831 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700832 PLOG(ERROR) << "Failed to determine size of " << path;
833 goto done;
834 }
835
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700836 LOG(INFO) << "About to discard " << range[1] << " on " << path;
837 if (ioctl(fd, BLKDISCARD, &range) == 0) {
838 LOG(INFO) << "Discard success on " << path;
839 res = 0;
840 } else {
841 PLOG(ERROR) << "Discard failure on " << path;
842 }
843
844done:
845 close(fd);
846 return res;
847}
848
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800849static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700850 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800851 return false;
852 } else {
853 return true;
854 }
855}
856
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700857std::string BuildKeyPath(const std::string& partGuid) {
858 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
859}
860
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600861std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700862 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600863}
864
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800865std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700866 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700867}
868
869std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700870 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700871}
872
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600873std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700874 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600875}
876
Jeff Sharkey47695b22016-02-01 17:02:29 -0700877std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700878 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700879}
880
881std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700882 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800883}
884
Calin Juravle79f55a42016-02-17 20:14:46 +0000885// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
886std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700887 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000888}
889
Andreas Huber71cd43f2018-01-22 11:25:29 -0800890std::string BuildDataVendorCePath(userid_t userId) {
891 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
892}
893
894std::string BuildDataVendorDePath(userid_t userId) {
895 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
896}
897
Paul Crowley3b71fc52017-10-09 10:55:21 -0700898std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800899 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700900 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800901 return "/data";
902 } else {
903 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700904 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800905 }
906}
907
Paul Crowley3b71fc52017-10-09 10:55:21 -0700908std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700909 // TODO: unify with installd path generation logic
910 std::string data(BuildDataPath(volumeUuid));
911 return StringPrintf("%s/media/%u", data.c_str(), userId);
912}
913
Paul Crowley3b71fc52017-10-09 10:55:21 -0700914std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800915 // TODO: unify with installd path generation logic
916 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700917 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800918 std::string legacy = StringPrintf("%s/data", data.c_str());
919 struct stat sb;
920 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
921 /* /data/data is dir, return /data/data for legacy system */
922 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800923 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800924 }
cjbaoeb501142017-04-12 00:09:00 +0800925 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800926}
927
Paul Crowley3b71fc52017-10-09 10:55:21 -0700928std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800929 // TODO: unify with installd path generation logic
930 std::string data(BuildDataPath(volumeUuid));
931 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
932}
933
Jeff Sharkey66270a22015-06-24 11:49:24 -0700934dev_t GetDevice(const std::string& path) {
935 struct stat sb;
936 if (stat(path.c_str(), &sb)) {
937 PLOG(WARNING) << "Failed to stat " << path;
938 return 0;
939 } else {
940 return sb.st_dev;
941 }
942}
943
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600944status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700945 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600946
Tom Cherryd6127ef2017-06-15 17:13:56 -0700947 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600948
Tom Cherryd6127ef2017-06-15 17:13:56 -0700949 android::base::SetProperty(kRestoreconString, "");
950 android::base::SetProperty(kRestoreconString, path);
951
952 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600953
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700954 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600955 return OK;
956}
957
Jeff Sharkey3472e522017-10-06 18:02:53 -0600958bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
959 // Shamelessly borrowed from android::base::Readlink()
960 result->clear();
961
962 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
963 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
964 // waste memory to just start there. We add 1 so that we can recognize
965 // whether it actually fit (rather than being truncated to 4095).
966 std::vector<char> buf(4095 + 1);
967 while (true) {
968 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
969 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700970 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600971 // It fit! (If size == buf.size(), it may have been truncated.)
972 if (static_cast<size_t>(size) < buf.size()) {
973 result->assign(&buf[0], size);
974 return true;
975 }
976 // Double our buffer and try again.
977 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900978 }
979}
980
Yu Ning942d4e82016-01-08 17:36:47 +0800981bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700982 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800983}
984
Sudheer Shanka295fb242019-01-16 23:04:07 -0800985static status_t findMountPointsWithPrefix(const std::string& prefix,
986 std::list<std::string>& mountPoints) {
987 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
988 // when the prefix is /foo/bar
989 std::string prefixWithSlash(prefix);
990 if (prefix.back() != '/') {
991 android::base::StringAppendF(&prefixWithSlash, "/");
992 }
993
994 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
995 if (!mnts) {
996 PLOG(ERROR) << "Unable to open /proc/mounts";
997 return -errno;
998 }
999
1000 // Some volumes can be stacked on each other, so force unmount in
1001 // reverse order to give us the best chance of success.
1002 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1003 while ((mnt = getmntent(mnts.get())) != nullptr) {
1004 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1005 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1006 mountPoints.push_front(mountPoint);
1007 }
1008 }
1009 return OK;
1010}
1011
1012// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1013status_t UnmountTreeWithPrefix(const std::string& prefix) {
1014 std::list<std::string> toUnmount;
1015 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1016 if (result < 0) {
1017 return result;
1018 }
1019 for (const auto& path : toUnmount) {
1020 if (umount2(path.c_str(), MNT_DETACH)) {
1021 PLOG(ERROR) << "Failed to unmount " << path;
1022 result = -errno;
1023 }
1024 }
1025 return result;
1026}
1027
1028status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001029 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1030 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001031 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001032 return -errno;
1033 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001034 return OK;
1035}
1036
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001037static status_t delete_dir_contents(DIR* dir) {
1038 // Shamelessly borrowed from android::installd
1039 int dfd = dirfd(dir);
1040 if (dfd < 0) {
1041 return -errno;
1042 }
1043
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001044 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001045 struct dirent* de;
1046 while ((de = readdir(dir))) {
1047 const char* name = de->d_name;
1048 if (de->d_type == DT_DIR) {
1049 /* always skip "." and ".." */
1050 if (name[0] == '.') {
1051 if (name[1] == 0) continue;
1052 if ((name[1] == '.') && (name[2] == 0)) continue;
1053 }
1054
1055 android::base::unique_fd subfd(
1056 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1057 if (subfd.get() == -1) {
1058 PLOG(ERROR) << "Couldn't openat " << name;
1059 result = -errno;
1060 continue;
1061 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001062 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1063 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001064 if (!subdirp) {
1065 PLOG(ERROR) << "Couldn't fdopendir " << name;
1066 result = -errno;
1067 continue;
1068 }
1069 result = delete_dir_contents(subdirp.get());
1070 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1071 PLOG(ERROR) << "Couldn't unlinkat " << name;
1072 result = -errno;
1073 }
1074 } else {
1075 if (unlinkat(dfd, name, 0) < 0) {
1076 PLOG(ERROR) << "Couldn't unlinkat " << name;
1077 result = -errno;
1078 }
1079 }
1080 }
1081 return result;
1082}
1083
1084status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001085 status_t res = DeleteDirContents(pathname);
1086 if (res < 0) {
1087 return res;
1088 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001089 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001090 PLOG(ERROR) << "rmdir failed on " << pathname;
1091 return -errno;
1092 }
1093 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1094 return OK;
1095}
1096
1097status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001098 // Shamelessly borrowed from android::installd
1099 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1100 if (!dirp) {
1101 if (errno == ENOENT) {
1102 return OK;
1103 }
1104 PLOG(ERROR) << "Failed to opendir " << pathname;
1105 return -errno;
1106 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001107 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001108}
1109
Paul Crowley298fa322018-10-30 15:59:24 -07001110// TODO(118708649): fix duplication with init/util.h
1111status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1112 android::base::Timer t;
1113 while (t.duration() < timeout) {
1114 struct stat sb;
1115 if (stat(filename, &sb) != -1) {
1116 LOG(INFO) << "wait for '" << filename << "' took " << t;
1117 return 0;
1118 }
1119 std::this_thread::sleep_for(10ms);
1120 }
1121 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1122 return -1;
1123}
1124
Paul Crowley621d9b92018-12-07 15:36:09 -08001125bool FsyncDirectory(const std::string& dirname) {
1126 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1127 if (fd == -1) {
1128 PLOG(ERROR) << "Failed to open " << dirname;
1129 return false;
1130 }
1131 if (fsync(fd) == -1) {
1132 if (errno == EROFS || errno == EINVAL) {
1133 PLOG(WARNING) << "Skip fsync " << dirname
1134 << " on a file system does not support synchronization";
1135 } else {
1136 PLOG(ERROR) << "Failed to fsync " << dirname;
1137 return false;
1138 }
1139 }
1140 return true;
1141}
1142
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001143bool writeStringToFile(const std::string& payload, const std::string& filename) {
1144 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1145 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1146 if (fd == -1) {
1147 PLOG(ERROR) << "Failed to open " << filename;
1148 return false;
1149 }
1150 if (!android::base::WriteStringToFd(payload, fd)) {
1151 PLOG(ERROR) << "Failed to write to " << filename;
1152 unlink(filename.c_str());
1153 return false;
1154 }
1155 // fsync as close won't guarantee flush data
1156 // see close(2), fsync(2) and b/68901441
1157 if (fsync(fd) == -1) {
1158 if (errno == EROFS || errno == EINVAL) {
1159 PLOG(WARNING) << "Skip fsync " << filename
1160 << " on a file system does not support synchronization";
1161 } else {
1162 PLOG(ERROR) << "Failed to fsync " << filename;
1163 unlink(filename.c_str());
1164 return false;
1165 }
1166 }
1167 return true;
1168}
1169
Zima438b242019-09-25 14:37:38 +01001170status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1171 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1172 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1173 std::string fuse_path(
1174 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1175
1176 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1177 std::string pass_through_path(
1178 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001179
Zim1242be82020-01-22 18:22:29 +00001180 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1181 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001182 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001183 if (result != android::OK) {
1184 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1185 return -1;
1186 }
1187
Zim06b0caf2020-01-05 02:11:47 +00001188 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1189 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1190 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1191 // These bits should be consistent with what is set in zygote in
1192 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001193 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001194 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001195 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001196 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001197 return -1;
1198 }
1199
Zima438b242019-09-25 14:37:38 +01001200 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1201 if (result != android::OK) {
1202 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1203 return -1;
1204 }
1205
Zim26eec702020-01-31 16:00:58 +00001206 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001207 if (result != android::OK) {
1208 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1209 return -1;
1210 }
1211
Zim26eec702020-01-31 16:00:58 +00001212 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001213 if (result != android::OK) {
1214 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1215 return -1;
1216 }
1217
1218 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001219 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1220 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001221 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001222 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001223 return -1;
1224 }
Zime5393d42019-11-15 11:44:12 +00001225 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001226 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001227
1228 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001229 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001230 if (result != android::OK) {
1231 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1232 return -1;
1233 }
1234 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001235 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001236 }
1237
Nandana Dutta914cc72019-08-29 15:22:42 +01001238 // Open fuse fd.
1239 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1240 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001241 PLOG(ERROR) << "Failed to open /dev/fuse";
1242 return -1;
1243 }
1244
1245 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1246 // permission checks before routing to FUSE daemon.
1247 const auto opts = StringPrintf(
1248 "fd=%i,"
1249 "rootmode=40000,"
1250 "allow_other,"
1251 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001252 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001253
Zima438b242019-09-25 14:37:38 +01001254 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1255 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1256 opts.c_str()));
1257 if (result != 0) {
1258 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001259 return -errno;
1260 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001261
Martijn Coenen86f21a22020-01-06 09:48:14 +01001262 if (IsFilesystemSupported("sdcardfs")) {
1263 std::string sdcardfs_path(
1264 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1265
1266 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1267 return BindMount(sdcardfs_path, pass_through_path);
1268 } else {
1269 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1270 return BindMount(absolute_lower_path, pass_through_path);
1271 }
Zima438b242019-09-25 14:37:38 +01001272}
1273
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001274status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1275 const std::string& relative_upper_path) {
1276 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1277 std::string pass_through_path(
1278 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1279
Zima438b242019-09-25 14:37:38 +01001280 // Best effort unmount pass_through path
1281 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001282 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1283 auto status = ForceUnmount(pass_through_path);
1284 if (status != android::OK) {
1285 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1286 }
Martijn Coenen57002612019-11-28 11:56:13 +01001287 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001288
1289 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001290 android::status_t result = ForceUnmount(fuse_path);
1291 sSleepOnUnmount = true;
1292 if (result != android::OK) {
1293 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1294 // Figure out why we get EBUSY and remove this special casing if possible.
1295 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1296 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1297 errno != ENOENT) {
1298 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1299 return -errno;
1300 }
Martijn Coenen57002612019-11-28 11:56:13 +01001301 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001302 }
Martijn Coenen57002612019-11-28 11:56:13 +01001303 rmdir(fuse_path.c_str());
1304
Zima438b242019-09-25 14:37:38 +01001305 return result;
Zim3623a212019-07-19 16:46:53 +01001306}
1307
Martijn Coenen62a4b272020-01-31 15:23:09 +01001308status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1309 std::string androidDir = volumeRoot + kAndroidDir;
1310 std::string androidDataDir = volumeRoot + kAppDataDir;
1311 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001312 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001313
1314 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1315
1316 if (fs_prepare_dir(androidDir.c_str(), 0771, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1317 PLOG(ERROR) << "Failed to create " << androidDir;
1318 return -errno;
1319 }
1320
1321 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
1322 if (fs_prepare_dir(androidDataDir.c_str(), 0771, AID_MEDIA_RW, dataGid) != 0) {
1323 PLOG(ERROR) << "Failed to create " << androidDataDir;
1324 return -errno;
1325 }
1326
1327 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
1328 if (fs_prepare_dir(androidObbDir.c_str(), 0771, AID_MEDIA_RW, obbGid) != 0) {
1329 PLOG(ERROR) << "Failed to create " << androidObbDir;
1330 return -errno;
1331 }
1332
Zima13d81b2020-02-07 16:39:31 +00001333 if (fs_prepare_dir(androidMediaDir.c_str(), 0771, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1334 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1335 return -errno;
1336 }
1337
Martijn Coenen62a4b272020-01-31 15:23:09 +01001338 return OK;
1339}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001340} // namespace vold
1341} // namespace android