blob: 5c58aaf9d946ad7f87dd78eaf8831efd412e2088 [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
Ricky Wai07e64a42020-02-11 14:31:24 +000085static const char* kMediaProviderCtx = "u:r:mediaprovider:";
86static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
87
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060088// Lock used to protect process-level SELinux changes from racing with each
89// other between multiple threads.
90static std::mutex kSecurityLock;
91
Jeff Sharkeydeb24052015-03-02 21:01:40 -080092status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060093 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080094 const char* cpath = path.c_str();
95 status_t res = 0;
96
97 char* secontext = nullptr;
98 if (sehandle) {
99 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
100 setfscreatecon(secontext);
101 }
102 }
103
104 mode_t mode = 0660 | S_IFBLK;
105 if (mknod(cpath, mode, dev) < 0) {
106 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700107 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
108 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800109 res = -errno;
110 }
111 }
112
113 if (secontext) {
114 setfscreatecon(nullptr);
115 freecon(secontext);
116 }
117
118 return res;
119}
120
121status_t DestroyDeviceNode(const std::string& path) {
122 const char* cpath = path.c_str();
123 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
124 return -errno;
125 } else {
126 return OK;
127 }
128}
129
Martijn Coenen442bb832020-02-18 13:44:59 +0100130// Sets a default ACL on the directory.
131int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100132 if (IsFilesystemSupported("sdcardfs")) {
133 // sdcardfs magically takes care of this
134 return OK;
135 }
136
137 static constexpr size_t size =
138 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
139 auto buf = std::make_unique<uint8_t[]>(size);
140
141 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
142 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
143
144 posix_acl_xattr_entry* entry =
145 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
146
147 entry[0].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100148 // The existing mode_t mask has the ACL in the lower 9 bits:
149 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
150 // Use the mode_t masks to get these bits out, and shift them to get the
151 // correct value per entity.
152 //
153 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
154 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100155 entry[0].e_id = uid;
156
157 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100158 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100159 entry[1].e_id = gid;
160
161 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100162 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100163 entry[2].e_id = 0;
164
165 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
166
167 if (ret != 0) {
168 PLOG(ERROR) << "Failed to set default ACL on " << path;
169 }
170
171 return ret;
172}
173
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100174int SetQuotaInherit(const std::string& path) {
175 unsigned long flags;
176
177 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
178 if (fd == -1) {
179 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
180 return -1;
181 }
182
183 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
184 if (ret == -1) {
185 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
186 return ret;
187 }
188
189 flags |= FS_PROJINHERIT_FL;
190
191 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
192 if (ret == -1) {
193 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
194 return ret;
195 }
196
197 return 0;
198}
199
200int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100201 struct fsxattr fsx;
202
203 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
204 if (fd == -1) {
205 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
206 return -1;
207 }
208
209 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
210 if (ret == -1) {
211 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
212 return ret;
213 }
214
215 fsx.fsx_projid = projectId;
216 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
217}
218
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100219int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
220 long projectId) {
221 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
222
223 if (ret != 0) {
224 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100225 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100226
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100227 if (!IsFilesystemSupported("sdcardfs")) {
228 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100229 }
230
231 return ret;
232}
233
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100234int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid) {
235 long projectId;
236 size_t pos;
237 int ret = 0;
238
239 // Make sure the Android/ directories exist and are setup correctly
240 ret = PrepareAndroidDirs(root);
241 if (ret != 0) {
242 LOG(ERROR) << "Failed to prepare Android/ directories.";
243 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100244 }
245
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100246 // Now create the application-specific subdir(s)
247 // path is something like /data/media/0/Android/data/com.foo/files
248 // First, chop off the volume root, eg /data/media/0
249 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100250
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100251 uid_t uid = appUid;
252 gid_t gid = AID_MEDIA_RW;
253 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100254
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100255 // Check that the next part matches one of the allowed Android/ dirs
256 if (StartsWith(pathFromRoot, kAppDataDir)) {
257 appDir = kAppDataDir;
258 if (!IsFilesystemSupported("sdcardfs")) {
259 gid = AID_EXT_DATA_RW;
260 }
261 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
262 appDir = kAppMediaDir;
263 if (!IsFilesystemSupported("sdcardfs")) {
264 gid = AID_MEDIA_RW;
265 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000266 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100267 appDir = kAppObbDir;
268 if (!IsFilesystemSupported("sdcardfs")) {
269 gid = AID_EXT_OBB_RW;
270 }
271 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100272 LOG(ERROR) << "Invalid application directory: " << path;
273 return -EINVAL;
274 }
275
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100276 // mode = 770, plus sticky bit on directory to inherit GID when apps
277 // create subdirs
278 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100279 // the project ID for application-specific directories is directly
280 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100281
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100282 // Chop off the generic application-specific part, eg /Android/data/
283 // this leaves us with something like com.foo/files/
284 std::string leftToCreate = pathFromRoot.substr(appDir.length());
285 if (!EndsWith(leftToCreate, "/")) {
286 leftToCreate += "/";
287 }
288 std::string pathToCreate = root + appDir;
289 int depth = 0;
290 bool withinCache = false;
291 while ((pos = leftToCreate.find('/')) != std::string::npos) {
292 std::string component = leftToCreate.substr(0, pos + 1);
293 leftToCreate = leftToCreate.erase(0, pos + 1);
294 pathToCreate = pathToCreate + component;
295
296 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
297 // All dirs use the "app" project ID, except for the cache dirs in
298 // Android/data, eg Android/data/com.foo/cache
299 // Note that this "sticks" - eg subdirs of this dir need the same
300 // project ID.
301 withinCache = true;
302 }
303 if (withinCache) {
304 projectId = uid - AID_APP_START + AID_CACHE_GID_START;
305 } else {
306 projectId = uid - AID_APP_START + AID_EXT_GID_START;
307 }
308 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
309 if (ret != 0) {
310 return ret;
311 }
312
313 if (depth == 0) {
314 // Set the default ACL on the top-level application-specific directories,
315 // to ensure that even if applications run with a umask of 0077,
316 // new directories within these directories will allow the GID
317 // specified here to write; this is necessary for apps like
318 // installers and MTP, that require access here.
319 //
320 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100321 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100322 if (ret != 0) {
323 return ret;
324 }
325 }
326
327 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100328 }
329
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100330 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100331}
332
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700333status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600334 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700335 const char* cpath = path.c_str();
336
337 char* secontext = nullptr;
338 if (sehandle) {
339 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
340 setfscreatecon(secontext);
341 }
342 }
343
344 int res = fs_prepare_dir(cpath, mode, uid, gid);
345
346 if (secontext) {
347 setfscreatecon(nullptr);
348 freecon(secontext);
349 }
350
351 if (res == 0) {
352 return OK;
353 } else {
354 return -errno;
355 }
356}
357
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800358status_t ForceUnmount(const std::string& path) {
359 const char* cpath = path.c_str();
360 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
361 return OK;
362 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700363 // Apps might still be handling eject request, so wait before
364 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700365 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700366
Jeff Sharkey3472e522017-10-06 18:02:53 -0600367 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700368 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700369 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
370 return OK;
371 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700372
Jeff Sharkey3472e522017-10-06 18:02:53 -0600373 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700374 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800375 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
376 return OK;
377 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700378
Jeff Sharkey3472e522017-10-06 18:02:53 -0600379 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700380 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700381 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
382 return OK;
383 }
Zim3623a212019-07-19 16:46:53 +0100384 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800385 return -errno;
386}
387
Ricky Wai07e64a42020-02-11 14:31:24 +0000388status_t KillProcessesWithMountPrefix(const std::string& path) {
389 if (KillProcessesWithMounts(path, SIGINT) == 0) {
390 return OK;
391 }
392 if (sSleepOnUnmount) sleep(5);
393
394 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
395 return OK;
396 }
397 if (sSleepOnUnmount) sleep(5);
398
399 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
400 return OK;
401 }
402 if (sSleepOnUnmount) sleep(5);
403
404 // Send SIGKILL a second time to determine if we've
405 // actually killed everyone mount
406 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
407 return OK;
408 }
409 PLOG(ERROR) << "Failed to kill processes using " << path;
410 return -EBUSY;
411}
412
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700413status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600414 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700415 return OK;
416 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700417 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700418
Jeff Sharkey3472e522017-10-06 18:02:53 -0600419 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700420 return OK;
421 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700422 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700423
Jeff Sharkey3472e522017-10-06 18:02:53 -0600424 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700425 return OK;
426 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700427 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700428
429 // Send SIGKILL a second time to determine if we've
430 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600431 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700432 return OK;
433 }
434 PLOG(ERROR) << "Failed to kill processes using " << path;
435 return -EBUSY;
436}
437
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700438status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800439 if (UnmountTree(target) < 0) {
440 return -errno;
441 }
442 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700443 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
444 return -errno;
445 }
446 return OK;
447}
448
Sudheer Shanka023b5392019-02-06 12:39:19 -0800449status_t Symlink(const std::string& target, const std::string& linkpath) {
450 if (Unlink(linkpath) < 0) {
451 return -errno;
452 }
453 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
454 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
455 return -errno;
456 }
457 return OK;
458}
459
460status_t Unlink(const std::string& linkpath) {
461 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
462 PLOG(ERROR) << "Failed to unlink " << linkpath;
463 return -errno;
464 }
465 return OK;
466}
467
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000468status_t CreateDir(const std::string& dir, mode_t mode) {
469 struct stat sb;
470 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
471 if (S_ISDIR(sb.st_mode)) {
472 return OK;
473 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
474 PLOG(ERROR) << "Failed to unlink " << dir;
475 return -errno;
476 }
477 } else if (errno != ENOENT) {
478 PLOG(ERROR) << "Failed to stat " << dir;
479 return -errno;
480 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800481 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000482 PLOG(ERROR) << "Failed to mkdir " << dir;
483 return -errno;
484 }
485 return OK;
486}
487
Jeff Sharkey3472e522017-10-06 18:02:53 -0600488bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
489 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800490 size_t start = 0;
491 while (true) {
492 start = raw.find(qual, start);
493 if (start == std::string::npos) return false;
494 if (start == 0 || raw[start - 1] == ' ') {
495 break;
496 }
497 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600498 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600499 start += qual.length();
500
501 auto end = raw.find("\"", start);
502 if (end == std::string::npos) return false;
503
504 *value = raw.substr(start, end - start);
505 return true;
506}
507
Paul Crowley14c8c072018-09-18 13:30:21 -0700508static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
509 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600510 fsType->clear();
511 fsUuid->clear();
512 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700513
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700514 std::vector<std::string> cmd;
515 cmd.push_back(kBlkidPath);
516 cmd.push_back("-c");
517 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700518 cmd.push_back("-s");
519 cmd.push_back("TYPE");
520 cmd.push_back("-s");
521 cmd.push_back("UUID");
522 cmd.push_back("-s");
523 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700524 cmd.push_back(path);
525
526 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800527 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700528 if (res != OK) {
529 LOG(WARNING) << "blkid failed to identify " << path;
530 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700531 }
532
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700533 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700534 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600535 FindValue(line, "TYPE", fsType);
536 FindValue(line, "UUID", fsUuid);
537 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700538 }
539
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700540 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700541}
542
Paul Crowley14c8c072018-09-18 13:30:21 -0700543status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
544 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700545 return readMetadata(path, fsType, fsUuid, fsLabel, false);
546}
547
Paul Crowley14c8c072018-09-18 13:30:21 -0700548status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
549 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700550 return readMetadata(path, fsType, fsUuid, fsLabel, true);
551}
552
Paul Crowleyde2d6202018-11-30 11:43:47 -0800553static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
554 std::vector<const char*> argv;
555 argv.reserve(args.size() + 1);
556 for (const auto& arg : args) {
557 if (argv.empty()) {
558 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700559 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800560 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700561 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800562 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700563 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800564 argv.emplace_back(nullptr);
565 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700566}
567
Paul Crowleyde2d6202018-11-30 11:43:47 -0800568static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
569 android::base::unique_fd ufd) {
570 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700571 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800572 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700573 return -errno;
574 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800575 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700576 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800577 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700578 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800579 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700580 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800581 return OK;
582}
583
584status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
585 security_context_t context) {
586 auto argv = ConvertToArgv(args);
587
Paul Crowleye6d76632018-11-30 11:43:47 -0800588 android::base::unique_fd pipe_read, pipe_write;
589 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
590 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800591 return -errno;
592 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800593
594 pid_t pid = fork();
595 if (pid == 0) {
596 if (context) {
597 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800598 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800599 abort();
600 }
601 }
602 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800603 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
604 PLOG(ERROR) << "dup2 in ForkExecvp";
605 _exit(EXIT_FAILURE);
606 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800607 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800608 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800609 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800610 _exit(EXIT_FAILURE);
611 }
612 if (pid == -1) {
613 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700614 return -errno;
615 }
616
Paul Crowleyde2d6202018-11-30 11:43:47 -0800617 pipe_write.reset();
618 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
619 if (st != 0) return st;
620
621 int status;
622 if (waitpid(pid, &status, 0) == -1) {
623 PLOG(ERROR) << "waitpid in ForkExecvp";
624 return -errno;
625 }
626 if (!WIFEXITED(status)) {
627 LOG(ERROR) << "Process did not exit normally, status: " << status;
628 return -ECHILD;
629 }
630 if (WEXITSTATUS(status)) {
631 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
632 return WEXITSTATUS(status);
633 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700634 return OK;
635}
636
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700637pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800638 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700639
640 pid_t pid = fork();
641 if (pid == 0) {
642 close(STDIN_FILENO);
643 close(STDOUT_FILENO);
644 close(STDERR_FILENO);
645
Paul Crowleyde2d6202018-11-30 11:43:47 -0800646 execvp(argv[0], const_cast<char**>(argv.data()));
647 PLOG(ERROR) << "exec in ForkExecvpAsync";
648 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700649 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700650 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800651 PLOG(ERROR) << "fork in ForkExecvpAsync";
652 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700653 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700654 return pid;
655}
656
Jeff Sharkey9c484982015-03-31 10:35:33 -0700657status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100658 out.resize(bytes);
659 return ReadRandomBytes(bytes, &out[0]);
660}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700661
Pavel Grafove2e2d302017-08-01 17:15:53 +0100662status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700663 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
664 if (fd == -1) {
665 return -errno;
666 }
667
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800668 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100669 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700670 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100671 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700672 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700673 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700674
675 if (bytes == 0) {
676 return OK;
677 } else {
678 return -EIO;
679 }
680}
681
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600682status_t GenerateRandomUuid(std::string& out) {
683 status_t res = ReadRandomBytes(16, out);
684 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700685 out[6] &= 0x0f; /* clear version */
686 out[6] |= 0x40; /* set to version 4 */
687 out[8] &= 0x3f; /* clear variant */
688 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600689 }
690 return res;
691}
692
Jeff Sharkey9c484982015-03-31 10:35:33 -0700693status_t HexToStr(const std::string& hex, std::string& str) {
694 str.clear();
695 bool even = true;
696 char cur = 0;
697 for (size_t i = 0; i < hex.size(); i++) {
698 int val = 0;
699 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700700 // clang-format off
701 case ' ': case '-': case ':': continue;
702 case 'f': case 'F': val = 15; break;
703 case 'e': case 'E': val = 14; break;
704 case 'd': case 'D': val = 13; break;
705 case 'c': case 'C': val = 12; break;
706 case 'b': case 'B': val = 11; break;
707 case 'a': case 'A': val = 10; break;
708 case '9': val = 9; break;
709 case '8': val = 8; break;
710 case '7': val = 7; break;
711 case '6': val = 6; break;
712 case '5': val = 5; break;
713 case '4': val = 4; break;
714 case '3': val = 3; break;
715 case '2': val = 2; break;
716 case '1': val = 1; break;
717 case '0': val = 0; break;
718 default: return -EINVAL;
719 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700720 }
721
722 if (even) {
723 cur = val << 4;
724 } else {
725 cur += val;
726 str.push_back(cur);
727 cur = 0;
728 }
729 even = !even;
730 }
731 return even ? OK : -EINVAL;
732}
733
734static const char* kLookup = "0123456789abcdef";
735
736status_t StrToHex(const std::string& str, std::string& hex) {
737 hex.clear();
738 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700739 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700740 hex.push_back(kLookup[str[i] & 0x0F]);
741 }
742 return OK;
743}
744
Pavel Grafove2e2d302017-08-01 17:15:53 +0100745status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
746 hex.clear();
747 for (size_t i = 0; i < str.size(); i++) {
748 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
749 hex.push_back(kLookup[str.data()[i] & 0x0F]);
750 }
751 return OK;
752}
753
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700754status_t NormalizeHex(const std::string& in, std::string& out) {
755 std::string tmp;
756 if (HexToStr(in, tmp)) {
757 return -EINVAL;
758 }
759 return StrToHex(tmp, out);
760}
761
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200762status_t GetBlockDevSize(int fd, uint64_t* size) {
763 if (ioctl(fd, BLKGETSIZE64, size)) {
764 return -errno;
765 }
766
767 return OK;
768}
769
770status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
771 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
772 status_t res = OK;
773
774 if (fd < 0) {
775 return -errno;
776 }
777
778 res = GetBlockDevSize(fd, size);
779
780 close(fd);
781
782 return res;
783}
784
785status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
786 uint64_t size;
787 status_t res = GetBlockDevSize(path, &size);
788
789 if (res != OK) {
790 return res;
791 }
792
793 *nr_sec = size / 512;
794
795 return OK;
796}
797
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700798uint64_t GetFreeBytes(const std::string& path) {
799 struct statvfs sb;
800 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700801 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700802 } else {
803 return -1;
804 }
805}
806
807// TODO: borrowed from frameworks/native/libs/diskusage/ which should
808// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700809static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700810 int64_t blksize = s->st_blksize;
811 // count actual blocks used instead of nominal file size
812 int64_t size = s->st_blocks * 512;
813
814 if (blksize) {
815 /* round up to filesystem block size */
816 size = (size + blksize - 1) & (~(blksize - 1));
817 }
818
819 return size;
820}
821
822// TODO: borrowed from frameworks/native/libs/diskusage/ which should
823// eventually be migrated into system/
824int64_t calculate_dir_size(int dfd) {
825 int64_t size = 0;
826 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700827 DIR* d;
828 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700829
830 d = fdopendir(dfd);
831 if (d == NULL) {
832 close(dfd);
833 return 0;
834 }
835
836 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700837 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700838 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
839 size += stat_size(&s);
840 }
841 if (de->d_type == DT_DIR) {
842 int subfd;
843
844 /* always skip "." and ".." */
845 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700846 if (name[1] == 0) continue;
847 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700848 }
849
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600850 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700851 if (subfd >= 0) {
852 size += calculate_dir_size(subfd);
853 }
854 }
855 }
856 closedir(d);
857 return size;
858}
859
860uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600861 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700862 if (dirfd < 0) {
863 PLOG(WARNING) << "Failed to open " << path;
864 return -1;
865 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700866 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700867 }
868}
869
Ricky Wai07e64a42020-02-11 14:31:24 +0000870// TODO: Use a better way to determine if it's media provider app.
871bool IsFuseDaemon(const pid_t pid) {
872 auto path = StringPrintf("/proc/%d/mounts", pid);
873 char* tmp;
874 if (lgetfilecon(path.c_str(), &tmp) < 0) {
875 return false;
876 }
877 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
878 || android::base::StartsWith(tmp, kMediaProviderCtx);
879 freecon(tmp);
880 return result;
881}
882
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700883bool IsFilesystemSupported(const std::string& fsType) {
884 std::string supported;
885 if (!ReadFileToString(kProcFilesystems, &supported)) {
886 PLOG(ERROR) << "Failed to read supported filesystems";
887 return false;
888 }
889 return supported.find(fsType + "\n") != std::string::npos;
890}
891
892status_t WipeBlockDevice(const std::string& path) {
893 status_t res = -1;
894 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200895 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700896
897 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
898 if (fd == -1) {
899 PLOG(ERROR) << "Failed to open " << path;
900 goto done;
901 }
902
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200903 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700904 PLOG(ERROR) << "Failed to determine size of " << path;
905 goto done;
906 }
907
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700908 LOG(INFO) << "About to discard " << range[1] << " on " << path;
909 if (ioctl(fd, BLKDISCARD, &range) == 0) {
910 LOG(INFO) << "Discard success on " << path;
911 res = 0;
912 } else {
913 PLOG(ERROR) << "Discard failure on " << path;
914 }
915
916done:
917 close(fd);
918 return res;
919}
920
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800921static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700922 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800923 return false;
924 } else {
925 return true;
926 }
927}
928
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700929std::string BuildKeyPath(const std::string& partGuid) {
930 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
931}
932
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600933std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700934 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600935}
936
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800937std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700938 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700939}
940
941std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700942 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700943}
944
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600945std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700946 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600947}
948
Jeff Sharkey47695b22016-02-01 17:02:29 -0700949std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700950 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700951}
952
953std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700954 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800955}
956
Calin Juravle79f55a42016-02-17 20:14:46 +0000957// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
958std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700959 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000960}
961
Andreas Huber71cd43f2018-01-22 11:25:29 -0800962std::string BuildDataVendorCePath(userid_t userId) {
963 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
964}
965
966std::string BuildDataVendorDePath(userid_t userId) {
967 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
968}
969
Paul Crowley3b71fc52017-10-09 10:55:21 -0700970std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800971 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700972 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800973 return "/data";
974 } else {
975 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700976 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800977 }
978}
979
Paul Crowley3b71fc52017-10-09 10:55:21 -0700980std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700981 // TODO: unify with installd path generation logic
982 std::string data(BuildDataPath(volumeUuid));
983 return StringPrintf("%s/media/%u", data.c_str(), userId);
984}
985
Paul Crowley3b71fc52017-10-09 10:55:21 -0700986std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800987 // TODO: unify with installd path generation logic
988 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700989 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800990 std::string legacy = StringPrintf("%s/data", data.c_str());
991 struct stat sb;
992 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
993 /* /data/data is dir, return /data/data for legacy system */
994 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800995 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800996 }
cjbaoeb501142017-04-12 00:09:00 +0800997 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800998}
999
Paul Crowley3b71fc52017-10-09 10:55:21 -07001000std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001001 // TODO: unify with installd path generation logic
1002 std::string data(BuildDataPath(volumeUuid));
1003 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1004}
1005
Jeff Sharkey66270a22015-06-24 11:49:24 -07001006dev_t GetDevice(const std::string& path) {
1007 struct stat sb;
1008 if (stat(path.c_str(), &sb)) {
1009 PLOG(WARNING) << "Failed to stat " << path;
1010 return 0;
1011 } else {
1012 return sb.st_dev;
1013 }
1014}
1015
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001016status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001017 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001018
Tom Cherryd6127ef2017-06-15 17:13:56 -07001019 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001020
Tom Cherryd6127ef2017-06-15 17:13:56 -07001021 android::base::SetProperty(kRestoreconString, "");
1022 android::base::SetProperty(kRestoreconString, path);
1023
1024 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001025
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001026 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001027 return OK;
1028}
1029
Jeff Sharkey3472e522017-10-06 18:02:53 -06001030bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1031 // Shamelessly borrowed from android::base::Readlink()
1032 result->clear();
1033
1034 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1035 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1036 // waste memory to just start there. We add 1 so that we can recognize
1037 // whether it actually fit (rather than being truncated to 4095).
1038 std::vector<char> buf(4095 + 1);
1039 while (true) {
1040 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1041 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001042 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001043 // It fit! (If size == buf.size(), it may have been truncated.)
1044 if (static_cast<size_t>(size) < buf.size()) {
1045 result->assign(&buf[0], size);
1046 return true;
1047 }
1048 // Double our buffer and try again.
1049 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001050 }
1051}
1052
Yu Ning942d4e82016-01-08 17:36:47 +08001053bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -07001054 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +08001055}
1056
Sudheer Shanka295fb242019-01-16 23:04:07 -08001057static status_t findMountPointsWithPrefix(const std::string& prefix,
1058 std::list<std::string>& mountPoints) {
1059 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1060 // when the prefix is /foo/bar
1061 std::string prefixWithSlash(prefix);
1062 if (prefix.back() != '/') {
1063 android::base::StringAppendF(&prefixWithSlash, "/");
1064 }
1065
1066 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1067 if (!mnts) {
1068 PLOG(ERROR) << "Unable to open /proc/mounts";
1069 return -errno;
1070 }
1071
1072 // Some volumes can be stacked on each other, so force unmount in
1073 // reverse order to give us the best chance of success.
1074 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1075 while ((mnt = getmntent(mnts.get())) != nullptr) {
1076 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1077 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1078 mountPoints.push_front(mountPoint);
1079 }
1080 }
1081 return OK;
1082}
1083
1084// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1085status_t UnmountTreeWithPrefix(const std::string& prefix) {
1086 std::list<std::string> toUnmount;
1087 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1088 if (result < 0) {
1089 return result;
1090 }
1091 for (const auto& path : toUnmount) {
1092 if (umount2(path.c_str(), MNT_DETACH)) {
1093 PLOG(ERROR) << "Failed to unmount " << path;
1094 result = -errno;
1095 }
1096 }
1097 return result;
1098}
1099
1100status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001101 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1102 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001103 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001104 return -errno;
1105 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001106 return OK;
1107}
1108
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001109static status_t delete_dir_contents(DIR* dir) {
1110 // Shamelessly borrowed from android::installd
1111 int dfd = dirfd(dir);
1112 if (dfd < 0) {
1113 return -errno;
1114 }
1115
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001116 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001117 struct dirent* de;
1118 while ((de = readdir(dir))) {
1119 const char* name = de->d_name;
1120 if (de->d_type == DT_DIR) {
1121 /* always skip "." and ".." */
1122 if (name[0] == '.') {
1123 if (name[1] == 0) continue;
1124 if ((name[1] == '.') && (name[2] == 0)) continue;
1125 }
1126
1127 android::base::unique_fd subfd(
1128 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1129 if (subfd.get() == -1) {
1130 PLOG(ERROR) << "Couldn't openat " << name;
1131 result = -errno;
1132 continue;
1133 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001134 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1135 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001136 if (!subdirp) {
1137 PLOG(ERROR) << "Couldn't fdopendir " << name;
1138 result = -errno;
1139 continue;
1140 }
1141 result = delete_dir_contents(subdirp.get());
1142 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1143 PLOG(ERROR) << "Couldn't unlinkat " << name;
1144 result = -errno;
1145 }
1146 } else {
1147 if (unlinkat(dfd, name, 0) < 0) {
1148 PLOG(ERROR) << "Couldn't unlinkat " << name;
1149 result = -errno;
1150 }
1151 }
1152 }
1153 return result;
1154}
1155
1156status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001157 status_t res = DeleteDirContents(pathname);
1158 if (res < 0) {
1159 return res;
1160 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001161 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001162 PLOG(ERROR) << "rmdir failed on " << pathname;
1163 return -errno;
1164 }
1165 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1166 return OK;
1167}
1168
1169status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001170 // Shamelessly borrowed from android::installd
1171 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1172 if (!dirp) {
1173 if (errno == ENOENT) {
1174 return OK;
1175 }
1176 PLOG(ERROR) << "Failed to opendir " << pathname;
1177 return -errno;
1178 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001179 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001180}
1181
Paul Crowley298fa322018-10-30 15:59:24 -07001182// TODO(118708649): fix duplication with init/util.h
1183status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1184 android::base::Timer t;
1185 while (t.duration() < timeout) {
1186 struct stat sb;
1187 if (stat(filename, &sb) != -1) {
1188 LOG(INFO) << "wait for '" << filename << "' took " << t;
1189 return 0;
1190 }
1191 std::this_thread::sleep_for(10ms);
1192 }
1193 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1194 return -1;
1195}
1196
Paul Crowley621d9b92018-12-07 15:36:09 -08001197bool FsyncDirectory(const std::string& dirname) {
1198 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1199 if (fd == -1) {
1200 PLOG(ERROR) << "Failed to open " << dirname;
1201 return false;
1202 }
1203 if (fsync(fd) == -1) {
1204 if (errno == EROFS || errno == EINVAL) {
1205 PLOG(WARNING) << "Skip fsync " << dirname
1206 << " on a file system does not support synchronization";
1207 } else {
1208 PLOG(ERROR) << "Failed to fsync " << dirname;
1209 return false;
1210 }
1211 }
1212 return true;
1213}
1214
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001215bool writeStringToFile(const std::string& payload, const std::string& filename) {
1216 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1217 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1218 if (fd == -1) {
1219 PLOG(ERROR) << "Failed to open " << filename;
1220 return false;
1221 }
1222 if (!android::base::WriteStringToFd(payload, fd)) {
1223 PLOG(ERROR) << "Failed to write to " << filename;
1224 unlink(filename.c_str());
1225 return false;
1226 }
1227 // fsync as close won't guarantee flush data
1228 // see close(2), fsync(2) and b/68901441
1229 if (fsync(fd) == -1) {
1230 if (errno == EROFS || errno == EINVAL) {
1231 PLOG(WARNING) << "Skip fsync " << filename
1232 << " on a file system does not support synchronization";
1233 } else {
1234 PLOG(ERROR) << "Failed to fsync " << filename;
1235 unlink(filename.c_str());
1236 return false;
1237 }
1238 }
1239 return true;
1240}
1241
Ricky Wai07e64a42020-02-11 14:31:24 +00001242status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1243 if (access(path.c_str(), F_OK) != 0) {
1244 PLOG(WARNING) << "Dir does not exist: " << path;
1245 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1246 return -errno;
1247 }
1248 }
1249 return OK;
1250}
1251
Zima438b242019-09-25 14:37:38 +01001252status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1253 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1254 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1255 std::string fuse_path(
1256 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1257
1258 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1259 std::string pass_through_path(
1260 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001261
Zim1242be82020-01-22 18:22:29 +00001262 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1263 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001264 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001265 if (result != android::OK) {
1266 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1267 return -1;
1268 }
1269
Zim06b0caf2020-01-05 02:11:47 +00001270 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1271 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1272 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1273 // These bits should be consistent with what is set in zygote in
1274 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001275 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001276 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001277 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001278 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001279 return -1;
1280 }
1281
Zima438b242019-09-25 14:37:38 +01001282 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1283 if (result != android::OK) {
1284 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1285 return -1;
1286 }
1287
Zim26eec702020-01-31 16:00:58 +00001288 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001289 if (result != android::OK) {
1290 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1291 return -1;
1292 }
1293
Zim26eec702020-01-31 16:00:58 +00001294 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001295 if (result != android::OK) {
1296 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1297 return -1;
1298 }
1299
1300 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001301 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1302 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001303 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001304 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001305 return -1;
1306 }
Zime5393d42019-11-15 11:44:12 +00001307 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001308 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001309
1310 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001311 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001312 if (result != android::OK) {
1313 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1314 return -1;
1315 }
1316 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001317 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001318 }
1319
Nandana Dutta914cc72019-08-29 15:22:42 +01001320 // Open fuse fd.
1321 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1322 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001323 PLOG(ERROR) << "Failed to open /dev/fuse";
1324 return -1;
1325 }
1326
1327 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1328 // permission checks before routing to FUSE daemon.
1329 const auto opts = StringPrintf(
1330 "fd=%i,"
1331 "rootmode=40000,"
1332 "allow_other,"
1333 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001334 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001335
Zima438b242019-09-25 14:37:38 +01001336 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1337 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1338 opts.c_str()));
1339 if (result != 0) {
1340 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001341 return -errno;
1342 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001343
Martijn Coenen86f21a22020-01-06 09:48:14 +01001344 if (IsFilesystemSupported("sdcardfs")) {
1345 std::string sdcardfs_path(
1346 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1347
1348 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1349 return BindMount(sdcardfs_path, pass_through_path);
1350 } else {
1351 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1352 return BindMount(absolute_lower_path, pass_through_path);
1353 }
Zima438b242019-09-25 14:37:38 +01001354}
1355
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001356status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1357 const std::string& relative_upper_path) {
1358 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1359 std::string pass_through_path(
1360 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1361
Zima438b242019-09-25 14:37:38 +01001362 // Best effort unmount pass_through path
1363 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001364 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1365 auto status = ForceUnmount(pass_through_path);
1366 if (status != android::OK) {
1367 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1368 }
Martijn Coenen57002612019-11-28 11:56:13 +01001369 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001370
1371 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001372 android::status_t result = ForceUnmount(fuse_path);
1373 sSleepOnUnmount = true;
1374 if (result != android::OK) {
1375 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1376 // Figure out why we get EBUSY and remove this special casing if possible.
1377 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1378 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1379 errno != ENOENT) {
1380 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1381 return -errno;
1382 }
Martijn Coenen57002612019-11-28 11:56:13 +01001383 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001384 }
Martijn Coenen57002612019-11-28 11:56:13 +01001385 rmdir(fuse_path.c_str());
1386
Zima438b242019-09-25 14:37:38 +01001387 return result;
Zim3623a212019-07-19 16:46:53 +01001388}
1389
Martijn Coenen62a4b272020-01-31 15:23:09 +01001390status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1391 std::string androidDir = volumeRoot + kAndroidDir;
1392 std::string androidDataDir = volumeRoot + kAppDataDir;
1393 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001394 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001395
1396 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1397
Martijn Coenen10570c02020-02-18 10:41:37 +01001398 // mode 0771 + sticky bit for inheriting GIDs
1399 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1400 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001401 PLOG(ERROR) << "Failed to create " << androidDir;
1402 return -errno;
1403 }
1404
1405 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001406 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001407 PLOG(ERROR) << "Failed to create " << androidDataDir;
1408 return -errno;
1409 }
1410
1411 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001412 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001413 PLOG(ERROR) << "Failed to create " << androidObbDir;
1414 return -errno;
1415 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001416 // Some other apps, like installers, have write access to the OBB directory
1417 // to pre-download them. To make sure newly created folders in this directory
1418 // have the right permissions, set a default ACL.
1419 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001420
Martijn Coenen10570c02020-02-18 10:41:37 +01001421 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001422 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1423 return -errno;
1424 }
1425
Martijn Coenen62a4b272020-01-31 15:23:09 +01001426 return OK;
1427}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001428} // namespace vold
1429} // namespace android