blob: af0027f1c0b1d1c25c428481d1e91dd47734122f [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;
Nikita Ioffedcee5c12020-06-12 12:59:45 +010066using android::base::unique_fd;
Jeff Sharkey9c484982015-03-31 10:35:33 -070067
Jeff Sharkeydeb24052015-03-02 21:01:40 -080068namespace android {
69namespace vold {
70
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070071security_context_t sBlkidContext = nullptr;
72security_context_t sBlkidUntrustedContext = nullptr;
73security_context_t sFsckContext = nullptr;
74security_context_t sFsckUntrustedContext = nullptr;
75
Paul Crowley56292ef2017-10-20 08:07:53 -070076bool sSleepOnUnmount = true;
77
Jeff Sharkey9c484982015-03-31 10:35:33 -070078static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070079static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070080
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070081static const char* kProcDevices = "/proc/devices";
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070082static const char* kProcFilesystems = "/proc/filesystems";
83
Martijn Coenen04bb17f2020-02-10 23:48:11 +010084static const char* kAndroidDir = "/Android/";
85static const char* kAppDataDir = "/Android/data/";
86static const char* kAppMediaDir = "/Android/media/";
87static const char* kAppObbDir = "/Android/obb/";
88
Ricky Wai07e64a42020-02-11 14:31:24 +000089static const char* kMediaProviderCtx = "u:r:mediaprovider:";
90static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
91
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060092// Lock used to protect process-level SELinux changes from racing with each
93// other between multiple threads.
94static std::mutex kSecurityLock;
95
Nikita Ioffedcee5c12020-06-12 12:59:45 +010096std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path) {
97 return StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str());
98}
99
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800100status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600101 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800102 const char* cpath = path.c_str();
103 status_t res = 0;
104
105 char* secontext = nullptr;
106 if (sehandle) {
107 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
108 setfscreatecon(secontext);
109 }
110 }
111
112 mode_t mode = 0660 | S_IFBLK;
113 if (mknod(cpath, mode, dev) < 0) {
114 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700115 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
116 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800117 res = -errno;
118 }
119 }
120
121 if (secontext) {
122 setfscreatecon(nullptr);
123 freecon(secontext);
124 }
125
126 return res;
127}
128
129status_t DestroyDeviceNode(const std::string& path) {
130 const char* cpath = path.c_str();
131 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
132 return -errno;
133 } else {
134 return OK;
135 }
136}
137
Martijn Coenen442bb832020-02-18 13:44:59 +0100138// Sets a default ACL on the directory.
139int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700140 if (IsSdcardfsUsed()) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100141 // sdcardfs magically takes care of this
142 return OK;
143 }
144
145 static constexpr size_t size =
146 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
147 auto buf = std::make_unique<uint8_t[]>(size);
148
149 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
150 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
151
152 posix_acl_xattr_entry* entry =
153 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
154
155 entry[0].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100156 // The existing mode_t mask has the ACL in the lower 9 bits:
157 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
158 // Use the mode_t masks to get these bits out, and shift them to get the
159 // correct value per entity.
160 //
161 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
162 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100163 entry[0].e_id = uid;
164
165 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100166 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100167 entry[1].e_id = gid;
168
169 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100170 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100171 entry[2].e_id = 0;
172
173 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
174
175 if (ret != 0) {
176 PLOG(ERROR) << "Failed to set default ACL on " << path;
177 }
178
179 return ret;
180}
181
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100182int SetQuotaInherit(const std::string& path) {
183 unsigned long flags;
184
185 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
186 if (fd == -1) {
187 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
188 return -1;
189 }
190
191 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
192 if (ret == -1) {
193 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
194 return ret;
195 }
196
197 flags |= FS_PROJINHERIT_FL;
198
199 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
200 if (ret == -1) {
201 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
202 return ret;
203 }
204
205 return 0;
206}
207
208int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100209 struct fsxattr fsx;
210
211 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
212 if (fd == -1) {
213 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
214 return -1;
215 }
216
217 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
218 if (ret == -1) {
219 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
220 return ret;
221 }
222
223 fsx.fsx_projid = projectId;
224 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
225}
226
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100227int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
228 long projectId) {
229 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
230
231 if (ret != 0) {
232 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100233 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100234
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700235 if (!IsSdcardfsUsed()) {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100236 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100237 }
238
239 return ret;
240}
241
Martijn Coenen816f4d92020-02-18 15:06:37 +0100242static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
243 namespace fs = std::filesystem;
244
245 // Setup the directory itself correctly
246 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
247 if (ret != OK) {
248 return ret;
249 }
250
251 // Fixup all of its file entries
252 for (const auto& itEntry : fs::directory_iterator(path)) {
253 ret = lchown(itEntry.path().c_str(), uid, gid);
254 if (ret != 0) {
255 return ret;
256 }
257
258 ret = chmod(itEntry.path().c_str(), mode);
259 if (ret != 0) {
260 return ret;
261 }
262
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700263 if (!IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +0100264 ret = SetQuotaProjectId(itEntry.path(), projectId);
265 if (ret != 0) {
266 return ret;
267 }
268 }
269 }
270
271 return OK;
272}
273
274int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
275 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100276 long projectId;
277 size_t pos;
278 int ret = 0;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700279 bool sdcardfsSupport = IsSdcardfsUsed();
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100280
281 // Make sure the Android/ directories exist and are setup correctly
282 ret = PrepareAndroidDirs(root);
283 if (ret != 0) {
284 LOG(ERROR) << "Failed to prepare Android/ directories.";
285 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100286 }
287
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100288 // Now create the application-specific subdir(s)
289 // path is something like /data/media/0/Android/data/com.foo/files
290 // First, chop off the volume root, eg /data/media/0
291 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100292
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100293 uid_t uid = appUid;
294 gid_t gid = AID_MEDIA_RW;
295 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100296
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100297 // Check that the next part matches one of the allowed Android/ dirs
298 if (StartsWith(pathFromRoot, kAppDataDir)) {
299 appDir = kAppDataDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700300 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100301 gid = AID_EXT_DATA_RW;
302 }
303 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
304 appDir = kAppMediaDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700305 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100306 gid = AID_MEDIA_RW;
307 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000308 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100309 appDir = kAppObbDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700310 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100311 gid = AID_EXT_OBB_RW;
312 }
313 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100314 LOG(ERROR) << "Invalid application directory: " << path;
315 return -EINVAL;
316 }
317
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100318 // mode = 770, plus sticky bit on directory to inherit GID when apps
319 // create subdirs
320 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100321 // the project ID for application-specific directories is directly
322 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100323
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100324 // Chop off the generic application-specific part, eg /Android/data/
325 // this leaves us with something like com.foo/files/
326 std::string leftToCreate = pathFromRoot.substr(appDir.length());
327 if (!EndsWith(leftToCreate, "/")) {
328 leftToCreate += "/";
329 }
330 std::string pathToCreate = root + appDir;
331 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100332 // Derive initial project ID
333 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
334 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
335 } else if (appDir == kAppObbDir) {
336 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
337 }
338
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100339 while ((pos = leftToCreate.find('/')) != std::string::npos) {
340 std::string component = leftToCreate.substr(0, pos + 1);
341 leftToCreate = leftToCreate.erase(0, pos + 1);
342 pathToCreate = pathToCreate + component;
343
344 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
345 // All dirs use the "app" project ID, except for the cache dirs in
346 // Android/data, eg Android/data/com.foo/cache
347 // Note that this "sticks" - eg subdirs of this dir need the same
348 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100349 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100350 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100351
352 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
353 // Fixup all files in this existing directory with the correct UID/GID
354 // and project ID.
355 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
356 } else {
357 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
358 }
359
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100360 if (ret != 0) {
361 return ret;
362 }
363
364 if (depth == 0) {
365 // Set the default ACL on the top-level application-specific directories,
366 // to ensure that even if applications run with a umask of 0077,
367 // new directories within these directories will allow the GID
368 // specified here to write; this is necessary for apps like
369 // installers and MTP, that require access here.
370 //
371 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100372 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100373 if (ret != 0) {
374 return ret;
375 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100376
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700377 if (!sdcardfsSupport) {
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100378 // Set project ID inheritance, so that future subdirectories inherit the
379 // same project ID
380 ret = SetQuotaInherit(pathToCreate);
381 if (ret != 0) {
382 return ret;
383 }
384 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100385 }
386
387 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100388 }
389
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100390 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100391}
392
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700393status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600394 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700395 const char* cpath = path.c_str();
396
397 char* secontext = nullptr;
398 if (sehandle) {
399 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
400 setfscreatecon(secontext);
401 }
402 }
403
404 int res = fs_prepare_dir(cpath, mode, uid, gid);
405
406 if (secontext) {
407 setfscreatecon(nullptr);
408 freecon(secontext);
409 }
410
411 if (res == 0) {
412 return OK;
413 } else {
414 return -errno;
415 }
416}
417
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800418status_t ForceUnmount(const std::string& path) {
419 const char* cpath = path.c_str();
420 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
421 return OK;
422 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700423 // Apps might still be handling eject request, so wait before
424 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700425 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700426
Jeff Sharkey3472e522017-10-06 18:02:53 -0600427 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700428 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700429 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
430 return OK;
431 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700432
Jeff Sharkey3472e522017-10-06 18:02:53 -0600433 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700434 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800435 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
436 return OK;
437 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700438
Jeff Sharkey3472e522017-10-06 18:02:53 -0600439 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700440 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700441 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
442 return OK;
443 }
Zim3623a212019-07-19 16:46:53 +0100444 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800445 return -errno;
446}
447
Ricky Wai07e64a42020-02-11 14:31:24 +0000448status_t KillProcessesWithMountPrefix(const std::string& path) {
449 if (KillProcessesWithMounts(path, SIGINT) == 0) {
450 return OK;
451 }
452 if (sSleepOnUnmount) sleep(5);
453
454 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
455 return OK;
456 }
457 if (sSleepOnUnmount) sleep(5);
458
459 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
460 return OK;
461 }
462 if (sSleepOnUnmount) sleep(5);
463
464 // Send SIGKILL a second time to determine if we've
465 // actually killed everyone mount
466 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
467 return OK;
468 }
469 PLOG(ERROR) << "Failed to kill processes using " << path;
470 return -EBUSY;
471}
472
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700473status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600474 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700475 return OK;
476 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700477 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700478
Jeff Sharkey3472e522017-10-06 18:02:53 -0600479 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700480 return OK;
481 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700482 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700483
Jeff Sharkey3472e522017-10-06 18:02:53 -0600484 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700485 return OK;
486 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700487 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700488
489 // Send SIGKILL a second time to determine if we've
490 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600491 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700492 return OK;
493 }
494 PLOG(ERROR) << "Failed to kill processes using " << path;
495 return -EBUSY;
496}
497
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700498status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800499 if (UnmountTree(target) < 0) {
500 return -errno;
501 }
502 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700503 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
504 return -errno;
505 }
506 return OK;
507}
508
Sudheer Shanka023b5392019-02-06 12:39:19 -0800509status_t Symlink(const std::string& target, const std::string& linkpath) {
510 if (Unlink(linkpath) < 0) {
511 return -errno;
512 }
513 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
514 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
515 return -errno;
516 }
517 return OK;
518}
519
520status_t Unlink(const std::string& linkpath) {
521 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
522 PLOG(ERROR) << "Failed to unlink " << linkpath;
523 return -errno;
524 }
525 return OK;
526}
527
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000528status_t CreateDir(const std::string& dir, mode_t mode) {
529 struct stat sb;
530 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
531 if (S_ISDIR(sb.st_mode)) {
532 return OK;
533 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
534 PLOG(ERROR) << "Failed to unlink " << dir;
535 return -errno;
536 }
537 } else if (errno != ENOENT) {
538 PLOG(ERROR) << "Failed to stat " << dir;
539 return -errno;
540 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800541 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000542 PLOG(ERROR) << "Failed to mkdir " << dir;
543 return -errno;
544 }
545 return OK;
546}
547
Jeff Sharkey3472e522017-10-06 18:02:53 -0600548bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
549 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800550 size_t start = 0;
551 while (true) {
552 start = raw.find(qual, start);
553 if (start == std::string::npos) return false;
554 if (start == 0 || raw[start - 1] == ' ') {
555 break;
556 }
557 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600558 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600559 start += qual.length();
560
561 auto end = raw.find("\"", start);
562 if (end == std::string::npos) return false;
563
564 *value = raw.substr(start, end - start);
565 return true;
566}
567
Paul Crowley14c8c072018-09-18 13:30:21 -0700568static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
569 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600570 fsType->clear();
571 fsUuid->clear();
572 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700573
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700574 std::vector<std::string> cmd;
575 cmd.push_back(kBlkidPath);
576 cmd.push_back("-c");
577 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700578 cmd.push_back("-s");
579 cmd.push_back("TYPE");
580 cmd.push_back("-s");
581 cmd.push_back("UUID");
582 cmd.push_back("-s");
583 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700584 cmd.push_back(path);
585
586 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800587 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700588 if (res != OK) {
589 LOG(WARNING) << "blkid failed to identify " << path;
590 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700591 }
592
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700593 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700594 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600595 FindValue(line, "TYPE", fsType);
596 FindValue(line, "UUID", fsUuid);
597 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700598 }
599
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700600 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700601}
602
Paul Crowley14c8c072018-09-18 13:30:21 -0700603status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
604 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700605 return readMetadata(path, fsType, fsUuid, fsLabel, false);
606}
607
Paul Crowley14c8c072018-09-18 13:30:21 -0700608status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
609 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700610 return readMetadata(path, fsType, fsUuid, fsLabel, true);
611}
612
Paul Crowleyde2d6202018-11-30 11:43:47 -0800613static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
614 std::vector<const char*> argv;
615 argv.reserve(args.size() + 1);
616 for (const auto& arg : args) {
617 if (argv.empty()) {
618 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700619 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800620 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700621 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800622 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700623 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800624 argv.emplace_back(nullptr);
625 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700626}
627
Paul Crowleyde2d6202018-11-30 11:43:47 -0800628static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
629 android::base::unique_fd ufd) {
630 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700631 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800632 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700633 return -errno;
634 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800635 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700636 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800637 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700638 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800639 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700640 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800641 return OK;
642}
643
644status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
645 security_context_t context) {
646 auto argv = ConvertToArgv(args);
647
Paul Crowleye6d76632018-11-30 11:43:47 -0800648 android::base::unique_fd pipe_read, pipe_write;
649 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
650 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800651 return -errno;
652 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800653
654 pid_t pid = fork();
655 if (pid == 0) {
656 if (context) {
657 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800658 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800659 abort();
660 }
661 }
662 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800663 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
664 PLOG(ERROR) << "dup2 in ForkExecvp";
665 _exit(EXIT_FAILURE);
666 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800667 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800668 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800669 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800670 _exit(EXIT_FAILURE);
671 }
672 if (pid == -1) {
673 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700674 return -errno;
675 }
676
Paul Crowleyde2d6202018-11-30 11:43:47 -0800677 pipe_write.reset();
678 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
679 if (st != 0) return st;
680
681 int status;
682 if (waitpid(pid, &status, 0) == -1) {
683 PLOG(ERROR) << "waitpid in ForkExecvp";
684 return -errno;
685 }
686 if (!WIFEXITED(status)) {
687 LOG(ERROR) << "Process did not exit normally, status: " << status;
688 return -ECHILD;
689 }
690 if (WEXITSTATUS(status)) {
691 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
692 return WEXITSTATUS(status);
693 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700694 return OK;
695}
696
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700697pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800698 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700699
700 pid_t pid = fork();
701 if (pid == 0) {
702 close(STDIN_FILENO);
703 close(STDOUT_FILENO);
704 close(STDERR_FILENO);
705
Paul Crowleyde2d6202018-11-30 11:43:47 -0800706 execvp(argv[0], const_cast<char**>(argv.data()));
707 PLOG(ERROR) << "exec in ForkExecvpAsync";
708 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700709 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700710 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800711 PLOG(ERROR) << "fork in ForkExecvpAsync";
712 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700713 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700714 return pid;
715}
716
Jeff Sharkey9c484982015-03-31 10:35:33 -0700717status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100718 out.resize(bytes);
719 return ReadRandomBytes(bytes, &out[0]);
720}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700721
Pavel Grafove2e2d302017-08-01 17:15:53 +0100722status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700723 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
724 if (fd == -1) {
725 return -errno;
726 }
727
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800728 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100729 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700730 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100731 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700732 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700733 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700734
735 if (bytes == 0) {
736 return OK;
737 } else {
738 return -EIO;
739 }
740}
741
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600742status_t GenerateRandomUuid(std::string& out) {
743 status_t res = ReadRandomBytes(16, out);
744 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700745 out[6] &= 0x0f; /* clear version */
746 out[6] |= 0x40; /* set to version 4 */
747 out[8] &= 0x3f; /* clear variant */
748 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600749 }
750 return res;
751}
752
Jeff Sharkey9c484982015-03-31 10:35:33 -0700753status_t HexToStr(const std::string& hex, std::string& str) {
754 str.clear();
755 bool even = true;
756 char cur = 0;
757 for (size_t i = 0; i < hex.size(); i++) {
758 int val = 0;
759 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700760 // clang-format off
761 case ' ': case '-': case ':': continue;
762 case 'f': case 'F': val = 15; break;
763 case 'e': case 'E': val = 14; break;
764 case 'd': case 'D': val = 13; break;
765 case 'c': case 'C': val = 12; break;
766 case 'b': case 'B': val = 11; break;
767 case 'a': case 'A': val = 10; break;
768 case '9': val = 9; break;
769 case '8': val = 8; break;
770 case '7': val = 7; break;
771 case '6': val = 6; break;
772 case '5': val = 5; break;
773 case '4': val = 4; break;
774 case '3': val = 3; break;
775 case '2': val = 2; break;
776 case '1': val = 1; break;
777 case '0': val = 0; break;
778 default: return -EINVAL;
779 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700780 }
781
782 if (even) {
783 cur = val << 4;
784 } else {
785 cur += val;
786 str.push_back(cur);
787 cur = 0;
788 }
789 even = !even;
790 }
791 return even ? OK : -EINVAL;
792}
793
794static const char* kLookup = "0123456789abcdef";
795
796status_t StrToHex(const std::string& str, std::string& hex) {
797 hex.clear();
798 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700799 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700800 hex.push_back(kLookup[str[i] & 0x0F]);
801 }
802 return OK;
803}
804
Pavel Grafove2e2d302017-08-01 17:15:53 +0100805status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
806 hex.clear();
807 for (size_t i = 0; i < str.size(); i++) {
808 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
809 hex.push_back(kLookup[str.data()[i] & 0x0F]);
810 }
811 return OK;
812}
813
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700814status_t NormalizeHex(const std::string& in, std::string& out) {
815 std::string tmp;
816 if (HexToStr(in, tmp)) {
817 return -EINVAL;
818 }
819 return StrToHex(tmp, out);
820}
821
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200822status_t GetBlockDevSize(int fd, uint64_t* size) {
823 if (ioctl(fd, BLKGETSIZE64, size)) {
824 return -errno;
825 }
826
827 return OK;
828}
829
830status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
831 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
832 status_t res = OK;
833
834 if (fd < 0) {
835 return -errno;
836 }
837
838 res = GetBlockDevSize(fd, size);
839
840 close(fd);
841
842 return res;
843}
844
845status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
846 uint64_t size;
847 status_t res = GetBlockDevSize(path, &size);
848
849 if (res != OK) {
850 return res;
851 }
852
853 *nr_sec = size / 512;
854
855 return OK;
856}
857
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700858uint64_t GetFreeBytes(const std::string& path) {
859 struct statvfs sb;
860 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700861 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700862 } else {
863 return -1;
864 }
865}
866
867// TODO: borrowed from frameworks/native/libs/diskusage/ which should
868// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700869static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700870 int64_t blksize = s->st_blksize;
871 // count actual blocks used instead of nominal file size
872 int64_t size = s->st_blocks * 512;
873
874 if (blksize) {
875 /* round up to filesystem block size */
876 size = (size + blksize - 1) & (~(blksize - 1));
877 }
878
879 return size;
880}
881
882// TODO: borrowed from frameworks/native/libs/diskusage/ which should
883// eventually be migrated into system/
884int64_t calculate_dir_size(int dfd) {
885 int64_t size = 0;
886 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700887 DIR* d;
888 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700889
890 d = fdopendir(dfd);
891 if (d == NULL) {
892 close(dfd);
893 return 0;
894 }
895
896 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700897 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700898 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
899 size += stat_size(&s);
900 }
901 if (de->d_type == DT_DIR) {
902 int subfd;
903
904 /* always skip "." and ".." */
905 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700906 if (name[1] == 0) continue;
907 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700908 }
909
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600910 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700911 if (subfd >= 0) {
912 size += calculate_dir_size(subfd);
913 }
914 }
915 }
916 closedir(d);
917 return size;
918}
919
920uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600921 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700922 if (dirfd < 0) {
923 PLOG(WARNING) << "Failed to open " << path;
924 return -1;
925 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700926 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700927 }
928}
929
Ricky Wai07e64a42020-02-11 14:31:24 +0000930// TODO: Use a better way to determine if it's media provider app.
931bool IsFuseDaemon(const pid_t pid) {
932 auto path = StringPrintf("/proc/%d/mounts", pid);
933 char* tmp;
934 if (lgetfilecon(path.c_str(), &tmp) < 0) {
935 return false;
936 }
937 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
938 || android::base::StartsWith(tmp, kMediaProviderCtx);
939 freecon(tmp);
940 return result;
941}
942
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700943bool IsFilesystemSupported(const std::string& fsType) {
944 std::string supported;
945 if (!ReadFileToString(kProcFilesystems, &supported)) {
946 PLOG(ERROR) << "Failed to read supported filesystems";
947 return false;
948 }
949 return supported.find(fsType + "\n") != std::string::npos;
950}
951
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700952bool IsSdcardfsUsed() {
953 return IsFilesystemSupported("sdcardfs") &&
954 base::GetBoolProperty(kExternalStorageSdcardfs, true);
955}
956
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700957status_t WipeBlockDevice(const std::string& path) {
958 status_t res = -1;
959 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200960 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700961
962 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
963 if (fd == -1) {
964 PLOG(ERROR) << "Failed to open " << path;
965 goto done;
966 }
967
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200968 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700969 PLOG(ERROR) << "Failed to determine size of " << path;
970 goto done;
971 }
972
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700973 LOG(INFO) << "About to discard " << range[1] << " on " << path;
974 if (ioctl(fd, BLKDISCARD, &range) == 0) {
975 LOG(INFO) << "Discard success on " << path;
976 res = 0;
977 } else {
978 PLOG(ERROR) << "Discard failure on " << path;
979 }
980
981done:
982 close(fd);
983 return res;
984}
985
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800986static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700987 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800988 return false;
989 } else {
990 return true;
991 }
992}
993
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700994std::string BuildKeyPath(const std::string& partGuid) {
995 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
996}
997
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600998std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700999 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001000}
1001
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001002std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001003 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001004}
1005
1006std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001007 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001008}
1009
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001010std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001011 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001012}
1013
Jeff Sharkey47695b22016-02-01 17:02:29 -07001014std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001015 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001016}
1017
1018std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001019 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001020}
1021
Calin Juravle79f55a42016-02-17 20:14:46 +00001022// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1023std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001024 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001025}
1026
Andreas Huber71cd43f2018-01-22 11:25:29 -08001027std::string BuildDataVendorCePath(userid_t userId) {
1028 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1029}
1030
1031std::string BuildDataVendorDePath(userid_t userId) {
1032 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1033}
1034
Paul Crowley3b71fc52017-10-09 10:55:21 -07001035std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001036 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001037 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001038 return "/data";
1039 } else {
1040 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001041 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001042 }
1043}
1044
Paul Crowley3b71fc52017-10-09 10:55:21 -07001045std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001046 // TODO: unify with installd path generation logic
1047 std::string data(BuildDataPath(volumeUuid));
1048 return StringPrintf("%s/media/%u", data.c_str(), userId);
1049}
1050
Paul Crowley3b71fc52017-10-09 10:55:21 -07001051std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001052 // TODO: unify with installd path generation logic
1053 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001054 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001055 std::string legacy = StringPrintf("%s/data", data.c_str());
1056 struct stat sb;
1057 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1058 /* /data/data is dir, return /data/data for legacy system */
1059 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001060 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001061 }
cjbaoeb501142017-04-12 00:09:00 +08001062 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001063}
1064
Paul Crowley3b71fc52017-10-09 10:55:21 -07001065std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001066 // TODO: unify with installd path generation logic
1067 std::string data(BuildDataPath(volumeUuid));
1068 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1069}
1070
Jeff Sharkey66270a22015-06-24 11:49:24 -07001071dev_t GetDevice(const std::string& path) {
1072 struct stat sb;
1073 if (stat(path.c_str(), &sb)) {
1074 PLOG(WARNING) << "Failed to stat " << path;
1075 return 0;
1076 } else {
1077 return sb.st_dev;
1078 }
1079}
1080
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001081status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001082 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001083
Tom Cherryd6127ef2017-06-15 17:13:56 -07001084 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001085
Tom Cherryd6127ef2017-06-15 17:13:56 -07001086 android::base::SetProperty(kRestoreconString, "");
1087 android::base::SetProperty(kRestoreconString, path);
1088
1089 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001090
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001091 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001092 return OK;
1093}
1094
Jeff Sharkey3472e522017-10-06 18:02:53 -06001095bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1096 // Shamelessly borrowed from android::base::Readlink()
1097 result->clear();
1098
1099 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1100 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1101 // waste memory to just start there. We add 1 so that we can recognize
1102 // whether it actually fit (rather than being truncated to 4095).
1103 std::vector<char> buf(4095 + 1);
1104 while (true) {
1105 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1106 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001107 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001108 // It fit! (If size == buf.size(), it may have been truncated.)
1109 if (static_cast<size_t>(size) < buf.size()) {
1110 result->assign(&buf[0], size);
1111 return true;
1112 }
1113 // Double our buffer and try again.
1114 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001115 }
1116}
1117
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001118static unsigned int GetMajorBlockVirtioBlk() {
1119 std::string devices;
1120 if (!ReadFileToString(kProcDevices, &devices)) {
1121 PLOG(ERROR) << "Unable to open /proc/devices";
1122 return 0;
1123 }
1124
1125 bool blockSection = false;
1126 for (auto line : android::base::Split(devices, "\n")) {
1127 if (line == "Block devices:") {
1128 blockSection = true;
1129 } else if (line == "Character devices:") {
1130 blockSection = false;
1131 } else if (blockSection) {
1132 auto tokens = android::base::Split(line, " ");
1133 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1134 return std::stoul(tokens[0]);
1135 }
1136 }
1137 }
1138
1139 return 0;
1140}
1141
1142bool IsVirtioBlkDevice(unsigned int major) {
1143 // Most virtualized platforms expose block devices with the virtio-blk
1144 // block device driver. Unfortunately, this driver does not use a fixed
1145 // major number, but relies on the kernel to assign one from a specific
1146 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1147 // per Documentation/devices.txt. This is true even for the latest Linux
1148 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1149 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1150 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001151}
1152
Sudheer Shanka295fb242019-01-16 23:04:07 -08001153static status_t findMountPointsWithPrefix(const std::string& prefix,
1154 std::list<std::string>& mountPoints) {
1155 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1156 // when the prefix is /foo/bar
1157 std::string prefixWithSlash(prefix);
1158 if (prefix.back() != '/') {
1159 android::base::StringAppendF(&prefixWithSlash, "/");
1160 }
1161
1162 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1163 if (!mnts) {
1164 PLOG(ERROR) << "Unable to open /proc/mounts";
1165 return -errno;
1166 }
1167
1168 // Some volumes can be stacked on each other, so force unmount in
1169 // reverse order to give us the best chance of success.
1170 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1171 while ((mnt = getmntent(mnts.get())) != nullptr) {
1172 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1173 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1174 mountPoints.push_front(mountPoint);
1175 }
1176 }
1177 return OK;
1178}
1179
1180// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1181status_t UnmountTreeWithPrefix(const std::string& prefix) {
1182 std::list<std::string> toUnmount;
1183 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1184 if (result < 0) {
1185 return result;
1186 }
1187 for (const auto& path : toUnmount) {
1188 if (umount2(path.c_str(), MNT_DETACH)) {
1189 PLOG(ERROR) << "Failed to unmount " << path;
1190 result = -errno;
1191 }
1192 }
1193 return result;
1194}
1195
1196status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001197 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1198 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001199 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001200 return -errno;
1201 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001202 return OK;
1203}
1204
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001205static status_t delete_dir_contents(DIR* dir) {
1206 // Shamelessly borrowed from android::installd
1207 int dfd = dirfd(dir);
1208 if (dfd < 0) {
1209 return -errno;
1210 }
1211
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001212 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001213 struct dirent* de;
1214 while ((de = readdir(dir))) {
1215 const char* name = de->d_name;
1216 if (de->d_type == DT_DIR) {
1217 /* always skip "." and ".." */
1218 if (name[0] == '.') {
1219 if (name[1] == 0) continue;
1220 if ((name[1] == '.') && (name[2] == 0)) continue;
1221 }
1222
1223 android::base::unique_fd subfd(
1224 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1225 if (subfd.get() == -1) {
1226 PLOG(ERROR) << "Couldn't openat " << name;
1227 result = -errno;
1228 continue;
1229 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001230 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1231 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001232 if (!subdirp) {
1233 PLOG(ERROR) << "Couldn't fdopendir " << name;
1234 result = -errno;
1235 continue;
1236 }
1237 result = delete_dir_contents(subdirp.get());
1238 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1239 PLOG(ERROR) << "Couldn't unlinkat " << name;
1240 result = -errno;
1241 }
1242 } else {
1243 if (unlinkat(dfd, name, 0) < 0) {
1244 PLOG(ERROR) << "Couldn't unlinkat " << name;
1245 result = -errno;
1246 }
1247 }
1248 }
1249 return result;
1250}
1251
1252status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001253 status_t res = DeleteDirContents(pathname);
1254 if (res < 0) {
1255 return res;
1256 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001257 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001258 PLOG(ERROR) << "rmdir failed on " << pathname;
1259 return -errno;
1260 }
1261 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1262 return OK;
1263}
1264
1265status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001266 // Shamelessly borrowed from android::installd
1267 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1268 if (!dirp) {
1269 if (errno == ENOENT) {
1270 return OK;
1271 }
1272 PLOG(ERROR) << "Failed to opendir " << pathname;
1273 return -errno;
1274 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001275 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001276}
1277
Paul Crowley298fa322018-10-30 15:59:24 -07001278// TODO(118708649): fix duplication with init/util.h
1279status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1280 android::base::Timer t;
1281 while (t.duration() < timeout) {
1282 struct stat sb;
1283 if (stat(filename, &sb) != -1) {
1284 LOG(INFO) << "wait for '" << filename << "' took " << t;
1285 return 0;
1286 }
1287 std::this_thread::sleep_for(10ms);
1288 }
1289 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1290 return -1;
1291}
1292
Paul Crowley621d9b92018-12-07 15:36:09 -08001293bool FsyncDirectory(const std::string& dirname) {
1294 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1295 if (fd == -1) {
1296 PLOG(ERROR) << "Failed to open " << dirname;
1297 return false;
1298 }
1299 if (fsync(fd) == -1) {
1300 if (errno == EROFS || errno == EINVAL) {
1301 PLOG(WARNING) << "Skip fsync " << dirname
1302 << " on a file system does not support synchronization";
1303 } else {
1304 PLOG(ERROR) << "Failed to fsync " << dirname;
1305 return false;
1306 }
1307 }
1308 return true;
1309}
1310
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001311bool writeStringToFile(const std::string& payload, const std::string& filename) {
1312 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1313 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1314 if (fd == -1) {
1315 PLOG(ERROR) << "Failed to open " << filename;
1316 return false;
1317 }
1318 if (!android::base::WriteStringToFd(payload, fd)) {
1319 PLOG(ERROR) << "Failed to write to " << filename;
1320 unlink(filename.c_str());
1321 return false;
1322 }
1323 // fsync as close won't guarantee flush data
1324 // see close(2), fsync(2) and b/68901441
1325 if (fsync(fd) == -1) {
1326 if (errno == EROFS || errno == EINVAL) {
1327 PLOG(WARNING) << "Skip fsync " << filename
1328 << " on a file system does not support synchronization";
1329 } else {
1330 PLOG(ERROR) << "Failed to fsync " << filename;
1331 unlink(filename.c_str());
1332 return false;
1333 }
1334 }
1335 return true;
1336}
1337
Martijn Coenen23c04452020-04-29 07:49:41 +02001338status_t AbortFuseConnections() {
1339 namespace fs = std::filesystem;
1340
1341 for (const auto& itEntry : fs::directory_iterator("/sys/fs/fuse/connections")) {
1342 std::string abortPath = itEntry.path().string() + "/abort";
1343 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1344 bool ret = writeStringToFile("1", abortPath);
1345 if (!ret) {
1346 LOG(WARNING) << "Failed to write to " << abortPath;
1347 }
1348 }
1349
1350 return OK;
1351}
1352
Ricky Wai07e64a42020-02-11 14:31:24 +00001353status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1354 if (access(path.c_str(), F_OK) != 0) {
1355 PLOG(WARNING) << "Dir does not exist: " << path;
1356 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1357 return -errno;
1358 }
1359 }
1360 return OK;
1361}
1362
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001363// Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1364// writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
1365void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1366 LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1367 << read_ahead_kb << "kb";
1368 // First figure out MAJOR:MINOR of fuse_mount. Simplest way is to stat the path.
1369 struct stat info;
1370 if (stat(fuse_mount.c_str(), &info) != 0) {
1371 PLOG(ERROR) << "Failed to stat " << fuse_mount;
1372 return;
1373 }
1374 unsigned int maj = major(info.st_dev);
1375 unsigned int min = minor(info.st_dev);
1376 LOG(INFO) << fuse_mount << " has major:minor " << maj << ":" << min;
1377 // We found major:minor of our filesystem, time to configure read ahead!
1378 std::string read_ahead_file = StringPrintf("/sys/class/bdi/%u:%u/read_ahead_kb", maj, min);
1379 unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1380 if (fd.get() == -1) {
1381 PLOG(ERROR) << "Failed to open " << read_ahead_file;
1382 return;
1383 }
1384 LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1385 if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1386 PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1387 }
1388}
1389
Zima438b242019-09-25 14:37:38 +01001390status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1391 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1392 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1393 std::string fuse_path(
1394 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1395
1396 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1397 std::string pass_through_path(
1398 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001399
Zim1242be82020-01-22 18:22:29 +00001400 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1401 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001402 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001403 if (result != android::OK) {
1404 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1405 return -1;
1406 }
1407
Zim06b0caf2020-01-05 02:11:47 +00001408 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1409 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1410 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1411 // These bits should be consistent with what is set in zygote in
1412 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001413 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001414 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001415 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001416 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001417 return -1;
1418 }
1419
Zima438b242019-09-25 14:37:38 +01001420 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1421 if (result != android::OK) {
1422 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1423 return -1;
1424 }
1425
Zim26eec702020-01-31 16:00:58 +00001426 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001427 if (result != android::OK) {
1428 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1429 return -1;
1430 }
1431
Zim26eec702020-01-31 16:00:58 +00001432 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001433 if (result != android::OK) {
1434 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1435 return -1;
1436 }
1437
1438 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001439 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1440 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001441 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001442 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001443 return -1;
1444 }
Zime5393d42019-11-15 11:44:12 +00001445 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001446 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001447
1448 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001449 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001450 if (result != android::OK) {
1451 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1452 return -1;
1453 }
1454 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001455 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001456 }
1457
Nandana Dutta914cc72019-08-29 15:22:42 +01001458 // Open fuse fd.
1459 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1460 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001461 PLOG(ERROR) << "Failed to open /dev/fuse";
1462 return -1;
1463 }
1464
1465 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1466 // permission checks before routing to FUSE daemon.
1467 const auto opts = StringPrintf(
1468 "fd=%i,"
1469 "rootmode=40000,"
1470 "allow_other,"
1471 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001472 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001473
Zima438b242019-09-25 14:37:38 +01001474 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1475 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1476 opts.c_str()));
1477 if (result != 0) {
1478 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001479 return -errno;
1480 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001481
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001482 if (IsSdcardfsUsed()) {
Martijn Coenen86f21a22020-01-06 09:48:14 +01001483 std::string sdcardfs_path(
1484 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1485
1486 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1487 return BindMount(sdcardfs_path, pass_through_path);
1488 } else {
1489 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1490 return BindMount(absolute_lower_path, pass_through_path);
1491 }
Zima438b242019-09-25 14:37:38 +01001492}
1493
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001494status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1495 const std::string& relative_upper_path) {
1496 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1497 std::string pass_through_path(
1498 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1499
Zima438b242019-09-25 14:37:38 +01001500 // Best effort unmount pass_through path
1501 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001502 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1503 auto status = ForceUnmount(pass_through_path);
1504 if (status != android::OK) {
1505 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1506 }
Martijn Coenen57002612019-11-28 11:56:13 +01001507 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001508
1509 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001510 android::status_t result = ForceUnmount(fuse_path);
1511 sSleepOnUnmount = true;
1512 if (result != android::OK) {
1513 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1514 // Figure out why we get EBUSY and remove this special casing if possible.
1515 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1516 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1517 errno != ENOENT) {
1518 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1519 return -errno;
1520 }
Martijn Coenen57002612019-11-28 11:56:13 +01001521 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001522 }
Martijn Coenen57002612019-11-28 11:56:13 +01001523 rmdir(fuse_path.c_str());
1524
Zima438b242019-09-25 14:37:38 +01001525 return result;
Zim3623a212019-07-19 16:46:53 +01001526}
1527
Martijn Coenen62a4b272020-01-31 15:23:09 +01001528status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1529 std::string androidDir = volumeRoot + kAndroidDir;
1530 std::string androidDataDir = volumeRoot + kAppDataDir;
1531 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001532 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001533
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001534 bool useSdcardFs = IsSdcardfsUsed();
Martijn Coenen62a4b272020-01-31 15:23:09 +01001535
Martijn Coenen10570c02020-02-18 10:41:37 +01001536 // mode 0771 + sticky bit for inheriting GIDs
1537 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1538 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001539 PLOG(ERROR) << "Failed to create " << androidDir;
1540 return -errno;
1541 }
1542
1543 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001544 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001545 PLOG(ERROR) << "Failed to create " << androidDataDir;
1546 return -errno;
1547 }
1548
1549 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001550 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001551 PLOG(ERROR) << "Failed to create " << androidObbDir;
1552 return -errno;
1553 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001554 // Some other apps, like installers, have write access to the OBB directory
1555 // to pre-download them. To make sure newly created folders in this directory
1556 // have the right permissions, set a default ACL.
1557 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001558
Martijn Coenen10570c02020-02-18 10:41:37 +01001559 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001560 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1561 return -errno;
1562 }
1563
Martijn Coenen62a4b272020-01-31 15:23:09 +01001564 return OK;
1565}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001566} // namespace vold
1567} // namespace android