blob: c4070d136a86a97aa238c8ff3742d7e282c36b9d [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>
Eric Biggersc7c4f5a2023-03-01 20:08:59 +000026#include <android-base/scopeguard.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080027#include <android-base/stringprintf.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070028#include <android-base/strings.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070029#include <android-base/unique_fd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080030#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070031#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070032#include <private/android_filesystem_config.h>
Martijn Coenenaee40512020-02-18 16:29:25 +010033#include <private/android_projectid_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080034
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070035#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080036#include <fcntl.h>
37#include <linux/fs.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010038#include <linux/posix_acl.h>
39#include <linux/posix_acl_xattr.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070040#include <mntent.h>
41#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080042#include <stdlib.h>
43#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080044#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070045#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070046#include <sys/sysmacros.h>
47#include <sys/types.h>
48#include <sys/wait.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010049#include <sys/xattr.h>
Paul Crowley747b4212019-04-05 04:09:57 -070050#include <unistd.h>
Paul Crowley298fa322018-10-30 15:59:24 -070051
Martijn Coenen816f4d92020-02-18 15:06:37 +010052#include <filesystem>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070053#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070054#include <mutex>
Martijn Coenen04bb17f2020-02-10 23:48:11 +010055#include <regex>
Paul Crowley298fa322018-10-30 15:59:24 -070056#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080057
58#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070059#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080060#endif
61
Paul Crowley298fa322018-10-30 15:59:24 -070062using namespace std::chrono_literals;
Martijn Coenenba9868b2020-01-31 15:49:24 +010063using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070064using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010065using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070066using android::base::StringPrintf;
Nikita Ioffedcee5c12020-06-12 12:59:45 +010067using android::base::unique_fd;
Jeff Sharkey9c484982015-03-31 10:35:33 -070068
Jeff Sharkeydeb24052015-03-02 21:01:40 -080069namespace android {
70namespace vold {
71
ThiƩbaud Weksteenae8550f2021-09-10 10:51:08 +020072char* sBlkidContext = nullptr;
73char* sBlkidUntrustedContext = nullptr;
74char* sFsckContext = nullptr;
75char* sFsckUntrustedContext = nullptr;
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070076
Paul Crowley56292ef2017-10-20 08:07:53 -070077bool sSleepOnUnmount = true;
78
Jeff Sharkey9c484982015-03-31 10:35:33 -070079static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070080static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070081
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070082static const char* kProcDevices = "/proc/devices";
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070083static const char* kProcFilesystems = "/proc/filesystems";
84
Martijn Coenen04bb17f2020-02-10 23:48:11 +010085static const char* kAndroidDir = "/Android/";
86static const char* kAppDataDir = "/Android/data/";
87static const char* kAppMediaDir = "/Android/media/";
88static const char* kAppObbDir = "/Android/obb/";
89
Ricky Wai07e64a42020-02-11 14:31:24 +000090static const char* kMediaProviderCtx = "u:r:mediaprovider:";
91static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
92
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060093// Lock used to protect process-level SELinux changes from racing with each
94// other between multiple threads.
95static std::mutex kSecurityLock;
96
Nikita Ioffedcee5c12020-06-12 12:59:45 +010097std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path) {
98 return StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str());
99}
100
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800101status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600102 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800103 const char* cpath = path.c_str();
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000104 auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); });
105 auto secontext = std::unique_ptr<char, void (*)(char*)>(nullptr, freecon);
106 char* tmp_secontext;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800107
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000108 if (selabel_lookup(sehandle, &tmp_secontext, cpath, S_IFBLK) == 0) {
109 secontext.reset(tmp_secontext);
110 if (setfscreatecon(secontext.get()) != 0) {
111 LOG(ERROR) << "Failed to setfscreatecon for device node " << path;
112 return -EINVAL;
Austin Delgadob0f997d2023-02-28 21:58:08 +0000113 }
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000114 } else if (errno == ENOENT) {
115 LOG(DEBUG) << "No selabel defined for device node " << path;
116 } else {
117 PLOG(ERROR) << "Failed to look up selabel for device node " << path;
118 return -errno;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800119 }
120
121 mode_t mode = 0660 | S_IFBLK;
122 if (mknod(cpath, mode, dev) < 0) {
123 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700124 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
125 << " at " << path;
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000126 return -errno;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800127 }
128 }
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000129 return OK;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800130}
131
132status_t DestroyDeviceNode(const std::string& path) {
133 const char* cpath = path.c_str();
134 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
135 return -errno;
136 } else {
137 return OK;
138 }
139}
140
Martijn Coenen442bb832020-02-18 13:44:59 +0100141// Sets a default ACL on the directory.
Martijn Coenen5adf92a2021-02-01 07:57:02 +0000142status_t SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
143 std::vector<gid_t> additionalGids) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700144 if (IsSdcardfsUsed()) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100145 // sdcardfs magically takes care of this
146 return OK;
147 }
148
Martijn Coenen1129b812020-06-16 14:58:52 +0200149 size_t num_entries = 3 + (additionalGids.size() > 0 ? additionalGids.size() + 1 : 0);
150 size_t size = sizeof(posix_acl_xattr_header) + num_entries * sizeof(posix_acl_xattr_entry);
Martijn Coenen879fa802020-02-11 12:37:25 +0100151 auto buf = std::make_unique<uint8_t[]>(size);
152
153 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
154 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
155
156 posix_acl_xattr_entry* entry =
157 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
158
Martijn Coenen1129b812020-06-16 14:58:52 +0200159 int tag_index = 0;
160
161 entry[tag_index].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100162 // The existing mode_t mask has the ACL in the lower 9 bits:
163 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
164 // Use the mode_t masks to get these bits out, and shift them to get the
165 // correct value per entity.
166 //
167 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
Martijn Coenen1129b812020-06-16 14:58:52 +0200168 entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
169 entry[tag_index].e_id = uid;
170 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100171
Martijn Coenen1129b812020-06-16 14:58:52 +0200172 entry[tag_index].e_tag = ACL_GROUP_OBJ;
173 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
174 entry[tag_index].e_id = gid;
175 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100176
Martijn Coenen1129b812020-06-16 14:58:52 +0200177 if (additionalGids.size() > 0) {
178 for (gid_t additional_gid : additionalGids) {
179 entry[tag_index].e_tag = ACL_GROUP;
180 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
181 entry[tag_index].e_id = additional_gid;
182 tag_index++;
183 }
184
185 entry[tag_index].e_tag = ACL_MASK;
186 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
187 entry[tag_index].e_id = 0;
188 tag_index++;
189 }
190
191 entry[tag_index].e_tag = ACL_OTHER;
192 entry[tag_index].e_perm = mode & S_IRWXO;
193 entry[tag_index].e_id = 0;
Martijn Coenen879fa802020-02-11 12:37:25 +0100194
195 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
196
197 if (ret != 0) {
198 PLOG(ERROR) << "Failed to set default ACL on " << path;
199 }
200
201 return ret;
202}
203
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100204int SetQuotaInherit(const std::string& path) {
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700205 unsigned int flags;
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100206
207 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
208 if (fd == -1) {
209 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
210 return -1;
211 }
212
213 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
214 if (ret == -1) {
215 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
216 return ret;
217 }
218
219 flags |= FS_PROJINHERIT_FL;
220
221 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
222 if (ret == -1) {
223 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
224 return ret;
225 }
226
227 return 0;
228}
229
230int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100231 struct fsxattr fsx;
232
233 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
234 if (fd == -1) {
235 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
236 return -1;
237 }
238
239 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
240 if (ret == -1) {
241 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
242 return ret;
243 }
244
245 fsx.fsx_projid = projectId;
Eric Biggers39aa9582021-05-03 12:29:40 -0700246 ret = ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
247 if (ret == -1) {
248 PLOG(ERROR) << "Failed to set project id on " << path;
249 return ret;
250 }
251 return 0;
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100252}
253
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100254int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
255 long projectId) {
256 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
257
258 if (ret != 0) {
259 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100260 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100261
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700262 if (!IsSdcardfsUsed()) {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100263 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100264 }
265
266 return ret;
267}
268
Martijn Coenen816f4d92020-02-18 15:06:37 +0100269static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
270 namespace fs = std::filesystem;
271
272 // Setup the directory itself correctly
273 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
274 if (ret != OK) {
275 return ret;
276 }
277
278 // Fixup all of its file entries
279 for (const auto& itEntry : fs::directory_iterator(path)) {
280 ret = lchown(itEntry.path().c_str(), uid, gid);
281 if (ret != 0) {
282 return ret;
283 }
284
285 ret = chmod(itEntry.path().c_str(), mode);
286 if (ret != 0) {
287 return ret;
288 }
289
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700290 if (!IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +0100291 ret = SetQuotaProjectId(itEntry.path(), projectId);
292 if (ret != 0) {
293 return ret;
294 }
295 }
296 }
297
298 return OK;
299}
300
301int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
302 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100303 long projectId;
304 size_t pos;
305 int ret = 0;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700306 bool sdcardfsSupport = IsSdcardfsUsed();
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100307
308 // Make sure the Android/ directories exist and are setup correctly
309 ret = PrepareAndroidDirs(root);
310 if (ret != 0) {
311 LOG(ERROR) << "Failed to prepare Android/ directories.";
312 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100313 }
314
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100315 // Now create the application-specific subdir(s)
316 // path is something like /data/media/0/Android/data/com.foo/files
317 // First, chop off the volume root, eg /data/media/0
318 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100319
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100320 uid_t uid = appUid;
321 gid_t gid = AID_MEDIA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200322 std::vector<gid_t> additionalGids;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100323 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100324
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100325 // Check that the next part matches one of the allowed Android/ dirs
326 if (StartsWith(pathFromRoot, kAppDataDir)) {
327 appDir = kAppDataDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700328 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100329 gid = AID_EXT_DATA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200330 // Also add the app's own UID as a group; since apps belong to a group
331 // that matches their UID, this ensures that they will always have access to
332 // the files created in these dirs, even if they are created by other processes
333 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100334 }
335 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
336 appDir = kAppMediaDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700337 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100338 gid = AID_MEDIA_RW;
339 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000340 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100341 appDir = kAppObbDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700342 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100343 gid = AID_EXT_OBB_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200344 // See comments for kAppDataDir above
345 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100346 }
347 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100348 LOG(ERROR) << "Invalid application directory: " << path;
349 return -EINVAL;
350 }
351
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100352 // mode = 770, plus sticky bit on directory to inherit GID when apps
353 // create subdirs
354 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100355 // the project ID for application-specific directories is directly
356 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100357
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100358 // Chop off the generic application-specific part, eg /Android/data/
359 // this leaves us with something like com.foo/files/
360 std::string leftToCreate = pathFromRoot.substr(appDir.length());
361 if (!EndsWith(leftToCreate, "/")) {
362 leftToCreate += "/";
363 }
364 std::string pathToCreate = root + appDir;
365 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100366 // Derive initial project ID
367 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
368 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
369 } else if (appDir == kAppObbDir) {
370 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
371 }
372
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100373 while ((pos = leftToCreate.find('/')) != std::string::npos) {
374 std::string component = leftToCreate.substr(0, pos + 1);
375 leftToCreate = leftToCreate.erase(0, pos + 1);
376 pathToCreate = pathToCreate + component;
377
378 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
379 // All dirs use the "app" project ID, except for the cache dirs in
380 // Android/data, eg Android/data/com.foo/cache
381 // Note that this "sticks" - eg subdirs of this dir need the same
382 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100383 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100384 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100385
386 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
387 // Fixup all files in this existing directory with the correct UID/GID
388 // and project ID.
389 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
390 } else {
391 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
392 }
393
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100394 if (ret != 0) {
395 return ret;
396 }
397
398 if (depth == 0) {
399 // Set the default ACL on the top-level application-specific directories,
400 // to ensure that even if applications run with a umask of 0077,
401 // new directories within these directories will allow the GID
402 // specified here to write; this is necessary for apps like
403 // installers and MTP, that require access here.
404 //
405 // See man (5) acl for more details.
Martijn Coenen1129b812020-06-16 14:58:52 +0200406 ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100407 if (ret != 0) {
408 return ret;
409 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100410
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700411 if (!sdcardfsSupport) {
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100412 // Set project ID inheritance, so that future subdirectories inherit the
413 // same project ID
414 ret = SetQuotaInherit(pathToCreate);
415 if (ret != 0) {
416 return ret;
417 }
418 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100419 }
420
421 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100422 }
423
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100424 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100425}
426
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700427int SetAttrs(const std::string& path, unsigned int attrs) {
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700428 unsigned int flags;
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700429 android::base::unique_fd fd(
430 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
431
432 if (fd == -1) {
433 PLOG(ERROR) << "Failed to open " << path;
434 return -1;
435 }
436
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700437 if (ioctl(fd, FS_IOC_GETFLAGS, &flags)) {
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700438 PLOG(ERROR) << "Failed to get flags for " << path;
439 return -1;
440 }
441
442 if ((flags & attrs) == attrs) return 0;
443 flags |= attrs;
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700444 if (ioctl(fd, FS_IOC_SETFLAGS, &flags)) {
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700445 PLOG(ERROR) << "Failed to set flags for " << path << "(0x" << std::hex << attrs << ")";
446 return -1;
447 }
448 return 0;
449}
450
451status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
452 unsigned int attrs) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600453 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700454 const char* cpath = path.c_str();
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000455 auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); });
456 auto secontext = std::unique_ptr<char, void (*)(char*)>(nullptr, freecon);
457 char* tmp_secontext;
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700458
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000459 if (selabel_lookup(sehandle, &tmp_secontext, cpath, S_IFDIR) == 0) {
460 secontext.reset(tmp_secontext);
461 if (setfscreatecon(secontext.get()) != 0) {
462 LOG(ERROR) << "Failed to setfscreatecon for directory " << path;
463 return -EINVAL;
Austin Delgadob0f997d2023-02-28 21:58:08 +0000464 }
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000465 } else if (errno == ENOENT) {
466 LOG(DEBUG) << "No selabel defined for directory " << path;
Austin Delgadob0f997d2023-02-28 21:58:08 +0000467 } else {
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000468 PLOG(ERROR) << "Failed to look up selabel for directory " << path;
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700469 return -errno;
470 }
Eric Biggersc7c4f5a2023-03-01 20:08:59 +0000471
472 if (fs_prepare_dir(cpath, mode, uid, gid) != 0) return -errno;
473 if (attrs && SetAttrs(path, attrs) != 0) return -errno;
474 return OK;
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700475}
476
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800477status_t ForceUnmount(const std::string& path) {
478 const char* cpath = path.c_str();
479 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
480 return OK;
481 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700482 // Apps might still be handling eject request, so wait before
483 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700484 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700485
Jeff Sharkey3472e522017-10-06 18:02:53 -0600486 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700487 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700488 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
489 return OK;
490 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700491
Jeff Sharkey3472e522017-10-06 18:02:53 -0600492 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700493 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800494 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
495 return OK;
496 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700497
Jeff Sharkey3472e522017-10-06 18:02:53 -0600498 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700499 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700500 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
501 return OK;
502 }
Zim3623a212019-07-19 16:46:53 +0100503 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800504 return -errno;
505}
506
Ricky Wai23356372021-04-30 09:53:07 +0100507status_t KillProcessesWithTmpfsMountPrefix(const std::string& path) {
508 if (KillProcessesWithTmpfsMounts(path, SIGINT) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000509 return OK;
510 }
511 if (sSleepOnUnmount) sleep(5);
512
Ricky Wai23356372021-04-30 09:53:07 +0100513 if (KillProcessesWithTmpfsMounts(path, SIGTERM) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000514 return OK;
515 }
516 if (sSleepOnUnmount) sleep(5);
517
Ricky Wai23356372021-04-30 09:53:07 +0100518 if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000519 return OK;
520 }
521 if (sSleepOnUnmount) sleep(5);
522
523 // Send SIGKILL a second time to determine if we've
524 // actually killed everyone mount
Ricky Wai23356372021-04-30 09:53:07 +0100525 if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000526 return OK;
527 }
528 PLOG(ERROR) << "Failed to kill processes using " << path;
529 return -EBUSY;
530}
531
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700532status_t KillProcessesUsingPath(const std::string& path) {
Zim75273002021-03-04 12:21:24 +0000533 if (KillProcessesWithOpenFiles(path, SIGINT, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700534 return OK;
535 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700536 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700537
Zim75273002021-03-04 12:21:24 +0000538 if (KillProcessesWithOpenFiles(path, SIGTERM, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700539 return OK;
540 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700541 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700542
Zim75273002021-03-04 12:21:24 +0000543 if (KillProcessesWithOpenFiles(path, SIGKILL, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700544 return OK;
545 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700546 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700547
548 // Send SIGKILL a second time to determine if we've
549 // actually killed everyone with open files
Zim75273002021-03-04 12:21:24 +0000550 // This time, we also kill the FUSE daemon if found
551 if (KillProcessesWithOpenFiles(path, SIGKILL, true /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700552 return OK;
553 }
554 PLOG(ERROR) << "Failed to kill processes using " << path;
555 return -EBUSY;
556}
557
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700558status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800559 if (UnmountTree(target) < 0) {
560 return -errno;
561 }
562 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700563 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
564 return -errno;
565 }
566 return OK;
567}
568
Sudheer Shanka023b5392019-02-06 12:39:19 -0800569status_t Symlink(const std::string& target, const std::string& linkpath) {
570 if (Unlink(linkpath) < 0) {
571 return -errno;
572 }
573 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
574 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
575 return -errno;
576 }
577 return OK;
578}
579
580status_t Unlink(const std::string& linkpath) {
581 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
582 PLOG(ERROR) << "Failed to unlink " << linkpath;
583 return -errno;
584 }
585 return OK;
586}
587
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000588status_t CreateDir(const std::string& dir, mode_t mode) {
589 struct stat sb;
590 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
591 if (S_ISDIR(sb.st_mode)) {
592 return OK;
593 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
594 PLOG(ERROR) << "Failed to unlink " << dir;
595 return -errno;
596 }
597 } else if (errno != ENOENT) {
598 PLOG(ERROR) << "Failed to stat " << dir;
599 return -errno;
600 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800601 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000602 PLOG(ERROR) << "Failed to mkdir " << dir;
603 return -errno;
604 }
605 return OK;
606}
607
Jeff Sharkey3472e522017-10-06 18:02:53 -0600608bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
609 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800610 size_t start = 0;
611 while (true) {
612 start = raw.find(qual, start);
613 if (start == std::string::npos) return false;
614 if (start == 0 || raw[start - 1] == ' ') {
615 break;
616 }
617 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600618 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600619 start += qual.length();
620
621 auto end = raw.find("\"", start);
622 if (end == std::string::npos) return false;
623
624 *value = raw.substr(start, end - start);
625 return true;
626}
627
Paul Crowley14c8c072018-09-18 13:30:21 -0700628static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
629 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600630 fsType->clear();
631 fsUuid->clear();
632 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700633
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700634 std::vector<std::string> cmd;
635 cmd.push_back(kBlkidPath);
636 cmd.push_back("-c");
637 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700638 cmd.push_back("-s");
639 cmd.push_back("TYPE");
640 cmd.push_back("-s");
641 cmd.push_back("UUID");
642 cmd.push_back("-s");
643 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700644 cmd.push_back(path);
645
646 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800647 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700648 if (res != OK) {
649 LOG(WARNING) << "blkid failed to identify " << path;
650 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700651 }
652
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700653 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700654 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600655 FindValue(line, "TYPE", fsType);
656 FindValue(line, "UUID", fsUuid);
657 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700658 }
659
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700660 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700661}
662
Paul Crowley14c8c072018-09-18 13:30:21 -0700663status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
664 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700665 return readMetadata(path, fsType, fsUuid, fsLabel, false);
666}
667
Paul Crowley14c8c072018-09-18 13:30:21 -0700668status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
669 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700670 return readMetadata(path, fsType, fsUuid, fsLabel, true);
671}
672
Paul Crowleyde2d6202018-11-30 11:43:47 -0800673static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
674 std::vector<const char*> argv;
675 argv.reserve(args.size() + 1);
676 for (const auto& arg : args) {
677 if (argv.empty()) {
678 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700679 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800680 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700681 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800682 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700683 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800684 argv.emplace_back(nullptr);
685 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700686}
687
Paul Crowleyde2d6202018-11-30 11:43:47 -0800688static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
689 android::base::unique_fd ufd) {
690 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700691 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800692 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700693 return -errno;
694 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800695 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700696 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800697 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700698 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800699 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700700 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800701 return OK;
702}
703
704status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
ThiƩbaud Weksteenae8550f2021-09-10 10:51:08 +0200705 char* context) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800706 auto argv = ConvertToArgv(args);
707
Paul Crowleye6d76632018-11-30 11:43:47 -0800708 android::base::unique_fd pipe_read, pipe_write;
709 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
710 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800711 return -errno;
712 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800713
714 pid_t pid = fork();
715 if (pid == 0) {
716 if (context) {
717 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800718 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800719 abort();
720 }
721 }
722 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800723 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
724 PLOG(ERROR) << "dup2 in ForkExecvp";
725 _exit(EXIT_FAILURE);
726 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800727 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800728 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800729 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800730 _exit(EXIT_FAILURE);
731 }
732 if (pid == -1) {
733 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700734 return -errno;
735 }
736
Paul Crowleyde2d6202018-11-30 11:43:47 -0800737 pipe_write.reset();
738 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
739 if (st != 0) return st;
740
741 int status;
742 if (waitpid(pid, &status, 0) == -1) {
743 PLOG(ERROR) << "waitpid in ForkExecvp";
744 return -errno;
745 }
746 if (!WIFEXITED(status)) {
747 LOG(ERROR) << "Process did not exit normally, status: " << status;
748 return -ECHILD;
749 }
750 if (WEXITSTATUS(status)) {
751 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
752 return WEXITSTATUS(status);
753 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700754 return OK;
755}
756
Daniel Rosenberg8c5dd6e2024-07-18 18:10:39 -0700757status_t ForkTimeout(int (*func)(void*), void* args, std::chrono::seconds timeout) {
758 int status;
759
760 // We're waiting on either the timeout or workload process to finish, so we're
761 // initially forking to get away from any other vold children
762 pid_t wait_timeout_pid = fork();
763 if (wait_timeout_pid == 0) {
764 pid_t pid = fork();
765 if (pid == 0) {
766 _exit(func(args));
767 }
768 if (pid == -1) {
769 _exit(EXIT_FAILURE);
770 }
771 pid_t timer_pid = fork();
772 if (timer_pid == 0) {
773 std::this_thread::sleep_for(timeout);
774 _exit(ETIMEDOUT);
775 }
776 if (timer_pid == -1) {
777 PLOG(ERROR) << "fork in ForkTimeout failed";
778 kill(pid, SIGTERM);
779 _exit(EXIT_FAILURE);
780 }
781 // Preserve the exit code of the first process to finish, and end the other
782 pid_t finished = wait(&status);
783 if (finished == pid) {
784 kill(timer_pid, SIGTERM);
785 } else {
786 kill(pid, SIGTERM);
787 }
788 if (!WIFEXITED(status)) {
789 _exit(ECHILD);
790 }
791 _exit(WEXITSTATUS(status));
792 }
793 if (waitpid(wait_timeout_pid, &status, 0) == -1) {
794 PLOG(ERROR) << "waitpid in ForkTimeout failed";
795 return -errno;
796 }
797 if (!WIFEXITED(status)) {
798 LOG(ERROR) << "Process did not exit normally, status: " << status;
799 return -ECHILD;
800 }
801 if (WEXITSTATUS(status)) {
802 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
803 return WEXITSTATUS(status);
804 }
805 return OK;
806}
807
Daniel Rosenbergd9261b12021-09-14 17:32:06 -0700808status_t ForkExecvpTimeout(const std::vector<std::string>& args, std::chrono::seconds timeout,
809 char* context) {
810 int status;
811
812 pid_t wait_timeout_pid = fork();
813 if (wait_timeout_pid == 0) {
814 pid_t pid = ForkExecvpAsync(args, context);
815 if (pid == -1) {
816 _exit(EXIT_FAILURE);
817 }
818 pid_t timer_pid = fork();
819 if (timer_pid == 0) {
Daniel Rosenberg8cd81fa2022-11-21 16:46:13 -0800820 std::this_thread::sleep_for(timeout);
Daniel Rosenbergd9261b12021-09-14 17:32:06 -0700821 _exit(ETIMEDOUT);
822 }
823 if (timer_pid == -1) {
824 PLOG(ERROR) << "fork in ForkExecvpAsync_timeout";
825 kill(pid, SIGTERM);
826 _exit(EXIT_FAILURE);
827 }
828 pid_t finished = wait(&status);
829 if (finished == pid) {
830 kill(timer_pid, SIGTERM);
831 } else {
832 kill(pid, SIGTERM);
833 }
834 if (!WIFEXITED(status)) {
835 _exit(ECHILD);
836 }
837 _exit(WEXITSTATUS(status));
838 }
839 if (waitpid(wait_timeout_pid, &status, 0) == -1) {
840 PLOG(ERROR) << "waitpid in ForkExecvpAsync_timeout";
841 return -errno;
842 }
843 if (!WIFEXITED(status)) {
844 LOG(ERROR) << "Process did not exit normally, status: " << status;
845 return -ECHILD;
846 }
847 if (WEXITSTATUS(status)) {
848 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
849 return WEXITSTATUS(status);
850 }
851 return OK;
852}
853
854pid_t ForkExecvpAsync(const std::vector<std::string>& args, char* context) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800855 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700856
857 pid_t pid = fork();
858 if (pid == 0) {
859 close(STDIN_FILENO);
860 close(STDOUT_FILENO);
861 close(STDERR_FILENO);
Daniel Rosenbergd9261b12021-09-14 17:32:06 -0700862 if (context) {
863 if (setexeccon(context)) {
864 LOG(ERROR) << "Failed to setexeccon in ForkExecvpAsync";
865 abort();
866 }
867 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700868
Paul Crowleyde2d6202018-11-30 11:43:47 -0800869 execvp(argv[0], const_cast<char**>(argv.data()));
870 PLOG(ERROR) << "exec in ForkExecvpAsync";
871 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700872 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700873 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800874 PLOG(ERROR) << "fork in ForkExecvpAsync";
875 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700876 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700877 return pid;
878}
879
Jeff Sharkey9c484982015-03-31 10:35:33 -0700880status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100881 out.resize(bytes);
882 return ReadRandomBytes(bytes, &out[0]);
883}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700884
Pavel Grafove2e2d302017-08-01 17:15:53 +0100885status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700886 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
887 if (fd == -1) {
888 return -errno;
889 }
890
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800891 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100892 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700893 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100894 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700895 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700896 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700897
898 if (bytes == 0) {
899 return OK;
900 } else {
901 return -EIO;
902 }
903}
904
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600905status_t GenerateRandomUuid(std::string& out) {
906 status_t res = ReadRandomBytes(16, out);
907 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700908 out[6] &= 0x0f; /* clear version */
909 out[6] |= 0x40; /* set to version 4 */
910 out[8] &= 0x3f; /* clear variant */
911 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600912 }
913 return res;
914}
915
Jeff Sharkey9c484982015-03-31 10:35:33 -0700916status_t HexToStr(const std::string& hex, std::string& str) {
917 str.clear();
918 bool even = true;
919 char cur = 0;
920 for (size_t i = 0; i < hex.size(); i++) {
921 int val = 0;
922 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700923 // clang-format off
924 case ' ': case '-': case ':': continue;
925 case 'f': case 'F': val = 15; break;
926 case 'e': case 'E': val = 14; break;
927 case 'd': case 'D': val = 13; break;
928 case 'c': case 'C': val = 12; break;
929 case 'b': case 'B': val = 11; break;
930 case 'a': case 'A': val = 10; break;
931 case '9': val = 9; break;
932 case '8': val = 8; break;
933 case '7': val = 7; break;
934 case '6': val = 6; break;
935 case '5': val = 5; break;
936 case '4': val = 4; break;
937 case '3': val = 3; break;
938 case '2': val = 2; break;
939 case '1': val = 1; break;
940 case '0': val = 0; break;
941 default: return -EINVAL;
942 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700943 }
944
945 if (even) {
946 cur = val << 4;
947 } else {
948 cur += val;
949 str.push_back(cur);
950 cur = 0;
951 }
952 even = !even;
953 }
954 return even ? OK : -EINVAL;
955}
956
957static const char* kLookup = "0123456789abcdef";
958
959status_t StrToHex(const std::string& str, std::string& hex) {
960 hex.clear();
961 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700962 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700963 hex.push_back(kLookup[str[i] & 0x0F]);
964 }
965 return OK;
966}
967
Pavel Grafove2e2d302017-08-01 17:15:53 +0100968status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
969 hex.clear();
970 for (size_t i = 0; i < str.size(); i++) {
971 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
972 hex.push_back(kLookup[str.data()[i] & 0x0F]);
973 }
974 return OK;
975}
976
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700977status_t NormalizeHex(const std::string& in, std::string& out) {
978 std::string tmp;
979 if (HexToStr(in, tmp)) {
980 return -EINVAL;
981 }
982 return StrToHex(tmp, out);
983}
984
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200985status_t GetBlockDevSize(int fd, uint64_t* size) {
986 if (ioctl(fd, BLKGETSIZE64, size)) {
987 return -errno;
988 }
989
990 return OK;
991}
992
993status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
994 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
995 status_t res = OK;
996
997 if (fd < 0) {
998 return -errno;
999 }
1000
1001 res = GetBlockDevSize(fd, size);
1002
1003 close(fd);
1004
1005 return res;
1006}
1007
1008status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
1009 uint64_t size;
1010 status_t res = GetBlockDevSize(path, &size);
1011
1012 if (res != OK) {
1013 return res;
1014 }
1015
1016 *nr_sec = size / 512;
1017
1018 return OK;
1019}
1020
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001021uint64_t GetFreeBytes(const std::string& path) {
1022 struct statvfs sb;
1023 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001024 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001025 } else {
1026 return -1;
1027 }
1028}
1029
1030// TODO: borrowed from frameworks/native/libs/diskusage/ which should
1031// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -07001032static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001033 int64_t blksize = s->st_blksize;
1034 // count actual blocks used instead of nominal file size
1035 int64_t size = s->st_blocks * 512;
1036
1037 if (blksize) {
1038 /* round up to filesystem block size */
1039 size = (size + blksize - 1) & (~(blksize - 1));
1040 }
1041
1042 return size;
1043}
1044
1045// TODO: borrowed from frameworks/native/libs/diskusage/ which should
1046// eventually be migrated into system/
1047int64_t calculate_dir_size(int dfd) {
1048 int64_t size = 0;
1049 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -07001050 DIR* d;
1051 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001052
1053 d = fdopendir(dfd);
1054 if (d == NULL) {
1055 close(dfd);
1056 return 0;
1057 }
1058
1059 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001060 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001061 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
1062 size += stat_size(&s);
1063 }
1064 if (de->d_type == DT_DIR) {
1065 int subfd;
1066
1067 /* always skip "." and ".." */
Eric Biggers7bcf4272020-11-02 15:31:56 -08001068 if (IsDotOrDotDot(*de)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001069
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -06001070 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001071 if (subfd >= 0) {
1072 size += calculate_dir_size(subfd);
1073 }
1074 }
1075 }
1076 closedir(d);
1077 return size;
1078}
1079
1080uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -06001081 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001082 if (dirfd < 0) {
1083 PLOG(WARNING) << "Failed to open " << path;
1084 return -1;
1085 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -07001086 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001087 }
1088}
1089
Ricky Wai07e64a42020-02-11 14:31:24 +00001090// TODO: Use a better way to determine if it's media provider app.
1091bool IsFuseDaemon(const pid_t pid) {
1092 auto path = StringPrintf("/proc/%d/mounts", pid);
1093 char* tmp;
1094 if (lgetfilecon(path.c_str(), &tmp) < 0) {
1095 return false;
1096 }
1097 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
1098 || android::base::StartsWith(tmp, kMediaProviderCtx);
1099 freecon(tmp);
1100 return result;
1101}
1102
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001103bool IsFilesystemSupported(const std::string& fsType) {
1104 std::string supported;
1105 if (!ReadFileToString(kProcFilesystems, &supported)) {
1106 PLOG(ERROR) << "Failed to read supported filesystems";
1107 return false;
1108 }
1109 return supported.find(fsType + "\n") != std::string::npos;
1110}
1111
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001112bool IsSdcardfsUsed() {
1113 return IsFilesystemSupported("sdcardfs") &&
1114 base::GetBoolProperty(kExternalStorageSdcardfs, true);
1115}
1116
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001117status_t WipeBlockDevice(const std::string& path) {
1118 status_t res = -1;
1119 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001120 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001121
1122 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
1123 if (fd == -1) {
1124 PLOG(ERROR) << "Failed to open " << path;
1125 goto done;
1126 }
1127
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001128 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001129 PLOG(ERROR) << "Failed to determine size of " << path;
1130 goto done;
1131 }
1132
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001133 LOG(INFO) << "About to discard " << range[1] << " on " << path;
1134 if (ioctl(fd, BLKDISCARD, &range) == 0) {
1135 LOG(INFO) << "Discard success on " << path;
1136 res = 0;
1137 } else {
1138 PLOG(ERROR) << "Discard failure on " << path;
1139 }
1140
1141done:
1142 close(fd);
1143 return res;
1144}
1145
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001146static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001147 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001148 return false;
1149 } else {
1150 return true;
1151 }
1152}
1153
Jeff Sharkeybc40cc82015-06-18 14:25:08 -07001154std::string BuildKeyPath(const std::string& partGuid) {
1155 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1156}
1157
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001158std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001159 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001160}
1161
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001162std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001163 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001164}
1165
1166std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001167 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001168}
1169
Calin Juravle79f55a42016-02-17 20:14:46 +00001170// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1171std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001172 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001173}
1174
Andreas Huber71cd43f2018-01-22 11:25:29 -08001175std::string BuildDataVendorCePath(userid_t userId) {
1176 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1177}
1178
1179std::string BuildDataVendorDePath(userid_t userId) {
1180 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1181}
1182
Paul Crowley3b71fc52017-10-09 10:55:21 -07001183std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001184 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001185 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001186 return "/data";
1187 } else {
1188 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001189 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001190 }
1191}
1192
Paul Crowley3b71fc52017-10-09 10:55:21 -07001193std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001194 // TODO: unify with installd path generation logic
1195 std::string data(BuildDataPath(volumeUuid));
1196 return StringPrintf("%s/media/%u", data.c_str(), userId);
1197}
1198
Mohammad Samiul Islamb4595912022-03-07 20:27:06 +00001199std::string BuildDataMiscCePath(const std::string& volumeUuid, userid_t userId) {
1200 return StringPrintf("%s/misc_ce/%u", BuildDataPath(volumeUuid).c_str(), userId);
1201}
1202
1203std::string BuildDataMiscDePath(const std::string& volumeUuid, userid_t userId) {
1204 return StringPrintf("%s/misc_de/%u", BuildDataPath(volumeUuid).c_str(), userId);
1205}
1206
Paul Crowley3b71fc52017-10-09 10:55:21 -07001207std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001208 // TODO: unify with installd path generation logic
1209 std::string data(BuildDataPath(volumeUuid));
cjbaoeb501142017-04-12 00:09:00 +08001210 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001211}
1212
Paul Crowley3b71fc52017-10-09 10:55:21 -07001213std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001214 // TODO: unify with installd path generation logic
1215 std::string data(BuildDataPath(volumeUuid));
1216 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1217}
1218
Jeff Sharkey66270a22015-06-24 11:49:24 -07001219dev_t GetDevice(const std::string& path) {
1220 struct stat sb;
1221 if (stat(path.c_str(), &sb)) {
1222 PLOG(WARNING) << "Failed to stat " << path;
1223 return 0;
1224 } else {
1225 return sb.st_dev;
1226 }
1227}
1228
Eric Biggers9ea53442022-05-11 05:33:25 +00001229// Returns true if |path| exists and is a symlink.
1230bool IsSymlink(const std::string& path) {
1231 struct stat stbuf;
1232 return lstat(path.c_str(), &stbuf) == 0 && S_ISLNK(stbuf.st_mode);
1233}
1234
Eric Biggersf74373b2020-11-05 19:58:26 -08001235// Returns true if |path1| names the same existing file or directory as |path2|.
1236bool IsSameFile(const std::string& path1, const std::string& path2) {
1237 struct stat stbuf1, stbuf2;
1238 if (stat(path1.c_str(), &stbuf1) != 0 || stat(path2.c_str(), &stbuf2) != 0) return false;
1239 return stbuf1.st_ino == stbuf2.st_ino && stbuf1.st_dev == stbuf2.st_dev;
1240}
1241
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001242status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001243 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001244
Tom Cherryd6127ef2017-06-15 17:13:56 -07001245 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001246
Tom Cherryd6127ef2017-06-15 17:13:56 -07001247 android::base::SetProperty(kRestoreconString, "");
1248 android::base::SetProperty(kRestoreconString, path);
1249
1250 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001251
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001252 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001253 return OK;
1254}
1255
Jeff Sharkey3472e522017-10-06 18:02:53 -06001256bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1257 // Shamelessly borrowed from android::base::Readlink()
1258 result->clear();
1259
1260 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1261 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1262 // waste memory to just start there. We add 1 so that we can recognize
1263 // whether it actually fit (rather than being truncated to 4095).
1264 std::vector<char> buf(4095 + 1);
1265 while (true) {
1266 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1267 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001268 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001269 // It fit! (If size == buf.size(), it may have been truncated.)
1270 if (static_cast<size_t>(size) < buf.size()) {
1271 result->assign(&buf[0], size);
1272 return true;
1273 }
1274 // Double our buffer and try again.
1275 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001276 }
1277}
1278
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001279static unsigned int GetMajorBlockVirtioBlk() {
1280 std::string devices;
1281 if (!ReadFileToString(kProcDevices, &devices)) {
1282 PLOG(ERROR) << "Unable to open /proc/devices";
1283 return 0;
1284 }
1285
1286 bool blockSection = false;
1287 for (auto line : android::base::Split(devices, "\n")) {
1288 if (line == "Block devices:") {
1289 blockSection = true;
1290 } else if (line == "Character devices:") {
1291 blockSection = false;
1292 } else if (blockSection) {
1293 auto tokens = android::base::Split(line, " ");
1294 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1295 return std::stoul(tokens[0]);
1296 }
1297 }
1298 }
1299
1300 return 0;
1301}
1302
1303bool IsVirtioBlkDevice(unsigned int major) {
1304 // Most virtualized platforms expose block devices with the virtio-blk
1305 // block device driver. Unfortunately, this driver does not use a fixed
1306 // major number, but relies on the kernel to assign one from a specific
1307 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1308 // per Documentation/devices.txt. This is true even for the latest Linux
1309 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1310 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1311 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001312}
1313
Sudheer Shanka295fb242019-01-16 23:04:07 -08001314status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001315 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1316 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001317 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001318 return -errno;
1319 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001320 return OK;
1321}
1322
Eric Biggers7bcf4272020-11-02 15:31:56 -08001323bool IsDotOrDotDot(const struct dirent& ent) {
1324 return strcmp(ent.d_name, ".") == 0 || strcmp(ent.d_name, "..") == 0;
1325}
1326
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001327static status_t delete_dir_contents(DIR* dir) {
1328 // Shamelessly borrowed from android::installd
1329 int dfd = dirfd(dir);
1330 if (dfd < 0) {
1331 return -errno;
1332 }
1333
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001334 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001335 struct dirent* de;
1336 while ((de = readdir(dir))) {
1337 const char* name = de->d_name;
1338 if (de->d_type == DT_DIR) {
1339 /* always skip "." and ".." */
Eric Biggers7bcf4272020-11-02 15:31:56 -08001340 if (IsDotOrDotDot(*de)) continue;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001341
1342 android::base::unique_fd subfd(
1343 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1344 if (subfd.get() == -1) {
1345 PLOG(ERROR) << "Couldn't openat " << name;
1346 result = -errno;
1347 continue;
1348 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001349 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1350 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001351 if (!subdirp) {
1352 PLOG(ERROR) << "Couldn't fdopendir " << name;
1353 result = -errno;
1354 continue;
1355 }
1356 result = delete_dir_contents(subdirp.get());
1357 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1358 PLOG(ERROR) << "Couldn't unlinkat " << name;
1359 result = -errno;
1360 }
1361 } else {
1362 if (unlinkat(dfd, name, 0) < 0) {
1363 PLOG(ERROR) << "Couldn't unlinkat " << name;
1364 result = -errno;
1365 }
1366 }
1367 }
1368 return result;
1369}
1370
1371status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001372 status_t res = DeleteDirContents(pathname);
1373 if (res < 0) {
1374 return res;
1375 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001376 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001377 PLOG(ERROR) << "rmdir failed on " << pathname;
1378 return -errno;
1379 }
1380 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1381 return OK;
1382}
1383
1384status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001385 // Shamelessly borrowed from android::installd
1386 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1387 if (!dirp) {
1388 if (errno == ENOENT) {
1389 return OK;
1390 }
1391 PLOG(ERROR) << "Failed to opendir " << pathname;
1392 return -errno;
1393 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001394 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001395}
1396
Paul Crowley298fa322018-10-30 15:59:24 -07001397// TODO(118708649): fix duplication with init/util.h
1398status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1399 android::base::Timer t;
1400 while (t.duration() < timeout) {
1401 struct stat sb;
1402 if (stat(filename, &sb) != -1) {
1403 LOG(INFO) << "wait for '" << filename << "' took " << t;
1404 return 0;
1405 }
1406 std::this_thread::sleep_for(10ms);
1407 }
1408 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1409 return -1;
1410}
1411
Eric Biggersbd138dd2021-02-16 15:59:17 -08001412bool pathExists(const std::string& path) {
1413 return access(path.c_str(), F_OK) == 0;
1414}
1415
Paul Crowley621d9b92018-12-07 15:36:09 -08001416bool FsyncDirectory(const std::string& dirname) {
1417 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1418 if (fd == -1) {
1419 PLOG(ERROR) << "Failed to open " << dirname;
1420 return false;
1421 }
1422 if (fsync(fd) == -1) {
1423 if (errno == EROFS || errno == EINVAL) {
1424 PLOG(WARNING) << "Skip fsync " << dirname
1425 << " on a file system does not support synchronization";
1426 } else {
1427 PLOG(ERROR) << "Failed to fsync " << dirname;
1428 return false;
1429 }
1430 }
1431 return true;
1432}
1433
Eric Biggers3345a2a2021-02-16 15:59:17 -08001434bool FsyncParentDirectory(const std::string& path) {
1435 return FsyncDirectory(android::base::Dirname(path));
1436}
1437
Eric Biggersfec0c0e2021-02-16 15:59:17 -08001438// Creates all parent directories of |path| that don't already exist. Assigns
1439// the specified |mode| to any new directories, and also fsync()s their parent
1440// directories so that the new directories get written to disk right away.
1441bool MkdirsSync(const std::string& path, mode_t mode) {
1442 if (path[0] != '/') {
1443 LOG(ERROR) << "MkdirsSync() needs an absolute path, but got " << path;
1444 return false;
1445 }
1446 std::vector<std::string> components = android::base::Split(android::base::Dirname(path), "/");
1447
1448 std::string current_dir = "/";
1449 for (const std::string& component : components) {
1450 if (component.empty()) continue;
1451
1452 std::string parent_dir = current_dir;
1453 if (current_dir != "/") current_dir += "/";
1454 current_dir += component;
1455
1456 if (!pathExists(current_dir)) {
1457 if (mkdir(current_dir.c_str(), mode) != 0) {
1458 PLOG(ERROR) << "Failed to create " << current_dir;
1459 return false;
1460 }
1461 if (!FsyncDirectory(parent_dir)) return false;
1462 LOG(DEBUG) << "Created directory " << current_dir;
1463 }
1464 }
1465 return true;
1466}
1467
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001468bool writeStringToFile(const std::string& payload, const std::string& filename) {
1469 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1470 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1471 if (fd == -1) {
1472 PLOG(ERROR) << "Failed to open " << filename;
1473 return false;
1474 }
1475 if (!android::base::WriteStringToFd(payload, fd)) {
1476 PLOG(ERROR) << "Failed to write to " << filename;
1477 unlink(filename.c_str());
1478 return false;
1479 }
1480 // fsync as close won't guarantee flush data
1481 // see close(2), fsync(2) and b/68901441
1482 if (fsync(fd) == -1) {
1483 if (errno == EROFS || errno == EINVAL) {
1484 PLOG(WARNING) << "Skip fsync " << filename
1485 << " on a file system does not support synchronization";
1486 } else {
1487 PLOG(ERROR) << "Failed to fsync " << filename;
1488 unlink(filename.c_str());
1489 return false;
1490 }
1491 }
1492 return true;
1493}
1494
Martijn Coenen23c04452020-04-29 07:49:41 +02001495status_t AbortFuseConnections() {
1496 namespace fs = std::filesystem;
1497
Oleg Lyovin667de182022-11-02 16:26:53 +03001498 static constexpr const char* kFuseConnections = "/sys/fs/fuse/connections";
1499
1500 std::error_code ec;
1501 for (const auto& itEntry : fs::directory_iterator(kFuseConnections, ec)) {
Tao Wu3d989622020-08-06 19:31:21 -07001502 std::string fsPath = itEntry.path().string() + "/filesystem";
1503 std::string fs;
1504
1505 // Virtiofs is on top of fuse and there isn't any user space daemon.
1506 // Android user space doesn't manage it.
1507 if (android::base::ReadFileToString(fsPath, &fs, false) &&
1508 android::base::Trim(fs) == "virtiofs") {
1509 LOG(INFO) << "Ignore virtiofs connection entry " << itEntry.path().string();
1510 continue;
1511 }
1512
Martijn Coenen23c04452020-04-29 07:49:41 +02001513 std::string abortPath = itEntry.path().string() + "/abort";
1514 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1515 bool ret = writeStringToFile("1", abortPath);
1516 if (!ret) {
1517 LOG(WARNING) << "Failed to write to " << abortPath;
1518 }
1519 }
1520
Oleg Lyovin667de182022-11-02 16:26:53 +03001521 if (ec) {
1522 LOG(WARNING) << "Failed to iterate through " << kFuseConnections << ": " << ec.message();
1523 return -ec.value();
1524 }
1525
Martijn Coenen23c04452020-04-29 07:49:41 +02001526 return OK;
1527}
1528
Ricky Wai07e64a42020-02-11 14:31:24 +00001529status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1530 if (access(path.c_str(), F_OK) != 0) {
1531 PLOG(WARNING) << "Dir does not exist: " << path;
1532 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1533 return -errno;
1534 }
1535 }
1536 return OK;
1537}
1538
Martijn Coenena4850062020-06-29 11:53:34 +02001539// Gets the sysfs path for parameters of the backing device info (bdi)
1540static std::string getBdiPathForMount(const std::string& mount) {
1541 // First figure out MAJOR:MINOR of mount. Simplest way is to stat the path.
1542 struct stat info;
1543 if (stat(mount.c_str(), &info) != 0) {
1544 PLOG(ERROR) << "Failed to stat " << mount;
1545 return "";
1546 }
1547 unsigned int maj = major(info.st_dev);
1548 unsigned int min = minor(info.st_dev);
1549
1550 return StringPrintf("/sys/class/bdi/%u:%u", maj, min);
1551}
1552
1553// Configures max_ratio for the FUSE filesystem.
1554void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio) {
1555 LOG(INFO) << "Configuring max_ratio of " << fuse_mount << " fuse filesystem to " << max_ratio;
1556 if (max_ratio > 100) {
1557 LOG(ERROR) << "Invalid max_ratio: " << max_ratio;
1558 return;
1559 }
1560 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1561 if (fuseBdiPath == "") {
1562 return;
1563 }
1564 std::string max_ratio_file = StringPrintf("%s/max_ratio", fuseBdiPath.c_str());
1565 unique_fd fd(TEMP_FAILURE_RETRY(open(max_ratio_file.c_str(), O_WRONLY | O_CLOEXEC)));
1566 if (fd.get() == -1) {
1567 PLOG(ERROR) << "Failed to open " << max_ratio_file;
1568 return;
1569 }
1570 LOG(INFO) << "Writing " << max_ratio << " to " << max_ratio_file;
1571 if (!WriteStringToFd(std::to_string(max_ratio), fd)) {
1572 PLOG(ERROR) << "Failed to write to " << max_ratio_file;
1573 }
1574}
1575
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001576// Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1577// writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
1578void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1579 LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1580 << read_ahead_kb << "kb";
Martijn Coenena4850062020-06-29 11:53:34 +02001581 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1582 if (fuseBdiPath == "") {
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001583 return;
1584 }
Martijn Coenena4850062020-06-29 11:53:34 +02001585 // We found the bdi path for our filesystem, time to configure read ahead!
1586 std::string read_ahead_file = StringPrintf("%s/read_ahead_kb", fuseBdiPath.c_str());
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001587 unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1588 if (fd.get() == -1) {
1589 PLOG(ERROR) << "Failed to open " << read_ahead_file;
1590 return;
1591 }
1592 LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1593 if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1594 PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1595 }
1596}
1597
Zima438b242019-09-25 14:37:38 +01001598status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1599 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1600 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1601 std::string fuse_path(
1602 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1603
1604 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1605 std::string pass_through_path(
1606 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001607
Zim1242be82020-01-22 18:22:29 +00001608 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1609 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001610 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001611 if (result != android::OK) {
1612 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1613 return -1;
1614 }
1615
Himanshu Gupta4f179692024-05-06 11:40:19 +01001616 result = PrepareMountDirForUser(user_id);
Zim3623a212019-07-19 16:46:53 +01001617 if (result != android::OK) {
Himanshu Gupta4f179692024-05-06 11:40:19 +01001618 PLOG(ERROR) << "Failed to create Mount Directory for user " << user_id;
Zim3623a212019-07-19 16:46:53 +01001619 return -1;
1620 }
1621
Zima438b242019-09-25 14:37:38 +01001622 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1623 if (result != android::OK) {
1624 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1625 return -1;
1626 }
1627
Zim26eec702020-01-31 16:00:58 +00001628 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001629 if (result != android::OK) {
1630 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1631 return -1;
1632 }
1633
Zim26eec702020-01-31 16:00:58 +00001634 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001635 if (result != android::OK) {
1636 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1637 return -1;
1638 }
1639
1640 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001641 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1642 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001643 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001644 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001645 return -1;
1646 }
Zime5393d42019-11-15 11:44:12 +00001647 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001648 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001649
1650 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001651 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001652 if (result != android::OK) {
1653 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1654 return -1;
1655 }
1656 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001657 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001658 }
1659
Nandana Dutta914cc72019-08-29 15:22:42 +01001660 // Open fuse fd.
1661 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1662 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001663 PLOG(ERROR) << "Failed to open /dev/fuse";
1664 return -1;
1665 }
1666
1667 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1668 // permission checks before routing to FUSE daemon.
1669 const auto opts = StringPrintf(
1670 "fd=%i,"
1671 "rootmode=40000,"
1672 "allow_other,"
1673 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001674 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001675
Zima438b242019-09-25 14:37:38 +01001676 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1677 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1678 opts.c_str()));
1679 if (result != 0) {
1680 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001681 return -errno;
1682 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001683
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001684 if (IsSdcardfsUsed()) {
Martijn Coenen86f21a22020-01-06 09:48:14 +01001685 std::string sdcardfs_path(
1686 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1687
1688 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1689 return BindMount(sdcardfs_path, pass_through_path);
1690 } else {
1691 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1692 return BindMount(absolute_lower_path, pass_through_path);
1693 }
Zima438b242019-09-25 14:37:38 +01001694}
1695
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001696status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1697 const std::string& relative_upper_path) {
1698 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1699 std::string pass_through_path(
1700 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1701
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001702 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001703 android::status_t result = ForceUnmount(fuse_path);
Zima438b242019-09-25 14:37:38 +01001704 if (result != android::OK) {
1705 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1706 // Figure out why we get EBUSY and remove this special casing if possible.
1707 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1708 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1709 errno != ENOENT) {
1710 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1711 return -errno;
1712 }
Martijn Coenen57002612019-11-28 11:56:13 +01001713 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001714 }
Martijn Coenen57002612019-11-28 11:56:13 +01001715 rmdir(fuse_path.c_str());
1716
Martijn Coenen64b3bba2020-11-05 10:34:28 +01001717 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1718 auto status = ForceUnmount(pass_through_path);
1719 if (status != android::OK) {
1720 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1721 }
1722 rmdir(pass_through_path.c_str());
1723
Zima438b242019-09-25 14:37:38 +01001724 return result;
Zim3623a212019-07-19 16:46:53 +01001725}
1726
Martijn Coenen62a4b272020-01-31 15:23:09 +01001727status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1728 std::string androidDir = volumeRoot + kAndroidDir;
1729 std::string androidDataDir = volumeRoot + kAppDataDir;
1730 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001731 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001732
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001733 bool useSdcardFs = IsSdcardfsUsed();
Martijn Coenen62a4b272020-01-31 15:23:09 +01001734
Martijn Coenen10570c02020-02-18 10:41:37 +01001735 // mode 0771 + sticky bit for inheriting GIDs
1736 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1737 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001738 PLOG(ERROR) << "Failed to create " << androidDir;
1739 return -errno;
1740 }
1741
1742 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001743 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001744 PLOG(ERROR) << "Failed to create " << androidDataDir;
1745 return -errno;
1746 }
1747
1748 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001749 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001750 PLOG(ERROR) << "Failed to create " << androidObbDir;
1751 return -errno;
1752 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001753 // Some other apps, like installers, have write access to the OBB directory
1754 // to pre-download them. To make sure newly created folders in this directory
1755 // have the right permissions, set a default ACL.
Martijn Coenen1129b812020-06-16 14:58:52 +02001756 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
Martijn Coenen62a4b272020-01-31 15:23:09 +01001757
Martijn Coenen10570c02020-02-18 10:41:37 +01001758 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001759 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1760 return -errno;
1761 }
1762
Martijn Coenen62a4b272020-01-31 15:23:09 +01001763 return OK;
1764}
Yurii Zubrytskyi40389822021-10-18 22:33:15 -07001765
1766namespace ab = android::base;
1767
1768static ab::unique_fd openDirFd(int parentFd, const char* name) {
1769 return ab::unique_fd{::openat(parentFd, name, O_CLOEXEC | O_DIRECTORY | O_PATH | O_NOFOLLOW)};
1770}
1771
1772static ab::unique_fd openAbsolutePathFd(std::string_view path) {
1773 if (path.empty() || path[0] != '/') {
1774 errno = EINVAL;
1775 return {};
1776 }
1777 if (path == "/") {
1778 return openDirFd(-1, "/");
1779 }
1780
1781 // first component is special - it includes the leading slash
1782 auto next = path.find('/', 1);
1783 auto component = std::string(path.substr(0, next));
1784 if (component == "..") {
1785 errno = EINVAL;
1786 return {};
1787 }
1788 auto fd = openDirFd(-1, component.c_str());
1789 if (!fd.ok()) {
1790 return fd;
1791 }
1792 path.remove_prefix(std::min(next + 1, path.size()));
1793 while (next != path.npos && !path.empty()) {
1794 next = path.find('/');
1795 component.assign(path.substr(0, next));
1796 fd = openDirFd(fd, component.c_str());
1797 if (!fd.ok()) {
1798 return fd;
1799 }
1800 path.remove_prefix(std::min(next + 1, path.size()));
1801 }
1802 return fd;
1803}
1804
1805std::pair<android::base::unique_fd, std::string> OpenDirInProcfs(std::string_view path) {
1806 auto fd = openAbsolutePathFd(path);
1807 if (!fd.ok()) {
1808 return {};
1809 }
1810
1811 auto linkPath = std::string("/proc/self/fd/") += std::to_string(fd.get());
1812 return {std::move(fd), std::move(linkPath)};
1813}
1814
Paul Lawrence9adf86a2023-04-14 10:06:49 -07001815static bool IsPropertySet(const char* name, bool& value) {
1816 if (base::GetProperty(name, "") == "") return false;
1817
1818 value = base::GetBoolProperty(name, false);
1819 LOG(INFO) << "fuse-bpf is " << (value ? "enabled" : "disabled") << " because of property "
1820 << name;
1821 return true;
1822}
1823
Alessio Balsini583ae3e2022-03-23 18:27:59 +00001824bool IsFuseBpfEnabled() {
Paul Lawrence9adf86a2023-04-14 10:06:49 -07001825 // This logic is reproduced in packages/providers/MediaProvider/jni/FuseDaemon.cpp
1826 // so changes made here must be reflected there
1827 bool enabled = false;
Paul Lawrence72781622023-03-01 14:32:46 -08001828
Paul Lawrence9adf86a2023-04-14 10:06:49 -07001829 if (IsPropertySet("ro.fuse.bpf.is_running", enabled)) return enabled;
Paul Lawrencea688c4f2022-12-14 14:35:05 -08001830
Paul Lawrence9adf86a2023-04-14 10:06:49 -07001831 if (!IsPropertySet("persist.sys.fuse.bpf.override", enabled) &&
1832 !IsPropertySet("ro.fuse.bpf.enabled", enabled)) {
1833 // If the kernel has fuse-bpf, /sys/fs/fuse/features/fuse_bpf will exist and have the
1834 // contents 'supported\n' - see fs/fuse/inode.c in the kernel source
1835 std::string contents;
1836 const char* filename = "/sys/fs/fuse/features/fuse_bpf";
1837 if (!base::ReadFileToString(filename, &contents)) {
1838 LOG(INFO) << "fuse-bpf is disabled because " << filename << " cannot be read";
1839 enabled = false;
1840 } else if (contents == "supported\n") {
1841 LOG(INFO) << "fuse-bpf is enabled because " << filename << " reads 'supported'";
1842 enabled = true;
1843 } else {
1844 LOG(INFO) << "fuse-bpf is disabled because " << filename
1845 << " does not read 'supported'";
1846 enabled = false;
1847 }
Alessio Balsini583ae3e2022-03-23 18:27:59 +00001848 }
Paul Lawrence9adf86a2023-04-14 10:06:49 -07001849
1850 std::string value = enabled ? "true" : "false";
1851 LOG(INFO) << "Setting ro.fuse.bpf.is_running to " << value;
1852 base::SetProperty("ro.fuse.bpf.is_running", value);
1853 return enabled;
Alessio Balsini583ae3e2022-03-23 18:27:59 +00001854}
1855
Himanshu Gupta4f179692024-05-06 11:40:19 +01001856status_t PrepareMountDirForUser(userid_t user_id) {
1857 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1858 LOG(INFO) << "Creating mount directory " << pre_fuse_path;
1859 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1860 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1861 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1862 // These bits should be consistent with what is set in zygote in
1863 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
1864 auto result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
1865 multiuser_get_uid(user_id, AID_EVERYBODY));
1866 if (result != android::OK) {
1867 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
1868 return -1;
1869 }
1870 return result;
1871}
1872
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001873} // namespace vold
1874} // namespace android