blob: 0974a0bf5be06972e5373036c27e6faf4aab0973 [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>
Martijn Coenenaee40512020-02-18 16:29:25 +010032#include <private/android_projectid_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080033
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070034#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080035#include <fcntl.h>
36#include <linux/fs.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010037#include <linux/posix_acl.h>
38#include <linux/posix_acl_xattr.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070039#include <mntent.h>
40#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080041#include <stdlib.h>
42#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080043#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070044#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070045#include <sys/sysmacros.h>
46#include <sys/types.h>
47#include <sys/wait.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010048#include <sys/xattr.h>
Paul Crowley747b4212019-04-05 04:09:57 -070049#include <unistd.h>
Paul Crowley298fa322018-10-30 15:59:24 -070050
Martijn Coenen816f4d92020-02-18 15:06:37 +010051#include <filesystem>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070052#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070053#include <mutex>
Martijn Coenen04bb17f2020-02-10 23:48:11 +010054#include <regex>
Paul Crowley298fa322018-10-30 15:59:24 -070055#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080056
57#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070058#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080059#endif
60
Paul Crowley298fa322018-10-30 15:59:24 -070061using namespace std::chrono_literals;
Martijn Coenenba9868b2020-01-31 15:49:24 +010062using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070063using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010064using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070065using android::base::StringPrintf;
66
Jeff Sharkeydeb24052015-03-02 21:01:40 -080067namespace android {
68namespace vold {
69
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070070security_context_t sBlkidContext = nullptr;
71security_context_t sBlkidUntrustedContext = nullptr;
72security_context_t sFsckContext = nullptr;
73security_context_t sFsckUntrustedContext = nullptr;
74
Paul Crowley56292ef2017-10-20 08:07:53 -070075bool sSleepOnUnmount = true;
76
Jeff Sharkey9c484982015-03-31 10:35:33 -070077static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070078static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070079
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070080static const char* kProcFilesystems = "/proc/filesystems";
81
Martijn Coenen04bb17f2020-02-10 23:48:11 +010082static const char* kAndroidDir = "/Android/";
83static const char* kAppDataDir = "/Android/data/";
84static const char* kAppMediaDir = "/Android/media/";
85static const char* kAppObbDir = "/Android/obb/";
86
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060087// Lock used to protect process-level SELinux changes from racing with each
88// other between multiple threads.
89static std::mutex kSecurityLock;
90
Jeff Sharkeydeb24052015-03-02 21:01:40 -080091status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060092 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080093 const char* cpath = path.c_str();
94 status_t res = 0;
95
96 char* secontext = nullptr;
97 if (sehandle) {
98 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
99 setfscreatecon(secontext);
100 }
101 }
102
103 mode_t mode = 0660 | S_IFBLK;
104 if (mknod(cpath, mode, dev) < 0) {
105 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700106 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
107 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800108 res = -errno;
109 }
110 }
111
112 if (secontext) {
113 setfscreatecon(nullptr);
114 freecon(secontext);
115 }
116
117 return res;
118}
119
120status_t DestroyDeviceNode(const std::string& path) {
121 const char* cpath = path.c_str();
122 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
123 return -errno;
124 } else {
125 return OK;
126 }
127}
128
Martijn Coenen442bb832020-02-18 13:44:59 +0100129// Sets a default ACL on the directory.
130int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100131 if (IsFilesystemSupported("sdcardfs")) {
132 // sdcardfs magically takes care of this
133 return OK;
134 }
135
136 static constexpr size_t size =
137 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
138 auto buf = std::make_unique<uint8_t[]>(size);
139
140 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
141 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
142
143 posix_acl_xattr_entry* entry =
144 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
145
146 entry[0].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100147 // The existing mode_t mask has the ACL in the lower 9 bits:
148 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
149 // Use the mode_t masks to get these bits out, and shift them to get the
150 // correct value per entity.
151 //
152 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
153 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100154 entry[0].e_id = uid;
155
156 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100157 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100158 entry[1].e_id = gid;
159
160 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100161 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100162 entry[2].e_id = 0;
163
164 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
165
166 if (ret != 0) {
167 PLOG(ERROR) << "Failed to set default ACL on " << path;
168 }
169
170 return ret;
171}
172
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100173int SetQuotaInherit(const std::string& path) {
174 unsigned long flags;
175
176 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
177 if (fd == -1) {
178 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
179 return -1;
180 }
181
182 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
183 if (ret == -1) {
184 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
185 return ret;
186 }
187
188 flags |= FS_PROJINHERIT_FL;
189
190 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
191 if (ret == -1) {
192 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
193 return ret;
194 }
195
196 return 0;
197}
198
199int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100200 struct fsxattr fsx;
201
202 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
203 if (fd == -1) {
204 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
205 return -1;
206 }
207
208 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
209 if (ret == -1) {
210 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
211 return ret;
212 }
213
214 fsx.fsx_projid = projectId;
215 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
216}
217
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100218int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
219 long projectId) {
220 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
221
222 if (ret != 0) {
223 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100224 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100225
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100226 if (!IsFilesystemSupported("sdcardfs")) {
227 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100228 }
229
230 return ret;
231}
232
Martijn Coenen816f4d92020-02-18 15:06:37 +0100233static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
234 namespace fs = std::filesystem;
235
236 // Setup the directory itself correctly
237 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
238 if (ret != OK) {
239 return ret;
240 }
241
242 // Fixup all of its file entries
243 for (const auto& itEntry : fs::directory_iterator(path)) {
244 ret = lchown(itEntry.path().c_str(), uid, gid);
245 if (ret != 0) {
246 return ret;
247 }
248
249 ret = chmod(itEntry.path().c_str(), mode);
250 if (ret != 0) {
251 return ret;
252 }
253
254 if (!IsFilesystemSupported("sdcardfs")) {
255 ret = SetQuotaProjectId(itEntry.path(), projectId);
256 if (ret != 0) {
257 return ret;
258 }
259 }
260 }
261
262 return OK;
263}
264
265int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
266 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100267 long projectId;
268 size_t pos;
269 int ret = 0;
270
271 // Make sure the Android/ directories exist and are setup correctly
272 ret = PrepareAndroidDirs(root);
273 if (ret != 0) {
274 LOG(ERROR) << "Failed to prepare Android/ directories.";
275 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100276 }
277
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100278 // Now create the application-specific subdir(s)
279 // path is something like /data/media/0/Android/data/com.foo/files
280 // First, chop off the volume root, eg /data/media/0
281 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100282
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100283 uid_t uid = appUid;
284 gid_t gid = AID_MEDIA_RW;
285 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100286
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100287 // Check that the next part matches one of the allowed Android/ dirs
288 if (StartsWith(pathFromRoot, kAppDataDir)) {
289 appDir = kAppDataDir;
290 if (!IsFilesystemSupported("sdcardfs")) {
291 gid = AID_EXT_DATA_RW;
292 }
293 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
294 appDir = kAppMediaDir;
295 if (!IsFilesystemSupported("sdcardfs")) {
296 gid = AID_MEDIA_RW;
297 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000298 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100299 appDir = kAppObbDir;
300 if (!IsFilesystemSupported("sdcardfs")) {
301 gid = AID_EXT_OBB_RW;
302 }
303 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100304 LOG(ERROR) << "Invalid application directory: " << path;
305 return -EINVAL;
306 }
307
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100308 // mode = 770, plus sticky bit on directory to inherit GID when apps
309 // create subdirs
310 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100311 // the project ID for application-specific directories is directly
312 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100313
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100314 // Chop off the generic application-specific part, eg /Android/data/
315 // this leaves us with something like com.foo/files/
316 std::string leftToCreate = pathFromRoot.substr(appDir.length());
317 if (!EndsWith(leftToCreate, "/")) {
318 leftToCreate += "/";
319 }
320 std::string pathToCreate = root + appDir;
321 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100322 // Derive initial project ID
323 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
324 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
325 } else if (appDir == kAppObbDir) {
326 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
327 }
328
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100329 while ((pos = leftToCreate.find('/')) != std::string::npos) {
330 std::string component = leftToCreate.substr(0, pos + 1);
331 leftToCreate = leftToCreate.erase(0, pos + 1);
332 pathToCreate = pathToCreate + component;
333
334 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
335 // All dirs use the "app" project ID, except for the cache dirs in
336 // Android/data, eg Android/data/com.foo/cache
337 // Note that this "sticks" - eg subdirs of this dir need the same
338 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100339 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100340 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100341
342 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
343 // Fixup all files in this existing directory with the correct UID/GID
344 // and project ID.
345 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
346 } else {
347 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
348 }
349
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100350 if (ret != 0) {
351 return ret;
352 }
353
354 if (depth == 0) {
355 // Set the default ACL on the top-level application-specific directories,
356 // to ensure that even if applications run with a umask of 0077,
357 // new directories within these directories will allow the GID
358 // specified here to write; this is necessary for apps like
359 // installers and MTP, that require access here.
360 //
361 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100362 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100363 if (ret != 0) {
364 return ret;
365 }
366 }
367
368 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100369 }
370
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100371 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100372}
373
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700374status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600375 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700376 const char* cpath = path.c_str();
377
378 char* secontext = nullptr;
379 if (sehandle) {
380 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
381 setfscreatecon(secontext);
382 }
383 }
384
385 int res = fs_prepare_dir(cpath, mode, uid, gid);
386
387 if (secontext) {
388 setfscreatecon(nullptr);
389 freecon(secontext);
390 }
391
392 if (res == 0) {
393 return OK;
394 } else {
395 return -errno;
396 }
397}
398
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800399status_t ForceUnmount(const std::string& path) {
400 const char* cpath = path.c_str();
401 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
402 return OK;
403 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700404 // Apps might still be handling eject request, so wait before
405 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700406 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700407
Jeff Sharkey3472e522017-10-06 18:02:53 -0600408 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700409 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700410 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
411 return OK;
412 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700413
Jeff Sharkey3472e522017-10-06 18:02:53 -0600414 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700415 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800416 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
417 return OK;
418 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700419
Jeff Sharkey3472e522017-10-06 18:02:53 -0600420 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700421 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700422 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
423 return OK;
424 }
Zim3623a212019-07-19 16:46:53 +0100425 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800426 return -errno;
427}
428
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700429status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600430 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700431 return OK;
432 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700433 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700434
Jeff Sharkey3472e522017-10-06 18:02:53 -0600435 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700436 return OK;
437 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700438 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700439
Jeff Sharkey3472e522017-10-06 18:02:53 -0600440 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700441 return OK;
442 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700443 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700444
445 // Send SIGKILL a second time to determine if we've
446 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600447 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700448 return OK;
449 }
450 PLOG(ERROR) << "Failed to kill processes using " << path;
451 return -EBUSY;
452}
453
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700454status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800455 if (UnmountTree(target) < 0) {
456 return -errno;
457 }
458 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700459 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
460 return -errno;
461 }
462 return OK;
463}
464
Sudheer Shanka023b5392019-02-06 12:39:19 -0800465status_t Symlink(const std::string& target, const std::string& linkpath) {
466 if (Unlink(linkpath) < 0) {
467 return -errno;
468 }
469 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
470 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
471 return -errno;
472 }
473 return OK;
474}
475
476status_t Unlink(const std::string& linkpath) {
477 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
478 PLOG(ERROR) << "Failed to unlink " << linkpath;
479 return -errno;
480 }
481 return OK;
482}
483
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000484status_t CreateDir(const std::string& dir, mode_t mode) {
485 struct stat sb;
486 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
487 if (S_ISDIR(sb.st_mode)) {
488 return OK;
489 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
490 PLOG(ERROR) << "Failed to unlink " << dir;
491 return -errno;
492 }
493 } else if (errno != ENOENT) {
494 PLOG(ERROR) << "Failed to stat " << dir;
495 return -errno;
496 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800497 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000498 PLOG(ERROR) << "Failed to mkdir " << dir;
499 return -errno;
500 }
501 return OK;
502}
503
Jeff Sharkey3472e522017-10-06 18:02:53 -0600504bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
505 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800506 size_t start = 0;
507 while (true) {
508 start = raw.find(qual, start);
509 if (start == std::string::npos) return false;
510 if (start == 0 || raw[start - 1] == ' ') {
511 break;
512 }
513 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600514 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600515 start += qual.length();
516
517 auto end = raw.find("\"", start);
518 if (end == std::string::npos) return false;
519
520 *value = raw.substr(start, end - start);
521 return true;
522}
523
Paul Crowley14c8c072018-09-18 13:30:21 -0700524static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
525 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600526 fsType->clear();
527 fsUuid->clear();
528 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700529
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700530 std::vector<std::string> cmd;
531 cmd.push_back(kBlkidPath);
532 cmd.push_back("-c");
533 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700534 cmd.push_back("-s");
535 cmd.push_back("TYPE");
536 cmd.push_back("-s");
537 cmd.push_back("UUID");
538 cmd.push_back("-s");
539 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700540 cmd.push_back(path);
541
542 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800543 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700544 if (res != OK) {
545 LOG(WARNING) << "blkid failed to identify " << path;
546 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700547 }
548
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700549 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700550 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600551 FindValue(line, "TYPE", fsType);
552 FindValue(line, "UUID", fsUuid);
553 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700554 }
555
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700556 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700557}
558
Paul Crowley14c8c072018-09-18 13:30:21 -0700559status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
560 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700561 return readMetadata(path, fsType, fsUuid, fsLabel, false);
562}
563
Paul Crowley14c8c072018-09-18 13:30:21 -0700564status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
565 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700566 return readMetadata(path, fsType, fsUuid, fsLabel, true);
567}
568
Paul Crowleyde2d6202018-11-30 11:43:47 -0800569static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
570 std::vector<const char*> argv;
571 argv.reserve(args.size() + 1);
572 for (const auto& arg : args) {
573 if (argv.empty()) {
574 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700575 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800576 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700577 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800578 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700579 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800580 argv.emplace_back(nullptr);
581 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700582}
583
Paul Crowleyde2d6202018-11-30 11:43:47 -0800584static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
585 android::base::unique_fd ufd) {
586 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700587 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800588 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700589 return -errno;
590 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800591 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700592 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800593 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700594 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800595 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700596 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800597 return OK;
598}
599
600status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
601 security_context_t context) {
602 auto argv = ConvertToArgv(args);
603
Paul Crowleye6d76632018-11-30 11:43:47 -0800604 android::base::unique_fd pipe_read, pipe_write;
605 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
606 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800607 return -errno;
608 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800609
610 pid_t pid = fork();
611 if (pid == 0) {
612 if (context) {
613 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800614 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800615 abort();
616 }
617 }
618 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800619 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
620 PLOG(ERROR) << "dup2 in ForkExecvp";
621 _exit(EXIT_FAILURE);
622 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800623 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800624 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800625 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800626 _exit(EXIT_FAILURE);
627 }
628 if (pid == -1) {
629 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700630 return -errno;
631 }
632
Paul Crowleyde2d6202018-11-30 11:43:47 -0800633 pipe_write.reset();
634 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
635 if (st != 0) return st;
636
637 int status;
638 if (waitpid(pid, &status, 0) == -1) {
639 PLOG(ERROR) << "waitpid in ForkExecvp";
640 return -errno;
641 }
642 if (!WIFEXITED(status)) {
643 LOG(ERROR) << "Process did not exit normally, status: " << status;
644 return -ECHILD;
645 }
646 if (WEXITSTATUS(status)) {
647 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
648 return WEXITSTATUS(status);
649 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700650 return OK;
651}
652
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700653pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800654 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700655
656 pid_t pid = fork();
657 if (pid == 0) {
658 close(STDIN_FILENO);
659 close(STDOUT_FILENO);
660 close(STDERR_FILENO);
661
Paul Crowleyde2d6202018-11-30 11:43:47 -0800662 execvp(argv[0], const_cast<char**>(argv.data()));
663 PLOG(ERROR) << "exec in ForkExecvpAsync";
664 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700665 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700666 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800667 PLOG(ERROR) << "fork in ForkExecvpAsync";
668 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700669 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700670 return pid;
671}
672
Jeff Sharkey9c484982015-03-31 10:35:33 -0700673status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100674 out.resize(bytes);
675 return ReadRandomBytes(bytes, &out[0]);
676}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700677
Pavel Grafove2e2d302017-08-01 17:15:53 +0100678status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700679 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
680 if (fd == -1) {
681 return -errno;
682 }
683
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800684 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100685 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700686 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100687 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700688 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700689 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700690
691 if (bytes == 0) {
692 return OK;
693 } else {
694 return -EIO;
695 }
696}
697
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600698status_t GenerateRandomUuid(std::string& out) {
699 status_t res = ReadRandomBytes(16, out);
700 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700701 out[6] &= 0x0f; /* clear version */
702 out[6] |= 0x40; /* set to version 4 */
703 out[8] &= 0x3f; /* clear variant */
704 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600705 }
706 return res;
707}
708
Jeff Sharkey9c484982015-03-31 10:35:33 -0700709status_t HexToStr(const std::string& hex, std::string& str) {
710 str.clear();
711 bool even = true;
712 char cur = 0;
713 for (size_t i = 0; i < hex.size(); i++) {
714 int val = 0;
715 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700716 // clang-format off
717 case ' ': case '-': case ':': continue;
718 case 'f': case 'F': val = 15; break;
719 case 'e': case 'E': val = 14; break;
720 case 'd': case 'D': val = 13; break;
721 case 'c': case 'C': val = 12; break;
722 case 'b': case 'B': val = 11; break;
723 case 'a': case 'A': val = 10; break;
724 case '9': val = 9; break;
725 case '8': val = 8; break;
726 case '7': val = 7; break;
727 case '6': val = 6; break;
728 case '5': val = 5; break;
729 case '4': val = 4; break;
730 case '3': val = 3; break;
731 case '2': val = 2; break;
732 case '1': val = 1; break;
733 case '0': val = 0; break;
734 default: return -EINVAL;
735 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700736 }
737
738 if (even) {
739 cur = val << 4;
740 } else {
741 cur += val;
742 str.push_back(cur);
743 cur = 0;
744 }
745 even = !even;
746 }
747 return even ? OK : -EINVAL;
748}
749
750static const char* kLookup = "0123456789abcdef";
751
752status_t StrToHex(const std::string& str, std::string& hex) {
753 hex.clear();
754 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700755 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700756 hex.push_back(kLookup[str[i] & 0x0F]);
757 }
758 return OK;
759}
760
Pavel Grafove2e2d302017-08-01 17:15:53 +0100761status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
762 hex.clear();
763 for (size_t i = 0; i < str.size(); i++) {
764 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
765 hex.push_back(kLookup[str.data()[i] & 0x0F]);
766 }
767 return OK;
768}
769
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700770status_t NormalizeHex(const std::string& in, std::string& out) {
771 std::string tmp;
772 if (HexToStr(in, tmp)) {
773 return -EINVAL;
774 }
775 return StrToHex(tmp, out);
776}
777
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200778status_t GetBlockDevSize(int fd, uint64_t* size) {
779 if (ioctl(fd, BLKGETSIZE64, size)) {
780 return -errno;
781 }
782
783 return OK;
784}
785
786status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
787 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
788 status_t res = OK;
789
790 if (fd < 0) {
791 return -errno;
792 }
793
794 res = GetBlockDevSize(fd, size);
795
796 close(fd);
797
798 return res;
799}
800
801status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
802 uint64_t size;
803 status_t res = GetBlockDevSize(path, &size);
804
805 if (res != OK) {
806 return res;
807 }
808
809 *nr_sec = size / 512;
810
811 return OK;
812}
813
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700814uint64_t GetFreeBytes(const std::string& path) {
815 struct statvfs sb;
816 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700817 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700818 } else {
819 return -1;
820 }
821}
822
823// TODO: borrowed from frameworks/native/libs/diskusage/ which should
824// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700825static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700826 int64_t blksize = s->st_blksize;
827 // count actual blocks used instead of nominal file size
828 int64_t size = s->st_blocks * 512;
829
830 if (blksize) {
831 /* round up to filesystem block size */
832 size = (size + blksize - 1) & (~(blksize - 1));
833 }
834
835 return size;
836}
837
838// TODO: borrowed from frameworks/native/libs/diskusage/ which should
839// eventually be migrated into system/
840int64_t calculate_dir_size(int dfd) {
841 int64_t size = 0;
842 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700843 DIR* d;
844 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700845
846 d = fdopendir(dfd);
847 if (d == NULL) {
848 close(dfd);
849 return 0;
850 }
851
852 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700853 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700854 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
855 size += stat_size(&s);
856 }
857 if (de->d_type == DT_DIR) {
858 int subfd;
859
860 /* always skip "." and ".." */
861 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700862 if (name[1] == 0) continue;
863 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700864 }
865
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600866 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700867 if (subfd >= 0) {
868 size += calculate_dir_size(subfd);
869 }
870 }
871 }
872 closedir(d);
873 return size;
874}
875
876uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600877 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700878 if (dirfd < 0) {
879 PLOG(WARNING) << "Failed to open " << path;
880 return -1;
881 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700882 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700883 }
884}
885
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700886bool IsFilesystemSupported(const std::string& fsType) {
887 std::string supported;
888 if (!ReadFileToString(kProcFilesystems, &supported)) {
889 PLOG(ERROR) << "Failed to read supported filesystems";
890 return false;
891 }
892 return supported.find(fsType + "\n") != std::string::npos;
893}
894
895status_t WipeBlockDevice(const std::string& path) {
896 status_t res = -1;
897 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200898 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700899
900 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
901 if (fd == -1) {
902 PLOG(ERROR) << "Failed to open " << path;
903 goto done;
904 }
905
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200906 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700907 PLOG(ERROR) << "Failed to determine size of " << path;
908 goto done;
909 }
910
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700911 LOG(INFO) << "About to discard " << range[1] << " on " << path;
912 if (ioctl(fd, BLKDISCARD, &range) == 0) {
913 LOG(INFO) << "Discard success on " << path;
914 res = 0;
915 } else {
916 PLOG(ERROR) << "Discard failure on " << path;
917 }
918
919done:
920 close(fd);
921 return res;
922}
923
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800924static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700925 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800926 return false;
927 } else {
928 return true;
929 }
930}
931
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700932std::string BuildKeyPath(const std::string& partGuid) {
933 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
934}
935
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600936std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700937 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600938}
939
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800940std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700941 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700942}
943
944std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700945 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700946}
947
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600948std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700949 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600950}
951
Jeff Sharkey47695b22016-02-01 17:02:29 -0700952std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700953 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700954}
955
956std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700957 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800958}
959
Calin Juravle79f55a42016-02-17 20:14:46 +0000960// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
961std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700962 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000963}
964
Andreas Huber71cd43f2018-01-22 11:25:29 -0800965std::string BuildDataVendorCePath(userid_t userId) {
966 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
967}
968
969std::string BuildDataVendorDePath(userid_t userId) {
970 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
971}
972
Paul Crowley3b71fc52017-10-09 10:55:21 -0700973std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800974 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700975 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800976 return "/data";
977 } else {
978 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700979 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800980 }
981}
982
Paul Crowley3b71fc52017-10-09 10:55:21 -0700983std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700984 // TODO: unify with installd path generation logic
985 std::string data(BuildDataPath(volumeUuid));
986 return StringPrintf("%s/media/%u", data.c_str(), userId);
987}
988
Paul Crowley3b71fc52017-10-09 10:55:21 -0700989std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800990 // TODO: unify with installd path generation logic
991 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700992 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800993 std::string legacy = StringPrintf("%s/data", data.c_str());
994 struct stat sb;
995 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
996 /* /data/data is dir, return /data/data for legacy system */
997 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800998 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800999 }
cjbaoeb501142017-04-12 00:09:00 +08001000 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001001}
1002
Paul Crowley3b71fc52017-10-09 10:55:21 -07001003std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001004 // TODO: unify with installd path generation logic
1005 std::string data(BuildDataPath(volumeUuid));
1006 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1007}
1008
Jeff Sharkey66270a22015-06-24 11:49:24 -07001009dev_t GetDevice(const std::string& path) {
1010 struct stat sb;
1011 if (stat(path.c_str(), &sb)) {
1012 PLOG(WARNING) << "Failed to stat " << path;
1013 return 0;
1014 } else {
1015 return sb.st_dev;
1016 }
1017}
1018
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001019status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001020 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001021
Tom Cherryd6127ef2017-06-15 17:13:56 -07001022 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001023
Tom Cherryd6127ef2017-06-15 17:13:56 -07001024 android::base::SetProperty(kRestoreconString, "");
1025 android::base::SetProperty(kRestoreconString, path);
1026
1027 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001028
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001029 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001030 return OK;
1031}
1032
Jeff Sharkey3472e522017-10-06 18:02:53 -06001033bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1034 // Shamelessly borrowed from android::base::Readlink()
1035 result->clear();
1036
1037 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1038 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1039 // waste memory to just start there. We add 1 so that we can recognize
1040 // whether it actually fit (rather than being truncated to 4095).
1041 std::vector<char> buf(4095 + 1);
1042 while (true) {
1043 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1044 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001045 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001046 // It fit! (If size == buf.size(), it may have been truncated.)
1047 if (static_cast<size_t>(size) < buf.size()) {
1048 result->assign(&buf[0], size);
1049 return true;
1050 }
1051 // Double our buffer and try again.
1052 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001053 }
1054}
1055
Yu Ning942d4e82016-01-08 17:36:47 +08001056bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -07001057 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +08001058}
1059
Sudheer Shanka295fb242019-01-16 23:04:07 -08001060static status_t findMountPointsWithPrefix(const std::string& prefix,
1061 std::list<std::string>& mountPoints) {
1062 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1063 // when the prefix is /foo/bar
1064 std::string prefixWithSlash(prefix);
1065 if (prefix.back() != '/') {
1066 android::base::StringAppendF(&prefixWithSlash, "/");
1067 }
1068
1069 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1070 if (!mnts) {
1071 PLOG(ERROR) << "Unable to open /proc/mounts";
1072 return -errno;
1073 }
1074
1075 // Some volumes can be stacked on each other, so force unmount in
1076 // reverse order to give us the best chance of success.
1077 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1078 while ((mnt = getmntent(mnts.get())) != nullptr) {
1079 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1080 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1081 mountPoints.push_front(mountPoint);
1082 }
1083 }
1084 return OK;
1085}
1086
1087// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1088status_t UnmountTreeWithPrefix(const std::string& prefix) {
1089 std::list<std::string> toUnmount;
1090 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1091 if (result < 0) {
1092 return result;
1093 }
1094 for (const auto& path : toUnmount) {
1095 if (umount2(path.c_str(), MNT_DETACH)) {
1096 PLOG(ERROR) << "Failed to unmount " << path;
1097 result = -errno;
1098 }
1099 }
1100 return result;
1101}
1102
1103status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001104 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1105 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001106 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001107 return -errno;
1108 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001109 return OK;
1110}
1111
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001112static status_t delete_dir_contents(DIR* dir) {
1113 // Shamelessly borrowed from android::installd
1114 int dfd = dirfd(dir);
1115 if (dfd < 0) {
1116 return -errno;
1117 }
1118
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001119 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001120 struct dirent* de;
1121 while ((de = readdir(dir))) {
1122 const char* name = de->d_name;
1123 if (de->d_type == DT_DIR) {
1124 /* always skip "." and ".." */
1125 if (name[0] == '.') {
1126 if (name[1] == 0) continue;
1127 if ((name[1] == '.') && (name[2] == 0)) continue;
1128 }
1129
1130 android::base::unique_fd subfd(
1131 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1132 if (subfd.get() == -1) {
1133 PLOG(ERROR) << "Couldn't openat " << name;
1134 result = -errno;
1135 continue;
1136 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001137 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1138 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001139 if (!subdirp) {
1140 PLOG(ERROR) << "Couldn't fdopendir " << name;
1141 result = -errno;
1142 continue;
1143 }
1144 result = delete_dir_contents(subdirp.get());
1145 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1146 PLOG(ERROR) << "Couldn't unlinkat " << name;
1147 result = -errno;
1148 }
1149 } else {
1150 if (unlinkat(dfd, name, 0) < 0) {
1151 PLOG(ERROR) << "Couldn't unlinkat " << name;
1152 result = -errno;
1153 }
1154 }
1155 }
1156 return result;
1157}
1158
1159status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001160 status_t res = DeleteDirContents(pathname);
1161 if (res < 0) {
1162 return res;
1163 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001164 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001165 PLOG(ERROR) << "rmdir failed on " << pathname;
1166 return -errno;
1167 }
1168 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1169 return OK;
1170}
1171
1172status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001173 // Shamelessly borrowed from android::installd
1174 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1175 if (!dirp) {
1176 if (errno == ENOENT) {
1177 return OK;
1178 }
1179 PLOG(ERROR) << "Failed to opendir " << pathname;
1180 return -errno;
1181 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001182 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001183}
1184
Paul Crowley298fa322018-10-30 15:59:24 -07001185// TODO(118708649): fix duplication with init/util.h
1186status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1187 android::base::Timer t;
1188 while (t.duration() < timeout) {
1189 struct stat sb;
1190 if (stat(filename, &sb) != -1) {
1191 LOG(INFO) << "wait for '" << filename << "' took " << t;
1192 return 0;
1193 }
1194 std::this_thread::sleep_for(10ms);
1195 }
1196 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1197 return -1;
1198}
1199
Paul Crowley621d9b92018-12-07 15:36:09 -08001200bool FsyncDirectory(const std::string& dirname) {
1201 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1202 if (fd == -1) {
1203 PLOG(ERROR) << "Failed to open " << dirname;
1204 return false;
1205 }
1206 if (fsync(fd) == -1) {
1207 if (errno == EROFS || errno == EINVAL) {
1208 PLOG(WARNING) << "Skip fsync " << dirname
1209 << " on a file system does not support synchronization";
1210 } else {
1211 PLOG(ERROR) << "Failed to fsync " << dirname;
1212 return false;
1213 }
1214 }
1215 return true;
1216}
1217
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001218bool writeStringToFile(const std::string& payload, const std::string& filename) {
1219 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1220 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1221 if (fd == -1) {
1222 PLOG(ERROR) << "Failed to open " << filename;
1223 return false;
1224 }
1225 if (!android::base::WriteStringToFd(payload, fd)) {
1226 PLOG(ERROR) << "Failed to write to " << filename;
1227 unlink(filename.c_str());
1228 return false;
1229 }
1230 // fsync as close won't guarantee flush data
1231 // see close(2), fsync(2) and b/68901441
1232 if (fsync(fd) == -1) {
1233 if (errno == EROFS || errno == EINVAL) {
1234 PLOG(WARNING) << "Skip fsync " << filename
1235 << " on a file system does not support synchronization";
1236 } else {
1237 PLOG(ERROR) << "Failed to fsync " << filename;
1238 unlink(filename.c_str());
1239 return false;
1240 }
1241 }
1242 return true;
1243}
1244
Zima438b242019-09-25 14:37:38 +01001245status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1246 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1247 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1248 std::string fuse_path(
1249 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1250
1251 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1252 std::string pass_through_path(
1253 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001254
Zim1242be82020-01-22 18:22:29 +00001255 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1256 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001257 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001258 if (result != android::OK) {
1259 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1260 return -1;
1261 }
1262
Zim06b0caf2020-01-05 02:11:47 +00001263 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1264 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1265 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1266 // These bits should be consistent with what is set in zygote in
1267 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001268 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001269 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001270 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001271 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001272 return -1;
1273 }
1274
Zima438b242019-09-25 14:37:38 +01001275 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1276 if (result != android::OK) {
1277 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1278 return -1;
1279 }
1280
Zim26eec702020-01-31 16:00:58 +00001281 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001282 if (result != android::OK) {
1283 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1284 return -1;
1285 }
1286
Zim26eec702020-01-31 16:00:58 +00001287 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001288 if (result != android::OK) {
1289 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1290 return -1;
1291 }
1292
1293 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001294 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1295 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001296 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001297 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001298 return -1;
1299 }
Zime5393d42019-11-15 11:44:12 +00001300 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001301 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001302
1303 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001304 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001305 if (result != android::OK) {
1306 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1307 return -1;
1308 }
1309 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001310 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001311 }
1312
Nandana Dutta914cc72019-08-29 15:22:42 +01001313 // Open fuse fd.
1314 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1315 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001316 PLOG(ERROR) << "Failed to open /dev/fuse";
1317 return -1;
1318 }
1319
1320 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1321 // permission checks before routing to FUSE daemon.
1322 const auto opts = StringPrintf(
1323 "fd=%i,"
1324 "rootmode=40000,"
1325 "allow_other,"
1326 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001327 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001328
Zima438b242019-09-25 14:37:38 +01001329 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1330 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1331 opts.c_str()));
1332 if (result != 0) {
1333 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001334 return -errno;
1335 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001336
Martijn Coenen86f21a22020-01-06 09:48:14 +01001337 if (IsFilesystemSupported("sdcardfs")) {
1338 std::string sdcardfs_path(
1339 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1340
1341 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1342 return BindMount(sdcardfs_path, pass_through_path);
1343 } else {
1344 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1345 return BindMount(absolute_lower_path, pass_through_path);
1346 }
Zima438b242019-09-25 14:37:38 +01001347}
1348
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001349status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1350 const std::string& relative_upper_path) {
1351 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1352 std::string pass_through_path(
1353 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1354
Zima438b242019-09-25 14:37:38 +01001355 // Best effort unmount pass_through path
1356 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001357 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1358 auto status = ForceUnmount(pass_through_path);
1359 if (status != android::OK) {
1360 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1361 }
Martijn Coenen57002612019-11-28 11:56:13 +01001362 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001363
1364 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001365 android::status_t result = ForceUnmount(fuse_path);
1366 sSleepOnUnmount = true;
1367 if (result != android::OK) {
1368 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1369 // Figure out why we get EBUSY and remove this special casing if possible.
1370 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1371 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1372 errno != ENOENT) {
1373 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1374 return -errno;
1375 }
Martijn Coenen57002612019-11-28 11:56:13 +01001376 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001377 }
Martijn Coenen57002612019-11-28 11:56:13 +01001378 rmdir(fuse_path.c_str());
1379
Zima438b242019-09-25 14:37:38 +01001380 return result;
Zim3623a212019-07-19 16:46:53 +01001381}
1382
Martijn Coenen62a4b272020-01-31 15:23:09 +01001383status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1384 std::string androidDir = volumeRoot + kAndroidDir;
1385 std::string androidDataDir = volumeRoot + kAppDataDir;
1386 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001387 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001388
1389 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1390
Martijn Coenen10570c02020-02-18 10:41:37 +01001391 // mode 0771 + sticky bit for inheriting GIDs
1392 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1393 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001394 PLOG(ERROR) << "Failed to create " << androidDir;
1395 return -errno;
1396 }
1397
1398 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001399 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001400 PLOG(ERROR) << "Failed to create " << androidDataDir;
1401 return -errno;
1402 }
1403
1404 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001405 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001406 PLOG(ERROR) << "Failed to create " << androidObbDir;
1407 return -errno;
1408 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001409 // Some other apps, like installers, have write access to the OBB directory
1410 // to pre-download them. To make sure newly created folders in this directory
1411 // have the right permissions, set a default ACL.
1412 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001413
Martijn Coenen10570c02020-02-18 10:41:37 +01001414 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001415 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1416 return -errno;
1417 }
1418
Martijn Coenen62a4b272020-01-31 15:23:09 +01001419 return OK;
1420}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001421} // namespace vold
1422} // namespace android