blob: 7f64d33be0b09b95a57586076f932753f1b162a3 [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 Biggers2ef4e852023-02-24 18:09:25 +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 Biggers2ef4e852023-02-24 18:09:25 +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 Biggers2ef4e852023-02-24 18:09:25 +0000108 if (selabel_lookup(sehandle, &tmp_secontext, cpath, S_IFBLK) != 0) {
109 PLOG(ERROR) << "Failed to look up selabel for device node " << path;
110 return -errno;
111 }
112 secontext.reset(tmp_secontext);
113 if (setfscreatecon(secontext.get()) != 0) {
114 LOG(ERROR) << "Failed to setfscreatecon for device node " << path;
115 return -EINVAL;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800116 }
117
118 mode_t mode = 0660 | S_IFBLK;
119 if (mknod(cpath, mode, dev) < 0) {
120 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700121 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
122 << " at " << path;
Eric Biggers2ef4e852023-02-24 18:09:25 +0000123 return -errno;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800124 }
125 }
Eric Biggers2ef4e852023-02-24 18:09:25 +0000126 return OK;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800127}
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.
Martijn Coenen5adf92a2021-02-01 07:57:02 +0000139status_t SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
140 std::vector<gid_t> additionalGids) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700141 if (IsSdcardfsUsed()) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100142 // sdcardfs magically takes care of this
143 return OK;
144 }
145
Martijn Coenen1129b812020-06-16 14:58:52 +0200146 size_t num_entries = 3 + (additionalGids.size() > 0 ? additionalGids.size() + 1 : 0);
147 size_t size = sizeof(posix_acl_xattr_header) + num_entries * sizeof(posix_acl_xattr_entry);
Martijn Coenen879fa802020-02-11 12:37:25 +0100148 auto buf = std::make_unique<uint8_t[]>(size);
149
150 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
151 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
152
153 posix_acl_xattr_entry* entry =
154 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
155
Martijn Coenen1129b812020-06-16 14:58:52 +0200156 int tag_index = 0;
157
158 entry[tag_index].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100159 // The existing mode_t mask has the ACL in the lower 9 bits:
160 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
161 // Use the mode_t masks to get these bits out, and shift them to get the
162 // correct value per entity.
163 //
164 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
Martijn Coenen1129b812020-06-16 14:58:52 +0200165 entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
166 entry[tag_index].e_id = uid;
167 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100168
Martijn Coenen1129b812020-06-16 14:58:52 +0200169 entry[tag_index].e_tag = ACL_GROUP_OBJ;
170 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
171 entry[tag_index].e_id = gid;
172 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100173
Martijn Coenen1129b812020-06-16 14:58:52 +0200174 if (additionalGids.size() > 0) {
175 for (gid_t additional_gid : additionalGids) {
176 entry[tag_index].e_tag = ACL_GROUP;
177 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
178 entry[tag_index].e_id = additional_gid;
179 tag_index++;
180 }
181
182 entry[tag_index].e_tag = ACL_MASK;
183 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
184 entry[tag_index].e_id = 0;
185 tag_index++;
186 }
187
188 entry[tag_index].e_tag = ACL_OTHER;
189 entry[tag_index].e_perm = mode & S_IRWXO;
190 entry[tag_index].e_id = 0;
Martijn Coenen879fa802020-02-11 12:37:25 +0100191
192 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
193
194 if (ret != 0) {
195 PLOG(ERROR) << "Failed to set default ACL on " << path;
196 }
197
198 return ret;
199}
200
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100201int SetQuotaInherit(const std::string& path) {
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700202 unsigned int flags;
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100203
204 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
205 if (fd == -1) {
206 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
207 return -1;
208 }
209
210 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
211 if (ret == -1) {
212 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
213 return ret;
214 }
215
216 flags |= FS_PROJINHERIT_FL;
217
218 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
219 if (ret == -1) {
220 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
221 return ret;
222 }
223
224 return 0;
225}
226
227int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100228 struct fsxattr fsx;
229
230 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
231 if (fd == -1) {
232 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
233 return -1;
234 }
235
236 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
237 if (ret == -1) {
238 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
239 return ret;
240 }
241
242 fsx.fsx_projid = projectId;
Eric Biggers39aa9582021-05-03 12:29:40 -0700243 ret = ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
244 if (ret == -1) {
245 PLOG(ERROR) << "Failed to set project id on " << path;
246 return ret;
247 }
248 return 0;
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100249}
250
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100251int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
252 long projectId) {
253 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
254
255 if (ret != 0) {
256 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100257 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100258
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700259 if (!IsSdcardfsUsed()) {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100260 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100261 }
262
263 return ret;
264}
265
Martijn Coenen816f4d92020-02-18 15:06:37 +0100266static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
267 namespace fs = std::filesystem;
268
269 // Setup the directory itself correctly
270 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
271 if (ret != OK) {
272 return ret;
273 }
274
275 // Fixup all of its file entries
276 for (const auto& itEntry : fs::directory_iterator(path)) {
277 ret = lchown(itEntry.path().c_str(), uid, gid);
278 if (ret != 0) {
279 return ret;
280 }
281
282 ret = chmod(itEntry.path().c_str(), mode);
283 if (ret != 0) {
284 return ret;
285 }
286
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700287 if (!IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +0100288 ret = SetQuotaProjectId(itEntry.path(), projectId);
289 if (ret != 0) {
290 return ret;
291 }
292 }
293 }
294
295 return OK;
296}
297
298int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
299 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100300 long projectId;
301 size_t pos;
302 int ret = 0;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700303 bool sdcardfsSupport = IsSdcardfsUsed();
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100304
305 // Make sure the Android/ directories exist and are setup correctly
306 ret = PrepareAndroidDirs(root);
307 if (ret != 0) {
308 LOG(ERROR) << "Failed to prepare Android/ directories.";
309 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100310 }
311
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100312 // Now create the application-specific subdir(s)
313 // path is something like /data/media/0/Android/data/com.foo/files
314 // First, chop off the volume root, eg /data/media/0
315 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100316
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100317 uid_t uid = appUid;
318 gid_t gid = AID_MEDIA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200319 std::vector<gid_t> additionalGids;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100320 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100321
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100322 // Check that the next part matches one of the allowed Android/ dirs
323 if (StartsWith(pathFromRoot, kAppDataDir)) {
324 appDir = kAppDataDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700325 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100326 gid = AID_EXT_DATA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200327 // Also add the app's own UID as a group; since apps belong to a group
328 // that matches their UID, this ensures that they will always have access to
329 // the files created in these dirs, even if they are created by other processes
330 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100331 }
332 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
333 appDir = kAppMediaDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700334 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100335 gid = AID_MEDIA_RW;
336 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000337 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100338 appDir = kAppObbDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700339 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100340 gid = AID_EXT_OBB_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200341 // See comments for kAppDataDir above
342 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100343 }
344 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100345 LOG(ERROR) << "Invalid application directory: " << path;
346 return -EINVAL;
347 }
348
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100349 // mode = 770, plus sticky bit on directory to inherit GID when apps
350 // create subdirs
351 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100352 // the project ID for application-specific directories is directly
353 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100354
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100355 // Chop off the generic application-specific part, eg /Android/data/
356 // this leaves us with something like com.foo/files/
357 std::string leftToCreate = pathFromRoot.substr(appDir.length());
358 if (!EndsWith(leftToCreate, "/")) {
359 leftToCreate += "/";
360 }
361 std::string pathToCreate = root + appDir;
362 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100363 // Derive initial project ID
364 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
365 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
366 } else if (appDir == kAppObbDir) {
367 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
368 }
369
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100370 while ((pos = leftToCreate.find('/')) != std::string::npos) {
371 std::string component = leftToCreate.substr(0, pos + 1);
372 leftToCreate = leftToCreate.erase(0, pos + 1);
373 pathToCreate = pathToCreate + component;
374
375 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
376 // All dirs use the "app" project ID, except for the cache dirs in
377 // Android/data, eg Android/data/com.foo/cache
378 // Note that this "sticks" - eg subdirs of this dir need the same
379 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100380 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100381 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100382
383 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
384 // Fixup all files in this existing directory with the correct UID/GID
385 // and project ID.
386 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
387 } else {
388 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
389 }
390
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100391 if (ret != 0) {
392 return ret;
393 }
394
395 if (depth == 0) {
396 // Set the default ACL on the top-level application-specific directories,
397 // to ensure that even if applications run with a umask of 0077,
398 // new directories within these directories will allow the GID
399 // specified here to write; this is necessary for apps like
400 // installers and MTP, that require access here.
401 //
402 // See man (5) acl for more details.
Martijn Coenen1129b812020-06-16 14:58:52 +0200403 ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100404 if (ret != 0) {
405 return ret;
406 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100407
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700408 if (!sdcardfsSupport) {
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100409 // Set project ID inheritance, so that future subdirectories inherit the
410 // same project ID
411 ret = SetQuotaInherit(pathToCreate);
412 if (ret != 0) {
413 return ret;
414 }
415 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100416 }
417
418 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100419 }
420
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100421 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100422}
423
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700424int SetAttrs(const std::string& path, unsigned int attrs) {
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700425 unsigned int flags;
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700426 android::base::unique_fd fd(
427 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
428
429 if (fd == -1) {
430 PLOG(ERROR) << "Failed to open " << path;
431 return -1;
432 }
433
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700434 if (ioctl(fd, FS_IOC_GETFLAGS, &flags)) {
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700435 PLOG(ERROR) << "Failed to get flags for " << path;
436 return -1;
437 }
438
439 if ((flags & attrs) == attrs) return 0;
440 flags |= attrs;
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700441 if (ioctl(fd, FS_IOC_SETFLAGS, &flags)) {
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700442 PLOG(ERROR) << "Failed to set flags for " << path << "(0x" << std::hex << attrs << ")";
443 return -1;
444 }
445 return 0;
446}
447
448status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
449 unsigned int attrs) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600450 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700451 const char* cpath = path.c_str();
Eric Biggers2ef4e852023-02-24 18:09:25 +0000452 auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); });
453 auto secontext = std::unique_ptr<char, void (*)(char*)>(nullptr, freecon);
454 char* tmp_secontext;
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700455
Eric Biggers2ef4e852023-02-24 18:09:25 +0000456 if (selabel_lookup(sehandle, &tmp_secontext, cpath, S_IFDIR) != 0) {
457 PLOG(ERROR) << "Failed to look up selabel for directory " << path;
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700458 return -errno;
459 }
Eric Biggers2ef4e852023-02-24 18:09:25 +0000460 secontext.reset(tmp_secontext);
461 if (setfscreatecon(secontext.get()) != 0) {
462 LOG(ERROR) << "Failed to setfscreatecon for directory " << path;
463 return -EINVAL;
464 }
465
466 if (fs_prepare_dir(cpath, mode, uid, gid) != 0) return -errno;
467 if (attrs && SetAttrs(path, attrs) != 0) return -errno;
468 return OK;
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700469}
470
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800471status_t ForceUnmount(const std::string& path) {
472 const char* cpath = path.c_str();
473 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
474 return OK;
475 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700476 // Apps might still be handling eject request, so wait before
477 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700478 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700479
Jeff Sharkey3472e522017-10-06 18:02:53 -0600480 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700481 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700482 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
483 return OK;
484 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700485
Jeff Sharkey3472e522017-10-06 18:02:53 -0600486 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700487 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800488 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
489 return OK;
490 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700491
Jeff Sharkey3472e522017-10-06 18:02:53 -0600492 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700493 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700494 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
495 return OK;
496 }
Zim3623a212019-07-19 16:46:53 +0100497 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800498 return -errno;
499}
500
Ricky Wai23356372021-04-30 09:53:07 +0100501status_t KillProcessesWithTmpfsMountPrefix(const std::string& path) {
502 if (KillProcessesWithTmpfsMounts(path, SIGINT) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000503 return OK;
504 }
505 if (sSleepOnUnmount) sleep(5);
506
Ricky Wai23356372021-04-30 09:53:07 +0100507 if (KillProcessesWithTmpfsMounts(path, SIGTERM) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000508 return OK;
509 }
510 if (sSleepOnUnmount) sleep(5);
511
Ricky Wai23356372021-04-30 09:53:07 +0100512 if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000513 return OK;
514 }
515 if (sSleepOnUnmount) sleep(5);
516
517 // Send SIGKILL a second time to determine if we've
518 // actually killed everyone mount
Ricky Wai23356372021-04-30 09:53:07 +0100519 if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000520 return OK;
521 }
522 PLOG(ERROR) << "Failed to kill processes using " << path;
523 return -EBUSY;
524}
525
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700526status_t KillProcessesUsingPath(const std::string& path) {
Zim75273002021-03-04 12:21:24 +0000527 if (KillProcessesWithOpenFiles(path, SIGINT, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700528 return OK;
529 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700530 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700531
Zim75273002021-03-04 12:21:24 +0000532 if (KillProcessesWithOpenFiles(path, SIGTERM, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700533 return OK;
534 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700535 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700536
Zim75273002021-03-04 12:21:24 +0000537 if (KillProcessesWithOpenFiles(path, SIGKILL, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700538 return OK;
539 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700540 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700541
542 // Send SIGKILL a second time to determine if we've
543 // actually killed everyone with open files
Zim75273002021-03-04 12:21:24 +0000544 // This time, we also kill the FUSE daemon if found
545 if (KillProcessesWithOpenFiles(path, SIGKILL, true /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700546 return OK;
547 }
548 PLOG(ERROR) << "Failed to kill processes using " << path;
549 return -EBUSY;
550}
551
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700552status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800553 if (UnmountTree(target) < 0) {
554 return -errno;
555 }
556 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700557 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
558 return -errno;
559 }
560 return OK;
561}
562
Sudheer Shanka023b5392019-02-06 12:39:19 -0800563status_t Symlink(const std::string& target, const std::string& linkpath) {
564 if (Unlink(linkpath) < 0) {
565 return -errno;
566 }
567 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
568 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
569 return -errno;
570 }
571 return OK;
572}
573
574status_t Unlink(const std::string& linkpath) {
575 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
576 PLOG(ERROR) << "Failed to unlink " << linkpath;
577 return -errno;
578 }
579 return OK;
580}
581
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000582status_t CreateDir(const std::string& dir, mode_t mode) {
583 struct stat sb;
584 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
585 if (S_ISDIR(sb.st_mode)) {
586 return OK;
587 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
588 PLOG(ERROR) << "Failed to unlink " << dir;
589 return -errno;
590 }
591 } else if (errno != ENOENT) {
592 PLOG(ERROR) << "Failed to stat " << dir;
593 return -errno;
594 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800595 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000596 PLOG(ERROR) << "Failed to mkdir " << dir;
597 return -errno;
598 }
599 return OK;
600}
601
Jeff Sharkey3472e522017-10-06 18:02:53 -0600602bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
603 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800604 size_t start = 0;
605 while (true) {
606 start = raw.find(qual, start);
607 if (start == std::string::npos) return false;
608 if (start == 0 || raw[start - 1] == ' ') {
609 break;
610 }
611 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600612 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600613 start += qual.length();
614
615 auto end = raw.find("\"", start);
616 if (end == std::string::npos) return false;
617
618 *value = raw.substr(start, end - start);
619 return true;
620}
621
Paul Crowley14c8c072018-09-18 13:30:21 -0700622static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
623 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600624 fsType->clear();
625 fsUuid->clear();
626 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700627
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700628 std::vector<std::string> cmd;
629 cmd.push_back(kBlkidPath);
630 cmd.push_back("-c");
631 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700632 cmd.push_back("-s");
633 cmd.push_back("TYPE");
634 cmd.push_back("-s");
635 cmd.push_back("UUID");
636 cmd.push_back("-s");
637 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700638 cmd.push_back(path);
639
640 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800641 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700642 if (res != OK) {
643 LOG(WARNING) << "blkid failed to identify " << path;
644 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700645 }
646
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700647 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700648 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600649 FindValue(line, "TYPE", fsType);
650 FindValue(line, "UUID", fsUuid);
651 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700652 }
653
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700654 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700655}
656
Paul Crowley14c8c072018-09-18 13:30:21 -0700657status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
658 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700659 return readMetadata(path, fsType, fsUuid, fsLabel, false);
660}
661
Paul Crowley14c8c072018-09-18 13:30:21 -0700662status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
663 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700664 return readMetadata(path, fsType, fsUuid, fsLabel, true);
665}
666
Paul Crowleyde2d6202018-11-30 11:43:47 -0800667static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
668 std::vector<const char*> argv;
669 argv.reserve(args.size() + 1);
670 for (const auto& arg : args) {
671 if (argv.empty()) {
672 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700673 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800674 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700675 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800676 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700677 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800678 argv.emplace_back(nullptr);
679 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700680}
681
Paul Crowleyde2d6202018-11-30 11:43:47 -0800682static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
683 android::base::unique_fd ufd) {
684 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700685 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800686 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700687 return -errno;
688 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800689 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700690 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800691 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700692 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800693 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700694 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800695 return OK;
696}
697
698status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
ThiƩbaud Weksteenae8550f2021-09-10 10:51:08 +0200699 char* context) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800700 auto argv = ConvertToArgv(args);
701
Paul Crowleye6d76632018-11-30 11:43:47 -0800702 android::base::unique_fd pipe_read, pipe_write;
703 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
704 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800705 return -errno;
706 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800707
708 pid_t pid = fork();
709 if (pid == 0) {
710 if (context) {
711 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800712 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800713 abort();
714 }
715 }
716 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800717 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
718 PLOG(ERROR) << "dup2 in ForkExecvp";
719 _exit(EXIT_FAILURE);
720 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800721 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800722 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800723 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800724 _exit(EXIT_FAILURE);
725 }
726 if (pid == -1) {
727 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700728 return -errno;
729 }
730
Paul Crowleyde2d6202018-11-30 11:43:47 -0800731 pipe_write.reset();
732 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
733 if (st != 0) return st;
734
735 int status;
736 if (waitpid(pid, &status, 0) == -1) {
737 PLOG(ERROR) << "waitpid in ForkExecvp";
738 return -errno;
739 }
740 if (!WIFEXITED(status)) {
741 LOG(ERROR) << "Process did not exit normally, status: " << status;
742 return -ECHILD;
743 }
744 if (WEXITSTATUS(status)) {
745 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
746 return WEXITSTATUS(status);
747 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700748 return OK;
749}
750
Daniel Rosenbergd9261b12021-09-14 17:32:06 -0700751status_t ForkExecvpTimeout(const std::vector<std::string>& args, std::chrono::seconds timeout,
752 char* context) {
753 int status;
754
755 pid_t wait_timeout_pid = fork();
756 if (wait_timeout_pid == 0) {
757 pid_t pid = ForkExecvpAsync(args, context);
758 if (pid == -1) {
759 _exit(EXIT_FAILURE);
760 }
761 pid_t timer_pid = fork();
762 if (timer_pid == 0) {
Daniel Rosenberg8cd81fa2022-11-21 16:46:13 -0800763 std::this_thread::sleep_for(timeout);
Daniel Rosenbergd9261b12021-09-14 17:32:06 -0700764 _exit(ETIMEDOUT);
765 }
766 if (timer_pid == -1) {
767 PLOG(ERROR) << "fork in ForkExecvpAsync_timeout";
768 kill(pid, SIGTERM);
769 _exit(EXIT_FAILURE);
770 }
771 pid_t finished = wait(&status);
772 if (finished == pid) {
773 kill(timer_pid, SIGTERM);
774 } else {
775 kill(pid, SIGTERM);
776 }
777 if (!WIFEXITED(status)) {
778 _exit(ECHILD);
779 }
780 _exit(WEXITSTATUS(status));
781 }
782 if (waitpid(wait_timeout_pid, &status, 0) == -1) {
783 PLOG(ERROR) << "waitpid in ForkExecvpAsync_timeout";
784 return -errno;
785 }
786 if (!WIFEXITED(status)) {
787 LOG(ERROR) << "Process did not exit normally, status: " << status;
788 return -ECHILD;
789 }
790 if (WEXITSTATUS(status)) {
791 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
792 return WEXITSTATUS(status);
793 }
794 return OK;
795}
796
797pid_t ForkExecvpAsync(const std::vector<std::string>& args, char* context) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800798 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700799
800 pid_t pid = fork();
801 if (pid == 0) {
802 close(STDIN_FILENO);
803 close(STDOUT_FILENO);
804 close(STDERR_FILENO);
Daniel Rosenbergd9261b12021-09-14 17:32:06 -0700805 if (context) {
806 if (setexeccon(context)) {
807 LOG(ERROR) << "Failed to setexeccon in ForkExecvpAsync";
808 abort();
809 }
810 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700811
Paul Crowleyde2d6202018-11-30 11:43:47 -0800812 execvp(argv[0], const_cast<char**>(argv.data()));
813 PLOG(ERROR) << "exec in ForkExecvpAsync";
814 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700815 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700816 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800817 PLOG(ERROR) << "fork in ForkExecvpAsync";
818 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700819 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700820 return pid;
821}
822
Jeff Sharkey9c484982015-03-31 10:35:33 -0700823status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100824 out.resize(bytes);
825 return ReadRandomBytes(bytes, &out[0]);
826}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700827
Pavel Grafove2e2d302017-08-01 17:15:53 +0100828status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700829 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
830 if (fd == -1) {
831 return -errno;
832 }
833
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800834 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100835 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700836 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100837 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700838 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700839 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700840
841 if (bytes == 0) {
842 return OK;
843 } else {
844 return -EIO;
845 }
846}
847
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600848status_t GenerateRandomUuid(std::string& out) {
849 status_t res = ReadRandomBytes(16, out);
850 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700851 out[6] &= 0x0f; /* clear version */
852 out[6] |= 0x40; /* set to version 4 */
853 out[8] &= 0x3f; /* clear variant */
854 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600855 }
856 return res;
857}
858
Jeff Sharkey9c484982015-03-31 10:35:33 -0700859status_t HexToStr(const std::string& hex, std::string& str) {
860 str.clear();
861 bool even = true;
862 char cur = 0;
863 for (size_t i = 0; i < hex.size(); i++) {
864 int val = 0;
865 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700866 // clang-format off
867 case ' ': case '-': case ':': continue;
868 case 'f': case 'F': val = 15; break;
869 case 'e': case 'E': val = 14; break;
870 case 'd': case 'D': val = 13; break;
871 case 'c': case 'C': val = 12; break;
872 case 'b': case 'B': val = 11; break;
873 case 'a': case 'A': val = 10; break;
874 case '9': val = 9; break;
875 case '8': val = 8; break;
876 case '7': val = 7; break;
877 case '6': val = 6; break;
878 case '5': val = 5; break;
879 case '4': val = 4; break;
880 case '3': val = 3; break;
881 case '2': val = 2; break;
882 case '1': val = 1; break;
883 case '0': val = 0; break;
884 default: return -EINVAL;
885 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700886 }
887
888 if (even) {
889 cur = val << 4;
890 } else {
891 cur += val;
892 str.push_back(cur);
893 cur = 0;
894 }
895 even = !even;
896 }
897 return even ? OK : -EINVAL;
898}
899
900static const char* kLookup = "0123456789abcdef";
901
902status_t StrToHex(const std::string& str, std::string& hex) {
903 hex.clear();
904 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700905 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700906 hex.push_back(kLookup[str[i] & 0x0F]);
907 }
908 return OK;
909}
910
Pavel Grafove2e2d302017-08-01 17:15:53 +0100911status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
912 hex.clear();
913 for (size_t i = 0; i < str.size(); i++) {
914 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
915 hex.push_back(kLookup[str.data()[i] & 0x0F]);
916 }
917 return OK;
918}
919
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700920status_t NormalizeHex(const std::string& in, std::string& out) {
921 std::string tmp;
922 if (HexToStr(in, tmp)) {
923 return -EINVAL;
924 }
925 return StrToHex(tmp, out);
926}
927
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200928status_t GetBlockDevSize(int fd, uint64_t* size) {
929 if (ioctl(fd, BLKGETSIZE64, size)) {
930 return -errno;
931 }
932
933 return OK;
934}
935
936status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
937 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
938 status_t res = OK;
939
940 if (fd < 0) {
941 return -errno;
942 }
943
944 res = GetBlockDevSize(fd, size);
945
946 close(fd);
947
948 return res;
949}
950
951status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
952 uint64_t size;
953 status_t res = GetBlockDevSize(path, &size);
954
955 if (res != OK) {
956 return res;
957 }
958
959 *nr_sec = size / 512;
960
961 return OK;
962}
963
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700964uint64_t GetFreeBytes(const std::string& path) {
965 struct statvfs sb;
966 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700967 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700968 } else {
969 return -1;
970 }
971}
972
973// TODO: borrowed from frameworks/native/libs/diskusage/ which should
974// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700975static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700976 int64_t blksize = s->st_blksize;
977 // count actual blocks used instead of nominal file size
978 int64_t size = s->st_blocks * 512;
979
980 if (blksize) {
981 /* round up to filesystem block size */
982 size = (size + blksize - 1) & (~(blksize - 1));
983 }
984
985 return size;
986}
987
988// TODO: borrowed from frameworks/native/libs/diskusage/ which should
989// eventually be migrated into system/
990int64_t calculate_dir_size(int dfd) {
991 int64_t size = 0;
992 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700993 DIR* d;
994 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700995
996 d = fdopendir(dfd);
997 if (d == NULL) {
998 close(dfd);
999 return 0;
1000 }
1001
1002 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001003 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001004 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
1005 size += stat_size(&s);
1006 }
1007 if (de->d_type == DT_DIR) {
1008 int subfd;
1009
1010 /* always skip "." and ".." */
Eric Biggers7bcf4272020-11-02 15:31:56 -08001011 if (IsDotOrDotDot(*de)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001012
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -06001013 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001014 if (subfd >= 0) {
1015 size += calculate_dir_size(subfd);
1016 }
1017 }
1018 }
1019 closedir(d);
1020 return size;
1021}
1022
1023uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -06001024 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001025 if (dirfd < 0) {
1026 PLOG(WARNING) << "Failed to open " << path;
1027 return -1;
1028 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -07001029 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001030 }
1031}
1032
Ricky Wai07e64a42020-02-11 14:31:24 +00001033// TODO: Use a better way to determine if it's media provider app.
1034bool IsFuseDaemon(const pid_t pid) {
1035 auto path = StringPrintf("/proc/%d/mounts", pid);
1036 char* tmp;
1037 if (lgetfilecon(path.c_str(), &tmp) < 0) {
1038 return false;
1039 }
1040 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
1041 || android::base::StartsWith(tmp, kMediaProviderCtx);
1042 freecon(tmp);
1043 return result;
1044}
1045
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001046bool IsFilesystemSupported(const std::string& fsType) {
1047 std::string supported;
1048 if (!ReadFileToString(kProcFilesystems, &supported)) {
1049 PLOG(ERROR) << "Failed to read supported filesystems";
1050 return false;
1051 }
1052 return supported.find(fsType + "\n") != std::string::npos;
1053}
1054
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001055bool IsSdcardfsUsed() {
1056 return IsFilesystemSupported("sdcardfs") &&
1057 base::GetBoolProperty(kExternalStorageSdcardfs, true);
1058}
1059
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001060status_t WipeBlockDevice(const std::string& path) {
1061 status_t res = -1;
1062 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001063 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001064
1065 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
1066 if (fd == -1) {
1067 PLOG(ERROR) << "Failed to open " << path;
1068 goto done;
1069 }
1070
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001071 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001072 PLOG(ERROR) << "Failed to determine size of " << path;
1073 goto done;
1074 }
1075
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001076 LOG(INFO) << "About to discard " << range[1] << " on " << path;
1077 if (ioctl(fd, BLKDISCARD, &range) == 0) {
1078 LOG(INFO) << "Discard success on " << path;
1079 res = 0;
1080 } else {
1081 PLOG(ERROR) << "Discard failure on " << path;
1082 }
1083
1084done:
1085 close(fd);
1086 return res;
1087}
1088
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001089static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001090 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001091 return false;
1092 } else {
1093 return true;
1094 }
1095}
1096
Jeff Sharkeybc40cc82015-06-18 14:25:08 -07001097std::string BuildKeyPath(const std::string& partGuid) {
1098 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1099}
1100
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001101std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001102 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001103}
1104
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001105std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001106 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001107}
1108
1109std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001110 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001111}
1112
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001113std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001114 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001115}
1116
Calin Juravle79f55a42016-02-17 20:14:46 +00001117// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1118std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001119 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001120}
1121
Andreas Huber71cd43f2018-01-22 11:25:29 -08001122std::string BuildDataVendorCePath(userid_t userId) {
1123 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1124}
1125
1126std::string BuildDataVendorDePath(userid_t userId) {
1127 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1128}
1129
Paul Crowley3b71fc52017-10-09 10:55:21 -07001130std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001131 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001132 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001133 return "/data";
1134 } else {
1135 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001136 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001137 }
1138}
1139
Paul Crowley3b71fc52017-10-09 10:55:21 -07001140std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001141 // TODO: unify with installd path generation logic
1142 std::string data(BuildDataPath(volumeUuid));
1143 return StringPrintf("%s/media/%u", data.c_str(), userId);
1144}
1145
Mohammad Samiul Islamb4595912022-03-07 20:27:06 +00001146std::string BuildDataMiscCePath(const std::string& volumeUuid, userid_t userId) {
1147 return StringPrintf("%s/misc_ce/%u", BuildDataPath(volumeUuid).c_str(), userId);
1148}
1149
1150std::string BuildDataMiscDePath(const std::string& volumeUuid, userid_t userId) {
1151 return StringPrintf("%s/misc_de/%u", BuildDataPath(volumeUuid).c_str(), userId);
1152}
1153
Paul Crowley3b71fc52017-10-09 10:55:21 -07001154std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001155 // TODO: unify with installd path generation logic
1156 std::string data(BuildDataPath(volumeUuid));
cjbaoeb501142017-04-12 00:09:00 +08001157 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001158}
1159
Paul Crowley3b71fc52017-10-09 10:55:21 -07001160std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001161 // TODO: unify with installd path generation logic
1162 std::string data(BuildDataPath(volumeUuid));
1163 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1164}
1165
Jeff Sharkey66270a22015-06-24 11:49:24 -07001166dev_t GetDevice(const std::string& path) {
1167 struct stat sb;
1168 if (stat(path.c_str(), &sb)) {
1169 PLOG(WARNING) << "Failed to stat " << path;
1170 return 0;
1171 } else {
1172 return sb.st_dev;
1173 }
1174}
1175
Eric Biggers9ea53442022-05-11 05:33:25 +00001176// Returns true if |path| exists and is a symlink.
1177bool IsSymlink(const std::string& path) {
1178 struct stat stbuf;
1179 return lstat(path.c_str(), &stbuf) == 0 && S_ISLNK(stbuf.st_mode);
1180}
1181
Eric Biggersf74373b2020-11-05 19:58:26 -08001182// Returns true if |path1| names the same existing file or directory as |path2|.
1183bool IsSameFile(const std::string& path1, const std::string& path2) {
1184 struct stat stbuf1, stbuf2;
1185 if (stat(path1.c_str(), &stbuf1) != 0 || stat(path2.c_str(), &stbuf2) != 0) return false;
1186 return stbuf1.st_ino == stbuf2.st_ino && stbuf1.st_dev == stbuf2.st_dev;
1187}
1188
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001189status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001190 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001191
Tom Cherryd6127ef2017-06-15 17:13:56 -07001192 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001193
Tom Cherryd6127ef2017-06-15 17:13:56 -07001194 android::base::SetProperty(kRestoreconString, "");
1195 android::base::SetProperty(kRestoreconString, path);
1196
1197 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001198
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001199 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001200 return OK;
1201}
1202
Jeff Sharkey3472e522017-10-06 18:02:53 -06001203bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1204 // Shamelessly borrowed from android::base::Readlink()
1205 result->clear();
1206
1207 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1208 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1209 // waste memory to just start there. We add 1 so that we can recognize
1210 // whether it actually fit (rather than being truncated to 4095).
1211 std::vector<char> buf(4095 + 1);
1212 while (true) {
1213 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1214 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001215 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001216 // It fit! (If size == buf.size(), it may have been truncated.)
1217 if (static_cast<size_t>(size) < buf.size()) {
1218 result->assign(&buf[0], size);
1219 return true;
1220 }
1221 // Double our buffer and try again.
1222 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001223 }
1224}
1225
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001226static unsigned int GetMajorBlockVirtioBlk() {
1227 std::string devices;
1228 if (!ReadFileToString(kProcDevices, &devices)) {
1229 PLOG(ERROR) << "Unable to open /proc/devices";
1230 return 0;
1231 }
1232
1233 bool blockSection = false;
1234 for (auto line : android::base::Split(devices, "\n")) {
1235 if (line == "Block devices:") {
1236 blockSection = true;
1237 } else if (line == "Character devices:") {
1238 blockSection = false;
1239 } else if (blockSection) {
1240 auto tokens = android::base::Split(line, " ");
1241 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1242 return std::stoul(tokens[0]);
1243 }
1244 }
1245 }
1246
1247 return 0;
1248}
1249
1250bool IsVirtioBlkDevice(unsigned int major) {
1251 // Most virtualized platforms expose block devices with the virtio-blk
1252 // block device driver. Unfortunately, this driver does not use a fixed
1253 // major number, but relies on the kernel to assign one from a specific
1254 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1255 // per Documentation/devices.txt. This is true even for the latest Linux
1256 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1257 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1258 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001259}
1260
Sudheer Shanka295fb242019-01-16 23:04:07 -08001261status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001262 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1263 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001264 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001265 return -errno;
1266 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001267 return OK;
1268}
1269
Eric Biggers7bcf4272020-11-02 15:31:56 -08001270bool IsDotOrDotDot(const struct dirent& ent) {
1271 return strcmp(ent.d_name, ".") == 0 || strcmp(ent.d_name, "..") == 0;
1272}
1273
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001274static status_t delete_dir_contents(DIR* dir) {
1275 // Shamelessly borrowed from android::installd
1276 int dfd = dirfd(dir);
1277 if (dfd < 0) {
1278 return -errno;
1279 }
1280
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001281 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001282 struct dirent* de;
1283 while ((de = readdir(dir))) {
1284 const char* name = de->d_name;
1285 if (de->d_type == DT_DIR) {
1286 /* always skip "." and ".." */
Eric Biggers7bcf4272020-11-02 15:31:56 -08001287 if (IsDotOrDotDot(*de)) continue;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001288
1289 android::base::unique_fd subfd(
1290 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1291 if (subfd.get() == -1) {
1292 PLOG(ERROR) << "Couldn't openat " << name;
1293 result = -errno;
1294 continue;
1295 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001296 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1297 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001298 if (!subdirp) {
1299 PLOG(ERROR) << "Couldn't fdopendir " << name;
1300 result = -errno;
1301 continue;
1302 }
1303 result = delete_dir_contents(subdirp.get());
1304 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1305 PLOG(ERROR) << "Couldn't unlinkat " << name;
1306 result = -errno;
1307 }
1308 } else {
1309 if (unlinkat(dfd, name, 0) < 0) {
1310 PLOG(ERROR) << "Couldn't unlinkat " << name;
1311 result = -errno;
1312 }
1313 }
1314 }
1315 return result;
1316}
1317
1318status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001319 status_t res = DeleteDirContents(pathname);
1320 if (res < 0) {
1321 return res;
1322 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001323 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001324 PLOG(ERROR) << "rmdir failed on " << pathname;
1325 return -errno;
1326 }
1327 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1328 return OK;
1329}
1330
1331status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001332 // Shamelessly borrowed from android::installd
1333 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1334 if (!dirp) {
1335 if (errno == ENOENT) {
1336 return OK;
1337 }
1338 PLOG(ERROR) << "Failed to opendir " << pathname;
1339 return -errno;
1340 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001341 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001342}
1343
Paul Crowley298fa322018-10-30 15:59:24 -07001344// TODO(118708649): fix duplication with init/util.h
1345status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1346 android::base::Timer t;
1347 while (t.duration() < timeout) {
1348 struct stat sb;
1349 if (stat(filename, &sb) != -1) {
1350 LOG(INFO) << "wait for '" << filename << "' took " << t;
1351 return 0;
1352 }
1353 std::this_thread::sleep_for(10ms);
1354 }
1355 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1356 return -1;
1357}
1358
Eric Biggersbd138dd2021-02-16 15:59:17 -08001359bool pathExists(const std::string& path) {
1360 return access(path.c_str(), F_OK) == 0;
1361}
1362
Paul Crowley621d9b92018-12-07 15:36:09 -08001363bool FsyncDirectory(const std::string& dirname) {
1364 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1365 if (fd == -1) {
1366 PLOG(ERROR) << "Failed to open " << dirname;
1367 return false;
1368 }
1369 if (fsync(fd) == -1) {
1370 if (errno == EROFS || errno == EINVAL) {
1371 PLOG(WARNING) << "Skip fsync " << dirname
1372 << " on a file system does not support synchronization";
1373 } else {
1374 PLOG(ERROR) << "Failed to fsync " << dirname;
1375 return false;
1376 }
1377 }
1378 return true;
1379}
1380
Eric Biggers3345a2a2021-02-16 15:59:17 -08001381bool FsyncParentDirectory(const std::string& path) {
1382 return FsyncDirectory(android::base::Dirname(path));
1383}
1384
Eric Biggersfec0c0e2021-02-16 15:59:17 -08001385// Creates all parent directories of |path| that don't already exist. Assigns
1386// the specified |mode| to any new directories, and also fsync()s their parent
1387// directories so that the new directories get written to disk right away.
1388bool MkdirsSync(const std::string& path, mode_t mode) {
1389 if (path[0] != '/') {
1390 LOG(ERROR) << "MkdirsSync() needs an absolute path, but got " << path;
1391 return false;
1392 }
1393 std::vector<std::string> components = android::base::Split(android::base::Dirname(path), "/");
1394
1395 std::string current_dir = "/";
1396 for (const std::string& component : components) {
1397 if (component.empty()) continue;
1398
1399 std::string parent_dir = current_dir;
1400 if (current_dir != "/") current_dir += "/";
1401 current_dir += component;
1402
1403 if (!pathExists(current_dir)) {
1404 if (mkdir(current_dir.c_str(), mode) != 0) {
1405 PLOG(ERROR) << "Failed to create " << current_dir;
1406 return false;
1407 }
1408 if (!FsyncDirectory(parent_dir)) return false;
1409 LOG(DEBUG) << "Created directory " << current_dir;
1410 }
1411 }
1412 return true;
1413}
1414
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001415bool writeStringToFile(const std::string& payload, const std::string& filename) {
1416 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1417 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1418 if (fd == -1) {
1419 PLOG(ERROR) << "Failed to open " << filename;
1420 return false;
1421 }
1422 if (!android::base::WriteStringToFd(payload, fd)) {
1423 PLOG(ERROR) << "Failed to write to " << filename;
1424 unlink(filename.c_str());
1425 return false;
1426 }
1427 // fsync as close won't guarantee flush data
1428 // see close(2), fsync(2) and b/68901441
1429 if (fsync(fd) == -1) {
1430 if (errno == EROFS || errno == EINVAL) {
1431 PLOG(WARNING) << "Skip fsync " << filename
1432 << " on a file system does not support synchronization";
1433 } else {
1434 PLOG(ERROR) << "Failed to fsync " << filename;
1435 unlink(filename.c_str());
1436 return false;
1437 }
1438 }
1439 return true;
1440}
1441
Martijn Coenen23c04452020-04-29 07:49:41 +02001442status_t AbortFuseConnections() {
1443 namespace fs = std::filesystem;
1444
Oleg Lyovin667de182022-11-02 16:26:53 +03001445 static constexpr const char* kFuseConnections = "/sys/fs/fuse/connections";
1446
1447 std::error_code ec;
1448 for (const auto& itEntry : fs::directory_iterator(kFuseConnections, ec)) {
Tao Wu3d989622020-08-06 19:31:21 -07001449 std::string fsPath = itEntry.path().string() + "/filesystem";
1450 std::string fs;
1451
1452 // Virtiofs is on top of fuse and there isn't any user space daemon.
1453 // Android user space doesn't manage it.
1454 if (android::base::ReadFileToString(fsPath, &fs, false) &&
1455 android::base::Trim(fs) == "virtiofs") {
1456 LOG(INFO) << "Ignore virtiofs connection entry " << itEntry.path().string();
1457 continue;
1458 }
1459
Martijn Coenen23c04452020-04-29 07:49:41 +02001460 std::string abortPath = itEntry.path().string() + "/abort";
1461 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1462 bool ret = writeStringToFile("1", abortPath);
1463 if (!ret) {
1464 LOG(WARNING) << "Failed to write to " << abortPath;
1465 }
1466 }
1467
Oleg Lyovin667de182022-11-02 16:26:53 +03001468 if (ec) {
1469 LOG(WARNING) << "Failed to iterate through " << kFuseConnections << ": " << ec.message();
1470 return -ec.value();
1471 }
1472
Martijn Coenen23c04452020-04-29 07:49:41 +02001473 return OK;
1474}
1475
Ricky Wai07e64a42020-02-11 14:31:24 +00001476status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1477 if (access(path.c_str(), F_OK) != 0) {
1478 PLOG(WARNING) << "Dir does not exist: " << path;
1479 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1480 return -errno;
1481 }
1482 }
1483 return OK;
1484}
1485
Martijn Coenena4850062020-06-29 11:53:34 +02001486// Gets the sysfs path for parameters of the backing device info (bdi)
1487static std::string getBdiPathForMount(const std::string& mount) {
1488 // First figure out MAJOR:MINOR of mount. Simplest way is to stat the path.
1489 struct stat info;
1490 if (stat(mount.c_str(), &info) != 0) {
1491 PLOG(ERROR) << "Failed to stat " << mount;
1492 return "";
1493 }
1494 unsigned int maj = major(info.st_dev);
1495 unsigned int min = minor(info.st_dev);
1496
1497 return StringPrintf("/sys/class/bdi/%u:%u", maj, min);
1498}
1499
1500// Configures max_ratio for the FUSE filesystem.
1501void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio) {
1502 LOG(INFO) << "Configuring max_ratio of " << fuse_mount << " fuse filesystem to " << max_ratio;
1503 if (max_ratio > 100) {
1504 LOG(ERROR) << "Invalid max_ratio: " << max_ratio;
1505 return;
1506 }
1507 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1508 if (fuseBdiPath == "") {
1509 return;
1510 }
1511 std::string max_ratio_file = StringPrintf("%s/max_ratio", fuseBdiPath.c_str());
1512 unique_fd fd(TEMP_FAILURE_RETRY(open(max_ratio_file.c_str(), O_WRONLY | O_CLOEXEC)));
1513 if (fd.get() == -1) {
1514 PLOG(ERROR) << "Failed to open " << max_ratio_file;
1515 return;
1516 }
1517 LOG(INFO) << "Writing " << max_ratio << " to " << max_ratio_file;
1518 if (!WriteStringToFd(std::to_string(max_ratio), fd)) {
1519 PLOG(ERROR) << "Failed to write to " << max_ratio_file;
1520 }
1521}
1522
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001523// Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1524// writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
1525void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1526 LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1527 << read_ahead_kb << "kb";
Martijn Coenena4850062020-06-29 11:53:34 +02001528 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1529 if (fuseBdiPath == "") {
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001530 return;
1531 }
Martijn Coenena4850062020-06-29 11:53:34 +02001532 // We found the bdi path for our filesystem, time to configure read ahead!
1533 std::string read_ahead_file = StringPrintf("%s/read_ahead_kb", fuseBdiPath.c_str());
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001534 unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1535 if (fd.get() == -1) {
1536 PLOG(ERROR) << "Failed to open " << read_ahead_file;
1537 return;
1538 }
1539 LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1540 if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1541 PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1542 }
1543}
1544
Zima438b242019-09-25 14:37:38 +01001545status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1546 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1547 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1548 std::string fuse_path(
1549 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1550
1551 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1552 std::string pass_through_path(
1553 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001554
Zim1242be82020-01-22 18:22:29 +00001555 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1556 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001557 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001558 if (result != android::OK) {
1559 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1560 return -1;
1561 }
1562
Zim06b0caf2020-01-05 02:11:47 +00001563 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1564 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1565 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1566 // These bits should be consistent with what is set in zygote in
1567 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001568 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001569 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001570 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001571 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001572 return -1;
1573 }
1574
Zima438b242019-09-25 14:37:38 +01001575 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1576 if (result != android::OK) {
1577 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1578 return -1;
1579 }
1580
Zim26eec702020-01-31 16:00:58 +00001581 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001582 if (result != android::OK) {
1583 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1584 return -1;
1585 }
1586
Zim26eec702020-01-31 16:00:58 +00001587 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001588 if (result != android::OK) {
1589 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1590 return -1;
1591 }
1592
1593 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001594 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1595 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001596 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001597 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001598 return -1;
1599 }
Zime5393d42019-11-15 11:44:12 +00001600 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001601 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001602
1603 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001604 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001605 if (result != android::OK) {
1606 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1607 return -1;
1608 }
1609 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001610 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001611 }
1612
Nandana Dutta914cc72019-08-29 15:22:42 +01001613 // Open fuse fd.
1614 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1615 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001616 PLOG(ERROR) << "Failed to open /dev/fuse";
1617 return -1;
1618 }
1619
1620 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1621 // permission checks before routing to FUSE daemon.
1622 const auto opts = StringPrintf(
1623 "fd=%i,"
1624 "rootmode=40000,"
1625 "allow_other,"
1626 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001627 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001628
Zima438b242019-09-25 14:37:38 +01001629 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1630 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1631 opts.c_str()));
1632 if (result != 0) {
1633 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001634 return -errno;
1635 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001636
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001637 if (IsSdcardfsUsed()) {
Martijn Coenen86f21a22020-01-06 09:48:14 +01001638 std::string sdcardfs_path(
1639 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1640
1641 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1642 return BindMount(sdcardfs_path, pass_through_path);
1643 } else {
1644 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1645 return BindMount(absolute_lower_path, pass_through_path);
1646 }
Zima438b242019-09-25 14:37:38 +01001647}
1648
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001649status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1650 const std::string& relative_upper_path) {
1651 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1652 std::string pass_through_path(
1653 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1654
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001655 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001656 android::status_t result = ForceUnmount(fuse_path);
Zima438b242019-09-25 14:37:38 +01001657 if (result != android::OK) {
1658 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1659 // Figure out why we get EBUSY and remove this special casing if possible.
1660 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1661 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1662 errno != ENOENT) {
1663 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1664 return -errno;
1665 }
Martijn Coenen57002612019-11-28 11:56:13 +01001666 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001667 }
Martijn Coenen57002612019-11-28 11:56:13 +01001668 rmdir(fuse_path.c_str());
1669
Martijn Coenen64b3bba2020-11-05 10:34:28 +01001670 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1671 auto status = ForceUnmount(pass_through_path);
1672 if (status != android::OK) {
1673 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1674 }
1675 rmdir(pass_through_path.c_str());
1676
Zima438b242019-09-25 14:37:38 +01001677 return result;
Zim3623a212019-07-19 16:46:53 +01001678}
1679
Martijn Coenen62a4b272020-01-31 15:23:09 +01001680status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1681 std::string androidDir = volumeRoot + kAndroidDir;
1682 std::string androidDataDir = volumeRoot + kAppDataDir;
1683 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001684 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001685
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001686 bool useSdcardFs = IsSdcardfsUsed();
Martijn Coenen62a4b272020-01-31 15:23:09 +01001687
Martijn Coenen10570c02020-02-18 10:41:37 +01001688 // mode 0771 + sticky bit for inheriting GIDs
1689 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1690 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001691 PLOG(ERROR) << "Failed to create " << androidDir;
1692 return -errno;
1693 }
1694
1695 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001696 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001697 PLOG(ERROR) << "Failed to create " << androidDataDir;
1698 return -errno;
1699 }
1700
1701 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001702 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001703 PLOG(ERROR) << "Failed to create " << androidObbDir;
1704 return -errno;
1705 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001706 // Some other apps, like installers, have write access to the OBB directory
1707 // to pre-download them. To make sure newly created folders in this directory
1708 // have the right permissions, set a default ACL.
Martijn Coenen1129b812020-06-16 14:58:52 +02001709 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
Martijn Coenen62a4b272020-01-31 15:23:09 +01001710
Martijn Coenen10570c02020-02-18 10:41:37 +01001711 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001712 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1713 return -errno;
1714 }
1715
Martijn Coenen62a4b272020-01-31 15:23:09 +01001716 return OK;
1717}
Yurii Zubrytskyi40389822021-10-18 22:33:15 -07001718
1719namespace ab = android::base;
1720
1721static ab::unique_fd openDirFd(int parentFd, const char* name) {
1722 return ab::unique_fd{::openat(parentFd, name, O_CLOEXEC | O_DIRECTORY | O_PATH | O_NOFOLLOW)};
1723}
1724
1725static ab::unique_fd openAbsolutePathFd(std::string_view path) {
1726 if (path.empty() || path[0] != '/') {
1727 errno = EINVAL;
1728 return {};
1729 }
1730 if (path == "/") {
1731 return openDirFd(-1, "/");
1732 }
1733
1734 // first component is special - it includes the leading slash
1735 auto next = path.find('/', 1);
1736 auto component = std::string(path.substr(0, next));
1737 if (component == "..") {
1738 errno = EINVAL;
1739 return {};
1740 }
1741 auto fd = openDirFd(-1, component.c_str());
1742 if (!fd.ok()) {
1743 return fd;
1744 }
1745 path.remove_prefix(std::min(next + 1, path.size()));
1746 while (next != path.npos && !path.empty()) {
1747 next = path.find('/');
1748 component.assign(path.substr(0, next));
1749 fd = openDirFd(fd, component.c_str());
1750 if (!fd.ok()) {
1751 return fd;
1752 }
1753 path.remove_prefix(std::min(next + 1, path.size()));
1754 }
1755 return fd;
1756}
1757
1758std::pair<android::base::unique_fd, std::string> OpenDirInProcfs(std::string_view path) {
1759 auto fd = openAbsolutePathFd(path);
1760 if (!fd.ok()) {
1761 return {};
1762 }
1763
1764 auto linkPath = std::string("/proc/self/fd/") += std::to_string(fd.get());
1765 return {std::move(fd), std::move(linkPath)};
1766}
1767
Alessio Balsini583ae3e2022-03-23 18:27:59 +00001768bool IsFuseBpfEnabled() {
Paul Lawrence8c250752022-12-12 12:28:35 -08001769 // TODO Once kernel supports flag, trigger off kernel flag unless
1770 // ro.fuse.bpf.enabled is explicitly set to false
Paul Lawrencea688c4f2022-12-14 14:35:05 -08001771 bool enabled;
1772 if (base::GetProperty("ro.fuse.bpf.is_running", "") != "")
1773 enabled = base::GetBoolProperty("ro.fuse.bpf.is_running", false);
1774 else if (base::GetProperty("persist.sys.fuse.bpf.override", "") != "")
1775 enabled = base::GetBoolProperty("persist.sys.fuse.bpf.override", false);
1776 else
1777 enabled = base::GetBoolProperty("ro.fuse.bpf.enabled", false);
1778
1779 if (enabled) {
Paul Lawrence8c250752022-12-12 12:28:35 -08001780 base::SetProperty("ro.fuse.bpf.is_running", "true");
Alessio Balsini583ae3e2022-03-23 18:27:59 +00001781 return true;
Paul Lawrence8c250752022-12-12 12:28:35 -08001782 } else {
1783 base::SetProperty("ro.fuse.bpf.is_running", "false");
Alessio Balsini583ae3e2022-03-23 18:27:59 +00001784 return false;
1785 }
Alessio Balsini583ae3e2022-03-23 18:27:59 +00001786}
1787
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001788} // namespace vold
1789} // namespace android