blob: 9f9b3571337a2aa909ca99d3678ec309b8a63101 [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
Martijn Coenen816f4d92020-02-18 15:06:37 +010050#include <filesystem>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070051#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070052#include <mutex>
Martijn Coenen04bb17f2020-02-10 23:48:11 +010053#include <regex>
Paul Crowley298fa322018-10-30 15:59:24 -070054#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080055
56#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070057#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080058#endif
59
Paul Crowley298fa322018-10-30 15:59:24 -070060using namespace std::chrono_literals;
Martijn Coenenba9868b2020-01-31 15:49:24 +010061using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070062using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010063using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070064using android::base::StringPrintf;
65
Jeff Sharkeydeb24052015-03-02 21:01:40 -080066namespace android {
67namespace vold {
68
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070069security_context_t sBlkidContext = nullptr;
70security_context_t sBlkidUntrustedContext = nullptr;
71security_context_t sFsckContext = nullptr;
72security_context_t sFsckUntrustedContext = nullptr;
73
Paul Crowley56292ef2017-10-20 08:07:53 -070074bool sSleepOnUnmount = true;
75
Jeff Sharkey9c484982015-03-31 10:35:33 -070076static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070077static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070078
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070079static const char* kProcFilesystems = "/proc/filesystems";
80
Martijn Coenen04bb17f2020-02-10 23:48:11 +010081static const char* kAndroidDir = "/Android/";
82static const char* kAppDataDir = "/Android/data/";
83static const char* kAppMediaDir = "/Android/media/";
84static const char* kAppObbDir = "/Android/obb/";
85
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060086// Lock used to protect process-level SELinux changes from racing with each
87// other between multiple threads.
88static std::mutex kSecurityLock;
89
Jeff Sharkeydeb24052015-03-02 21:01:40 -080090status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060091 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080092 const char* cpath = path.c_str();
93 status_t res = 0;
94
95 char* secontext = nullptr;
96 if (sehandle) {
97 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
98 setfscreatecon(secontext);
99 }
100 }
101
102 mode_t mode = 0660 | S_IFBLK;
103 if (mknod(cpath, mode, dev) < 0) {
104 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700105 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
106 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800107 res = -errno;
108 }
109 }
110
111 if (secontext) {
112 setfscreatecon(nullptr);
113 freecon(secontext);
114 }
115
116 return res;
117}
118
119status_t DestroyDeviceNode(const std::string& path) {
120 const char* cpath = path.c_str();
121 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
122 return -errno;
123 } else {
124 return OK;
125 }
126}
127
Martijn Coenen442bb832020-02-18 13:44:59 +0100128// Sets a default ACL on the directory.
129int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100130 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;
Martijn Coenen442bb832020-02-18 13:44:59 +0100146 // The existing mode_t mask has the ACL in the lower 9 bits:
147 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
148 // Use the mode_t masks to get these bits out, and shift them to get the
149 // correct value per entity.
150 //
151 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
152 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100153 entry[0].e_id = uid;
154
155 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100156 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100157 entry[1].e_id = gid;
158
159 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100160 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100161 entry[2].e_id = 0;
162
163 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
164
165 if (ret != 0) {
166 PLOG(ERROR) << "Failed to set default ACL on " << path;
167 }
168
169 return ret;
170}
171
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100172int SetQuotaInherit(const std::string& path) {
173 unsigned long flags;
174
175 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
176 if (fd == -1) {
177 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
178 return -1;
179 }
180
181 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
182 if (ret == -1) {
183 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
184 return ret;
185 }
186
187 flags |= FS_PROJINHERIT_FL;
188
189 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
190 if (ret == -1) {
191 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
192 return ret;
193 }
194
195 return 0;
196}
197
198int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100199 struct fsxattr fsx;
200
201 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
202 if (fd == -1) {
203 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
204 return -1;
205 }
206
207 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
208 if (ret == -1) {
209 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
210 return ret;
211 }
212
213 fsx.fsx_projid = projectId;
214 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
215}
216
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100217int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
218 long projectId) {
219 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
220
221 if (ret != 0) {
222 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100223 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100224
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100225 if (!IsFilesystemSupported("sdcardfs")) {
226 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100227 }
228
229 return ret;
230}
231
Martijn Coenen816f4d92020-02-18 15:06:37 +0100232static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
233 namespace fs = std::filesystem;
234
235 // Setup the directory itself correctly
236 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
237 if (ret != OK) {
238 return ret;
239 }
240
241 // Fixup all of its file entries
242 for (const auto& itEntry : fs::directory_iterator(path)) {
243 ret = lchown(itEntry.path().c_str(), uid, gid);
244 if (ret != 0) {
245 return ret;
246 }
247
248 ret = chmod(itEntry.path().c_str(), mode);
249 if (ret != 0) {
250 return ret;
251 }
252
253 if (!IsFilesystemSupported("sdcardfs")) {
254 ret = SetQuotaProjectId(itEntry.path(), projectId);
255 if (ret != 0) {
256 return ret;
257 }
258 }
259 }
260
261 return OK;
262}
263
264int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
265 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100266 long projectId;
267 size_t pos;
268 int ret = 0;
269
270 // Make sure the Android/ directories exist and are setup correctly
271 ret = PrepareAndroidDirs(root);
272 if (ret != 0) {
273 LOG(ERROR) << "Failed to prepare Android/ directories.";
274 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100275 }
276
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100277 // Now create the application-specific subdir(s)
278 // path is something like /data/media/0/Android/data/com.foo/files
279 // First, chop off the volume root, eg /data/media/0
280 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100281
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100282 uid_t uid = appUid;
283 gid_t gid = AID_MEDIA_RW;
284 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100285
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100286 // Check that the next part matches one of the allowed Android/ dirs
287 if (StartsWith(pathFromRoot, kAppDataDir)) {
288 appDir = kAppDataDir;
289 if (!IsFilesystemSupported("sdcardfs")) {
290 gid = AID_EXT_DATA_RW;
291 }
292 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
293 appDir = kAppMediaDir;
294 if (!IsFilesystemSupported("sdcardfs")) {
295 gid = AID_MEDIA_RW;
296 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000297 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100298 appDir = kAppObbDir;
299 if (!IsFilesystemSupported("sdcardfs")) {
300 gid = AID_EXT_OBB_RW;
301 }
302 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100303 LOG(ERROR) << "Invalid application directory: " << path;
304 return -EINVAL;
305 }
306
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100307 // mode = 770, plus sticky bit on directory to inherit GID when apps
308 // create subdirs
309 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100310 // the project ID for application-specific directories is directly
311 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100312
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100313 // Chop off the generic application-specific part, eg /Android/data/
314 // this leaves us with something like com.foo/files/
315 std::string leftToCreate = pathFromRoot.substr(appDir.length());
316 if (!EndsWith(leftToCreate, "/")) {
317 leftToCreate += "/";
318 }
319 std::string pathToCreate = root + appDir;
320 int depth = 0;
321 bool withinCache = false;
322 while ((pos = leftToCreate.find('/')) != std::string::npos) {
323 std::string component = leftToCreate.substr(0, pos + 1);
324 leftToCreate = leftToCreate.erase(0, pos + 1);
325 pathToCreate = pathToCreate + component;
326
327 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
328 // All dirs use the "app" project ID, except for the cache dirs in
329 // Android/data, eg Android/data/com.foo/cache
330 // Note that this "sticks" - eg subdirs of this dir need the same
331 // project ID.
332 withinCache = true;
333 }
334 if (withinCache) {
335 projectId = uid - AID_APP_START + AID_CACHE_GID_START;
336 } else {
337 projectId = uid - AID_APP_START + AID_EXT_GID_START;
338 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100339
340 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
341 // Fixup all files in this existing directory with the correct UID/GID
342 // and project ID.
343 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
344 } else {
345 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
346 }
347
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100348 if (ret != 0) {
349 return ret;
350 }
351
352 if (depth == 0) {
353 // Set the default ACL on the top-level application-specific directories,
354 // to ensure that even if applications run with a umask of 0077,
355 // new directories within these directories will allow the GID
356 // specified here to write; this is necessary for apps like
357 // installers and MTP, that require access here.
358 //
359 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100360 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100361 if (ret != 0) {
362 return ret;
363 }
364 }
365
366 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100367 }
368
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100369 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100370}
371
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700372status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600373 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700374 const char* cpath = path.c_str();
375
376 char* secontext = nullptr;
377 if (sehandle) {
378 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
379 setfscreatecon(secontext);
380 }
381 }
382
383 int res = fs_prepare_dir(cpath, mode, uid, gid);
384
385 if (secontext) {
386 setfscreatecon(nullptr);
387 freecon(secontext);
388 }
389
390 if (res == 0) {
391 return OK;
392 } else {
393 return -errno;
394 }
395}
396
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800397status_t ForceUnmount(const std::string& path) {
398 const char* cpath = path.c_str();
399 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
400 return OK;
401 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700402 // Apps might still be handling eject request, so wait before
403 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700404 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700405
Jeff Sharkey3472e522017-10-06 18:02:53 -0600406 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700407 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700408 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
409 return OK;
410 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700411
Jeff Sharkey3472e522017-10-06 18:02:53 -0600412 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700413 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800414 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
415 return OK;
416 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700417
Jeff Sharkey3472e522017-10-06 18:02:53 -0600418 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700419 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700420 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
421 return OK;
422 }
Zim3623a212019-07-19 16:46:53 +0100423 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800424 return -errno;
425}
426
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700427status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600428 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700429 return OK;
430 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700431 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700432
Jeff Sharkey3472e522017-10-06 18:02:53 -0600433 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700434 return OK;
435 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700436 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700437
Jeff Sharkey3472e522017-10-06 18:02:53 -0600438 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700439 return OK;
440 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700441 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700442
443 // Send SIGKILL a second time to determine if we've
444 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600445 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700446 return OK;
447 }
448 PLOG(ERROR) << "Failed to kill processes using " << path;
449 return -EBUSY;
450}
451
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700452status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800453 if (UnmountTree(target) < 0) {
454 return -errno;
455 }
456 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700457 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
458 return -errno;
459 }
460 return OK;
461}
462
Sudheer Shanka023b5392019-02-06 12:39:19 -0800463status_t Symlink(const std::string& target, const std::string& linkpath) {
464 if (Unlink(linkpath) < 0) {
465 return -errno;
466 }
467 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
468 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
469 return -errno;
470 }
471 return OK;
472}
473
474status_t Unlink(const std::string& linkpath) {
475 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
476 PLOG(ERROR) << "Failed to unlink " << linkpath;
477 return -errno;
478 }
479 return OK;
480}
481
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000482status_t CreateDir(const std::string& dir, mode_t mode) {
483 struct stat sb;
484 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
485 if (S_ISDIR(sb.st_mode)) {
486 return OK;
487 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
488 PLOG(ERROR) << "Failed to unlink " << dir;
489 return -errno;
490 }
491 } else if (errno != ENOENT) {
492 PLOG(ERROR) << "Failed to stat " << dir;
493 return -errno;
494 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800495 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000496 PLOG(ERROR) << "Failed to mkdir " << dir;
497 return -errno;
498 }
499 return OK;
500}
501
Jeff Sharkey3472e522017-10-06 18:02:53 -0600502bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
503 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800504 size_t start = 0;
505 while (true) {
506 start = raw.find(qual, start);
507 if (start == std::string::npos) return false;
508 if (start == 0 || raw[start - 1] == ' ') {
509 break;
510 }
511 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600512 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600513 start += qual.length();
514
515 auto end = raw.find("\"", start);
516 if (end == std::string::npos) return false;
517
518 *value = raw.substr(start, end - start);
519 return true;
520}
521
Paul Crowley14c8c072018-09-18 13:30:21 -0700522static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
523 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600524 fsType->clear();
525 fsUuid->clear();
526 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700527
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700528 std::vector<std::string> cmd;
529 cmd.push_back(kBlkidPath);
530 cmd.push_back("-c");
531 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700532 cmd.push_back("-s");
533 cmd.push_back("TYPE");
534 cmd.push_back("-s");
535 cmd.push_back("UUID");
536 cmd.push_back("-s");
537 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700538 cmd.push_back(path);
539
540 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800541 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700542 if (res != OK) {
543 LOG(WARNING) << "blkid failed to identify " << path;
544 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700545 }
546
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700547 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700548 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600549 FindValue(line, "TYPE", fsType);
550 FindValue(line, "UUID", fsUuid);
551 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700552 }
553
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700554 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700555}
556
Paul Crowley14c8c072018-09-18 13:30:21 -0700557status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
558 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700559 return readMetadata(path, fsType, fsUuid, fsLabel, false);
560}
561
Paul Crowley14c8c072018-09-18 13:30:21 -0700562status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
563 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700564 return readMetadata(path, fsType, fsUuid, fsLabel, true);
565}
566
Paul Crowleyde2d6202018-11-30 11:43:47 -0800567static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
568 std::vector<const char*> argv;
569 argv.reserve(args.size() + 1);
570 for (const auto& arg : args) {
571 if (argv.empty()) {
572 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700573 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800574 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700575 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800576 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700577 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800578 argv.emplace_back(nullptr);
579 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700580}
581
Paul Crowleyde2d6202018-11-30 11:43:47 -0800582static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
583 android::base::unique_fd ufd) {
584 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700585 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800586 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700587 return -errno;
588 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800589 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700590 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800591 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700592 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800593 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700594 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800595 return OK;
596}
597
598status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
599 security_context_t context) {
600 auto argv = ConvertToArgv(args);
601
Paul Crowleye6d76632018-11-30 11:43:47 -0800602 android::base::unique_fd pipe_read, pipe_write;
603 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
604 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800605 return -errno;
606 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800607
608 pid_t pid = fork();
609 if (pid == 0) {
610 if (context) {
611 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800612 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800613 abort();
614 }
615 }
616 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800617 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
618 PLOG(ERROR) << "dup2 in ForkExecvp";
619 _exit(EXIT_FAILURE);
620 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800621 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800622 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800623 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800624 _exit(EXIT_FAILURE);
625 }
626 if (pid == -1) {
627 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700628 return -errno;
629 }
630
Paul Crowleyde2d6202018-11-30 11:43:47 -0800631 pipe_write.reset();
632 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
633 if (st != 0) return st;
634
635 int status;
636 if (waitpid(pid, &status, 0) == -1) {
637 PLOG(ERROR) << "waitpid in ForkExecvp";
638 return -errno;
639 }
640 if (!WIFEXITED(status)) {
641 LOG(ERROR) << "Process did not exit normally, status: " << status;
642 return -ECHILD;
643 }
644 if (WEXITSTATUS(status)) {
645 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
646 return WEXITSTATUS(status);
647 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700648 return OK;
649}
650
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700651pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800652 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700653
654 pid_t pid = fork();
655 if (pid == 0) {
656 close(STDIN_FILENO);
657 close(STDOUT_FILENO);
658 close(STDERR_FILENO);
659
Paul Crowleyde2d6202018-11-30 11:43:47 -0800660 execvp(argv[0], const_cast<char**>(argv.data()));
661 PLOG(ERROR) << "exec in ForkExecvpAsync";
662 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700663 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700664 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800665 PLOG(ERROR) << "fork in ForkExecvpAsync";
666 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700667 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700668 return pid;
669}
670
Jeff Sharkey9c484982015-03-31 10:35:33 -0700671status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100672 out.resize(bytes);
673 return ReadRandomBytes(bytes, &out[0]);
674}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700675
Pavel Grafove2e2d302017-08-01 17:15:53 +0100676status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700677 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
678 if (fd == -1) {
679 return -errno;
680 }
681
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800682 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100683 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700684 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100685 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700686 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700687 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700688
689 if (bytes == 0) {
690 return OK;
691 } else {
692 return -EIO;
693 }
694}
695
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600696status_t GenerateRandomUuid(std::string& out) {
697 status_t res = ReadRandomBytes(16, out);
698 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700699 out[6] &= 0x0f; /* clear version */
700 out[6] |= 0x40; /* set to version 4 */
701 out[8] &= 0x3f; /* clear variant */
702 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600703 }
704 return res;
705}
706
Jeff Sharkey9c484982015-03-31 10:35:33 -0700707status_t HexToStr(const std::string& hex, std::string& str) {
708 str.clear();
709 bool even = true;
710 char cur = 0;
711 for (size_t i = 0; i < hex.size(); i++) {
712 int val = 0;
713 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700714 // clang-format off
715 case ' ': case '-': case ':': continue;
716 case 'f': case 'F': val = 15; break;
717 case 'e': case 'E': val = 14; break;
718 case 'd': case 'D': val = 13; break;
719 case 'c': case 'C': val = 12; break;
720 case 'b': case 'B': val = 11; break;
721 case 'a': case 'A': val = 10; break;
722 case '9': val = 9; break;
723 case '8': val = 8; break;
724 case '7': val = 7; break;
725 case '6': val = 6; break;
726 case '5': val = 5; break;
727 case '4': val = 4; break;
728 case '3': val = 3; break;
729 case '2': val = 2; break;
730 case '1': val = 1; break;
731 case '0': val = 0; break;
732 default: return -EINVAL;
733 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700734 }
735
736 if (even) {
737 cur = val << 4;
738 } else {
739 cur += val;
740 str.push_back(cur);
741 cur = 0;
742 }
743 even = !even;
744 }
745 return even ? OK : -EINVAL;
746}
747
748static const char* kLookup = "0123456789abcdef";
749
750status_t StrToHex(const std::string& str, std::string& hex) {
751 hex.clear();
752 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700753 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700754 hex.push_back(kLookup[str[i] & 0x0F]);
755 }
756 return OK;
757}
758
Pavel Grafove2e2d302017-08-01 17:15:53 +0100759status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
760 hex.clear();
761 for (size_t i = 0; i < str.size(); i++) {
762 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
763 hex.push_back(kLookup[str.data()[i] & 0x0F]);
764 }
765 return OK;
766}
767
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700768status_t NormalizeHex(const std::string& in, std::string& out) {
769 std::string tmp;
770 if (HexToStr(in, tmp)) {
771 return -EINVAL;
772 }
773 return StrToHex(tmp, out);
774}
775
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200776status_t GetBlockDevSize(int fd, uint64_t* size) {
777 if (ioctl(fd, BLKGETSIZE64, size)) {
778 return -errno;
779 }
780
781 return OK;
782}
783
784status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
785 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
786 status_t res = OK;
787
788 if (fd < 0) {
789 return -errno;
790 }
791
792 res = GetBlockDevSize(fd, size);
793
794 close(fd);
795
796 return res;
797}
798
799status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
800 uint64_t size;
801 status_t res = GetBlockDevSize(path, &size);
802
803 if (res != OK) {
804 return res;
805 }
806
807 *nr_sec = size / 512;
808
809 return OK;
810}
811
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700812uint64_t GetFreeBytes(const std::string& path) {
813 struct statvfs sb;
814 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700815 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700816 } else {
817 return -1;
818 }
819}
820
821// TODO: borrowed from frameworks/native/libs/diskusage/ which should
822// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700823static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700824 int64_t blksize = s->st_blksize;
825 // count actual blocks used instead of nominal file size
826 int64_t size = s->st_blocks * 512;
827
828 if (blksize) {
829 /* round up to filesystem block size */
830 size = (size + blksize - 1) & (~(blksize - 1));
831 }
832
833 return size;
834}
835
836// TODO: borrowed from frameworks/native/libs/diskusage/ which should
837// eventually be migrated into system/
838int64_t calculate_dir_size(int dfd) {
839 int64_t size = 0;
840 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700841 DIR* d;
842 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700843
844 d = fdopendir(dfd);
845 if (d == NULL) {
846 close(dfd);
847 return 0;
848 }
849
850 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700851 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700852 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
853 size += stat_size(&s);
854 }
855 if (de->d_type == DT_DIR) {
856 int subfd;
857
858 /* always skip "." and ".." */
859 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700860 if (name[1] == 0) continue;
861 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700862 }
863
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600864 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700865 if (subfd >= 0) {
866 size += calculate_dir_size(subfd);
867 }
868 }
869 }
870 closedir(d);
871 return size;
872}
873
874uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600875 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700876 if (dirfd < 0) {
877 PLOG(WARNING) << "Failed to open " << path;
878 return -1;
879 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700880 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700881 }
882}
883
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700884bool IsFilesystemSupported(const std::string& fsType) {
885 std::string supported;
886 if (!ReadFileToString(kProcFilesystems, &supported)) {
887 PLOG(ERROR) << "Failed to read supported filesystems";
888 return false;
889 }
890 return supported.find(fsType + "\n") != std::string::npos;
891}
892
893status_t WipeBlockDevice(const std::string& path) {
894 status_t res = -1;
895 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200896 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700897
898 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
899 if (fd == -1) {
900 PLOG(ERROR) << "Failed to open " << path;
901 goto done;
902 }
903
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200904 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700905 PLOG(ERROR) << "Failed to determine size of " << path;
906 goto done;
907 }
908
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700909 LOG(INFO) << "About to discard " << range[1] << " on " << path;
910 if (ioctl(fd, BLKDISCARD, &range) == 0) {
911 LOG(INFO) << "Discard success on " << path;
912 res = 0;
913 } else {
914 PLOG(ERROR) << "Discard failure on " << path;
915 }
916
917done:
918 close(fd);
919 return res;
920}
921
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800922static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700923 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800924 return false;
925 } else {
926 return true;
927 }
928}
929
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700930std::string BuildKeyPath(const std::string& partGuid) {
931 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
932}
933
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600934std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700935 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600936}
937
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800938std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700939 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700940}
941
942std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700943 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700944}
945
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600946std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700947 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600948}
949
Jeff Sharkey47695b22016-02-01 17:02:29 -0700950std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700951 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700952}
953
954std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700955 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800956}
957
Calin Juravle79f55a42016-02-17 20:14:46 +0000958// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
959std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700960 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000961}
962
Andreas Huber71cd43f2018-01-22 11:25:29 -0800963std::string BuildDataVendorCePath(userid_t userId) {
964 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
965}
966
967std::string BuildDataVendorDePath(userid_t userId) {
968 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
969}
970
Paul Crowley3b71fc52017-10-09 10:55:21 -0700971std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800972 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700973 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800974 return "/data";
975 } else {
976 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700977 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800978 }
979}
980
Paul Crowley3b71fc52017-10-09 10:55:21 -0700981std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700982 // TODO: unify with installd path generation logic
983 std::string data(BuildDataPath(volumeUuid));
984 return StringPrintf("%s/media/%u", data.c_str(), userId);
985}
986
Paul Crowley3b71fc52017-10-09 10:55:21 -0700987std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800988 // TODO: unify with installd path generation logic
989 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700990 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800991 std::string legacy = StringPrintf("%s/data", data.c_str());
992 struct stat sb;
993 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
994 /* /data/data is dir, return /data/data for legacy system */
995 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800996 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800997 }
cjbaoeb501142017-04-12 00:09:00 +0800998 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800999}
1000
Paul Crowley3b71fc52017-10-09 10:55:21 -07001001std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001002 // TODO: unify with installd path generation logic
1003 std::string data(BuildDataPath(volumeUuid));
1004 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1005}
1006
Jeff Sharkey66270a22015-06-24 11:49:24 -07001007dev_t GetDevice(const std::string& path) {
1008 struct stat sb;
1009 if (stat(path.c_str(), &sb)) {
1010 PLOG(WARNING) << "Failed to stat " << path;
1011 return 0;
1012 } else {
1013 return sb.st_dev;
1014 }
1015}
1016
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001017status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001018 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001019
Tom Cherryd6127ef2017-06-15 17:13:56 -07001020 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001021
Tom Cherryd6127ef2017-06-15 17:13:56 -07001022 android::base::SetProperty(kRestoreconString, "");
1023 android::base::SetProperty(kRestoreconString, path);
1024
1025 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001026
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001027 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001028 return OK;
1029}
1030
Jeff Sharkey3472e522017-10-06 18:02:53 -06001031bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1032 // Shamelessly borrowed from android::base::Readlink()
1033 result->clear();
1034
1035 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1036 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1037 // waste memory to just start there. We add 1 so that we can recognize
1038 // whether it actually fit (rather than being truncated to 4095).
1039 std::vector<char> buf(4095 + 1);
1040 while (true) {
1041 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1042 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001043 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001044 // It fit! (If size == buf.size(), it may have been truncated.)
1045 if (static_cast<size_t>(size) < buf.size()) {
1046 result->assign(&buf[0], size);
1047 return true;
1048 }
1049 // Double our buffer and try again.
1050 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001051 }
1052}
1053
Yu Ning942d4e82016-01-08 17:36:47 +08001054bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -07001055 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +08001056}
1057
Sudheer Shanka295fb242019-01-16 23:04:07 -08001058static status_t findMountPointsWithPrefix(const std::string& prefix,
1059 std::list<std::string>& mountPoints) {
1060 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1061 // when the prefix is /foo/bar
1062 std::string prefixWithSlash(prefix);
1063 if (prefix.back() != '/') {
1064 android::base::StringAppendF(&prefixWithSlash, "/");
1065 }
1066
1067 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1068 if (!mnts) {
1069 PLOG(ERROR) << "Unable to open /proc/mounts";
1070 return -errno;
1071 }
1072
1073 // Some volumes can be stacked on each other, so force unmount in
1074 // reverse order to give us the best chance of success.
1075 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1076 while ((mnt = getmntent(mnts.get())) != nullptr) {
1077 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1078 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1079 mountPoints.push_front(mountPoint);
1080 }
1081 }
1082 return OK;
1083}
1084
1085// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1086status_t UnmountTreeWithPrefix(const std::string& prefix) {
1087 std::list<std::string> toUnmount;
1088 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1089 if (result < 0) {
1090 return result;
1091 }
1092 for (const auto& path : toUnmount) {
1093 if (umount2(path.c_str(), MNT_DETACH)) {
1094 PLOG(ERROR) << "Failed to unmount " << path;
1095 result = -errno;
1096 }
1097 }
1098 return result;
1099}
1100
1101status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001102 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1103 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001104 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001105 return -errno;
1106 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001107 return OK;
1108}
1109
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001110static status_t delete_dir_contents(DIR* dir) {
1111 // Shamelessly borrowed from android::installd
1112 int dfd = dirfd(dir);
1113 if (dfd < 0) {
1114 return -errno;
1115 }
1116
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001117 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001118 struct dirent* de;
1119 while ((de = readdir(dir))) {
1120 const char* name = de->d_name;
1121 if (de->d_type == DT_DIR) {
1122 /* always skip "." and ".." */
1123 if (name[0] == '.') {
1124 if (name[1] == 0) continue;
1125 if ((name[1] == '.') && (name[2] == 0)) continue;
1126 }
1127
1128 android::base::unique_fd subfd(
1129 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1130 if (subfd.get() == -1) {
1131 PLOG(ERROR) << "Couldn't openat " << name;
1132 result = -errno;
1133 continue;
1134 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001135 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1136 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001137 if (!subdirp) {
1138 PLOG(ERROR) << "Couldn't fdopendir " << name;
1139 result = -errno;
1140 continue;
1141 }
1142 result = delete_dir_contents(subdirp.get());
1143 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1144 PLOG(ERROR) << "Couldn't unlinkat " << name;
1145 result = -errno;
1146 }
1147 } else {
1148 if (unlinkat(dfd, name, 0) < 0) {
1149 PLOG(ERROR) << "Couldn't unlinkat " << name;
1150 result = -errno;
1151 }
1152 }
1153 }
1154 return result;
1155}
1156
1157status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001158 status_t res = DeleteDirContents(pathname);
1159 if (res < 0) {
1160 return res;
1161 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001162 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001163 PLOG(ERROR) << "rmdir failed on " << pathname;
1164 return -errno;
1165 }
1166 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1167 return OK;
1168}
1169
1170status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001171 // Shamelessly borrowed from android::installd
1172 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1173 if (!dirp) {
1174 if (errno == ENOENT) {
1175 return OK;
1176 }
1177 PLOG(ERROR) << "Failed to opendir " << pathname;
1178 return -errno;
1179 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001180 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001181}
1182
Paul Crowley298fa322018-10-30 15:59:24 -07001183// TODO(118708649): fix duplication with init/util.h
1184status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1185 android::base::Timer t;
1186 while (t.duration() < timeout) {
1187 struct stat sb;
1188 if (stat(filename, &sb) != -1) {
1189 LOG(INFO) << "wait for '" << filename << "' took " << t;
1190 return 0;
1191 }
1192 std::this_thread::sleep_for(10ms);
1193 }
1194 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1195 return -1;
1196}
1197
Paul Crowley621d9b92018-12-07 15:36:09 -08001198bool FsyncDirectory(const std::string& dirname) {
1199 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1200 if (fd == -1) {
1201 PLOG(ERROR) << "Failed to open " << dirname;
1202 return false;
1203 }
1204 if (fsync(fd) == -1) {
1205 if (errno == EROFS || errno == EINVAL) {
1206 PLOG(WARNING) << "Skip fsync " << dirname
1207 << " on a file system does not support synchronization";
1208 } else {
1209 PLOG(ERROR) << "Failed to fsync " << dirname;
1210 return false;
1211 }
1212 }
1213 return true;
1214}
1215
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001216bool writeStringToFile(const std::string& payload, const std::string& filename) {
1217 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1218 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1219 if (fd == -1) {
1220 PLOG(ERROR) << "Failed to open " << filename;
1221 return false;
1222 }
1223 if (!android::base::WriteStringToFd(payload, fd)) {
1224 PLOG(ERROR) << "Failed to write to " << filename;
1225 unlink(filename.c_str());
1226 return false;
1227 }
1228 // fsync as close won't guarantee flush data
1229 // see close(2), fsync(2) and b/68901441
1230 if (fsync(fd) == -1) {
1231 if (errno == EROFS || errno == EINVAL) {
1232 PLOG(WARNING) << "Skip fsync " << filename
1233 << " on a file system does not support synchronization";
1234 } else {
1235 PLOG(ERROR) << "Failed to fsync " << filename;
1236 unlink(filename.c_str());
1237 return false;
1238 }
1239 }
1240 return true;
1241}
1242
Zima438b242019-09-25 14:37:38 +01001243status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1244 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1245 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1246 std::string fuse_path(
1247 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1248
1249 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1250 std::string pass_through_path(
1251 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001252
Zim1242be82020-01-22 18:22:29 +00001253 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1254 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001255 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001256 if (result != android::OK) {
1257 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1258 return -1;
1259 }
1260
Zim06b0caf2020-01-05 02:11:47 +00001261 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1262 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1263 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1264 // These bits should be consistent with what is set in zygote in
1265 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001266 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001267 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001268 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001269 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001270 return -1;
1271 }
1272
Zima438b242019-09-25 14:37:38 +01001273 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1274 if (result != android::OK) {
1275 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1276 return -1;
1277 }
1278
Zim26eec702020-01-31 16:00:58 +00001279 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001280 if (result != android::OK) {
1281 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1282 return -1;
1283 }
1284
Zim26eec702020-01-31 16:00:58 +00001285 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001286 if (result != android::OK) {
1287 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1288 return -1;
1289 }
1290
1291 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001292 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1293 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001294 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001295 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001296 return -1;
1297 }
Zime5393d42019-11-15 11:44:12 +00001298 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001299 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001300
1301 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001302 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001303 if (result != android::OK) {
1304 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1305 return -1;
1306 }
1307 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001308 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001309 }
1310
Nandana Dutta914cc72019-08-29 15:22:42 +01001311 // Open fuse fd.
1312 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1313 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001314 PLOG(ERROR) << "Failed to open /dev/fuse";
1315 return -1;
1316 }
1317
1318 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1319 // permission checks before routing to FUSE daemon.
1320 const auto opts = StringPrintf(
1321 "fd=%i,"
1322 "rootmode=40000,"
1323 "allow_other,"
1324 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001325 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001326
Zima438b242019-09-25 14:37:38 +01001327 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1328 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1329 opts.c_str()));
1330 if (result != 0) {
1331 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001332 return -errno;
1333 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001334
Martijn Coenen86f21a22020-01-06 09:48:14 +01001335 if (IsFilesystemSupported("sdcardfs")) {
1336 std::string sdcardfs_path(
1337 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1338
1339 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1340 return BindMount(sdcardfs_path, pass_through_path);
1341 } else {
1342 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1343 return BindMount(absolute_lower_path, pass_through_path);
1344 }
Zima438b242019-09-25 14:37:38 +01001345}
1346
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001347status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1348 const std::string& relative_upper_path) {
1349 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1350 std::string pass_through_path(
1351 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1352
Zima438b242019-09-25 14:37:38 +01001353 // Best effort unmount pass_through path
1354 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001355 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1356 auto status = ForceUnmount(pass_through_path);
1357 if (status != android::OK) {
1358 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1359 }
Martijn Coenen57002612019-11-28 11:56:13 +01001360 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001361
1362 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001363 android::status_t result = ForceUnmount(fuse_path);
1364 sSleepOnUnmount = true;
1365 if (result != android::OK) {
1366 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1367 // Figure out why we get EBUSY and remove this special casing if possible.
1368 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1369 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1370 errno != ENOENT) {
1371 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1372 return -errno;
1373 }
Martijn Coenen57002612019-11-28 11:56:13 +01001374 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001375 }
Martijn Coenen57002612019-11-28 11:56:13 +01001376 rmdir(fuse_path.c_str());
1377
Zima438b242019-09-25 14:37:38 +01001378 return result;
Zim3623a212019-07-19 16:46:53 +01001379}
1380
Martijn Coenen62a4b272020-01-31 15:23:09 +01001381status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1382 std::string androidDir = volumeRoot + kAndroidDir;
1383 std::string androidDataDir = volumeRoot + kAppDataDir;
1384 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001385 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001386
1387 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1388
Martijn Coenen10570c02020-02-18 10:41:37 +01001389 // mode 0771 + sticky bit for inheriting GIDs
1390 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1391 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001392 PLOG(ERROR) << "Failed to create " << androidDir;
1393 return -errno;
1394 }
1395
1396 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001397 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001398 PLOG(ERROR) << "Failed to create " << androidDataDir;
1399 return -errno;
1400 }
1401
1402 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001403 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001404 PLOG(ERROR) << "Failed to create " << androidObbDir;
1405 return -errno;
1406 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001407 // Some other apps, like installers, have write access to the OBB directory
1408 // to pre-download them. To make sure newly created folders in this directory
1409 // have the right permissions, set a default ACL.
1410 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001411
Martijn Coenen10570c02020-02-18 10:41:37 +01001412 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001413 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1414 return -errno;
1415 }
1416
Martijn Coenen62a4b272020-01-31 15:23:09 +01001417 return OK;
1418}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001419} // namespace vold
1420} // namespace android