blob: ef9dba686efbe2064ad1299dc50451fad0355d1a [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
Ricky Wai07e64a42020-02-11 14:31:24 +000086static const char* kMediaProviderCtx = "u:r:mediaprovider:";
87static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
88
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060089// Lock used to protect process-level SELinux changes from racing with each
90// other between multiple threads.
91static std::mutex kSecurityLock;
92
Jeff Sharkeydeb24052015-03-02 21:01:40 -080093status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060094 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080095 const char* cpath = path.c_str();
96 status_t res = 0;
97
98 char* secontext = nullptr;
99 if (sehandle) {
100 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
101 setfscreatecon(secontext);
102 }
103 }
104
105 mode_t mode = 0660 | S_IFBLK;
106 if (mknod(cpath, mode, dev) < 0) {
107 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700108 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
109 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800110 res = -errno;
111 }
112 }
113
114 if (secontext) {
115 setfscreatecon(nullptr);
116 freecon(secontext);
117 }
118
119 return res;
120}
121
122status_t DestroyDeviceNode(const std::string& path) {
123 const char* cpath = path.c_str();
124 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
125 return -errno;
126 } else {
127 return OK;
128 }
129}
130
Martijn Coenen442bb832020-02-18 13:44:59 +0100131// Sets a default ACL on the directory.
132int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100133 if (IsFilesystemSupported("sdcardfs")) {
134 // sdcardfs magically takes care of this
135 return OK;
136 }
137
138 static constexpr size_t size =
139 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
140 auto buf = std::make_unique<uint8_t[]>(size);
141
142 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
143 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
144
145 posix_acl_xattr_entry* entry =
146 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
147
148 entry[0].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100149 // The existing mode_t mask has the ACL in the lower 9 bits:
150 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
151 // Use the mode_t masks to get these bits out, and shift them to get the
152 // correct value per entity.
153 //
154 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
155 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100156 entry[0].e_id = uid;
157
158 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100159 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100160 entry[1].e_id = gid;
161
162 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100163 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100164 entry[2].e_id = 0;
165
166 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
167
168 if (ret != 0) {
169 PLOG(ERROR) << "Failed to set default ACL on " << path;
170 }
171
172 return ret;
173}
174
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100175int SetQuotaInherit(const std::string& path) {
176 unsigned long flags;
177
178 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
179 if (fd == -1) {
180 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
181 return -1;
182 }
183
184 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
185 if (ret == -1) {
186 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
187 return ret;
188 }
189
190 flags |= FS_PROJINHERIT_FL;
191
192 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
193 if (ret == -1) {
194 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
195 return ret;
196 }
197
198 return 0;
199}
200
201int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100202 struct fsxattr fsx;
203
204 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
205 if (fd == -1) {
206 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
207 return -1;
208 }
209
210 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
211 if (ret == -1) {
212 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
213 return ret;
214 }
215
216 fsx.fsx_projid = projectId;
217 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
218}
219
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100220int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
221 long projectId) {
222 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
223
224 if (ret != 0) {
225 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100226 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100227
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100228 if (!IsFilesystemSupported("sdcardfs")) {
229 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100230 }
231
232 return ret;
233}
234
Martijn Coenen816f4d92020-02-18 15:06:37 +0100235static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
236 namespace fs = std::filesystem;
237
238 // Setup the directory itself correctly
239 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
240 if (ret != OK) {
241 return ret;
242 }
243
244 // Fixup all of its file entries
245 for (const auto& itEntry : fs::directory_iterator(path)) {
246 ret = lchown(itEntry.path().c_str(), uid, gid);
247 if (ret != 0) {
248 return ret;
249 }
250
251 ret = chmod(itEntry.path().c_str(), mode);
252 if (ret != 0) {
253 return ret;
254 }
255
256 if (!IsFilesystemSupported("sdcardfs")) {
257 ret = SetQuotaProjectId(itEntry.path(), projectId);
258 if (ret != 0) {
259 return ret;
260 }
261 }
262 }
263
264 return OK;
265}
266
267int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
268 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100269 long projectId;
270 size_t pos;
271 int ret = 0;
272
273 // Make sure the Android/ directories exist and are setup correctly
274 ret = PrepareAndroidDirs(root);
275 if (ret != 0) {
276 LOG(ERROR) << "Failed to prepare Android/ directories.";
277 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100278 }
279
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100280 // Now create the application-specific subdir(s)
281 // path is something like /data/media/0/Android/data/com.foo/files
282 // First, chop off the volume root, eg /data/media/0
283 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100284
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100285 uid_t uid = appUid;
286 gid_t gid = AID_MEDIA_RW;
287 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100288
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100289 // Check that the next part matches one of the allowed Android/ dirs
290 if (StartsWith(pathFromRoot, kAppDataDir)) {
291 appDir = kAppDataDir;
292 if (!IsFilesystemSupported("sdcardfs")) {
293 gid = AID_EXT_DATA_RW;
294 }
295 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
296 appDir = kAppMediaDir;
297 if (!IsFilesystemSupported("sdcardfs")) {
298 gid = AID_MEDIA_RW;
299 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000300 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100301 appDir = kAppObbDir;
302 if (!IsFilesystemSupported("sdcardfs")) {
303 gid = AID_EXT_OBB_RW;
304 }
305 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100306 LOG(ERROR) << "Invalid application directory: " << path;
307 return -EINVAL;
308 }
309
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100310 // mode = 770, plus sticky bit on directory to inherit GID when apps
311 // create subdirs
312 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100313 // the project ID for application-specific directories is directly
314 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100315
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100316 // Chop off the generic application-specific part, eg /Android/data/
317 // this leaves us with something like com.foo/files/
318 std::string leftToCreate = pathFromRoot.substr(appDir.length());
319 if (!EndsWith(leftToCreate, "/")) {
320 leftToCreate += "/";
321 }
322 std::string pathToCreate = root + appDir;
323 int depth = 0;
324 bool withinCache = false;
325 while ((pos = leftToCreate.find('/')) != std::string::npos) {
326 std::string component = leftToCreate.substr(0, pos + 1);
327 leftToCreate = leftToCreate.erase(0, pos + 1);
328 pathToCreate = pathToCreate + component;
329
330 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
331 // All dirs use the "app" project ID, except for the cache dirs in
332 // Android/data, eg Android/data/com.foo/cache
333 // Note that this "sticks" - eg subdirs of this dir need the same
334 // project ID.
335 withinCache = true;
336 }
337 if (withinCache) {
338 projectId = uid - AID_APP_START + AID_CACHE_GID_START;
339 } else {
340 projectId = uid - AID_APP_START + AID_EXT_GID_START;
341 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100342
343 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
344 // Fixup all files in this existing directory with the correct UID/GID
345 // and project ID.
346 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
347 } else {
348 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
349 }
350
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100351 if (ret != 0) {
352 return ret;
353 }
354
355 if (depth == 0) {
356 // Set the default ACL on the top-level application-specific directories,
357 // to ensure that even if applications run with a umask of 0077,
358 // new directories within these directories will allow the GID
359 // specified here to write; this is necessary for apps like
360 // installers and MTP, that require access here.
361 //
362 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100363 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100364 if (ret != 0) {
365 return ret;
366 }
367 }
368
369 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100370 }
371
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100372 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100373}
374
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700375status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600376 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700377 const char* cpath = path.c_str();
378
379 char* secontext = nullptr;
380 if (sehandle) {
381 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
382 setfscreatecon(secontext);
383 }
384 }
385
386 int res = fs_prepare_dir(cpath, mode, uid, gid);
387
388 if (secontext) {
389 setfscreatecon(nullptr);
390 freecon(secontext);
391 }
392
393 if (res == 0) {
394 return OK;
395 } else {
396 return -errno;
397 }
398}
399
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800400status_t ForceUnmount(const std::string& path) {
401 const char* cpath = path.c_str();
402 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
403 return OK;
404 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700405 // Apps might still be handling eject request, so wait before
406 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700407 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700408
Jeff Sharkey3472e522017-10-06 18:02:53 -0600409 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700410 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700411 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
412 return OK;
413 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700414
Jeff Sharkey3472e522017-10-06 18:02:53 -0600415 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700416 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800417 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
418 return OK;
419 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700420
Jeff Sharkey3472e522017-10-06 18:02:53 -0600421 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700422 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700423 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
424 return OK;
425 }
Zim3623a212019-07-19 16:46:53 +0100426 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800427 return -errno;
428}
429
Ricky Wai07e64a42020-02-11 14:31:24 +0000430status_t KillProcessesWithMountPrefix(const std::string& path) {
431 if (KillProcessesWithMounts(path, SIGINT) == 0) {
432 return OK;
433 }
434 if (sSleepOnUnmount) sleep(5);
435
436 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
437 return OK;
438 }
439 if (sSleepOnUnmount) sleep(5);
440
441 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
442 return OK;
443 }
444 if (sSleepOnUnmount) sleep(5);
445
446 // Send SIGKILL a second time to determine if we've
447 // actually killed everyone mount
448 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
449 return OK;
450 }
451 PLOG(ERROR) << "Failed to kill processes using " << path;
452 return -EBUSY;
453}
454
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700455status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600456 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700457 return OK;
458 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700459 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700460
Jeff Sharkey3472e522017-10-06 18:02:53 -0600461 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700462 return OK;
463 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700464 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700465
Jeff Sharkey3472e522017-10-06 18:02:53 -0600466 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700467 return OK;
468 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700469 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700470
471 // Send SIGKILL a second time to determine if we've
472 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600473 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700474 return OK;
475 }
476 PLOG(ERROR) << "Failed to kill processes using " << path;
477 return -EBUSY;
478}
479
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700480status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800481 if (UnmountTree(target) < 0) {
482 return -errno;
483 }
484 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700485 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
486 return -errno;
487 }
488 return OK;
489}
490
Sudheer Shanka023b5392019-02-06 12:39:19 -0800491status_t Symlink(const std::string& target, const std::string& linkpath) {
492 if (Unlink(linkpath) < 0) {
493 return -errno;
494 }
495 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
496 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
497 return -errno;
498 }
499 return OK;
500}
501
502status_t Unlink(const std::string& linkpath) {
503 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
504 PLOG(ERROR) << "Failed to unlink " << linkpath;
505 return -errno;
506 }
507 return OK;
508}
509
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000510status_t CreateDir(const std::string& dir, mode_t mode) {
511 struct stat sb;
512 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
513 if (S_ISDIR(sb.st_mode)) {
514 return OK;
515 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
516 PLOG(ERROR) << "Failed to unlink " << dir;
517 return -errno;
518 }
519 } else if (errno != ENOENT) {
520 PLOG(ERROR) << "Failed to stat " << dir;
521 return -errno;
522 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800523 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000524 PLOG(ERROR) << "Failed to mkdir " << dir;
525 return -errno;
526 }
527 return OK;
528}
529
Jeff Sharkey3472e522017-10-06 18:02:53 -0600530bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
531 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800532 size_t start = 0;
533 while (true) {
534 start = raw.find(qual, start);
535 if (start == std::string::npos) return false;
536 if (start == 0 || raw[start - 1] == ' ') {
537 break;
538 }
539 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600540 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600541 start += qual.length();
542
543 auto end = raw.find("\"", start);
544 if (end == std::string::npos) return false;
545
546 *value = raw.substr(start, end - start);
547 return true;
548}
549
Paul Crowley14c8c072018-09-18 13:30:21 -0700550static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
551 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600552 fsType->clear();
553 fsUuid->clear();
554 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700555
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700556 std::vector<std::string> cmd;
557 cmd.push_back(kBlkidPath);
558 cmd.push_back("-c");
559 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700560 cmd.push_back("-s");
561 cmd.push_back("TYPE");
562 cmd.push_back("-s");
563 cmd.push_back("UUID");
564 cmd.push_back("-s");
565 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700566 cmd.push_back(path);
567
568 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800569 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700570 if (res != OK) {
571 LOG(WARNING) << "blkid failed to identify " << path;
572 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700573 }
574
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700575 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700576 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600577 FindValue(line, "TYPE", fsType);
578 FindValue(line, "UUID", fsUuid);
579 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700580 }
581
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700582 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700583}
584
Paul Crowley14c8c072018-09-18 13:30:21 -0700585status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
586 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700587 return readMetadata(path, fsType, fsUuid, fsLabel, false);
588}
589
Paul Crowley14c8c072018-09-18 13:30:21 -0700590status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
591 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700592 return readMetadata(path, fsType, fsUuid, fsLabel, true);
593}
594
Paul Crowleyde2d6202018-11-30 11:43:47 -0800595static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
596 std::vector<const char*> argv;
597 argv.reserve(args.size() + 1);
598 for (const auto& arg : args) {
599 if (argv.empty()) {
600 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700601 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800602 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700603 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800604 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700605 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800606 argv.emplace_back(nullptr);
607 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700608}
609
Paul Crowleyde2d6202018-11-30 11:43:47 -0800610static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
611 android::base::unique_fd ufd) {
612 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700613 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800614 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700615 return -errno;
616 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800617 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700618 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800619 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700620 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800621 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700622 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800623 return OK;
624}
625
626status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
627 security_context_t context) {
628 auto argv = ConvertToArgv(args);
629
Paul Crowleye6d76632018-11-30 11:43:47 -0800630 android::base::unique_fd pipe_read, pipe_write;
631 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
632 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800633 return -errno;
634 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800635
636 pid_t pid = fork();
637 if (pid == 0) {
638 if (context) {
639 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800640 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800641 abort();
642 }
643 }
644 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800645 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
646 PLOG(ERROR) << "dup2 in ForkExecvp";
647 _exit(EXIT_FAILURE);
648 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800649 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800650 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800651 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800652 _exit(EXIT_FAILURE);
653 }
654 if (pid == -1) {
655 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700656 return -errno;
657 }
658
Paul Crowleyde2d6202018-11-30 11:43:47 -0800659 pipe_write.reset();
660 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
661 if (st != 0) return st;
662
663 int status;
664 if (waitpid(pid, &status, 0) == -1) {
665 PLOG(ERROR) << "waitpid in ForkExecvp";
666 return -errno;
667 }
668 if (!WIFEXITED(status)) {
669 LOG(ERROR) << "Process did not exit normally, status: " << status;
670 return -ECHILD;
671 }
672 if (WEXITSTATUS(status)) {
673 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
674 return WEXITSTATUS(status);
675 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700676 return OK;
677}
678
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700679pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800680 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700681
682 pid_t pid = fork();
683 if (pid == 0) {
684 close(STDIN_FILENO);
685 close(STDOUT_FILENO);
686 close(STDERR_FILENO);
687
Paul Crowleyde2d6202018-11-30 11:43:47 -0800688 execvp(argv[0], const_cast<char**>(argv.data()));
689 PLOG(ERROR) << "exec in ForkExecvpAsync";
690 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700691 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700692 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800693 PLOG(ERROR) << "fork in ForkExecvpAsync";
694 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700695 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700696 return pid;
697}
698
Jeff Sharkey9c484982015-03-31 10:35:33 -0700699status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100700 out.resize(bytes);
701 return ReadRandomBytes(bytes, &out[0]);
702}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700703
Pavel Grafove2e2d302017-08-01 17:15:53 +0100704status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700705 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
706 if (fd == -1) {
707 return -errno;
708 }
709
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800710 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100711 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700712 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100713 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700714 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700715 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700716
717 if (bytes == 0) {
718 return OK;
719 } else {
720 return -EIO;
721 }
722}
723
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600724status_t GenerateRandomUuid(std::string& out) {
725 status_t res = ReadRandomBytes(16, out);
726 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700727 out[6] &= 0x0f; /* clear version */
728 out[6] |= 0x40; /* set to version 4 */
729 out[8] &= 0x3f; /* clear variant */
730 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600731 }
732 return res;
733}
734
Jeff Sharkey9c484982015-03-31 10:35:33 -0700735status_t HexToStr(const std::string& hex, std::string& str) {
736 str.clear();
737 bool even = true;
738 char cur = 0;
739 for (size_t i = 0; i < hex.size(); i++) {
740 int val = 0;
741 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700742 // clang-format off
743 case ' ': case '-': case ':': continue;
744 case 'f': case 'F': val = 15; break;
745 case 'e': case 'E': val = 14; break;
746 case 'd': case 'D': val = 13; break;
747 case 'c': case 'C': val = 12; break;
748 case 'b': case 'B': val = 11; break;
749 case 'a': case 'A': val = 10; break;
750 case '9': val = 9; break;
751 case '8': val = 8; break;
752 case '7': val = 7; break;
753 case '6': val = 6; break;
754 case '5': val = 5; break;
755 case '4': val = 4; break;
756 case '3': val = 3; break;
757 case '2': val = 2; break;
758 case '1': val = 1; break;
759 case '0': val = 0; break;
760 default: return -EINVAL;
761 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700762 }
763
764 if (even) {
765 cur = val << 4;
766 } else {
767 cur += val;
768 str.push_back(cur);
769 cur = 0;
770 }
771 even = !even;
772 }
773 return even ? OK : -EINVAL;
774}
775
776static const char* kLookup = "0123456789abcdef";
777
778status_t StrToHex(const std::string& str, std::string& hex) {
779 hex.clear();
780 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700781 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700782 hex.push_back(kLookup[str[i] & 0x0F]);
783 }
784 return OK;
785}
786
Pavel Grafove2e2d302017-08-01 17:15:53 +0100787status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
788 hex.clear();
789 for (size_t i = 0; i < str.size(); i++) {
790 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
791 hex.push_back(kLookup[str.data()[i] & 0x0F]);
792 }
793 return OK;
794}
795
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700796status_t NormalizeHex(const std::string& in, std::string& out) {
797 std::string tmp;
798 if (HexToStr(in, tmp)) {
799 return -EINVAL;
800 }
801 return StrToHex(tmp, out);
802}
803
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200804status_t GetBlockDevSize(int fd, uint64_t* size) {
805 if (ioctl(fd, BLKGETSIZE64, size)) {
806 return -errno;
807 }
808
809 return OK;
810}
811
812status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
813 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
814 status_t res = OK;
815
816 if (fd < 0) {
817 return -errno;
818 }
819
820 res = GetBlockDevSize(fd, size);
821
822 close(fd);
823
824 return res;
825}
826
827status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
828 uint64_t size;
829 status_t res = GetBlockDevSize(path, &size);
830
831 if (res != OK) {
832 return res;
833 }
834
835 *nr_sec = size / 512;
836
837 return OK;
838}
839
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700840uint64_t GetFreeBytes(const std::string& path) {
841 struct statvfs sb;
842 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700843 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700844 } else {
845 return -1;
846 }
847}
848
849// TODO: borrowed from frameworks/native/libs/diskusage/ which should
850// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700851static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700852 int64_t blksize = s->st_blksize;
853 // count actual blocks used instead of nominal file size
854 int64_t size = s->st_blocks * 512;
855
856 if (blksize) {
857 /* round up to filesystem block size */
858 size = (size + blksize - 1) & (~(blksize - 1));
859 }
860
861 return size;
862}
863
864// TODO: borrowed from frameworks/native/libs/diskusage/ which should
865// eventually be migrated into system/
866int64_t calculate_dir_size(int dfd) {
867 int64_t size = 0;
868 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700869 DIR* d;
870 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700871
872 d = fdopendir(dfd);
873 if (d == NULL) {
874 close(dfd);
875 return 0;
876 }
877
878 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700879 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700880 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
881 size += stat_size(&s);
882 }
883 if (de->d_type == DT_DIR) {
884 int subfd;
885
886 /* always skip "." and ".." */
887 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700888 if (name[1] == 0) continue;
889 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700890 }
891
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600892 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700893 if (subfd >= 0) {
894 size += calculate_dir_size(subfd);
895 }
896 }
897 }
898 closedir(d);
899 return size;
900}
901
902uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600903 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700904 if (dirfd < 0) {
905 PLOG(WARNING) << "Failed to open " << path;
906 return -1;
907 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700908 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700909 }
910}
911
Ricky Wai07e64a42020-02-11 14:31:24 +0000912// TODO: Use a better way to determine if it's media provider app.
913bool IsFuseDaemon(const pid_t pid) {
914 auto path = StringPrintf("/proc/%d/mounts", pid);
915 char* tmp;
916 if (lgetfilecon(path.c_str(), &tmp) < 0) {
917 return false;
918 }
919 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
920 || android::base::StartsWith(tmp, kMediaProviderCtx);
921 freecon(tmp);
922 return result;
923}
924
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700925bool IsFilesystemSupported(const std::string& fsType) {
926 std::string supported;
927 if (!ReadFileToString(kProcFilesystems, &supported)) {
928 PLOG(ERROR) << "Failed to read supported filesystems";
929 return false;
930 }
931 return supported.find(fsType + "\n") != std::string::npos;
932}
933
934status_t WipeBlockDevice(const std::string& path) {
935 status_t res = -1;
936 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200937 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700938
939 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
940 if (fd == -1) {
941 PLOG(ERROR) << "Failed to open " << path;
942 goto done;
943 }
944
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200945 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700946 PLOG(ERROR) << "Failed to determine size of " << path;
947 goto done;
948 }
949
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700950 LOG(INFO) << "About to discard " << range[1] << " on " << path;
951 if (ioctl(fd, BLKDISCARD, &range) == 0) {
952 LOG(INFO) << "Discard success on " << path;
953 res = 0;
954 } else {
955 PLOG(ERROR) << "Discard failure on " << path;
956 }
957
958done:
959 close(fd);
960 return res;
961}
962
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800963static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700964 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800965 return false;
966 } else {
967 return true;
968 }
969}
970
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700971std::string BuildKeyPath(const std::string& partGuid) {
972 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
973}
974
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600975std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700976 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600977}
978
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800979std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700980 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700981}
982
983std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700984 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700985}
986
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600987std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700988 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600989}
990
Jeff Sharkey47695b22016-02-01 17:02:29 -0700991std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700992 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700993}
994
995std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700996 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800997}
998
Calin Juravle79f55a42016-02-17 20:14:46 +0000999// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1000std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001001 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001002}
1003
Andreas Huber71cd43f2018-01-22 11:25:29 -08001004std::string BuildDataVendorCePath(userid_t userId) {
1005 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1006}
1007
1008std::string BuildDataVendorDePath(userid_t userId) {
1009 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1010}
1011
Paul Crowley3b71fc52017-10-09 10:55:21 -07001012std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001013 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001014 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001015 return "/data";
1016 } else {
1017 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001018 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001019 }
1020}
1021
Paul Crowley3b71fc52017-10-09 10:55:21 -07001022std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001023 // TODO: unify with installd path generation logic
1024 std::string data(BuildDataPath(volumeUuid));
1025 return StringPrintf("%s/media/%u", data.c_str(), userId);
1026}
1027
Paul Crowley3b71fc52017-10-09 10:55:21 -07001028std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001029 // TODO: unify with installd path generation logic
1030 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001031 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001032 std::string legacy = StringPrintf("%s/data", data.c_str());
1033 struct stat sb;
1034 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1035 /* /data/data is dir, return /data/data for legacy system */
1036 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001037 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001038 }
cjbaoeb501142017-04-12 00:09:00 +08001039 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001040}
1041
Paul Crowley3b71fc52017-10-09 10:55:21 -07001042std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001043 // TODO: unify with installd path generation logic
1044 std::string data(BuildDataPath(volumeUuid));
1045 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1046}
1047
Jeff Sharkey66270a22015-06-24 11:49:24 -07001048dev_t GetDevice(const std::string& path) {
1049 struct stat sb;
1050 if (stat(path.c_str(), &sb)) {
1051 PLOG(WARNING) << "Failed to stat " << path;
1052 return 0;
1053 } else {
1054 return sb.st_dev;
1055 }
1056}
1057
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001058status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001059 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001060
Tom Cherryd6127ef2017-06-15 17:13:56 -07001061 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001062
Tom Cherryd6127ef2017-06-15 17:13:56 -07001063 android::base::SetProperty(kRestoreconString, "");
1064 android::base::SetProperty(kRestoreconString, path);
1065
1066 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001067
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001068 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001069 return OK;
1070}
1071
Jeff Sharkey3472e522017-10-06 18:02:53 -06001072bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1073 // Shamelessly borrowed from android::base::Readlink()
1074 result->clear();
1075
1076 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1077 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1078 // waste memory to just start there. We add 1 so that we can recognize
1079 // whether it actually fit (rather than being truncated to 4095).
1080 std::vector<char> buf(4095 + 1);
1081 while (true) {
1082 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1083 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001084 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001085 // It fit! (If size == buf.size(), it may have been truncated.)
1086 if (static_cast<size_t>(size) < buf.size()) {
1087 result->assign(&buf[0], size);
1088 return true;
1089 }
1090 // Double our buffer and try again.
1091 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001092 }
1093}
1094
Yu Ning942d4e82016-01-08 17:36:47 +08001095bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -07001096 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +08001097}
1098
Sudheer Shanka295fb242019-01-16 23:04:07 -08001099static status_t findMountPointsWithPrefix(const std::string& prefix,
1100 std::list<std::string>& mountPoints) {
1101 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1102 // when the prefix is /foo/bar
1103 std::string prefixWithSlash(prefix);
1104 if (prefix.back() != '/') {
1105 android::base::StringAppendF(&prefixWithSlash, "/");
1106 }
1107
1108 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1109 if (!mnts) {
1110 PLOG(ERROR) << "Unable to open /proc/mounts";
1111 return -errno;
1112 }
1113
1114 // Some volumes can be stacked on each other, so force unmount in
1115 // reverse order to give us the best chance of success.
1116 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1117 while ((mnt = getmntent(mnts.get())) != nullptr) {
1118 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1119 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1120 mountPoints.push_front(mountPoint);
1121 }
1122 }
1123 return OK;
1124}
1125
1126// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1127status_t UnmountTreeWithPrefix(const std::string& prefix) {
1128 std::list<std::string> toUnmount;
1129 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1130 if (result < 0) {
1131 return result;
1132 }
1133 for (const auto& path : toUnmount) {
1134 if (umount2(path.c_str(), MNT_DETACH)) {
1135 PLOG(ERROR) << "Failed to unmount " << path;
1136 result = -errno;
1137 }
1138 }
1139 return result;
1140}
1141
1142status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001143 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1144 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001145 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001146 return -errno;
1147 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001148 return OK;
1149}
1150
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001151static status_t delete_dir_contents(DIR* dir) {
1152 // Shamelessly borrowed from android::installd
1153 int dfd = dirfd(dir);
1154 if (dfd < 0) {
1155 return -errno;
1156 }
1157
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001158 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001159 struct dirent* de;
1160 while ((de = readdir(dir))) {
1161 const char* name = de->d_name;
1162 if (de->d_type == DT_DIR) {
1163 /* always skip "." and ".." */
1164 if (name[0] == '.') {
1165 if (name[1] == 0) continue;
1166 if ((name[1] == '.') && (name[2] == 0)) continue;
1167 }
1168
1169 android::base::unique_fd subfd(
1170 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1171 if (subfd.get() == -1) {
1172 PLOG(ERROR) << "Couldn't openat " << name;
1173 result = -errno;
1174 continue;
1175 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001176 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1177 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001178 if (!subdirp) {
1179 PLOG(ERROR) << "Couldn't fdopendir " << name;
1180 result = -errno;
1181 continue;
1182 }
1183 result = delete_dir_contents(subdirp.get());
1184 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1185 PLOG(ERROR) << "Couldn't unlinkat " << name;
1186 result = -errno;
1187 }
1188 } else {
1189 if (unlinkat(dfd, name, 0) < 0) {
1190 PLOG(ERROR) << "Couldn't unlinkat " << name;
1191 result = -errno;
1192 }
1193 }
1194 }
1195 return result;
1196}
1197
1198status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001199 status_t res = DeleteDirContents(pathname);
1200 if (res < 0) {
1201 return res;
1202 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001203 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001204 PLOG(ERROR) << "rmdir failed on " << pathname;
1205 return -errno;
1206 }
1207 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1208 return OK;
1209}
1210
1211status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001212 // Shamelessly borrowed from android::installd
1213 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1214 if (!dirp) {
1215 if (errno == ENOENT) {
1216 return OK;
1217 }
1218 PLOG(ERROR) << "Failed to opendir " << pathname;
1219 return -errno;
1220 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001221 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001222}
1223
Paul Crowley298fa322018-10-30 15:59:24 -07001224// TODO(118708649): fix duplication with init/util.h
1225status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1226 android::base::Timer t;
1227 while (t.duration() < timeout) {
1228 struct stat sb;
1229 if (stat(filename, &sb) != -1) {
1230 LOG(INFO) << "wait for '" << filename << "' took " << t;
1231 return 0;
1232 }
1233 std::this_thread::sleep_for(10ms);
1234 }
1235 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1236 return -1;
1237}
1238
Paul Crowley621d9b92018-12-07 15:36:09 -08001239bool FsyncDirectory(const std::string& dirname) {
1240 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1241 if (fd == -1) {
1242 PLOG(ERROR) << "Failed to open " << dirname;
1243 return false;
1244 }
1245 if (fsync(fd) == -1) {
1246 if (errno == EROFS || errno == EINVAL) {
1247 PLOG(WARNING) << "Skip fsync " << dirname
1248 << " on a file system does not support synchronization";
1249 } else {
1250 PLOG(ERROR) << "Failed to fsync " << dirname;
1251 return false;
1252 }
1253 }
1254 return true;
1255}
1256
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001257bool writeStringToFile(const std::string& payload, const std::string& filename) {
1258 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1259 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1260 if (fd == -1) {
1261 PLOG(ERROR) << "Failed to open " << filename;
1262 return false;
1263 }
1264 if (!android::base::WriteStringToFd(payload, fd)) {
1265 PLOG(ERROR) << "Failed to write to " << filename;
1266 unlink(filename.c_str());
1267 return false;
1268 }
1269 // fsync as close won't guarantee flush data
1270 // see close(2), fsync(2) and b/68901441
1271 if (fsync(fd) == -1) {
1272 if (errno == EROFS || errno == EINVAL) {
1273 PLOG(WARNING) << "Skip fsync " << filename
1274 << " on a file system does not support synchronization";
1275 } else {
1276 PLOG(ERROR) << "Failed to fsync " << filename;
1277 unlink(filename.c_str());
1278 return false;
1279 }
1280 }
1281 return true;
1282}
1283
Ricky Wai07e64a42020-02-11 14:31:24 +00001284status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1285 if (access(path.c_str(), F_OK) != 0) {
1286 PLOG(WARNING) << "Dir does not exist: " << path;
1287 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1288 return -errno;
1289 }
1290 }
1291 return OK;
1292}
1293
Zima438b242019-09-25 14:37:38 +01001294status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1295 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1296 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1297 std::string fuse_path(
1298 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1299
1300 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1301 std::string pass_through_path(
1302 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001303
Zim1242be82020-01-22 18:22:29 +00001304 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1305 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001306 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001307 if (result != android::OK) {
1308 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1309 return -1;
1310 }
1311
Zim06b0caf2020-01-05 02:11:47 +00001312 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1313 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1314 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1315 // These bits should be consistent with what is set in zygote in
1316 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001317 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001318 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001319 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001320 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001321 return -1;
1322 }
1323
Zima438b242019-09-25 14:37:38 +01001324 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1325 if (result != android::OK) {
1326 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1327 return -1;
1328 }
1329
Zim26eec702020-01-31 16:00:58 +00001330 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001331 if (result != android::OK) {
1332 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1333 return -1;
1334 }
1335
Zim26eec702020-01-31 16:00:58 +00001336 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001337 if (result != android::OK) {
1338 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1339 return -1;
1340 }
1341
1342 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001343 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1344 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001345 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001346 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001347 return -1;
1348 }
Zime5393d42019-11-15 11:44:12 +00001349 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001350 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001351
1352 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001353 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001354 if (result != android::OK) {
1355 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1356 return -1;
1357 }
1358 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001359 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001360 }
1361
Nandana Dutta914cc72019-08-29 15:22:42 +01001362 // Open fuse fd.
1363 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1364 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001365 PLOG(ERROR) << "Failed to open /dev/fuse";
1366 return -1;
1367 }
1368
1369 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1370 // permission checks before routing to FUSE daemon.
1371 const auto opts = StringPrintf(
1372 "fd=%i,"
1373 "rootmode=40000,"
1374 "allow_other,"
1375 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001376 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001377
Zima438b242019-09-25 14:37:38 +01001378 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1379 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1380 opts.c_str()));
1381 if (result != 0) {
1382 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001383 return -errno;
1384 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001385
Martijn Coenen86f21a22020-01-06 09:48:14 +01001386 if (IsFilesystemSupported("sdcardfs")) {
1387 std::string sdcardfs_path(
1388 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1389
1390 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1391 return BindMount(sdcardfs_path, pass_through_path);
1392 } else {
1393 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1394 return BindMount(absolute_lower_path, pass_through_path);
1395 }
Zima438b242019-09-25 14:37:38 +01001396}
1397
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001398status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1399 const std::string& relative_upper_path) {
1400 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1401 std::string pass_through_path(
1402 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1403
Zima438b242019-09-25 14:37:38 +01001404 // Best effort unmount pass_through path
1405 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001406 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1407 auto status = ForceUnmount(pass_through_path);
1408 if (status != android::OK) {
1409 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1410 }
Martijn Coenen57002612019-11-28 11:56:13 +01001411 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001412
1413 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001414 android::status_t result = ForceUnmount(fuse_path);
1415 sSleepOnUnmount = true;
1416 if (result != android::OK) {
1417 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1418 // Figure out why we get EBUSY and remove this special casing if possible.
1419 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1420 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1421 errno != ENOENT) {
1422 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1423 return -errno;
1424 }
Martijn Coenen57002612019-11-28 11:56:13 +01001425 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001426 }
Martijn Coenen57002612019-11-28 11:56:13 +01001427 rmdir(fuse_path.c_str());
1428
Zima438b242019-09-25 14:37:38 +01001429 return result;
Zim3623a212019-07-19 16:46:53 +01001430}
1431
Martijn Coenen62a4b272020-01-31 15:23:09 +01001432status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1433 std::string androidDir = volumeRoot + kAndroidDir;
1434 std::string androidDataDir = volumeRoot + kAppDataDir;
1435 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001436 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001437
1438 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1439
Martijn Coenen10570c02020-02-18 10:41:37 +01001440 // mode 0771 + sticky bit for inheriting GIDs
1441 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1442 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001443 PLOG(ERROR) << "Failed to create " << androidDir;
1444 return -errno;
1445 }
1446
1447 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001448 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001449 PLOG(ERROR) << "Failed to create " << androidDataDir;
1450 return -errno;
1451 }
1452
1453 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001454 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001455 PLOG(ERROR) << "Failed to create " << androidObbDir;
1456 return -errno;
1457 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001458 // Some other apps, like installers, have write access to the OBB directory
1459 // to pre-download them. To make sure newly created folders in this directory
1460 // have the right permissions, set a default ACL.
1461 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001462
Martijn Coenen10570c02020-02-18 10:41:37 +01001463 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001464 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1465 return -errno;
1466 }
1467
Martijn Coenen62a4b272020-01-31 15:23:09 +01001468 return OK;
1469}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001470} // namespace vold
1471} // namespace android