blob: 1e20d75a4e18fd5d29b743030bc91ed71506dc78 [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 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100369
370 if (!IsFilesystemSupported("sdcardfs")) {
371 // Set project ID inheritance, so that future subdirectories inherit the
372 // same project ID
373 ret = SetQuotaInherit(pathToCreate);
374 if (ret != 0) {
375 return ret;
376 }
377 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100378 }
379
380 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100381 }
382
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100383 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100384}
385
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700386status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600387 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700388 const char* cpath = path.c_str();
389
390 char* secontext = nullptr;
391 if (sehandle) {
392 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
393 setfscreatecon(secontext);
394 }
395 }
396
397 int res = fs_prepare_dir(cpath, mode, uid, gid);
398
399 if (secontext) {
400 setfscreatecon(nullptr);
401 freecon(secontext);
402 }
403
404 if (res == 0) {
405 return OK;
406 } else {
407 return -errno;
408 }
409}
410
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800411status_t ForceUnmount(const std::string& path) {
412 const char* cpath = path.c_str();
413 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
414 return OK;
415 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700416 // Apps might still be handling eject request, so wait before
417 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700418 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700419
Jeff Sharkey3472e522017-10-06 18:02:53 -0600420 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700421 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700422 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
423 return OK;
424 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700425
Jeff Sharkey3472e522017-10-06 18:02:53 -0600426 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700427 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800428 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
429 return OK;
430 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700431
Jeff Sharkey3472e522017-10-06 18:02:53 -0600432 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700433 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700434 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
435 return OK;
436 }
Zim3623a212019-07-19 16:46:53 +0100437 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800438 return -errno;
439}
440
Ricky Wai07e64a42020-02-11 14:31:24 +0000441status_t KillProcessesWithMountPrefix(const std::string& path) {
442 if (KillProcessesWithMounts(path, SIGINT) == 0) {
443 return OK;
444 }
445 if (sSleepOnUnmount) sleep(5);
446
447 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
448 return OK;
449 }
450 if (sSleepOnUnmount) sleep(5);
451
452 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
453 return OK;
454 }
455 if (sSleepOnUnmount) sleep(5);
456
457 // Send SIGKILL a second time to determine if we've
458 // actually killed everyone mount
459 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
460 return OK;
461 }
462 PLOG(ERROR) << "Failed to kill processes using " << path;
463 return -EBUSY;
464}
465
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700466status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600467 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700468 return OK;
469 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700470 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700471
Jeff Sharkey3472e522017-10-06 18:02:53 -0600472 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700473 return OK;
474 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700475 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700476
Jeff Sharkey3472e522017-10-06 18:02:53 -0600477 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700478 return OK;
479 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700480 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700481
482 // Send SIGKILL a second time to determine if we've
483 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600484 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700485 return OK;
486 }
487 PLOG(ERROR) << "Failed to kill processes using " << path;
488 return -EBUSY;
489}
490
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700491status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800492 if (UnmountTree(target) < 0) {
493 return -errno;
494 }
495 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700496 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
497 return -errno;
498 }
499 return OK;
500}
501
Sudheer Shanka023b5392019-02-06 12:39:19 -0800502status_t Symlink(const std::string& target, const std::string& linkpath) {
503 if (Unlink(linkpath) < 0) {
504 return -errno;
505 }
506 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
507 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
508 return -errno;
509 }
510 return OK;
511}
512
513status_t Unlink(const std::string& linkpath) {
514 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
515 PLOG(ERROR) << "Failed to unlink " << linkpath;
516 return -errno;
517 }
518 return OK;
519}
520
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000521status_t CreateDir(const std::string& dir, mode_t mode) {
522 struct stat sb;
523 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
524 if (S_ISDIR(sb.st_mode)) {
525 return OK;
526 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
527 PLOG(ERROR) << "Failed to unlink " << dir;
528 return -errno;
529 }
530 } else if (errno != ENOENT) {
531 PLOG(ERROR) << "Failed to stat " << dir;
532 return -errno;
533 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800534 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000535 PLOG(ERROR) << "Failed to mkdir " << dir;
536 return -errno;
537 }
538 return OK;
539}
540
Jeff Sharkey3472e522017-10-06 18:02:53 -0600541bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
542 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800543 size_t start = 0;
544 while (true) {
545 start = raw.find(qual, start);
546 if (start == std::string::npos) return false;
547 if (start == 0 || raw[start - 1] == ' ') {
548 break;
549 }
550 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600551 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600552 start += qual.length();
553
554 auto end = raw.find("\"", start);
555 if (end == std::string::npos) return false;
556
557 *value = raw.substr(start, end - start);
558 return true;
559}
560
Paul Crowley14c8c072018-09-18 13:30:21 -0700561static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
562 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600563 fsType->clear();
564 fsUuid->clear();
565 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700566
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700567 std::vector<std::string> cmd;
568 cmd.push_back(kBlkidPath);
569 cmd.push_back("-c");
570 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700571 cmd.push_back("-s");
572 cmd.push_back("TYPE");
573 cmd.push_back("-s");
574 cmd.push_back("UUID");
575 cmd.push_back("-s");
576 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700577 cmd.push_back(path);
578
579 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800580 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700581 if (res != OK) {
582 LOG(WARNING) << "blkid failed to identify " << path;
583 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700584 }
585
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700586 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700587 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600588 FindValue(line, "TYPE", fsType);
589 FindValue(line, "UUID", fsUuid);
590 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700591 }
592
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700593 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700594}
595
Paul Crowley14c8c072018-09-18 13:30:21 -0700596status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
597 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700598 return readMetadata(path, fsType, fsUuid, fsLabel, false);
599}
600
Paul Crowley14c8c072018-09-18 13:30:21 -0700601status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
602 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700603 return readMetadata(path, fsType, fsUuid, fsLabel, true);
604}
605
Paul Crowleyde2d6202018-11-30 11:43:47 -0800606static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
607 std::vector<const char*> argv;
608 argv.reserve(args.size() + 1);
609 for (const auto& arg : args) {
610 if (argv.empty()) {
611 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700612 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800613 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700614 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800615 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700616 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800617 argv.emplace_back(nullptr);
618 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700619}
620
Paul Crowleyde2d6202018-11-30 11:43:47 -0800621static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
622 android::base::unique_fd ufd) {
623 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700624 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800625 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700626 return -errno;
627 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800628 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700629 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800630 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700631 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800632 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700633 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800634 return OK;
635}
636
637status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
638 security_context_t context) {
639 auto argv = ConvertToArgv(args);
640
Paul Crowleye6d76632018-11-30 11:43:47 -0800641 android::base::unique_fd pipe_read, pipe_write;
642 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
643 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800644 return -errno;
645 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800646
647 pid_t pid = fork();
648 if (pid == 0) {
649 if (context) {
650 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800651 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800652 abort();
653 }
654 }
655 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800656 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
657 PLOG(ERROR) << "dup2 in ForkExecvp";
658 _exit(EXIT_FAILURE);
659 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800660 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800661 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800662 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800663 _exit(EXIT_FAILURE);
664 }
665 if (pid == -1) {
666 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700667 return -errno;
668 }
669
Paul Crowleyde2d6202018-11-30 11:43:47 -0800670 pipe_write.reset();
671 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
672 if (st != 0) return st;
673
674 int status;
675 if (waitpid(pid, &status, 0) == -1) {
676 PLOG(ERROR) << "waitpid in ForkExecvp";
677 return -errno;
678 }
679 if (!WIFEXITED(status)) {
680 LOG(ERROR) << "Process did not exit normally, status: " << status;
681 return -ECHILD;
682 }
683 if (WEXITSTATUS(status)) {
684 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
685 return WEXITSTATUS(status);
686 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700687 return OK;
688}
689
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700690pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800691 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700692
693 pid_t pid = fork();
694 if (pid == 0) {
695 close(STDIN_FILENO);
696 close(STDOUT_FILENO);
697 close(STDERR_FILENO);
698
Paul Crowleyde2d6202018-11-30 11:43:47 -0800699 execvp(argv[0], const_cast<char**>(argv.data()));
700 PLOG(ERROR) << "exec in ForkExecvpAsync";
701 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700702 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700703 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800704 PLOG(ERROR) << "fork in ForkExecvpAsync";
705 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700706 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700707 return pid;
708}
709
Jeff Sharkey9c484982015-03-31 10:35:33 -0700710status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100711 out.resize(bytes);
712 return ReadRandomBytes(bytes, &out[0]);
713}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700714
Pavel Grafove2e2d302017-08-01 17:15:53 +0100715status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700716 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
717 if (fd == -1) {
718 return -errno;
719 }
720
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800721 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100722 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700723 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100724 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700725 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700726 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700727
728 if (bytes == 0) {
729 return OK;
730 } else {
731 return -EIO;
732 }
733}
734
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600735status_t GenerateRandomUuid(std::string& out) {
736 status_t res = ReadRandomBytes(16, out);
737 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700738 out[6] &= 0x0f; /* clear version */
739 out[6] |= 0x40; /* set to version 4 */
740 out[8] &= 0x3f; /* clear variant */
741 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600742 }
743 return res;
744}
745
Jeff Sharkey9c484982015-03-31 10:35:33 -0700746status_t HexToStr(const std::string& hex, std::string& str) {
747 str.clear();
748 bool even = true;
749 char cur = 0;
750 for (size_t i = 0; i < hex.size(); i++) {
751 int val = 0;
752 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700753 // clang-format off
754 case ' ': case '-': case ':': continue;
755 case 'f': case 'F': val = 15; break;
756 case 'e': case 'E': val = 14; break;
757 case 'd': case 'D': val = 13; break;
758 case 'c': case 'C': val = 12; break;
759 case 'b': case 'B': val = 11; break;
760 case 'a': case 'A': val = 10; break;
761 case '9': val = 9; break;
762 case '8': val = 8; break;
763 case '7': val = 7; break;
764 case '6': val = 6; break;
765 case '5': val = 5; break;
766 case '4': val = 4; break;
767 case '3': val = 3; break;
768 case '2': val = 2; break;
769 case '1': val = 1; break;
770 case '0': val = 0; break;
771 default: return -EINVAL;
772 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700773 }
774
775 if (even) {
776 cur = val << 4;
777 } else {
778 cur += val;
779 str.push_back(cur);
780 cur = 0;
781 }
782 even = !even;
783 }
784 return even ? OK : -EINVAL;
785}
786
787static const char* kLookup = "0123456789abcdef";
788
789status_t StrToHex(const std::string& str, std::string& hex) {
790 hex.clear();
791 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700792 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700793 hex.push_back(kLookup[str[i] & 0x0F]);
794 }
795 return OK;
796}
797
Pavel Grafove2e2d302017-08-01 17:15:53 +0100798status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
799 hex.clear();
800 for (size_t i = 0; i < str.size(); i++) {
801 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
802 hex.push_back(kLookup[str.data()[i] & 0x0F]);
803 }
804 return OK;
805}
806
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700807status_t NormalizeHex(const std::string& in, std::string& out) {
808 std::string tmp;
809 if (HexToStr(in, tmp)) {
810 return -EINVAL;
811 }
812 return StrToHex(tmp, out);
813}
814
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200815status_t GetBlockDevSize(int fd, uint64_t* size) {
816 if (ioctl(fd, BLKGETSIZE64, size)) {
817 return -errno;
818 }
819
820 return OK;
821}
822
823status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
824 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
825 status_t res = OK;
826
827 if (fd < 0) {
828 return -errno;
829 }
830
831 res = GetBlockDevSize(fd, size);
832
833 close(fd);
834
835 return res;
836}
837
838status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
839 uint64_t size;
840 status_t res = GetBlockDevSize(path, &size);
841
842 if (res != OK) {
843 return res;
844 }
845
846 *nr_sec = size / 512;
847
848 return OK;
849}
850
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700851uint64_t GetFreeBytes(const std::string& path) {
852 struct statvfs sb;
853 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700854 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700855 } else {
856 return -1;
857 }
858}
859
860// TODO: borrowed from frameworks/native/libs/diskusage/ which should
861// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700862static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700863 int64_t blksize = s->st_blksize;
864 // count actual blocks used instead of nominal file size
865 int64_t size = s->st_blocks * 512;
866
867 if (blksize) {
868 /* round up to filesystem block size */
869 size = (size + blksize - 1) & (~(blksize - 1));
870 }
871
872 return size;
873}
874
875// TODO: borrowed from frameworks/native/libs/diskusage/ which should
876// eventually be migrated into system/
877int64_t calculate_dir_size(int dfd) {
878 int64_t size = 0;
879 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700880 DIR* d;
881 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700882
883 d = fdopendir(dfd);
884 if (d == NULL) {
885 close(dfd);
886 return 0;
887 }
888
889 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700890 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700891 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
892 size += stat_size(&s);
893 }
894 if (de->d_type == DT_DIR) {
895 int subfd;
896
897 /* always skip "." and ".." */
898 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700899 if (name[1] == 0) continue;
900 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700901 }
902
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600903 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700904 if (subfd >= 0) {
905 size += calculate_dir_size(subfd);
906 }
907 }
908 }
909 closedir(d);
910 return size;
911}
912
913uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600914 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700915 if (dirfd < 0) {
916 PLOG(WARNING) << "Failed to open " << path;
917 return -1;
918 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700919 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700920 }
921}
922
Ricky Wai07e64a42020-02-11 14:31:24 +0000923// TODO: Use a better way to determine if it's media provider app.
924bool IsFuseDaemon(const pid_t pid) {
925 auto path = StringPrintf("/proc/%d/mounts", pid);
926 char* tmp;
927 if (lgetfilecon(path.c_str(), &tmp) < 0) {
928 return false;
929 }
930 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
931 || android::base::StartsWith(tmp, kMediaProviderCtx);
932 freecon(tmp);
933 return result;
934}
935
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700936bool IsFilesystemSupported(const std::string& fsType) {
937 std::string supported;
938 if (!ReadFileToString(kProcFilesystems, &supported)) {
939 PLOG(ERROR) << "Failed to read supported filesystems";
940 return false;
941 }
942 return supported.find(fsType + "\n") != std::string::npos;
943}
944
945status_t WipeBlockDevice(const std::string& path) {
946 status_t res = -1;
947 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200948 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700949
950 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
951 if (fd == -1) {
952 PLOG(ERROR) << "Failed to open " << path;
953 goto done;
954 }
955
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200956 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700957 PLOG(ERROR) << "Failed to determine size of " << path;
958 goto done;
959 }
960
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700961 LOG(INFO) << "About to discard " << range[1] << " on " << path;
962 if (ioctl(fd, BLKDISCARD, &range) == 0) {
963 LOG(INFO) << "Discard success on " << path;
964 res = 0;
965 } else {
966 PLOG(ERROR) << "Discard failure on " << path;
967 }
968
969done:
970 close(fd);
971 return res;
972}
973
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800974static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700975 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800976 return false;
977 } else {
978 return true;
979 }
980}
981
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700982std::string BuildKeyPath(const std::string& partGuid) {
983 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
984}
985
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600986std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700987 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600988}
989
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800990std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700991 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700992}
993
994std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700995 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700996}
997
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600998std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700999 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001000}
1001
Jeff Sharkey47695b22016-02-01 17:02:29 -07001002std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001003 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001004}
1005
1006std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001007 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001008}
1009
Calin Juravle79f55a42016-02-17 20:14:46 +00001010// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1011std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001012 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001013}
1014
Andreas Huber71cd43f2018-01-22 11:25:29 -08001015std::string BuildDataVendorCePath(userid_t userId) {
1016 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1017}
1018
1019std::string BuildDataVendorDePath(userid_t userId) {
1020 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1021}
1022
Paul Crowley3b71fc52017-10-09 10:55:21 -07001023std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001024 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001025 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001026 return "/data";
1027 } else {
1028 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001029 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001030 }
1031}
1032
Paul Crowley3b71fc52017-10-09 10:55:21 -07001033std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001034 // TODO: unify with installd path generation logic
1035 std::string data(BuildDataPath(volumeUuid));
1036 return StringPrintf("%s/media/%u", data.c_str(), userId);
1037}
1038
Paul Crowley3b71fc52017-10-09 10:55:21 -07001039std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001040 // TODO: unify with installd path generation logic
1041 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001042 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001043 std::string legacy = StringPrintf("%s/data", data.c_str());
1044 struct stat sb;
1045 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1046 /* /data/data is dir, return /data/data for legacy system */
1047 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001048 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001049 }
cjbaoeb501142017-04-12 00:09:00 +08001050 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001051}
1052
Paul Crowley3b71fc52017-10-09 10:55:21 -07001053std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001054 // TODO: unify with installd path generation logic
1055 std::string data(BuildDataPath(volumeUuid));
1056 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1057}
1058
Jeff Sharkey66270a22015-06-24 11:49:24 -07001059dev_t GetDevice(const std::string& path) {
1060 struct stat sb;
1061 if (stat(path.c_str(), &sb)) {
1062 PLOG(WARNING) << "Failed to stat " << path;
1063 return 0;
1064 } else {
1065 return sb.st_dev;
1066 }
1067}
1068
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001069status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001070 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001071
Tom Cherryd6127ef2017-06-15 17:13:56 -07001072 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001073
Tom Cherryd6127ef2017-06-15 17:13:56 -07001074 android::base::SetProperty(kRestoreconString, "");
1075 android::base::SetProperty(kRestoreconString, path);
1076
1077 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001078
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001079 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001080 return OK;
1081}
1082
Jeff Sharkey3472e522017-10-06 18:02:53 -06001083bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1084 // Shamelessly borrowed from android::base::Readlink()
1085 result->clear();
1086
1087 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1088 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1089 // waste memory to just start there. We add 1 so that we can recognize
1090 // whether it actually fit (rather than being truncated to 4095).
1091 std::vector<char> buf(4095 + 1);
1092 while (true) {
1093 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1094 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001095 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001096 // It fit! (If size == buf.size(), it may have been truncated.)
1097 if (static_cast<size_t>(size) < buf.size()) {
1098 result->assign(&buf[0], size);
1099 return true;
1100 }
1101 // Double our buffer and try again.
1102 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001103 }
1104}
1105
Yu Ning942d4e82016-01-08 17:36:47 +08001106bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -07001107 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +08001108}
1109
Sudheer Shanka295fb242019-01-16 23:04:07 -08001110static status_t findMountPointsWithPrefix(const std::string& prefix,
1111 std::list<std::string>& mountPoints) {
1112 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1113 // when the prefix is /foo/bar
1114 std::string prefixWithSlash(prefix);
1115 if (prefix.back() != '/') {
1116 android::base::StringAppendF(&prefixWithSlash, "/");
1117 }
1118
1119 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1120 if (!mnts) {
1121 PLOG(ERROR) << "Unable to open /proc/mounts";
1122 return -errno;
1123 }
1124
1125 // Some volumes can be stacked on each other, so force unmount in
1126 // reverse order to give us the best chance of success.
1127 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1128 while ((mnt = getmntent(mnts.get())) != nullptr) {
1129 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1130 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1131 mountPoints.push_front(mountPoint);
1132 }
1133 }
1134 return OK;
1135}
1136
1137// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1138status_t UnmountTreeWithPrefix(const std::string& prefix) {
1139 std::list<std::string> toUnmount;
1140 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1141 if (result < 0) {
1142 return result;
1143 }
1144 for (const auto& path : toUnmount) {
1145 if (umount2(path.c_str(), MNT_DETACH)) {
1146 PLOG(ERROR) << "Failed to unmount " << path;
1147 result = -errno;
1148 }
1149 }
1150 return result;
1151}
1152
1153status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001154 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1155 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001156 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001157 return -errno;
1158 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001159 return OK;
1160}
1161
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001162static status_t delete_dir_contents(DIR* dir) {
1163 // Shamelessly borrowed from android::installd
1164 int dfd = dirfd(dir);
1165 if (dfd < 0) {
1166 return -errno;
1167 }
1168
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001169 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001170 struct dirent* de;
1171 while ((de = readdir(dir))) {
1172 const char* name = de->d_name;
1173 if (de->d_type == DT_DIR) {
1174 /* always skip "." and ".." */
1175 if (name[0] == '.') {
1176 if (name[1] == 0) continue;
1177 if ((name[1] == '.') && (name[2] == 0)) continue;
1178 }
1179
1180 android::base::unique_fd subfd(
1181 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1182 if (subfd.get() == -1) {
1183 PLOG(ERROR) << "Couldn't openat " << name;
1184 result = -errno;
1185 continue;
1186 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001187 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1188 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001189 if (!subdirp) {
1190 PLOG(ERROR) << "Couldn't fdopendir " << name;
1191 result = -errno;
1192 continue;
1193 }
1194 result = delete_dir_contents(subdirp.get());
1195 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1196 PLOG(ERROR) << "Couldn't unlinkat " << name;
1197 result = -errno;
1198 }
1199 } else {
1200 if (unlinkat(dfd, name, 0) < 0) {
1201 PLOG(ERROR) << "Couldn't unlinkat " << name;
1202 result = -errno;
1203 }
1204 }
1205 }
1206 return result;
1207}
1208
1209status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001210 status_t res = DeleteDirContents(pathname);
1211 if (res < 0) {
1212 return res;
1213 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001214 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001215 PLOG(ERROR) << "rmdir failed on " << pathname;
1216 return -errno;
1217 }
1218 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1219 return OK;
1220}
1221
1222status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001223 // Shamelessly borrowed from android::installd
1224 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1225 if (!dirp) {
1226 if (errno == ENOENT) {
1227 return OK;
1228 }
1229 PLOG(ERROR) << "Failed to opendir " << pathname;
1230 return -errno;
1231 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001232 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001233}
1234
Paul Crowley298fa322018-10-30 15:59:24 -07001235// TODO(118708649): fix duplication with init/util.h
1236status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1237 android::base::Timer t;
1238 while (t.duration() < timeout) {
1239 struct stat sb;
1240 if (stat(filename, &sb) != -1) {
1241 LOG(INFO) << "wait for '" << filename << "' took " << t;
1242 return 0;
1243 }
1244 std::this_thread::sleep_for(10ms);
1245 }
1246 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1247 return -1;
1248}
1249
Paul Crowley621d9b92018-12-07 15:36:09 -08001250bool FsyncDirectory(const std::string& dirname) {
1251 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1252 if (fd == -1) {
1253 PLOG(ERROR) << "Failed to open " << dirname;
1254 return false;
1255 }
1256 if (fsync(fd) == -1) {
1257 if (errno == EROFS || errno == EINVAL) {
1258 PLOG(WARNING) << "Skip fsync " << dirname
1259 << " on a file system does not support synchronization";
1260 } else {
1261 PLOG(ERROR) << "Failed to fsync " << dirname;
1262 return false;
1263 }
1264 }
1265 return true;
1266}
1267
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001268bool writeStringToFile(const std::string& payload, const std::string& filename) {
1269 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1270 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1271 if (fd == -1) {
1272 PLOG(ERROR) << "Failed to open " << filename;
1273 return false;
1274 }
1275 if (!android::base::WriteStringToFd(payload, fd)) {
1276 PLOG(ERROR) << "Failed to write to " << filename;
1277 unlink(filename.c_str());
1278 return false;
1279 }
1280 // fsync as close won't guarantee flush data
1281 // see close(2), fsync(2) and b/68901441
1282 if (fsync(fd) == -1) {
1283 if (errno == EROFS || errno == EINVAL) {
1284 PLOG(WARNING) << "Skip fsync " << filename
1285 << " on a file system does not support synchronization";
1286 } else {
1287 PLOG(ERROR) << "Failed to fsync " << filename;
1288 unlink(filename.c_str());
1289 return false;
1290 }
1291 }
1292 return true;
1293}
1294
Ricky Wai07e64a42020-02-11 14:31:24 +00001295status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1296 if (access(path.c_str(), F_OK) != 0) {
1297 PLOG(WARNING) << "Dir does not exist: " << path;
1298 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1299 return -errno;
1300 }
1301 }
1302 return OK;
1303}
1304
Zima438b242019-09-25 14:37:38 +01001305status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1306 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1307 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1308 std::string fuse_path(
1309 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1310
1311 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1312 std::string pass_through_path(
1313 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001314
Zim1242be82020-01-22 18:22:29 +00001315 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1316 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001317 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001318 if (result != android::OK) {
1319 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1320 return -1;
1321 }
1322
Zim06b0caf2020-01-05 02:11:47 +00001323 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1324 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1325 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1326 // These bits should be consistent with what is set in zygote in
1327 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001328 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001329 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001330 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001331 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001332 return -1;
1333 }
1334
Zima438b242019-09-25 14:37:38 +01001335 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1336 if (result != android::OK) {
1337 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1338 return -1;
1339 }
1340
Zim26eec702020-01-31 16:00:58 +00001341 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001342 if (result != android::OK) {
1343 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1344 return -1;
1345 }
1346
Zim26eec702020-01-31 16:00:58 +00001347 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001348 if (result != android::OK) {
1349 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1350 return -1;
1351 }
1352
1353 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001354 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1355 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001356 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001357 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001358 return -1;
1359 }
Zime5393d42019-11-15 11:44:12 +00001360 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001361 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001362
1363 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001364 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001365 if (result != android::OK) {
1366 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1367 return -1;
1368 }
1369 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001370 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001371 }
1372
Nandana Dutta914cc72019-08-29 15:22:42 +01001373 // Open fuse fd.
1374 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1375 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001376 PLOG(ERROR) << "Failed to open /dev/fuse";
1377 return -1;
1378 }
1379
1380 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1381 // permission checks before routing to FUSE daemon.
1382 const auto opts = StringPrintf(
1383 "fd=%i,"
1384 "rootmode=40000,"
1385 "allow_other,"
1386 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001387 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001388
Zima438b242019-09-25 14:37:38 +01001389 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1390 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1391 opts.c_str()));
1392 if (result != 0) {
1393 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001394 return -errno;
1395 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001396
Martijn Coenen86f21a22020-01-06 09:48:14 +01001397 if (IsFilesystemSupported("sdcardfs")) {
1398 std::string sdcardfs_path(
1399 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1400
1401 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1402 return BindMount(sdcardfs_path, pass_through_path);
1403 } else {
1404 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1405 return BindMount(absolute_lower_path, pass_through_path);
1406 }
Zima438b242019-09-25 14:37:38 +01001407}
1408
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001409status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1410 const std::string& relative_upper_path) {
1411 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1412 std::string pass_through_path(
1413 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1414
Zima438b242019-09-25 14:37:38 +01001415 // Best effort unmount pass_through path
1416 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001417 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1418 auto status = ForceUnmount(pass_through_path);
1419 if (status != android::OK) {
1420 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1421 }
Martijn Coenen57002612019-11-28 11:56:13 +01001422 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001423
1424 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001425 android::status_t result = ForceUnmount(fuse_path);
1426 sSleepOnUnmount = true;
1427 if (result != android::OK) {
1428 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1429 // Figure out why we get EBUSY and remove this special casing if possible.
1430 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1431 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1432 errno != ENOENT) {
1433 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1434 return -errno;
1435 }
Martijn Coenen57002612019-11-28 11:56:13 +01001436 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001437 }
Martijn Coenen57002612019-11-28 11:56:13 +01001438 rmdir(fuse_path.c_str());
1439
Zima438b242019-09-25 14:37:38 +01001440 return result;
Zim3623a212019-07-19 16:46:53 +01001441}
1442
Martijn Coenen62a4b272020-01-31 15:23:09 +01001443status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1444 std::string androidDir = volumeRoot + kAndroidDir;
1445 std::string androidDataDir = volumeRoot + kAppDataDir;
1446 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001447 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001448
1449 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1450
Martijn Coenen10570c02020-02-18 10:41:37 +01001451 // mode 0771 + sticky bit for inheriting GIDs
1452 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1453 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001454 PLOG(ERROR) << "Failed to create " << androidDir;
1455 return -errno;
1456 }
1457
1458 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001459 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001460 PLOG(ERROR) << "Failed to create " << androidDataDir;
1461 return -errno;
1462 }
1463
1464 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001465 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001466 PLOG(ERROR) << "Failed to create " << androidObbDir;
1467 return -errno;
1468 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001469 // Some other apps, like installers, have write access to the OBB directory
1470 // to pre-download them. To make sure newly created folders in this directory
1471 // have the right permissions, set a default ACL.
1472 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001473
Martijn Coenen10570c02020-02-18 10:41:37 +01001474 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001475 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1476 return -errno;
1477 }
1478
Martijn Coenen62a4b272020-01-31 15:23:09 +01001479 return OK;
1480}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001481} // namespace vold
1482} // namespace android