blob: b129990904d92a2e0ad50440cb566451900f6160 [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
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070080static const char* kProcDevices = "/proc/devices";
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070081static const char* kProcFilesystems = "/proc/filesystems";
82
Martijn Coenen04bb17f2020-02-10 23:48:11 +010083static const char* kAndroidDir = "/Android/";
84static const char* kAppDataDir = "/Android/data/";
85static const char* kAppMediaDir = "/Android/media/";
86static const char* kAppObbDir = "/Android/obb/";
87
Ricky Wai07e64a42020-02-11 14:31:24 +000088static const char* kMediaProviderCtx = "u:r:mediaprovider:";
89static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
90
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060091// Lock used to protect process-level SELinux changes from racing with each
92// other between multiple threads.
93static std::mutex kSecurityLock;
94
Jeff Sharkeydeb24052015-03-02 21:01:40 -080095status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060096 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080097 const char* cpath = path.c_str();
98 status_t res = 0;
99
100 char* secontext = nullptr;
101 if (sehandle) {
102 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
103 setfscreatecon(secontext);
104 }
105 }
106
107 mode_t mode = 0660 | S_IFBLK;
108 if (mknod(cpath, mode, dev) < 0) {
109 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700110 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
111 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800112 res = -errno;
113 }
114 }
115
116 if (secontext) {
117 setfscreatecon(nullptr);
118 freecon(secontext);
119 }
120
121 return res;
122}
123
124status_t DestroyDeviceNode(const std::string& path) {
125 const char* cpath = path.c_str();
126 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
127 return -errno;
128 } else {
129 return OK;
130 }
131}
132
Martijn Coenen442bb832020-02-18 13:44:59 +0100133// Sets a default ACL on the directory.
134int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100135 if (IsFilesystemSupported("sdcardfs")) {
136 // sdcardfs magically takes care of this
137 return OK;
138 }
139
140 static constexpr size_t size =
141 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
142 auto buf = std::make_unique<uint8_t[]>(size);
143
144 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
145 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
146
147 posix_acl_xattr_entry* entry =
148 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
149
150 entry[0].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100151 // The existing mode_t mask has the ACL in the lower 9 bits:
152 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
153 // Use the mode_t masks to get these bits out, and shift them to get the
154 // correct value per entity.
155 //
156 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
157 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100158 entry[0].e_id = uid;
159
160 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100161 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100162 entry[1].e_id = gid;
163
164 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100165 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100166 entry[2].e_id = 0;
167
168 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
169
170 if (ret != 0) {
171 PLOG(ERROR) << "Failed to set default ACL on " << path;
172 }
173
174 return ret;
175}
176
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100177int SetQuotaInherit(const std::string& path) {
178 unsigned long flags;
179
180 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
181 if (fd == -1) {
182 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
183 return -1;
184 }
185
186 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
187 if (ret == -1) {
188 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
189 return ret;
190 }
191
192 flags |= FS_PROJINHERIT_FL;
193
194 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
195 if (ret == -1) {
196 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
197 return ret;
198 }
199
200 return 0;
201}
202
203int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100204 struct fsxattr fsx;
205
206 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
207 if (fd == -1) {
208 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
209 return -1;
210 }
211
212 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
213 if (ret == -1) {
214 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
215 return ret;
216 }
217
218 fsx.fsx_projid = projectId;
219 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
220}
221
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100222int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
223 long projectId) {
224 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
225
226 if (ret != 0) {
227 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100228 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100229
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100230 if (!IsFilesystemSupported("sdcardfs")) {
231 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100232 }
233
234 return ret;
235}
236
Martijn Coenen816f4d92020-02-18 15:06:37 +0100237static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
238 namespace fs = std::filesystem;
239
240 // Setup the directory itself correctly
241 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
242 if (ret != OK) {
243 return ret;
244 }
245
246 // Fixup all of its file entries
247 for (const auto& itEntry : fs::directory_iterator(path)) {
248 ret = lchown(itEntry.path().c_str(), uid, gid);
249 if (ret != 0) {
250 return ret;
251 }
252
253 ret = chmod(itEntry.path().c_str(), mode);
254 if (ret != 0) {
255 return ret;
256 }
257
258 if (!IsFilesystemSupported("sdcardfs")) {
259 ret = SetQuotaProjectId(itEntry.path(), projectId);
260 if (ret != 0) {
261 return ret;
262 }
263 }
264 }
265
266 return OK;
267}
268
269int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
270 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100271 long projectId;
272 size_t pos;
273 int ret = 0;
274
275 // Make sure the Android/ directories exist and are setup correctly
276 ret = PrepareAndroidDirs(root);
277 if (ret != 0) {
278 LOG(ERROR) << "Failed to prepare Android/ directories.";
279 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100280 }
281
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100282 // Now create the application-specific subdir(s)
283 // path is something like /data/media/0/Android/data/com.foo/files
284 // First, chop off the volume root, eg /data/media/0
285 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100286
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100287 uid_t uid = appUid;
288 gid_t gid = AID_MEDIA_RW;
289 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100290
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100291 // Check that the next part matches one of the allowed Android/ dirs
292 if (StartsWith(pathFromRoot, kAppDataDir)) {
293 appDir = kAppDataDir;
294 if (!IsFilesystemSupported("sdcardfs")) {
295 gid = AID_EXT_DATA_RW;
296 }
297 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
298 appDir = kAppMediaDir;
299 if (!IsFilesystemSupported("sdcardfs")) {
300 gid = AID_MEDIA_RW;
301 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000302 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100303 appDir = kAppObbDir;
304 if (!IsFilesystemSupported("sdcardfs")) {
305 gid = AID_EXT_OBB_RW;
306 }
307 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100308 LOG(ERROR) << "Invalid application directory: " << path;
309 return -EINVAL;
310 }
311
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100312 // mode = 770, plus sticky bit on directory to inherit GID when apps
313 // create subdirs
314 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100315 // the project ID for application-specific directories is directly
316 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100317
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100318 // Chop off the generic application-specific part, eg /Android/data/
319 // this leaves us with something like com.foo/files/
320 std::string leftToCreate = pathFromRoot.substr(appDir.length());
321 if (!EndsWith(leftToCreate, "/")) {
322 leftToCreate += "/";
323 }
324 std::string pathToCreate = root + appDir;
325 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100326 // Derive initial project ID
327 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
328 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
329 } else if (appDir == kAppObbDir) {
330 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
331 }
332
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100333 while ((pos = leftToCreate.find('/')) != std::string::npos) {
334 std::string component = leftToCreate.substr(0, pos + 1);
335 leftToCreate = leftToCreate.erase(0, pos + 1);
336 pathToCreate = pathToCreate + component;
337
338 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
339 // All dirs use the "app" project ID, except for the cache dirs in
340 // Android/data, eg Android/data/com.foo/cache
341 // Note that this "sticks" - eg subdirs of this dir need the same
342 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100343 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100344 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100345
346 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
347 // Fixup all files in this existing directory with the correct UID/GID
348 // and project ID.
349 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
350 } else {
351 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
352 }
353
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100354 if (ret != 0) {
355 return ret;
356 }
357
358 if (depth == 0) {
359 // Set the default ACL on the top-level application-specific directories,
360 // to ensure that even if applications run with a umask of 0077,
361 // new directories within these directories will allow the GID
362 // specified here to write; this is necessary for apps like
363 // installers and MTP, that require access here.
364 //
365 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100366 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100367 if (ret != 0) {
368 return ret;
369 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100370
371 if (!IsFilesystemSupported("sdcardfs")) {
372 // Set project ID inheritance, so that future subdirectories inherit the
373 // same project ID
374 ret = SetQuotaInherit(pathToCreate);
375 if (ret != 0) {
376 return ret;
377 }
378 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100379 }
380
381 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100382 }
383
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100384 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100385}
386
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700387status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600388 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700389 const char* cpath = path.c_str();
390
391 char* secontext = nullptr;
392 if (sehandle) {
393 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
394 setfscreatecon(secontext);
395 }
396 }
397
398 int res = fs_prepare_dir(cpath, mode, uid, gid);
399
400 if (secontext) {
401 setfscreatecon(nullptr);
402 freecon(secontext);
403 }
404
405 if (res == 0) {
406 return OK;
407 } else {
408 return -errno;
409 }
410}
411
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800412status_t ForceUnmount(const std::string& path) {
413 const char* cpath = path.c_str();
414 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
415 return OK;
416 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700417 // Apps might still be handling eject request, so wait before
418 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700419 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700420
Jeff Sharkey3472e522017-10-06 18:02:53 -0600421 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700422 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700423 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
424 return OK;
425 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700426
Jeff Sharkey3472e522017-10-06 18:02:53 -0600427 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700428 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800429 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
430 return OK;
431 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700432
Jeff Sharkey3472e522017-10-06 18:02:53 -0600433 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700434 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700435 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
436 return OK;
437 }
Zim3623a212019-07-19 16:46:53 +0100438 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800439 return -errno;
440}
441
Ricky Wai07e64a42020-02-11 14:31:24 +0000442status_t KillProcessesWithMountPrefix(const std::string& path) {
443 if (KillProcessesWithMounts(path, SIGINT) == 0) {
444 return OK;
445 }
446 if (sSleepOnUnmount) sleep(5);
447
448 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
449 return OK;
450 }
451 if (sSleepOnUnmount) sleep(5);
452
453 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
454 return OK;
455 }
456 if (sSleepOnUnmount) sleep(5);
457
458 // Send SIGKILL a second time to determine if we've
459 // actually killed everyone mount
460 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
461 return OK;
462 }
463 PLOG(ERROR) << "Failed to kill processes using " << path;
464 return -EBUSY;
465}
466
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700467status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600468 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700469 return OK;
470 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700471 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700472
Jeff Sharkey3472e522017-10-06 18:02:53 -0600473 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700474 return OK;
475 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700476 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700477
Jeff Sharkey3472e522017-10-06 18:02:53 -0600478 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700479 return OK;
480 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700481 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700482
483 // Send SIGKILL a second time to determine if we've
484 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600485 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700486 return OK;
487 }
488 PLOG(ERROR) << "Failed to kill processes using " << path;
489 return -EBUSY;
490}
491
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700492status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800493 if (UnmountTree(target) < 0) {
494 return -errno;
495 }
496 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700497 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
498 return -errno;
499 }
500 return OK;
501}
502
Sudheer Shanka023b5392019-02-06 12:39:19 -0800503status_t Symlink(const std::string& target, const std::string& linkpath) {
504 if (Unlink(linkpath) < 0) {
505 return -errno;
506 }
507 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
508 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
509 return -errno;
510 }
511 return OK;
512}
513
514status_t Unlink(const std::string& linkpath) {
515 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
516 PLOG(ERROR) << "Failed to unlink " << linkpath;
517 return -errno;
518 }
519 return OK;
520}
521
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000522status_t CreateDir(const std::string& dir, mode_t mode) {
523 struct stat sb;
524 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
525 if (S_ISDIR(sb.st_mode)) {
526 return OK;
527 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
528 PLOG(ERROR) << "Failed to unlink " << dir;
529 return -errno;
530 }
531 } else if (errno != ENOENT) {
532 PLOG(ERROR) << "Failed to stat " << dir;
533 return -errno;
534 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800535 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000536 PLOG(ERROR) << "Failed to mkdir " << dir;
537 return -errno;
538 }
539 return OK;
540}
541
Jeff Sharkey3472e522017-10-06 18:02:53 -0600542bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
543 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800544 size_t start = 0;
545 while (true) {
546 start = raw.find(qual, start);
547 if (start == std::string::npos) return false;
548 if (start == 0 || raw[start - 1] == ' ') {
549 break;
550 }
551 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600552 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600553 start += qual.length();
554
555 auto end = raw.find("\"", start);
556 if (end == std::string::npos) return false;
557
558 *value = raw.substr(start, end - start);
559 return true;
560}
561
Paul Crowley14c8c072018-09-18 13:30:21 -0700562static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
563 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600564 fsType->clear();
565 fsUuid->clear();
566 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700567
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700568 std::vector<std::string> cmd;
569 cmd.push_back(kBlkidPath);
570 cmd.push_back("-c");
571 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700572 cmd.push_back("-s");
573 cmd.push_back("TYPE");
574 cmd.push_back("-s");
575 cmd.push_back("UUID");
576 cmd.push_back("-s");
577 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700578 cmd.push_back(path);
579
580 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800581 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700582 if (res != OK) {
583 LOG(WARNING) << "blkid failed to identify " << path;
584 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700585 }
586
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700587 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700588 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600589 FindValue(line, "TYPE", fsType);
590 FindValue(line, "UUID", fsUuid);
591 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700592 }
593
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700594 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700595}
596
Paul Crowley14c8c072018-09-18 13:30:21 -0700597status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
598 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700599 return readMetadata(path, fsType, fsUuid, fsLabel, false);
600}
601
Paul Crowley14c8c072018-09-18 13:30:21 -0700602status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
603 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700604 return readMetadata(path, fsType, fsUuid, fsLabel, true);
605}
606
Paul Crowleyde2d6202018-11-30 11:43:47 -0800607static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
608 std::vector<const char*> argv;
609 argv.reserve(args.size() + 1);
610 for (const auto& arg : args) {
611 if (argv.empty()) {
612 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700613 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800614 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700615 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800616 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700617 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800618 argv.emplace_back(nullptr);
619 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700620}
621
Paul Crowleyde2d6202018-11-30 11:43:47 -0800622static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
623 android::base::unique_fd ufd) {
624 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700625 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800626 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700627 return -errno;
628 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800629 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700630 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800631 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700632 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800633 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700634 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800635 return OK;
636}
637
638status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
639 security_context_t context) {
640 auto argv = ConvertToArgv(args);
641
Paul Crowleye6d76632018-11-30 11:43:47 -0800642 android::base::unique_fd pipe_read, pipe_write;
643 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
644 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800645 return -errno;
646 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800647
648 pid_t pid = fork();
649 if (pid == 0) {
650 if (context) {
651 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800652 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800653 abort();
654 }
655 }
656 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800657 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
658 PLOG(ERROR) << "dup2 in ForkExecvp";
659 _exit(EXIT_FAILURE);
660 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800661 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800662 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800663 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800664 _exit(EXIT_FAILURE);
665 }
666 if (pid == -1) {
667 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700668 return -errno;
669 }
670
Paul Crowleyde2d6202018-11-30 11:43:47 -0800671 pipe_write.reset();
672 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
673 if (st != 0) return st;
674
675 int status;
676 if (waitpid(pid, &status, 0) == -1) {
677 PLOG(ERROR) << "waitpid in ForkExecvp";
678 return -errno;
679 }
680 if (!WIFEXITED(status)) {
681 LOG(ERROR) << "Process did not exit normally, status: " << status;
682 return -ECHILD;
683 }
684 if (WEXITSTATUS(status)) {
685 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
686 return WEXITSTATUS(status);
687 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700688 return OK;
689}
690
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700691pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800692 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700693
694 pid_t pid = fork();
695 if (pid == 0) {
696 close(STDIN_FILENO);
697 close(STDOUT_FILENO);
698 close(STDERR_FILENO);
699
Paul Crowleyde2d6202018-11-30 11:43:47 -0800700 execvp(argv[0], const_cast<char**>(argv.data()));
701 PLOG(ERROR) << "exec in ForkExecvpAsync";
702 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700703 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700704 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800705 PLOG(ERROR) << "fork in ForkExecvpAsync";
706 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700707 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700708 return pid;
709}
710
Jeff Sharkey9c484982015-03-31 10:35:33 -0700711status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100712 out.resize(bytes);
713 return ReadRandomBytes(bytes, &out[0]);
714}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700715
Pavel Grafove2e2d302017-08-01 17:15:53 +0100716status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700717 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
718 if (fd == -1) {
719 return -errno;
720 }
721
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800722 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100723 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700724 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100725 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700726 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700727 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700728
729 if (bytes == 0) {
730 return OK;
731 } else {
732 return -EIO;
733 }
734}
735
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600736status_t GenerateRandomUuid(std::string& out) {
737 status_t res = ReadRandomBytes(16, out);
738 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700739 out[6] &= 0x0f; /* clear version */
740 out[6] |= 0x40; /* set to version 4 */
741 out[8] &= 0x3f; /* clear variant */
742 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600743 }
744 return res;
745}
746
Jeff Sharkey9c484982015-03-31 10:35:33 -0700747status_t HexToStr(const std::string& hex, std::string& str) {
748 str.clear();
749 bool even = true;
750 char cur = 0;
751 for (size_t i = 0; i < hex.size(); i++) {
752 int val = 0;
753 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700754 // clang-format off
755 case ' ': case '-': case ':': continue;
756 case 'f': case 'F': val = 15; break;
757 case 'e': case 'E': val = 14; break;
758 case 'd': case 'D': val = 13; break;
759 case 'c': case 'C': val = 12; break;
760 case 'b': case 'B': val = 11; break;
761 case 'a': case 'A': val = 10; break;
762 case '9': val = 9; break;
763 case '8': val = 8; break;
764 case '7': val = 7; break;
765 case '6': val = 6; break;
766 case '5': val = 5; break;
767 case '4': val = 4; break;
768 case '3': val = 3; break;
769 case '2': val = 2; break;
770 case '1': val = 1; break;
771 case '0': val = 0; break;
772 default: return -EINVAL;
773 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700774 }
775
776 if (even) {
777 cur = val << 4;
778 } else {
779 cur += val;
780 str.push_back(cur);
781 cur = 0;
782 }
783 even = !even;
784 }
785 return even ? OK : -EINVAL;
786}
787
788static const char* kLookup = "0123456789abcdef";
789
790status_t StrToHex(const std::string& str, std::string& hex) {
791 hex.clear();
792 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700793 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700794 hex.push_back(kLookup[str[i] & 0x0F]);
795 }
796 return OK;
797}
798
Pavel Grafove2e2d302017-08-01 17:15:53 +0100799status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
800 hex.clear();
801 for (size_t i = 0; i < str.size(); i++) {
802 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
803 hex.push_back(kLookup[str.data()[i] & 0x0F]);
804 }
805 return OK;
806}
807
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700808status_t NormalizeHex(const std::string& in, std::string& out) {
809 std::string tmp;
810 if (HexToStr(in, tmp)) {
811 return -EINVAL;
812 }
813 return StrToHex(tmp, out);
814}
815
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200816status_t GetBlockDevSize(int fd, uint64_t* size) {
817 if (ioctl(fd, BLKGETSIZE64, size)) {
818 return -errno;
819 }
820
821 return OK;
822}
823
824status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
825 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
826 status_t res = OK;
827
828 if (fd < 0) {
829 return -errno;
830 }
831
832 res = GetBlockDevSize(fd, size);
833
834 close(fd);
835
836 return res;
837}
838
839status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
840 uint64_t size;
841 status_t res = GetBlockDevSize(path, &size);
842
843 if (res != OK) {
844 return res;
845 }
846
847 *nr_sec = size / 512;
848
849 return OK;
850}
851
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700852uint64_t GetFreeBytes(const std::string& path) {
853 struct statvfs sb;
854 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700855 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700856 } else {
857 return -1;
858 }
859}
860
861// TODO: borrowed from frameworks/native/libs/diskusage/ which should
862// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700863static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700864 int64_t blksize = s->st_blksize;
865 // count actual blocks used instead of nominal file size
866 int64_t size = s->st_blocks * 512;
867
868 if (blksize) {
869 /* round up to filesystem block size */
870 size = (size + blksize - 1) & (~(blksize - 1));
871 }
872
873 return size;
874}
875
876// TODO: borrowed from frameworks/native/libs/diskusage/ which should
877// eventually be migrated into system/
878int64_t calculate_dir_size(int dfd) {
879 int64_t size = 0;
880 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700881 DIR* d;
882 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700883
884 d = fdopendir(dfd);
885 if (d == NULL) {
886 close(dfd);
887 return 0;
888 }
889
890 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700891 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700892 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
893 size += stat_size(&s);
894 }
895 if (de->d_type == DT_DIR) {
896 int subfd;
897
898 /* always skip "." and ".." */
899 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700900 if (name[1] == 0) continue;
901 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700902 }
903
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600904 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700905 if (subfd >= 0) {
906 size += calculate_dir_size(subfd);
907 }
908 }
909 }
910 closedir(d);
911 return size;
912}
913
914uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600915 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700916 if (dirfd < 0) {
917 PLOG(WARNING) << "Failed to open " << path;
918 return -1;
919 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700920 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700921 }
922}
923
Ricky Wai07e64a42020-02-11 14:31:24 +0000924// TODO: Use a better way to determine if it's media provider app.
925bool IsFuseDaemon(const pid_t pid) {
926 auto path = StringPrintf("/proc/%d/mounts", pid);
927 char* tmp;
928 if (lgetfilecon(path.c_str(), &tmp) < 0) {
929 return false;
930 }
931 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
932 || android::base::StartsWith(tmp, kMediaProviderCtx);
933 freecon(tmp);
934 return result;
935}
936
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700937bool IsFilesystemSupported(const std::string& fsType) {
938 std::string supported;
939 if (!ReadFileToString(kProcFilesystems, &supported)) {
940 PLOG(ERROR) << "Failed to read supported filesystems";
941 return false;
942 }
943 return supported.find(fsType + "\n") != std::string::npos;
944}
945
946status_t WipeBlockDevice(const std::string& path) {
947 status_t res = -1;
948 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200949 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700950
951 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
952 if (fd == -1) {
953 PLOG(ERROR) << "Failed to open " << path;
954 goto done;
955 }
956
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200957 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700958 PLOG(ERROR) << "Failed to determine size of " << path;
959 goto done;
960 }
961
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700962 LOG(INFO) << "About to discard " << range[1] << " on " << path;
963 if (ioctl(fd, BLKDISCARD, &range) == 0) {
964 LOG(INFO) << "Discard success on " << path;
965 res = 0;
966 } else {
967 PLOG(ERROR) << "Discard failure on " << path;
968 }
969
970done:
971 close(fd);
972 return res;
973}
974
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800975static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700976 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800977 return false;
978 } else {
979 return true;
980 }
981}
982
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700983std::string BuildKeyPath(const std::string& partGuid) {
984 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
985}
986
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600987std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700988 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600989}
990
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800991std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700992 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700993}
994
995std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700996 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700997}
998
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600999std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001000 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001001}
1002
Jeff Sharkey47695b22016-02-01 17:02:29 -07001003std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001004 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001005}
1006
1007std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001008 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001009}
1010
Calin Juravle79f55a42016-02-17 20:14:46 +00001011// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1012std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001013 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001014}
1015
Andreas Huber71cd43f2018-01-22 11:25:29 -08001016std::string BuildDataVendorCePath(userid_t userId) {
1017 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1018}
1019
1020std::string BuildDataVendorDePath(userid_t userId) {
1021 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1022}
1023
Paul Crowley3b71fc52017-10-09 10:55:21 -07001024std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001025 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001026 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001027 return "/data";
1028 } else {
1029 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001030 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001031 }
1032}
1033
Paul Crowley3b71fc52017-10-09 10:55:21 -07001034std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001035 // TODO: unify with installd path generation logic
1036 std::string data(BuildDataPath(volumeUuid));
1037 return StringPrintf("%s/media/%u", data.c_str(), userId);
1038}
1039
Paul Crowley3b71fc52017-10-09 10:55:21 -07001040std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001041 // TODO: unify with installd path generation logic
1042 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001043 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001044 std::string legacy = StringPrintf("%s/data", data.c_str());
1045 struct stat sb;
1046 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1047 /* /data/data is dir, return /data/data for legacy system */
1048 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001049 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001050 }
cjbaoeb501142017-04-12 00:09:00 +08001051 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001052}
1053
Paul Crowley3b71fc52017-10-09 10:55:21 -07001054std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001055 // TODO: unify with installd path generation logic
1056 std::string data(BuildDataPath(volumeUuid));
1057 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1058}
1059
Jeff Sharkey66270a22015-06-24 11:49:24 -07001060dev_t GetDevice(const std::string& path) {
1061 struct stat sb;
1062 if (stat(path.c_str(), &sb)) {
1063 PLOG(WARNING) << "Failed to stat " << path;
1064 return 0;
1065 } else {
1066 return sb.st_dev;
1067 }
1068}
1069
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001070status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001071 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001072
Tom Cherryd6127ef2017-06-15 17:13:56 -07001073 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001074
Tom Cherryd6127ef2017-06-15 17:13:56 -07001075 android::base::SetProperty(kRestoreconString, "");
1076 android::base::SetProperty(kRestoreconString, path);
1077
1078 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001079
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001080 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001081 return OK;
1082}
1083
Jeff Sharkey3472e522017-10-06 18:02:53 -06001084bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1085 // Shamelessly borrowed from android::base::Readlink()
1086 result->clear();
1087
1088 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1089 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1090 // waste memory to just start there. We add 1 so that we can recognize
1091 // whether it actually fit (rather than being truncated to 4095).
1092 std::vector<char> buf(4095 + 1);
1093 while (true) {
1094 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1095 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001096 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001097 // It fit! (If size == buf.size(), it may have been truncated.)
1098 if (static_cast<size_t>(size) < buf.size()) {
1099 result->assign(&buf[0], size);
1100 return true;
1101 }
1102 // Double our buffer and try again.
1103 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001104 }
1105}
1106
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001107static unsigned int GetMajorBlockVirtioBlk() {
1108 std::string devices;
1109 if (!ReadFileToString(kProcDevices, &devices)) {
1110 PLOG(ERROR) << "Unable to open /proc/devices";
1111 return 0;
1112 }
1113
1114 bool blockSection = false;
1115 for (auto line : android::base::Split(devices, "\n")) {
1116 if (line == "Block devices:") {
1117 blockSection = true;
1118 } else if (line == "Character devices:") {
1119 blockSection = false;
1120 } else if (blockSection) {
1121 auto tokens = android::base::Split(line, " ");
1122 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1123 return std::stoul(tokens[0]);
1124 }
1125 }
1126 }
1127
1128 return 0;
1129}
1130
1131bool IsVirtioBlkDevice(unsigned int major) {
1132 // Most virtualized platforms expose block devices with the virtio-blk
1133 // block device driver. Unfortunately, this driver does not use a fixed
1134 // major number, but relies on the kernel to assign one from a specific
1135 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1136 // per Documentation/devices.txt. This is true even for the latest Linux
1137 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1138 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1139 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001140}
1141
Sudheer Shanka295fb242019-01-16 23:04:07 -08001142static status_t findMountPointsWithPrefix(const std::string& prefix,
1143 std::list<std::string>& mountPoints) {
1144 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1145 // when the prefix is /foo/bar
1146 std::string prefixWithSlash(prefix);
1147 if (prefix.back() != '/') {
1148 android::base::StringAppendF(&prefixWithSlash, "/");
1149 }
1150
1151 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1152 if (!mnts) {
1153 PLOG(ERROR) << "Unable to open /proc/mounts";
1154 return -errno;
1155 }
1156
1157 // Some volumes can be stacked on each other, so force unmount in
1158 // reverse order to give us the best chance of success.
1159 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1160 while ((mnt = getmntent(mnts.get())) != nullptr) {
1161 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1162 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1163 mountPoints.push_front(mountPoint);
1164 }
1165 }
1166 return OK;
1167}
1168
1169// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1170status_t UnmountTreeWithPrefix(const std::string& prefix) {
1171 std::list<std::string> toUnmount;
1172 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1173 if (result < 0) {
1174 return result;
1175 }
1176 for (const auto& path : toUnmount) {
1177 if (umount2(path.c_str(), MNT_DETACH)) {
1178 PLOG(ERROR) << "Failed to unmount " << path;
1179 result = -errno;
1180 }
1181 }
1182 return result;
1183}
1184
1185status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001186 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1187 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001188 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001189 return -errno;
1190 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001191 return OK;
1192}
1193
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001194static status_t delete_dir_contents(DIR* dir) {
1195 // Shamelessly borrowed from android::installd
1196 int dfd = dirfd(dir);
1197 if (dfd < 0) {
1198 return -errno;
1199 }
1200
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001201 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001202 struct dirent* de;
1203 while ((de = readdir(dir))) {
1204 const char* name = de->d_name;
1205 if (de->d_type == DT_DIR) {
1206 /* always skip "." and ".." */
1207 if (name[0] == '.') {
1208 if (name[1] == 0) continue;
1209 if ((name[1] == '.') && (name[2] == 0)) continue;
1210 }
1211
1212 android::base::unique_fd subfd(
1213 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1214 if (subfd.get() == -1) {
1215 PLOG(ERROR) << "Couldn't openat " << name;
1216 result = -errno;
1217 continue;
1218 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001219 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1220 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001221 if (!subdirp) {
1222 PLOG(ERROR) << "Couldn't fdopendir " << name;
1223 result = -errno;
1224 continue;
1225 }
1226 result = delete_dir_contents(subdirp.get());
1227 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1228 PLOG(ERROR) << "Couldn't unlinkat " << name;
1229 result = -errno;
1230 }
1231 } else {
1232 if (unlinkat(dfd, name, 0) < 0) {
1233 PLOG(ERROR) << "Couldn't unlinkat " << name;
1234 result = -errno;
1235 }
1236 }
1237 }
1238 return result;
1239}
1240
1241status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001242 status_t res = DeleteDirContents(pathname);
1243 if (res < 0) {
1244 return res;
1245 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001246 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001247 PLOG(ERROR) << "rmdir failed on " << pathname;
1248 return -errno;
1249 }
1250 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1251 return OK;
1252}
1253
1254status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001255 // Shamelessly borrowed from android::installd
1256 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1257 if (!dirp) {
1258 if (errno == ENOENT) {
1259 return OK;
1260 }
1261 PLOG(ERROR) << "Failed to opendir " << pathname;
1262 return -errno;
1263 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001264 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001265}
1266
Paul Crowley298fa322018-10-30 15:59:24 -07001267// TODO(118708649): fix duplication with init/util.h
1268status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1269 android::base::Timer t;
1270 while (t.duration() < timeout) {
1271 struct stat sb;
1272 if (stat(filename, &sb) != -1) {
1273 LOG(INFO) << "wait for '" << filename << "' took " << t;
1274 return 0;
1275 }
1276 std::this_thread::sleep_for(10ms);
1277 }
1278 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1279 return -1;
1280}
1281
Paul Crowley621d9b92018-12-07 15:36:09 -08001282bool FsyncDirectory(const std::string& dirname) {
1283 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1284 if (fd == -1) {
1285 PLOG(ERROR) << "Failed to open " << dirname;
1286 return false;
1287 }
1288 if (fsync(fd) == -1) {
1289 if (errno == EROFS || errno == EINVAL) {
1290 PLOG(WARNING) << "Skip fsync " << dirname
1291 << " on a file system does not support synchronization";
1292 } else {
1293 PLOG(ERROR) << "Failed to fsync " << dirname;
1294 return false;
1295 }
1296 }
1297 return true;
1298}
1299
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001300bool writeStringToFile(const std::string& payload, const std::string& filename) {
1301 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1302 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1303 if (fd == -1) {
1304 PLOG(ERROR) << "Failed to open " << filename;
1305 return false;
1306 }
1307 if (!android::base::WriteStringToFd(payload, fd)) {
1308 PLOG(ERROR) << "Failed to write to " << filename;
1309 unlink(filename.c_str());
1310 return false;
1311 }
1312 // fsync as close won't guarantee flush data
1313 // see close(2), fsync(2) and b/68901441
1314 if (fsync(fd) == -1) {
1315 if (errno == EROFS || errno == EINVAL) {
1316 PLOG(WARNING) << "Skip fsync " << filename
1317 << " on a file system does not support synchronization";
1318 } else {
1319 PLOG(ERROR) << "Failed to fsync " << filename;
1320 unlink(filename.c_str());
1321 return false;
1322 }
1323 }
1324 return true;
1325}
1326
Ricky Wai07e64a42020-02-11 14:31:24 +00001327status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1328 if (access(path.c_str(), F_OK) != 0) {
1329 PLOG(WARNING) << "Dir does not exist: " << path;
1330 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1331 return -errno;
1332 }
1333 }
1334 return OK;
1335}
1336
Zima438b242019-09-25 14:37:38 +01001337status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1338 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1339 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1340 std::string fuse_path(
1341 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1342
1343 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1344 std::string pass_through_path(
1345 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001346
Zim1242be82020-01-22 18:22:29 +00001347 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1348 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001349 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001350 if (result != android::OK) {
1351 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1352 return -1;
1353 }
1354
Zim06b0caf2020-01-05 02:11:47 +00001355 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1356 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1357 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1358 // These bits should be consistent with what is set in zygote in
1359 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001360 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001361 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001362 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001363 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001364 return -1;
1365 }
1366
Zima438b242019-09-25 14:37:38 +01001367 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1368 if (result != android::OK) {
1369 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1370 return -1;
1371 }
1372
Zim26eec702020-01-31 16:00:58 +00001373 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001374 if (result != android::OK) {
1375 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1376 return -1;
1377 }
1378
Zim26eec702020-01-31 16:00:58 +00001379 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001380 if (result != android::OK) {
1381 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1382 return -1;
1383 }
1384
1385 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001386 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1387 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001388 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001389 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001390 return -1;
1391 }
Zime5393d42019-11-15 11:44:12 +00001392 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001393 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001394
1395 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001396 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001397 if (result != android::OK) {
1398 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1399 return -1;
1400 }
1401 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001402 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001403 }
1404
Nandana Dutta914cc72019-08-29 15:22:42 +01001405 // Open fuse fd.
1406 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1407 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001408 PLOG(ERROR) << "Failed to open /dev/fuse";
1409 return -1;
1410 }
1411
1412 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1413 // permission checks before routing to FUSE daemon.
1414 const auto opts = StringPrintf(
1415 "fd=%i,"
1416 "rootmode=40000,"
1417 "allow_other,"
1418 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001419 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001420
Zima438b242019-09-25 14:37:38 +01001421 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1422 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1423 opts.c_str()));
1424 if (result != 0) {
1425 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001426 return -errno;
1427 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001428
Martijn Coenen86f21a22020-01-06 09:48:14 +01001429 if (IsFilesystemSupported("sdcardfs")) {
1430 std::string sdcardfs_path(
1431 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1432
1433 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1434 return BindMount(sdcardfs_path, pass_through_path);
1435 } else {
1436 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1437 return BindMount(absolute_lower_path, pass_through_path);
1438 }
Zima438b242019-09-25 14:37:38 +01001439}
1440
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001441status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1442 const std::string& relative_upper_path) {
1443 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1444 std::string pass_through_path(
1445 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1446
Zima438b242019-09-25 14:37:38 +01001447 // Best effort unmount pass_through path
1448 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001449 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1450 auto status = ForceUnmount(pass_through_path);
1451 if (status != android::OK) {
1452 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1453 }
Martijn Coenen57002612019-11-28 11:56:13 +01001454 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001455
1456 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001457 android::status_t result = ForceUnmount(fuse_path);
1458 sSleepOnUnmount = true;
1459 if (result != android::OK) {
1460 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1461 // Figure out why we get EBUSY and remove this special casing if possible.
1462 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1463 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1464 errno != ENOENT) {
1465 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1466 return -errno;
1467 }
Martijn Coenen57002612019-11-28 11:56:13 +01001468 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001469 }
Martijn Coenen57002612019-11-28 11:56:13 +01001470 rmdir(fuse_path.c_str());
1471
Zima438b242019-09-25 14:37:38 +01001472 return result;
Zim3623a212019-07-19 16:46:53 +01001473}
1474
Martijn Coenen62a4b272020-01-31 15:23:09 +01001475status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1476 std::string androidDir = volumeRoot + kAndroidDir;
1477 std::string androidDataDir = volumeRoot + kAppDataDir;
1478 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001479 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001480
1481 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1482
Martijn Coenen10570c02020-02-18 10:41:37 +01001483 // mode 0771 + sticky bit for inheriting GIDs
1484 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1485 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001486 PLOG(ERROR) << "Failed to create " << androidDir;
1487 return -errno;
1488 }
1489
1490 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001491 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001492 PLOG(ERROR) << "Failed to create " << androidDataDir;
1493 return -errno;
1494 }
1495
1496 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001497 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001498 PLOG(ERROR) << "Failed to create " << androidObbDir;
1499 return -errno;
1500 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001501 // Some other apps, like installers, have write access to the OBB directory
1502 // to pre-download them. To make sure newly created folders in this directory
1503 // have the right permissions, set a default ACL.
1504 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001505
Martijn Coenen10570c02020-02-18 10:41:37 +01001506 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001507 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1508 return -errno;
1509 }
1510
Martijn Coenen62a4b272020-01-31 15:23:09 +01001511 return OK;
1512}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001513} // namespace vold
1514} // namespace android