blob: 82ad1f120ca0e57aee214a3f1aeb608cc829fc4d [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
Ricky Wai07e64a42020-02-11 14:31:24 +000087static const char* kMediaProviderCtx = "u:r:mediaprovider:";
88static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
89
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060090// Lock used to protect process-level SELinux changes from racing with each
91// other between multiple threads.
92static std::mutex kSecurityLock;
93
Jeff Sharkeydeb24052015-03-02 21:01:40 -080094status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060095 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080096 const char* cpath = path.c_str();
97 status_t res = 0;
98
99 char* secontext = nullptr;
100 if (sehandle) {
101 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
102 setfscreatecon(secontext);
103 }
104 }
105
106 mode_t mode = 0660 | S_IFBLK;
107 if (mknod(cpath, mode, dev) < 0) {
108 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700109 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
110 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800111 res = -errno;
112 }
113 }
114
115 if (secontext) {
116 setfscreatecon(nullptr);
117 freecon(secontext);
118 }
119
120 return res;
121}
122
123status_t DestroyDeviceNode(const std::string& path) {
124 const char* cpath = path.c_str();
125 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
126 return -errno;
127 } else {
128 return OK;
129 }
130}
131
Martijn Coenen442bb832020-02-18 13:44:59 +0100132// Sets a default ACL on the directory.
133int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100134 if (IsFilesystemSupported("sdcardfs")) {
135 // sdcardfs magically takes care of this
136 return OK;
137 }
138
139 static constexpr size_t size =
140 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
141 auto buf = std::make_unique<uint8_t[]>(size);
142
143 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
144 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
145
146 posix_acl_xattr_entry* entry =
147 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
148
149 entry[0].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100150 // The existing mode_t mask has the ACL in the lower 9 bits:
151 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
152 // Use the mode_t masks to get these bits out, and shift them to get the
153 // correct value per entity.
154 //
155 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
156 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100157 entry[0].e_id = uid;
158
159 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100160 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100161 entry[1].e_id = gid;
162
163 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100164 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100165 entry[2].e_id = 0;
166
167 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
168
169 if (ret != 0) {
170 PLOG(ERROR) << "Failed to set default ACL on " << path;
171 }
172
173 return ret;
174}
175
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100176int SetQuotaInherit(const std::string& path) {
177 unsigned long flags;
178
179 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
180 if (fd == -1) {
181 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
182 return -1;
183 }
184
185 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
186 if (ret == -1) {
187 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
188 return ret;
189 }
190
191 flags |= FS_PROJINHERIT_FL;
192
193 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
194 if (ret == -1) {
195 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
196 return ret;
197 }
198
199 return 0;
200}
201
202int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100203 struct fsxattr fsx;
204
205 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
206 if (fd == -1) {
207 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
208 return -1;
209 }
210
211 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
212 if (ret == -1) {
213 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
214 return ret;
215 }
216
217 fsx.fsx_projid = projectId;
218 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
219}
220
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100221int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
222 long projectId) {
223 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
224
225 if (ret != 0) {
226 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100227 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100228
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100229 if (!IsFilesystemSupported("sdcardfs")) {
230 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100231 }
232
233 return ret;
234}
235
Martijn Coenen816f4d92020-02-18 15:06:37 +0100236static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
237 namespace fs = std::filesystem;
238
239 // Setup the directory itself correctly
240 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
241 if (ret != OK) {
242 return ret;
243 }
244
245 // Fixup all of its file entries
246 for (const auto& itEntry : fs::directory_iterator(path)) {
247 ret = lchown(itEntry.path().c_str(), uid, gid);
248 if (ret != 0) {
249 return ret;
250 }
251
252 ret = chmod(itEntry.path().c_str(), mode);
253 if (ret != 0) {
254 return ret;
255 }
256
257 if (!IsFilesystemSupported("sdcardfs")) {
258 ret = SetQuotaProjectId(itEntry.path(), projectId);
259 if (ret != 0) {
260 return ret;
261 }
262 }
263 }
264
265 return OK;
266}
267
268int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
269 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100270 long projectId;
271 size_t pos;
272 int ret = 0;
273
274 // Make sure the Android/ directories exist and are setup correctly
275 ret = PrepareAndroidDirs(root);
276 if (ret != 0) {
277 LOG(ERROR) << "Failed to prepare Android/ directories.";
278 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100279 }
280
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100281 // Now create the application-specific subdir(s)
282 // path is something like /data/media/0/Android/data/com.foo/files
283 // First, chop off the volume root, eg /data/media/0
284 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100285
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100286 uid_t uid = appUid;
287 gid_t gid = AID_MEDIA_RW;
288 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100289
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100290 // Check that the next part matches one of the allowed Android/ dirs
291 if (StartsWith(pathFromRoot, kAppDataDir)) {
292 appDir = kAppDataDir;
293 if (!IsFilesystemSupported("sdcardfs")) {
294 gid = AID_EXT_DATA_RW;
295 }
296 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
297 appDir = kAppMediaDir;
298 if (!IsFilesystemSupported("sdcardfs")) {
299 gid = AID_MEDIA_RW;
300 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000301 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100302 appDir = kAppObbDir;
303 if (!IsFilesystemSupported("sdcardfs")) {
304 gid = AID_EXT_OBB_RW;
305 }
306 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100307 LOG(ERROR) << "Invalid application directory: " << path;
308 return -EINVAL;
309 }
310
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100311 // mode = 770, plus sticky bit on directory to inherit GID when apps
312 // create subdirs
313 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100314 // the project ID for application-specific directories is directly
315 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100316
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100317 // Chop off the generic application-specific part, eg /Android/data/
318 // this leaves us with something like com.foo/files/
319 std::string leftToCreate = pathFromRoot.substr(appDir.length());
320 if (!EndsWith(leftToCreate, "/")) {
321 leftToCreate += "/";
322 }
323 std::string pathToCreate = root + appDir;
324 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100325 // Derive initial project ID
326 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
327 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
328 } else if (appDir == kAppObbDir) {
329 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
330 }
331
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100332 while ((pos = leftToCreate.find('/')) != std::string::npos) {
333 std::string component = leftToCreate.substr(0, pos + 1);
334 leftToCreate = leftToCreate.erase(0, pos + 1);
335 pathToCreate = pathToCreate + component;
336
337 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
338 // All dirs use the "app" project ID, except for the cache dirs in
339 // Android/data, eg Android/data/com.foo/cache
340 // Note that this "sticks" - eg subdirs of this dir need the same
341 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100342 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100343 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100344
345 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
346 // Fixup all files in this existing directory with the correct UID/GID
347 // and project ID.
348 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
349 } else {
350 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
351 }
352
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100353 if (ret != 0) {
354 return ret;
355 }
356
357 if (depth == 0) {
358 // Set the default ACL on the top-level application-specific directories,
359 // to ensure that even if applications run with a umask of 0077,
360 // new directories within these directories will allow the GID
361 // specified here to write; this is necessary for apps like
362 // installers and MTP, that require access here.
363 //
364 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100365 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100366 if (ret != 0) {
367 return ret;
368 }
369 }
370
371 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100372 }
373
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100374 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100375}
376
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700377status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600378 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700379 const char* cpath = path.c_str();
380
381 char* secontext = nullptr;
382 if (sehandle) {
383 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
384 setfscreatecon(secontext);
385 }
386 }
387
388 int res = fs_prepare_dir(cpath, mode, uid, gid);
389
390 if (secontext) {
391 setfscreatecon(nullptr);
392 freecon(secontext);
393 }
394
395 if (res == 0) {
396 return OK;
397 } else {
398 return -errno;
399 }
400}
401
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800402status_t ForceUnmount(const std::string& path) {
403 const char* cpath = path.c_str();
404 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
405 return OK;
406 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700407 // Apps might still be handling eject request, so wait before
408 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700409 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700410
Jeff Sharkey3472e522017-10-06 18:02:53 -0600411 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700412 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700413 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
414 return OK;
415 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700416
Jeff Sharkey3472e522017-10-06 18:02:53 -0600417 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700418 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800419 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
420 return OK;
421 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700422
Jeff Sharkey3472e522017-10-06 18:02:53 -0600423 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700424 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700425 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
426 return OK;
427 }
Zim3623a212019-07-19 16:46:53 +0100428 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800429 return -errno;
430}
431
Ricky Wai07e64a42020-02-11 14:31:24 +0000432status_t KillProcessesWithMountPrefix(const std::string& path) {
433 if (KillProcessesWithMounts(path, SIGINT) == 0) {
434 return OK;
435 }
436 if (sSleepOnUnmount) sleep(5);
437
438 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
439 return OK;
440 }
441 if (sSleepOnUnmount) sleep(5);
442
443 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
444 return OK;
445 }
446 if (sSleepOnUnmount) sleep(5);
447
448 // Send SIGKILL a second time to determine if we've
449 // actually killed everyone mount
450 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
451 return OK;
452 }
453 PLOG(ERROR) << "Failed to kill processes using " << path;
454 return -EBUSY;
455}
456
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700457status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600458 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700459 return OK;
460 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700461 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700462
Jeff Sharkey3472e522017-10-06 18:02:53 -0600463 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700464 return OK;
465 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700466 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700467
Jeff Sharkey3472e522017-10-06 18:02:53 -0600468 if (KillProcessesWithOpenFiles(path, SIGKILL) == 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
473 // Send SIGKILL a second time to determine if we've
474 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600475 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700476 return OK;
477 }
478 PLOG(ERROR) << "Failed to kill processes using " << path;
479 return -EBUSY;
480}
481
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700482status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800483 if (UnmountTree(target) < 0) {
484 return -errno;
485 }
486 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700487 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
488 return -errno;
489 }
490 return OK;
491}
492
Sudheer Shanka023b5392019-02-06 12:39:19 -0800493status_t Symlink(const std::string& target, const std::string& linkpath) {
494 if (Unlink(linkpath) < 0) {
495 return -errno;
496 }
497 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
498 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
499 return -errno;
500 }
501 return OK;
502}
503
504status_t Unlink(const std::string& linkpath) {
505 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
506 PLOG(ERROR) << "Failed to unlink " << linkpath;
507 return -errno;
508 }
509 return OK;
510}
511
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000512status_t CreateDir(const std::string& dir, mode_t mode) {
513 struct stat sb;
514 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
515 if (S_ISDIR(sb.st_mode)) {
516 return OK;
517 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
518 PLOG(ERROR) << "Failed to unlink " << dir;
519 return -errno;
520 }
521 } else if (errno != ENOENT) {
522 PLOG(ERROR) << "Failed to stat " << dir;
523 return -errno;
524 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800525 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000526 PLOG(ERROR) << "Failed to mkdir " << dir;
527 return -errno;
528 }
529 return OK;
530}
531
Jeff Sharkey3472e522017-10-06 18:02:53 -0600532bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
533 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800534 size_t start = 0;
535 while (true) {
536 start = raw.find(qual, start);
537 if (start == std::string::npos) return false;
538 if (start == 0 || raw[start - 1] == ' ') {
539 break;
540 }
541 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600542 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600543 start += qual.length();
544
545 auto end = raw.find("\"", start);
546 if (end == std::string::npos) return false;
547
548 *value = raw.substr(start, end - start);
549 return true;
550}
551
Paul Crowley14c8c072018-09-18 13:30:21 -0700552static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
553 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600554 fsType->clear();
555 fsUuid->clear();
556 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700557
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700558 std::vector<std::string> cmd;
559 cmd.push_back(kBlkidPath);
560 cmd.push_back("-c");
561 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700562 cmd.push_back("-s");
563 cmd.push_back("TYPE");
564 cmd.push_back("-s");
565 cmd.push_back("UUID");
566 cmd.push_back("-s");
567 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700568 cmd.push_back(path);
569
570 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800571 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700572 if (res != OK) {
573 LOG(WARNING) << "blkid failed to identify " << path;
574 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700575 }
576
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700577 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700578 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600579 FindValue(line, "TYPE", fsType);
580 FindValue(line, "UUID", fsUuid);
581 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700582 }
583
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700584 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700585}
586
Paul Crowley14c8c072018-09-18 13:30:21 -0700587status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
588 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700589 return readMetadata(path, fsType, fsUuid, fsLabel, false);
590}
591
Paul Crowley14c8c072018-09-18 13:30:21 -0700592status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
593 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700594 return readMetadata(path, fsType, fsUuid, fsLabel, true);
595}
596
Paul Crowleyde2d6202018-11-30 11:43:47 -0800597static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
598 std::vector<const char*> argv;
599 argv.reserve(args.size() + 1);
600 for (const auto& arg : args) {
601 if (argv.empty()) {
602 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700603 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800604 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700605 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800606 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700607 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800608 argv.emplace_back(nullptr);
609 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700610}
611
Paul Crowleyde2d6202018-11-30 11:43:47 -0800612static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
613 android::base::unique_fd ufd) {
614 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700615 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800616 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700617 return -errno;
618 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800619 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700620 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800621 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700622 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800623 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700624 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800625 return OK;
626}
627
628status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
629 security_context_t context) {
630 auto argv = ConvertToArgv(args);
631
Paul Crowleye6d76632018-11-30 11:43:47 -0800632 android::base::unique_fd pipe_read, pipe_write;
633 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
634 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800635 return -errno;
636 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800637
638 pid_t pid = fork();
639 if (pid == 0) {
640 if (context) {
641 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800642 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800643 abort();
644 }
645 }
646 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800647 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
648 PLOG(ERROR) << "dup2 in ForkExecvp";
649 _exit(EXIT_FAILURE);
650 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800651 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800652 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800653 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800654 _exit(EXIT_FAILURE);
655 }
656 if (pid == -1) {
657 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700658 return -errno;
659 }
660
Paul Crowleyde2d6202018-11-30 11:43:47 -0800661 pipe_write.reset();
662 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
663 if (st != 0) return st;
664
665 int status;
666 if (waitpid(pid, &status, 0) == -1) {
667 PLOG(ERROR) << "waitpid in ForkExecvp";
668 return -errno;
669 }
670 if (!WIFEXITED(status)) {
671 LOG(ERROR) << "Process did not exit normally, status: " << status;
672 return -ECHILD;
673 }
674 if (WEXITSTATUS(status)) {
675 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
676 return WEXITSTATUS(status);
677 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700678 return OK;
679}
680
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700681pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800682 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700683
684 pid_t pid = fork();
685 if (pid == 0) {
686 close(STDIN_FILENO);
687 close(STDOUT_FILENO);
688 close(STDERR_FILENO);
689
Paul Crowleyde2d6202018-11-30 11:43:47 -0800690 execvp(argv[0], const_cast<char**>(argv.data()));
691 PLOG(ERROR) << "exec in ForkExecvpAsync";
692 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700693 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700694 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800695 PLOG(ERROR) << "fork in ForkExecvpAsync";
696 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700697 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700698 return pid;
699}
700
Jeff Sharkey9c484982015-03-31 10:35:33 -0700701status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100702 out.resize(bytes);
703 return ReadRandomBytes(bytes, &out[0]);
704}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700705
Pavel Grafove2e2d302017-08-01 17:15:53 +0100706status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700707 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
708 if (fd == -1) {
709 return -errno;
710 }
711
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800712 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100713 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700714 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100715 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700716 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700717 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700718
719 if (bytes == 0) {
720 return OK;
721 } else {
722 return -EIO;
723 }
724}
725
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600726status_t GenerateRandomUuid(std::string& out) {
727 status_t res = ReadRandomBytes(16, out);
728 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700729 out[6] &= 0x0f; /* clear version */
730 out[6] |= 0x40; /* set to version 4 */
731 out[8] &= 0x3f; /* clear variant */
732 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600733 }
734 return res;
735}
736
Jeff Sharkey9c484982015-03-31 10:35:33 -0700737status_t HexToStr(const std::string& hex, std::string& str) {
738 str.clear();
739 bool even = true;
740 char cur = 0;
741 for (size_t i = 0; i < hex.size(); i++) {
742 int val = 0;
743 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700744 // clang-format off
745 case ' ': case '-': case ':': continue;
746 case 'f': case 'F': val = 15; break;
747 case 'e': case 'E': val = 14; break;
748 case 'd': case 'D': val = 13; break;
749 case 'c': case 'C': val = 12; break;
750 case 'b': case 'B': val = 11; break;
751 case 'a': case 'A': val = 10; break;
752 case '9': val = 9; break;
753 case '8': val = 8; break;
754 case '7': val = 7; break;
755 case '6': val = 6; break;
756 case '5': val = 5; break;
757 case '4': val = 4; break;
758 case '3': val = 3; break;
759 case '2': val = 2; break;
760 case '1': val = 1; break;
761 case '0': val = 0; break;
762 default: return -EINVAL;
763 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700764 }
765
766 if (even) {
767 cur = val << 4;
768 } else {
769 cur += val;
770 str.push_back(cur);
771 cur = 0;
772 }
773 even = !even;
774 }
775 return even ? OK : -EINVAL;
776}
777
778static const char* kLookup = "0123456789abcdef";
779
780status_t StrToHex(const std::string& str, std::string& hex) {
781 hex.clear();
782 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700783 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700784 hex.push_back(kLookup[str[i] & 0x0F]);
785 }
786 return OK;
787}
788
Pavel Grafove2e2d302017-08-01 17:15:53 +0100789status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
790 hex.clear();
791 for (size_t i = 0; i < str.size(); i++) {
792 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
793 hex.push_back(kLookup[str.data()[i] & 0x0F]);
794 }
795 return OK;
796}
797
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700798status_t NormalizeHex(const std::string& in, std::string& out) {
799 std::string tmp;
800 if (HexToStr(in, tmp)) {
801 return -EINVAL;
802 }
803 return StrToHex(tmp, out);
804}
805
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200806status_t GetBlockDevSize(int fd, uint64_t* size) {
807 if (ioctl(fd, BLKGETSIZE64, size)) {
808 return -errno;
809 }
810
811 return OK;
812}
813
814status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
815 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
816 status_t res = OK;
817
818 if (fd < 0) {
819 return -errno;
820 }
821
822 res = GetBlockDevSize(fd, size);
823
824 close(fd);
825
826 return res;
827}
828
829status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
830 uint64_t size;
831 status_t res = GetBlockDevSize(path, &size);
832
833 if (res != OK) {
834 return res;
835 }
836
837 *nr_sec = size / 512;
838
839 return OK;
840}
841
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700842uint64_t GetFreeBytes(const std::string& path) {
843 struct statvfs sb;
844 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700845 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700846 } else {
847 return -1;
848 }
849}
850
851// TODO: borrowed from frameworks/native/libs/diskusage/ which should
852// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700853static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700854 int64_t blksize = s->st_blksize;
855 // count actual blocks used instead of nominal file size
856 int64_t size = s->st_blocks * 512;
857
858 if (blksize) {
859 /* round up to filesystem block size */
860 size = (size + blksize - 1) & (~(blksize - 1));
861 }
862
863 return size;
864}
865
866// TODO: borrowed from frameworks/native/libs/diskusage/ which should
867// eventually be migrated into system/
868int64_t calculate_dir_size(int dfd) {
869 int64_t size = 0;
870 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700871 DIR* d;
872 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700873
874 d = fdopendir(dfd);
875 if (d == NULL) {
876 close(dfd);
877 return 0;
878 }
879
880 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700881 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700882 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
883 size += stat_size(&s);
884 }
885 if (de->d_type == DT_DIR) {
886 int subfd;
887
888 /* always skip "." and ".." */
889 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700890 if (name[1] == 0) continue;
891 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700892 }
893
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600894 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700895 if (subfd >= 0) {
896 size += calculate_dir_size(subfd);
897 }
898 }
899 }
900 closedir(d);
901 return size;
902}
903
904uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600905 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700906 if (dirfd < 0) {
907 PLOG(WARNING) << "Failed to open " << path;
908 return -1;
909 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700910 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700911 }
912}
913
Ricky Wai07e64a42020-02-11 14:31:24 +0000914// TODO: Use a better way to determine if it's media provider app.
915bool IsFuseDaemon(const pid_t pid) {
916 auto path = StringPrintf("/proc/%d/mounts", pid);
917 char* tmp;
918 if (lgetfilecon(path.c_str(), &tmp) < 0) {
919 return false;
920 }
921 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
922 || android::base::StartsWith(tmp, kMediaProviderCtx);
923 freecon(tmp);
924 return result;
925}
926
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700927bool IsFilesystemSupported(const std::string& fsType) {
928 std::string supported;
929 if (!ReadFileToString(kProcFilesystems, &supported)) {
930 PLOG(ERROR) << "Failed to read supported filesystems";
931 return false;
932 }
933 return supported.find(fsType + "\n") != std::string::npos;
934}
935
936status_t WipeBlockDevice(const std::string& path) {
937 status_t res = -1;
938 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200939 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700940
941 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
942 if (fd == -1) {
943 PLOG(ERROR) << "Failed to open " << path;
944 goto done;
945 }
946
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200947 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700948 PLOG(ERROR) << "Failed to determine size of " << path;
949 goto done;
950 }
951
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700952 LOG(INFO) << "About to discard " << range[1] << " on " << path;
953 if (ioctl(fd, BLKDISCARD, &range) == 0) {
954 LOG(INFO) << "Discard success on " << path;
955 res = 0;
956 } else {
957 PLOG(ERROR) << "Discard failure on " << path;
958 }
959
960done:
961 close(fd);
962 return res;
963}
964
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800965static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700966 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800967 return false;
968 } else {
969 return true;
970 }
971}
972
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700973std::string BuildKeyPath(const std::string& partGuid) {
974 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
975}
976
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600977std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700978 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600979}
980
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800981std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700982 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700983}
984
985std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700986 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700987}
988
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600989std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700990 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600991}
992
Jeff Sharkey47695b22016-02-01 17:02:29 -0700993std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700994 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700995}
996
997std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700998 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800999}
1000
Calin Juravle79f55a42016-02-17 20:14:46 +00001001// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1002std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001003 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001004}
1005
Andreas Huber71cd43f2018-01-22 11:25:29 -08001006std::string BuildDataVendorCePath(userid_t userId) {
1007 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1008}
1009
1010std::string BuildDataVendorDePath(userid_t userId) {
1011 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1012}
1013
Paul Crowley3b71fc52017-10-09 10:55:21 -07001014std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001015 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001016 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001017 return "/data";
1018 } else {
1019 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001020 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001021 }
1022}
1023
Paul Crowley3b71fc52017-10-09 10:55:21 -07001024std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001025 // TODO: unify with installd path generation logic
1026 std::string data(BuildDataPath(volumeUuid));
1027 return StringPrintf("%s/media/%u", data.c_str(), userId);
1028}
1029
Paul Crowley3b71fc52017-10-09 10:55:21 -07001030std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001031 // TODO: unify with installd path generation logic
1032 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001033 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001034 std::string legacy = StringPrintf("%s/data", data.c_str());
1035 struct stat sb;
1036 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1037 /* /data/data is dir, return /data/data for legacy system */
1038 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001039 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001040 }
cjbaoeb501142017-04-12 00:09:00 +08001041 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001042}
1043
Paul Crowley3b71fc52017-10-09 10:55:21 -07001044std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001045 // TODO: unify with installd path generation logic
1046 std::string data(BuildDataPath(volumeUuid));
1047 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1048}
1049
Jeff Sharkey66270a22015-06-24 11:49:24 -07001050dev_t GetDevice(const std::string& path) {
1051 struct stat sb;
1052 if (stat(path.c_str(), &sb)) {
1053 PLOG(WARNING) << "Failed to stat " << path;
1054 return 0;
1055 } else {
1056 return sb.st_dev;
1057 }
1058}
1059
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001060status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001061 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001062
Tom Cherryd6127ef2017-06-15 17:13:56 -07001063 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001064
Tom Cherryd6127ef2017-06-15 17:13:56 -07001065 android::base::SetProperty(kRestoreconString, "");
1066 android::base::SetProperty(kRestoreconString, path);
1067
1068 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001069
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001070 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001071 return OK;
1072}
1073
Jeff Sharkey3472e522017-10-06 18:02:53 -06001074bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1075 // Shamelessly borrowed from android::base::Readlink()
1076 result->clear();
1077
1078 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1079 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1080 // waste memory to just start there. We add 1 so that we can recognize
1081 // whether it actually fit (rather than being truncated to 4095).
1082 std::vector<char> buf(4095 + 1);
1083 while (true) {
1084 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1085 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001086 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001087 // It fit! (If size == buf.size(), it may have been truncated.)
1088 if (static_cast<size_t>(size) < buf.size()) {
1089 result->assign(&buf[0], size);
1090 return true;
1091 }
1092 // Double our buffer and try again.
1093 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001094 }
1095}
1096
Yu Ning942d4e82016-01-08 17:36:47 +08001097bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -07001098 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +08001099}
1100
Sudheer Shanka295fb242019-01-16 23:04:07 -08001101static status_t findMountPointsWithPrefix(const std::string& prefix,
1102 std::list<std::string>& mountPoints) {
1103 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1104 // when the prefix is /foo/bar
1105 std::string prefixWithSlash(prefix);
1106 if (prefix.back() != '/') {
1107 android::base::StringAppendF(&prefixWithSlash, "/");
1108 }
1109
1110 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1111 if (!mnts) {
1112 PLOG(ERROR) << "Unable to open /proc/mounts";
1113 return -errno;
1114 }
1115
1116 // Some volumes can be stacked on each other, so force unmount in
1117 // reverse order to give us the best chance of success.
1118 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1119 while ((mnt = getmntent(mnts.get())) != nullptr) {
1120 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1121 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1122 mountPoints.push_front(mountPoint);
1123 }
1124 }
1125 return OK;
1126}
1127
1128// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1129status_t UnmountTreeWithPrefix(const std::string& prefix) {
1130 std::list<std::string> toUnmount;
1131 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1132 if (result < 0) {
1133 return result;
1134 }
1135 for (const auto& path : toUnmount) {
1136 if (umount2(path.c_str(), MNT_DETACH)) {
1137 PLOG(ERROR) << "Failed to unmount " << path;
1138 result = -errno;
1139 }
1140 }
1141 return result;
1142}
1143
1144status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001145 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1146 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001147 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001148 return -errno;
1149 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001150 return OK;
1151}
1152
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001153static status_t delete_dir_contents(DIR* dir) {
1154 // Shamelessly borrowed from android::installd
1155 int dfd = dirfd(dir);
1156 if (dfd < 0) {
1157 return -errno;
1158 }
1159
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001160 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001161 struct dirent* de;
1162 while ((de = readdir(dir))) {
1163 const char* name = de->d_name;
1164 if (de->d_type == DT_DIR) {
1165 /* always skip "." and ".." */
1166 if (name[0] == '.') {
1167 if (name[1] == 0) continue;
1168 if ((name[1] == '.') && (name[2] == 0)) continue;
1169 }
1170
1171 android::base::unique_fd subfd(
1172 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1173 if (subfd.get() == -1) {
1174 PLOG(ERROR) << "Couldn't openat " << name;
1175 result = -errno;
1176 continue;
1177 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001178 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1179 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001180 if (!subdirp) {
1181 PLOG(ERROR) << "Couldn't fdopendir " << name;
1182 result = -errno;
1183 continue;
1184 }
1185 result = delete_dir_contents(subdirp.get());
1186 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1187 PLOG(ERROR) << "Couldn't unlinkat " << name;
1188 result = -errno;
1189 }
1190 } else {
1191 if (unlinkat(dfd, name, 0) < 0) {
1192 PLOG(ERROR) << "Couldn't unlinkat " << name;
1193 result = -errno;
1194 }
1195 }
1196 }
1197 return result;
1198}
1199
1200status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001201 status_t res = DeleteDirContents(pathname);
1202 if (res < 0) {
1203 return res;
1204 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001205 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001206 PLOG(ERROR) << "rmdir failed on " << pathname;
1207 return -errno;
1208 }
1209 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1210 return OK;
1211}
1212
1213status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001214 // Shamelessly borrowed from android::installd
1215 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1216 if (!dirp) {
1217 if (errno == ENOENT) {
1218 return OK;
1219 }
1220 PLOG(ERROR) << "Failed to opendir " << pathname;
1221 return -errno;
1222 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001223 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001224}
1225
Paul Crowley298fa322018-10-30 15:59:24 -07001226// TODO(118708649): fix duplication with init/util.h
1227status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1228 android::base::Timer t;
1229 while (t.duration() < timeout) {
1230 struct stat sb;
1231 if (stat(filename, &sb) != -1) {
1232 LOG(INFO) << "wait for '" << filename << "' took " << t;
1233 return 0;
1234 }
1235 std::this_thread::sleep_for(10ms);
1236 }
1237 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1238 return -1;
1239}
1240
Paul Crowley621d9b92018-12-07 15:36:09 -08001241bool FsyncDirectory(const std::string& dirname) {
1242 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1243 if (fd == -1) {
1244 PLOG(ERROR) << "Failed to open " << dirname;
1245 return false;
1246 }
1247 if (fsync(fd) == -1) {
1248 if (errno == EROFS || errno == EINVAL) {
1249 PLOG(WARNING) << "Skip fsync " << dirname
1250 << " on a file system does not support synchronization";
1251 } else {
1252 PLOG(ERROR) << "Failed to fsync " << dirname;
1253 return false;
1254 }
1255 }
1256 return true;
1257}
1258
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001259bool writeStringToFile(const std::string& payload, const std::string& filename) {
1260 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1261 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1262 if (fd == -1) {
1263 PLOG(ERROR) << "Failed to open " << filename;
1264 return false;
1265 }
1266 if (!android::base::WriteStringToFd(payload, fd)) {
1267 PLOG(ERROR) << "Failed to write to " << filename;
1268 unlink(filename.c_str());
1269 return false;
1270 }
1271 // fsync as close won't guarantee flush data
1272 // see close(2), fsync(2) and b/68901441
1273 if (fsync(fd) == -1) {
1274 if (errno == EROFS || errno == EINVAL) {
1275 PLOG(WARNING) << "Skip fsync " << filename
1276 << " on a file system does not support synchronization";
1277 } else {
1278 PLOG(ERROR) << "Failed to fsync " << filename;
1279 unlink(filename.c_str());
1280 return false;
1281 }
1282 }
1283 return true;
1284}
1285
Ricky Wai07e64a42020-02-11 14:31:24 +00001286status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1287 if (access(path.c_str(), F_OK) != 0) {
1288 PLOG(WARNING) << "Dir does not exist: " << path;
1289 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1290 return -errno;
1291 }
1292 }
1293 return OK;
1294}
1295
Zima438b242019-09-25 14:37:38 +01001296status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1297 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1298 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1299 std::string fuse_path(
1300 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1301
1302 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1303 std::string pass_through_path(
1304 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001305
Zim1242be82020-01-22 18:22:29 +00001306 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1307 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001308 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001309 if (result != android::OK) {
1310 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1311 return -1;
1312 }
1313
Zim06b0caf2020-01-05 02:11:47 +00001314 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1315 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1316 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1317 // These bits should be consistent with what is set in zygote in
1318 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001319 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001320 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001321 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001322 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001323 return -1;
1324 }
1325
Zima438b242019-09-25 14:37:38 +01001326 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1327 if (result != android::OK) {
1328 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1329 return -1;
1330 }
1331
Zim26eec702020-01-31 16:00:58 +00001332 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001333 if (result != android::OK) {
1334 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1335 return -1;
1336 }
1337
Zim26eec702020-01-31 16:00:58 +00001338 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001339 if (result != android::OK) {
1340 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1341 return -1;
1342 }
1343
1344 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001345 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1346 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001347 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001348 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001349 return -1;
1350 }
Zime5393d42019-11-15 11:44:12 +00001351 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001352 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001353
1354 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001355 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001356 if (result != android::OK) {
1357 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1358 return -1;
1359 }
1360 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001361 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001362 }
1363
Nandana Dutta914cc72019-08-29 15:22:42 +01001364 // Open fuse fd.
1365 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1366 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001367 PLOG(ERROR) << "Failed to open /dev/fuse";
1368 return -1;
1369 }
1370
1371 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1372 // permission checks before routing to FUSE daemon.
1373 const auto opts = StringPrintf(
1374 "fd=%i,"
1375 "rootmode=40000,"
1376 "allow_other,"
1377 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001378 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001379
Zima438b242019-09-25 14:37:38 +01001380 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1381 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1382 opts.c_str()));
1383 if (result != 0) {
1384 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001385 return -errno;
1386 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001387
Martijn Coenen86f21a22020-01-06 09:48:14 +01001388 if (IsFilesystemSupported("sdcardfs")) {
1389 std::string sdcardfs_path(
1390 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1391
1392 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1393 return BindMount(sdcardfs_path, pass_through_path);
1394 } else {
1395 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1396 return BindMount(absolute_lower_path, pass_through_path);
1397 }
Zima438b242019-09-25 14:37:38 +01001398}
1399
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001400status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1401 const std::string& relative_upper_path) {
1402 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1403 std::string pass_through_path(
1404 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1405
Zima438b242019-09-25 14:37:38 +01001406 // Best effort unmount pass_through path
1407 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001408 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1409 auto status = ForceUnmount(pass_through_path);
1410 if (status != android::OK) {
1411 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1412 }
Martijn Coenen57002612019-11-28 11:56:13 +01001413 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001414
1415 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001416 android::status_t result = ForceUnmount(fuse_path);
1417 sSleepOnUnmount = true;
1418 if (result != android::OK) {
1419 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1420 // Figure out why we get EBUSY and remove this special casing if possible.
1421 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1422 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1423 errno != ENOENT) {
1424 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1425 return -errno;
1426 }
Martijn Coenen57002612019-11-28 11:56:13 +01001427 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001428 }
Martijn Coenen57002612019-11-28 11:56:13 +01001429 rmdir(fuse_path.c_str());
1430
Zima438b242019-09-25 14:37:38 +01001431 return result;
Zim3623a212019-07-19 16:46:53 +01001432}
1433
Martijn Coenen62a4b272020-01-31 15:23:09 +01001434status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1435 std::string androidDir = volumeRoot + kAndroidDir;
1436 std::string androidDataDir = volumeRoot + kAppDataDir;
1437 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001438 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001439
1440 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1441
Martijn Coenen10570c02020-02-18 10:41:37 +01001442 // mode 0771 + sticky bit for inheriting GIDs
1443 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1444 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001445 PLOG(ERROR) << "Failed to create " << androidDir;
1446 return -errno;
1447 }
1448
1449 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001450 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001451 PLOG(ERROR) << "Failed to create " << androidDataDir;
1452 return -errno;
1453 }
1454
1455 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001456 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001457 PLOG(ERROR) << "Failed to create " << androidObbDir;
1458 return -errno;
1459 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001460 // Some other apps, like installers, have write access to the OBB directory
1461 // to pre-download them. To make sure newly created folders in this directory
1462 // have the right permissions, set a default ACL.
1463 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001464
Martijn Coenen10570c02020-02-18 10:41:37 +01001465 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001466 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1467 return -errno;
1468 }
1469
Martijn Coenen62a4b272020-01-31 15:23:09 +01001470 return OK;
1471}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001472} // namespace vold
1473} // namespace android