• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 #include "Utils.h"
18 
19 #include "Process.h"
20 #include "sehandle.h"
21 
22 #include <android-base/chrono_utils.h>
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/properties.h>
26 #include <android-base/scopeguard.h>
27 #include <android-base/stringprintf.h>
28 #include <android-base/strings.h>
29 #include <android-base/unique_fd.h>
30 #include <cutils/fs.h>
31 #include <logwrap/logwrap.h>
32 #include <private/android_filesystem_config.h>
33 #include <private/android_projectid_config.h>
34 
35 #include <dirent.h>
36 #include <fcntl.h>
37 #include <linux/fs.h>
38 #include <linux/posix_acl.h>
39 #include <linux/posix_acl_xattr.h>
40 #include <mntent.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <sys/mount.h>
44 #include <sys/stat.h>
45 #include <sys/statvfs.h>
46 #include <sys/sysmacros.h>
47 #include <sys/types.h>
48 #include <sys/wait.h>
49 #include <sys/xattr.h>
50 #include <unistd.h>
51 
52 #include <filesystem>
53 #include <list>
54 #include <mutex>
55 #include <regex>
56 #include <thread>
57 
58 #ifndef UMOUNT_NOFOLLOW
59 #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
60 #endif
61 
62 using namespace std::chrono_literals;
63 using android::base::EndsWith;
64 using android::base::ReadFileToString;
65 using android::base::StartsWith;
66 using android::base::StringPrintf;
67 using android::base::unique_fd;
68 
69 namespace android {
70 namespace vold {
71 
72 char* sBlkidContext = nullptr;
73 char* sBlkidUntrustedContext = nullptr;
74 char* sFsckContext = nullptr;
75 char* sFsckUntrustedContext = nullptr;
76 
77 bool sSleepOnUnmount = true;
78 
79 static const char* kBlkidPath = "/system/bin/blkid";
80 static const char* kKeyPath = "/data/misc/vold";
81 
82 static const char* kProcDevices = "/proc/devices";
83 static const char* kProcFilesystems = "/proc/filesystems";
84 
85 static const char* kAndroidDir = "/Android/";
86 static const char* kAppDataDir = "/Android/data/";
87 static const char* kAppMediaDir = "/Android/media/";
88 static const char* kAppObbDir = "/Android/obb/";
89 
90 static const char* kMediaProviderCtx = "u:r:mediaprovider:";
91 static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
92 
93 // Lock used to protect process-level SELinux changes from racing with each
94 // other between multiple threads.
95 static std::mutex kSecurityLock;
96 
GetFuseMountPathForUser(userid_t user_id,const std::string & relative_upper_path)97 std::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 
CreateDeviceNode(const std::string & path,dev_t dev)101 status_t CreateDeviceNode(const std::string& path, dev_t dev) {
102     std::lock_guard<std::mutex> lock(kSecurityLock);
103     const char* cpath = path.c_str();
104     auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); });
105     auto secontext = std::unique_ptr<char, void (*)(char*)>(nullptr, freecon);
106     char* tmp_secontext;
107 
108     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;
113         }
114     } 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;
119     }
120 
121     mode_t mode = 0660 | S_IFBLK;
122     if (mknod(cpath, mode, dev) < 0) {
123         if (errno != EEXIST) {
124             PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
125                         << " at " << path;
126             return -errno;
127         }
128     }
129     return OK;
130 }
131 
DestroyDeviceNode(const std::string & path)132 status_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 
141 // Sets a default ACL on the directory.
SetDefaultAcl(const std::string & path,mode_t mode,uid_t uid,gid_t gid,std::vector<gid_t> additionalGids)142 status_t SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
143                        std::vector<gid_t> additionalGids) {
144     if (IsSdcardfsUsed()) {
145         // sdcardfs magically takes care of this
146         return OK;
147     }
148 
149     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);
151     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 
159     int tag_index = 0;
160 
161     entry[tag_index].e_tag = ACL_USER_OBJ;
162     // 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
168     entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
169     entry[tag_index].e_id = uid;
170     tag_index++;
171 
172     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++;
176 
177     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;
194 
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 
SetQuotaInherit(const std::string & path)204 int SetQuotaInherit(const std::string& path) {
205     unsigned int flags;
206 
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 
SetQuotaProjectId(const std::string & path,long projectId)230 int SetQuotaProjectId(const std::string& path, long projectId) {
231     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;
246     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;
252 }
253 
PrepareDirWithProjectId(const std::string & path,mode_t mode,uid_t uid,gid_t gid,long projectId)254 int 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;
260     }
261 
262     if (!IsSdcardfsUsed()) {
263         ret = SetQuotaProjectId(path, projectId);
264     }
265 
266     return ret;
267 }
268 
FixupAppDir(const std::string & path,mode_t mode,uid_t uid,gid_t gid,long projectId)269 static 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 
290         if (!IsSdcardfsUsed()) {
291             ret = SetQuotaProjectId(itEntry.path(), projectId);
292             if (ret != 0) {
293                 return ret;
294             }
295         }
296     }
297 
298     return OK;
299 }
300 
PrepareAppDirFromRoot(const std::string & path,const std::string & root,int appUid,bool fixupExisting)301 int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
302                           bool fixupExisting) {
303     long projectId;
304     size_t pos;
305     int ret = 0;
306     bool sdcardfsSupport = IsSdcardfsUsed();
307 
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;
313     }
314 
315     // 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());
319 
320     uid_t uid = appUid;
321     gid_t gid = AID_MEDIA_RW;
322     std::vector<gid_t> additionalGids;
323     std::string appDir;
324 
325     // Check that the next part matches one of the allowed Android/ dirs
326     if (StartsWith(pathFromRoot, kAppDataDir)) {
327         appDir = kAppDataDir;
328         if (!sdcardfsSupport) {
329             gid = AID_EXT_DATA_RW;
330             // 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);
334         }
335     } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
336         appDir = kAppMediaDir;
337         if (!sdcardfsSupport) {
338             gid = AID_MEDIA_RW;
339         }
340     } else if (StartsWith(pathFromRoot, kAppObbDir)) {
341         appDir = kAppObbDir;
342         if (!sdcardfsSupport) {
343             gid = AID_EXT_OBB_RW;
344             // See comments for kAppDataDir above
345             additionalGids.push_back(uid);
346         }
347     } else {
348         LOG(ERROR) << "Invalid application directory: " << path;
349         return -EINVAL;
350     }
351 
352     // 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;
355     // the project ID for application-specific directories is directly
356     // derived from their uid
357 
358     // 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;
366     // 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 
373     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.
383             projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
384         }
385 
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 
394         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.
406             ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
407             if (ret != 0) {
408                 return ret;
409             }
410 
411             if (!sdcardfsSupport) {
412                 // 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             }
419         }
420 
421         depth++;
422     }
423 
424     return OK;
425 }
426 
SetAttrs(const std::string & path,unsigned int attrs)427 int SetAttrs(const std::string& path, unsigned int attrs) {
428     unsigned int flags;
429     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 
437     if (ioctl(fd, FS_IOC_GETFLAGS, &flags)) {
438         PLOG(ERROR) << "Failed to get flags for " << path;
439         return -1;
440     }
441 
442     if ((flags & attrs) == attrs) return 0;
443     flags |= attrs;
444     if (ioctl(fd, FS_IOC_SETFLAGS, &flags)) {
445         PLOG(ERROR) << "Failed to set flags for " << path << "(0x" << std::hex << attrs << ")";
446         return -1;
447     }
448     return 0;
449 }
450 
PrepareDir(const std::string & path,mode_t mode,uid_t uid,gid_t gid,unsigned int attrs)451 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
452                     unsigned int attrs) {
453     std::lock_guard<std::mutex> lock(kSecurityLock);
454     const char* cpath = path.c_str();
455     auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); });
456     auto secontext = std::unique_ptr<char, void (*)(char*)>(nullptr, freecon);
457     char* tmp_secontext;
458 
459     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;
464         }
465     } else if (errno == ENOENT) {
466         LOG(DEBUG) << "No selabel defined for directory " << path;
467     } else {
468         PLOG(ERROR) << "Failed to look up selabel for directory " << path;
469         return -errno;
470     }
471 
472     if (fs_prepare_dir(cpath, mode, uid, gid) != 0) return -errno;
473     if (attrs && SetAttrs(path, attrs) != 0) return -errno;
474     return OK;
475 }
476 
ForceUnmount(const std::string & path)477 status_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     }
482     // Apps might still be handling eject request, so wait before
483     // we start sending signals
484     if (sSleepOnUnmount) sleep(5);
485 
486     KillProcessesWithOpenFiles(path, SIGINT);
487     if (sSleepOnUnmount) sleep(5);
488     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
489         return OK;
490     }
491 
492     KillProcessesWithOpenFiles(path, SIGTERM);
493     if (sSleepOnUnmount) sleep(5);
494     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
495         return OK;
496     }
497 
498     KillProcessesWithOpenFiles(path, SIGKILL);
499     if (sSleepOnUnmount) sleep(5);
500     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
501         return OK;
502     }
503     PLOG(INFO) << "ForceUnmount failed";
504     return -errno;
505 }
506 
KillProcessesWithTmpfsMountPrefix(const std::string & path)507 status_t KillProcessesWithTmpfsMountPrefix(const std::string& path) {
508     if (KillProcessesWithTmpfsMounts(path, SIGINT) == 0) {
509         return OK;
510     }
511     if (sSleepOnUnmount) sleep(5);
512 
513     if (KillProcessesWithTmpfsMounts(path, SIGTERM) == 0) {
514         return OK;
515     }
516     if (sSleepOnUnmount) sleep(5);
517 
518     if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
519         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
525     if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
526         return OK;
527     }
528     PLOG(ERROR) << "Failed to kill processes using " << path;
529     return -EBUSY;
530 }
531 
KillProcessesUsingPath(const std::string & path)532 status_t KillProcessesUsingPath(const std::string& path) {
533     if (KillProcessesWithOpenFiles(path, SIGINT, false /* killFuseDaemon */) == 0) {
534         return OK;
535     }
536     if (sSleepOnUnmount) sleep(5);
537 
538     if (KillProcessesWithOpenFiles(path, SIGTERM, false /* killFuseDaemon */) == 0) {
539         return OK;
540     }
541     if (sSleepOnUnmount) sleep(5);
542 
543     if (KillProcessesWithOpenFiles(path, SIGKILL, false /* killFuseDaemon */) == 0) {
544         return OK;
545     }
546     if (sSleepOnUnmount) sleep(5);
547 
548     // Send SIGKILL a second time to determine if we've
549     // actually killed everyone with open files
550     // This time, we also kill the FUSE daemon if found
551     if (KillProcessesWithOpenFiles(path, SIGKILL, true /* killFuseDaemon */) == 0) {
552         return OK;
553     }
554     PLOG(ERROR) << "Failed to kill processes using " << path;
555     return -EBUSY;
556 }
557 
BindMount(const std::string & source,const std::string & target)558 status_t BindMount(const std::string& source, const std::string& target) {
559     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) {
563         PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
564         return -errno;
565     }
566     return OK;
567 }
568 
Symlink(const std::string & target,const std::string & linkpath)569 status_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 
Unlink(const std::string & linkpath)580 status_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 
CreateDir(const std::string & dir,mode_t mode)588 status_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     }
601     if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
602         PLOG(ERROR) << "Failed to mkdir " << dir;
603         return -errno;
604     }
605     return OK;
606 }
607 
FindValue(const std::string & raw,const std::string & key,std::string * value)608 bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
609     auto qual = key + "=\"";
610     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;
618     }
619     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 
readMetadata(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel,bool untrusted)628 static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
629                              std::string* fsLabel, bool untrusted) {
630     fsType->clear();
631     fsUuid->clear();
632     fsLabel->clear();
633 
634     std::vector<std::string> cmd;
635     cmd.push_back(kBlkidPath);
636     cmd.push_back("-c");
637     cmd.push_back("/dev/null");
638     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");
644     cmd.push_back(path);
645 
646     std::vector<std::string> output;
647     status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
648     if (res != OK) {
649         LOG(WARNING) << "blkid failed to identify " << path;
650         return res;
651     }
652 
653     for (const auto& line : output) {
654         // Extract values from blkid output, if defined
655         FindValue(line, "TYPE", fsType);
656         FindValue(line, "UUID", fsUuid);
657         FindValue(line, "LABEL", fsLabel);
658     }
659 
660     return OK;
661 }
662 
ReadMetadata(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel)663 status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
664                       std::string* fsLabel) {
665     return readMetadata(path, fsType, fsUuid, fsLabel, false);
666 }
667 
ReadMetadataUntrusted(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel)668 status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
669                                std::string* fsLabel) {
670     return readMetadata(path, fsType, fsUuid, fsLabel, true);
671 }
672 
ConvertToArgv(const std::vector<std::string> & args)673 static 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;
679         } else {
680             LOG(DEBUG) << "    " << arg;
681         }
682         argv.emplace_back(arg.data());
683     }
684     argv.emplace_back(nullptr);
685     return argv;
686 }
687 
ReadLinesFromFdAndLog(std::vector<std::string> * output,android::base::unique_fd ufd)688 static 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);
691     if (!fp) {
692         PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
693         return -errno;
694     }
695     if (output) output->clear();
696     char line[1024];
697     while (fgets(line, sizeof(line), fp.get()) != nullptr) {
698         LOG(DEBUG) << line;
699         if (output) output->emplace_back(line);
700     }
701     return OK;
702 }
703 
ForkExecvp(const std::vector<std::string> & args,std::vector<std::string> * output,char * context)704 status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
705                     char* context) {
706     auto argv = ConvertToArgv(args);
707 
708     android::base::unique_fd pipe_read, pipe_write;
709     if (!android::base::Pipe(&pipe_read, &pipe_write)) {
710         PLOG(ERROR) << "Pipe in ForkExecvp";
711         return -errno;
712     }
713 
714     pid_t pid = fork();
715     if (pid == 0) {
716         if (context) {
717             if (setexeccon(context)) {
718                 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
719                 abort();
720             }
721         }
722         pipe_read.reset();
723         if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
724             PLOG(ERROR) << "dup2 in ForkExecvp";
725             _exit(EXIT_FAILURE);
726         }
727         pipe_write.reset();
728         execvp(argv[0], const_cast<char**>(argv.data()));
729         PLOG(ERROR) << "exec in ForkExecvp";
730         _exit(EXIT_FAILURE);
731     }
732     if (pid == -1) {
733         PLOG(ERROR) << "fork in ForkExecvp";
734         return -errno;
735     }
736 
737     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     }
754     return OK;
755 }
756 
ForkExecvpTimeout(const std::vector<std::string> & args,std::chrono::seconds timeout,char * context)757 status_t ForkExecvpTimeout(const std::vector<std::string>& args, std::chrono::seconds timeout,
758                            char* context) {
759     int status;
760 
761     pid_t wait_timeout_pid = fork();
762     if (wait_timeout_pid == 0) {
763         pid_t pid = ForkExecvpAsync(args, context);
764         if (pid == -1) {
765             _exit(EXIT_FAILURE);
766         }
767         pid_t timer_pid = fork();
768         if (timer_pid == 0) {
769             std::this_thread::sleep_for(timeout);
770             _exit(ETIMEDOUT);
771         }
772         if (timer_pid == -1) {
773             PLOG(ERROR) << "fork in ForkExecvpAsync_timeout";
774             kill(pid, SIGTERM);
775             _exit(EXIT_FAILURE);
776         }
777         pid_t finished = wait(&status);
778         if (finished == pid) {
779             kill(timer_pid, SIGTERM);
780         } else {
781             kill(pid, SIGTERM);
782         }
783         if (!WIFEXITED(status)) {
784             _exit(ECHILD);
785         }
786         _exit(WEXITSTATUS(status));
787     }
788     if (waitpid(wait_timeout_pid, &status, 0) == -1) {
789         PLOG(ERROR) << "waitpid in ForkExecvpAsync_timeout";
790         return -errno;
791     }
792     if (!WIFEXITED(status)) {
793         LOG(ERROR) << "Process did not exit normally, status: " << status;
794         return -ECHILD;
795     }
796     if (WEXITSTATUS(status)) {
797         LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
798         return WEXITSTATUS(status);
799     }
800     return OK;
801 }
802 
ForkExecvpAsync(const std::vector<std::string> & args,char * context)803 pid_t ForkExecvpAsync(const std::vector<std::string>& args, char* context) {
804     auto argv = ConvertToArgv(args);
805 
806     pid_t pid = fork();
807     if (pid == 0) {
808         close(STDIN_FILENO);
809         close(STDOUT_FILENO);
810         close(STDERR_FILENO);
811         if (context) {
812             if (setexeccon(context)) {
813                 LOG(ERROR) << "Failed to setexeccon in ForkExecvpAsync";
814                 abort();
815             }
816         }
817 
818         execvp(argv[0], const_cast<char**>(argv.data()));
819         PLOG(ERROR) << "exec in ForkExecvpAsync";
820         _exit(EXIT_FAILURE);
821     }
822     if (pid == -1) {
823         PLOG(ERROR) << "fork in ForkExecvpAsync";
824         return -1;
825     }
826     return pid;
827 }
828 
ReadRandomBytes(size_t bytes,std::string & out)829 status_t ReadRandomBytes(size_t bytes, std::string& out) {
830     out.resize(bytes);
831     return ReadRandomBytes(bytes, &out[0]);
832 }
833 
ReadRandomBytes(size_t bytes,char * buf)834 status_t ReadRandomBytes(size_t bytes, char* buf) {
835     int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
836     if (fd == -1) {
837         return -errno;
838     }
839 
840     ssize_t n;
841     while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
842         bytes -= n;
843         buf += n;
844     }
845     close(fd);
846 
847     if (bytes == 0) {
848         return OK;
849     } else {
850         return -EIO;
851     }
852 }
853 
GenerateRandomUuid(std::string & out)854 status_t GenerateRandomUuid(std::string& out) {
855     status_t res = ReadRandomBytes(16, out);
856     if (res == OK) {
857         out[6] &= 0x0f; /* clear version        */
858         out[6] |= 0x40; /* set to version 4     */
859         out[8] &= 0x3f; /* clear variant        */
860         out[8] |= 0x80; /* set to IETF variant  */
861     }
862     return res;
863 }
864 
HexToStr(const std::string & hex,std::string & str)865 status_t HexToStr(const std::string& hex, std::string& str) {
866     str.clear();
867     bool even = true;
868     char cur = 0;
869     for (size_t i = 0; i < hex.size(); i++) {
870         int val = 0;
871         switch (hex[i]) {
872             // clang-format off
873             case ' ': case '-': case ':': continue;
874             case 'f': case 'F': val = 15; break;
875             case 'e': case 'E': val = 14; break;
876             case 'd': case 'D': val = 13; break;
877             case 'c': case 'C': val = 12; break;
878             case 'b': case 'B': val = 11; break;
879             case 'a': case 'A': val = 10; break;
880             case '9': val = 9; break;
881             case '8': val = 8; break;
882             case '7': val = 7; break;
883             case '6': val = 6; break;
884             case '5': val = 5; break;
885             case '4': val = 4; break;
886             case '3': val = 3; break;
887             case '2': val = 2; break;
888             case '1': val = 1; break;
889             case '0': val = 0; break;
890             default: return -EINVAL;
891                 // clang-format on
892         }
893 
894         if (even) {
895             cur = val << 4;
896         } else {
897             cur += val;
898             str.push_back(cur);
899             cur = 0;
900         }
901         even = !even;
902     }
903     return even ? OK : -EINVAL;
904 }
905 
906 static const char* kLookup = "0123456789abcdef";
907 
StrToHex(const std::string & str,std::string & hex)908 status_t StrToHex(const std::string& str, std::string& hex) {
909     hex.clear();
910     for (size_t i = 0; i < str.size(); i++) {
911         hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
912         hex.push_back(kLookup[str[i] & 0x0F]);
913     }
914     return OK;
915 }
916 
StrToHex(const KeyBuffer & str,KeyBuffer & hex)917 status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
918     hex.clear();
919     for (size_t i = 0; i < str.size(); i++) {
920         hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
921         hex.push_back(kLookup[str.data()[i] & 0x0F]);
922     }
923     return OK;
924 }
925 
NormalizeHex(const std::string & in,std::string & out)926 status_t NormalizeHex(const std::string& in, std::string& out) {
927     std::string tmp;
928     if (HexToStr(in, tmp)) {
929         return -EINVAL;
930     }
931     return StrToHex(tmp, out);
932 }
933 
GetBlockDevSize(int fd,uint64_t * size)934 status_t GetBlockDevSize(int fd, uint64_t* size) {
935     if (ioctl(fd, BLKGETSIZE64, size)) {
936         return -errno;
937     }
938 
939     return OK;
940 }
941 
GetBlockDevSize(const std::string & path,uint64_t * size)942 status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
943     int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
944     status_t res = OK;
945 
946     if (fd < 0) {
947         return -errno;
948     }
949 
950     res = GetBlockDevSize(fd, size);
951 
952     close(fd);
953 
954     return res;
955 }
956 
GetBlockDev512Sectors(const std::string & path,uint64_t * nr_sec)957 status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
958     uint64_t size;
959     status_t res = GetBlockDevSize(path, &size);
960 
961     if (res != OK) {
962         return res;
963     }
964 
965     *nr_sec = size / 512;
966 
967     return OK;
968 }
969 
GetFreeBytes(const std::string & path)970 uint64_t GetFreeBytes(const std::string& path) {
971     struct statvfs sb;
972     if (statvfs(path.c_str(), &sb) == 0) {
973         return (uint64_t)sb.f_bavail * sb.f_frsize;
974     } else {
975         return -1;
976     }
977 }
978 
979 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
980 // eventually be migrated into system/
stat_size(struct stat * s)981 static int64_t stat_size(struct stat* s) {
982     int64_t blksize = s->st_blksize;
983     // count actual blocks used instead of nominal file size
984     int64_t size = s->st_blocks * 512;
985 
986     if (blksize) {
987         /* round up to filesystem block size */
988         size = (size + blksize - 1) & (~(blksize - 1));
989     }
990 
991     return size;
992 }
993 
994 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
995 // eventually be migrated into system/
calculate_dir_size(int dfd)996 int64_t calculate_dir_size(int dfd) {
997     int64_t size = 0;
998     struct stat s;
999     DIR* d;
1000     struct dirent* de;
1001 
1002     d = fdopendir(dfd);
1003     if (d == NULL) {
1004         close(dfd);
1005         return 0;
1006     }
1007 
1008     while ((de = readdir(d))) {
1009         const char* name = de->d_name;
1010         if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
1011             size += stat_size(&s);
1012         }
1013         if (de->d_type == DT_DIR) {
1014             int subfd;
1015 
1016             /* always skip "." and ".." */
1017             if (IsDotOrDotDot(*de)) continue;
1018 
1019             subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1020             if (subfd >= 0) {
1021                 size += calculate_dir_size(subfd);
1022             }
1023         }
1024     }
1025     closedir(d);
1026     return size;
1027 }
1028 
GetTreeBytes(const std::string & path)1029 uint64_t GetTreeBytes(const std::string& path) {
1030     int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1031     if (dirfd < 0) {
1032         PLOG(WARNING) << "Failed to open " << path;
1033         return -1;
1034     } else {
1035         return calculate_dir_size(dirfd);
1036     }
1037 }
1038 
1039 // TODO: Use a better way to determine if it's media provider app.
IsFuseDaemon(const pid_t pid)1040 bool IsFuseDaemon(const pid_t pid) {
1041     auto path = StringPrintf("/proc/%d/mounts", pid);
1042     char* tmp;
1043     if (lgetfilecon(path.c_str(), &tmp) < 0) {
1044         return false;
1045     }
1046     bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
1047             || android::base::StartsWith(tmp, kMediaProviderCtx);
1048     freecon(tmp);
1049     return result;
1050 }
1051 
IsFilesystemSupported(const std::string & fsType)1052 bool IsFilesystemSupported(const std::string& fsType) {
1053     std::string supported;
1054     if (!ReadFileToString(kProcFilesystems, &supported)) {
1055         PLOG(ERROR) << "Failed to read supported filesystems";
1056         return false;
1057     }
1058     return supported.find(fsType + "\n") != std::string::npos;
1059 }
1060 
IsSdcardfsUsed()1061 bool IsSdcardfsUsed() {
1062     return IsFilesystemSupported("sdcardfs") &&
1063            base::GetBoolProperty(kExternalStorageSdcardfs, true);
1064 }
1065 
WipeBlockDevice(const std::string & path)1066 status_t WipeBlockDevice(const std::string& path) {
1067     status_t res = -1;
1068     const char* c_path = path.c_str();
1069     uint64_t range[2] = {0, 0};
1070 
1071     int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
1072     if (fd == -1) {
1073         PLOG(ERROR) << "Failed to open " << path;
1074         goto done;
1075     }
1076 
1077     if (GetBlockDevSize(fd, &range[1]) != OK) {
1078         PLOG(ERROR) << "Failed to determine size of " << path;
1079         goto done;
1080     }
1081 
1082     LOG(INFO) << "About to discard " << range[1] << " on " << path;
1083     if (ioctl(fd, BLKDISCARD, &range) == 0) {
1084         LOG(INFO) << "Discard success on " << path;
1085         res = 0;
1086     } else {
1087         PLOG(ERROR) << "Discard failure on " << path;
1088     }
1089 
1090 done:
1091     close(fd);
1092     return res;
1093 }
1094 
isValidFilename(const std::string & name)1095 static bool isValidFilename(const std::string& name) {
1096     if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
1097         return false;
1098     } else {
1099         return true;
1100     }
1101 }
1102 
BuildKeyPath(const std::string & partGuid)1103 std::string BuildKeyPath(const std::string& partGuid) {
1104     return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1105 }
1106 
BuildDataSystemLegacyPath(userid_t userId)1107 std::string BuildDataSystemLegacyPath(userid_t userId) {
1108     return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
1109 }
1110 
BuildDataSystemCePath(userid_t userId)1111 std::string BuildDataSystemCePath(userid_t userId) {
1112     return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
1113 }
1114 
BuildDataSystemDePath(userid_t userId)1115 std::string BuildDataSystemDePath(userid_t userId) {
1116     return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
1117 }
1118 
1119 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
BuildDataProfilesDePath(userid_t userId)1120 std::string BuildDataProfilesDePath(userid_t userId) {
1121     return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
1122 }
1123 
BuildDataVendorCePath(userid_t userId)1124 std::string BuildDataVendorCePath(userid_t userId) {
1125     return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1126 }
1127 
BuildDataVendorDePath(userid_t userId)1128 std::string BuildDataVendorDePath(userid_t userId) {
1129     return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1130 }
1131 
BuildDataPath(const std::string & volumeUuid)1132 std::string BuildDataPath(const std::string& volumeUuid) {
1133     // TODO: unify with installd path generation logic
1134     if (volumeUuid.empty()) {
1135         return "/data";
1136     } else {
1137         CHECK(isValidFilename(volumeUuid));
1138         return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
1139     }
1140 }
1141 
BuildDataMediaCePath(const std::string & volumeUuid,userid_t userId)1142 std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
1143     // TODO: unify with installd path generation logic
1144     std::string data(BuildDataPath(volumeUuid));
1145     return StringPrintf("%s/media/%u", data.c_str(), userId);
1146 }
1147 
BuildDataMiscCePath(const std::string & volumeUuid,userid_t userId)1148 std::string BuildDataMiscCePath(const std::string& volumeUuid, userid_t userId) {
1149     return StringPrintf("%s/misc_ce/%u", BuildDataPath(volumeUuid).c_str(), userId);
1150 }
1151 
BuildDataMiscDePath(const std::string & volumeUuid,userid_t userId)1152 std::string BuildDataMiscDePath(const std::string& volumeUuid, userid_t userId) {
1153     return StringPrintf("%s/misc_de/%u", BuildDataPath(volumeUuid).c_str(), userId);
1154 }
1155 
BuildDataUserCePath(const std::string & volumeUuid,userid_t userId)1156 std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
1157     // TODO: unify with installd path generation logic
1158     std::string data(BuildDataPath(volumeUuid));
1159     return StringPrintf("%s/user/%u", data.c_str(), userId);
1160 }
1161 
BuildDataUserDePath(const std::string & volumeUuid,userid_t userId)1162 std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
1163     // TODO: unify with installd path generation logic
1164     std::string data(BuildDataPath(volumeUuid));
1165     return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1166 }
1167 
GetDevice(const std::string & path)1168 dev_t GetDevice(const std::string& path) {
1169     struct stat sb;
1170     if (stat(path.c_str(), &sb)) {
1171         PLOG(WARNING) << "Failed to stat " << path;
1172         return 0;
1173     } else {
1174         return sb.st_dev;
1175     }
1176 }
1177 
1178 // Returns true if |path| exists and is a symlink.
IsSymlink(const std::string & path)1179 bool IsSymlink(const std::string& path) {
1180     struct stat stbuf;
1181     return lstat(path.c_str(), &stbuf) == 0 && S_ISLNK(stbuf.st_mode);
1182 }
1183 
1184 // Returns true if |path1| names the same existing file or directory as |path2|.
IsSameFile(const std::string & path1,const std::string & path2)1185 bool IsSameFile(const std::string& path1, const std::string& path2) {
1186     struct stat stbuf1, stbuf2;
1187     if (stat(path1.c_str(), &stbuf1) != 0 || stat(path2.c_str(), &stbuf2) != 0) return false;
1188     return stbuf1.st_ino == stbuf2.st_ino && stbuf1.st_dev == stbuf2.st_dev;
1189 }
1190 
RestoreconRecursive(const std::string & path)1191 status_t RestoreconRecursive(const std::string& path) {
1192     LOG(DEBUG) << "Starting restorecon of " << path;
1193 
1194     static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
1195 
1196     android::base::SetProperty(kRestoreconString, "");
1197     android::base::SetProperty(kRestoreconString, path);
1198 
1199     android::base::WaitForProperty(kRestoreconString, path);
1200 
1201     LOG(DEBUG) << "Finished restorecon of " << path;
1202     return OK;
1203 }
1204 
Readlinkat(int dirfd,const std::string & path,std::string * result)1205 bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1206     // Shamelessly borrowed from android::base::Readlink()
1207     result->clear();
1208 
1209     // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1210     // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1211     // waste memory to just start there. We add 1 so that we can recognize
1212     // whether it actually fit (rather than being truncated to 4095).
1213     std::vector<char> buf(4095 + 1);
1214     while (true) {
1215         ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1216         // Unrecoverable error?
1217         if (size == -1) return false;
1218         // It fit! (If size == buf.size(), it may have been truncated.)
1219         if (static_cast<size_t>(size) < buf.size()) {
1220             result->assign(&buf[0], size);
1221             return true;
1222         }
1223         // Double our buffer and try again.
1224         buf.resize(buf.size() * 2);
1225     }
1226 }
1227 
GetMajorBlockVirtioBlk()1228 static unsigned int GetMajorBlockVirtioBlk() {
1229     std::string devices;
1230     if (!ReadFileToString(kProcDevices, &devices)) {
1231         PLOG(ERROR) << "Unable to open /proc/devices";
1232         return 0;
1233     }
1234 
1235     bool blockSection = false;
1236     for (auto line : android::base::Split(devices, "\n")) {
1237         if (line == "Block devices:") {
1238             blockSection = true;
1239         } else if (line == "Character devices:") {
1240             blockSection = false;
1241         } else if (blockSection) {
1242             auto tokens = android::base::Split(line, " ");
1243             if (tokens.size() == 2 && tokens[1] == "virtblk") {
1244                 return std::stoul(tokens[0]);
1245             }
1246         }
1247     }
1248 
1249     return 0;
1250 }
1251 
IsVirtioBlkDevice(unsigned int major)1252 bool IsVirtioBlkDevice(unsigned int major) {
1253     // Most virtualized platforms expose block devices with the virtio-blk
1254     // block device driver. Unfortunately, this driver does not use a fixed
1255     // major number, but relies on the kernel to assign one from a specific
1256     // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1257     // per Documentation/devices.txt. This is true even for the latest Linux
1258     // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1259     static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1260     return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
1261 }
1262 
UnmountTree(const std::string & mountPoint)1263 status_t UnmountTree(const std::string& mountPoint) {
1264     if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1265         errno != ENOENT) {
1266         PLOG(ERROR) << "Failed to unmount " << mountPoint;
1267         return -errno;
1268     }
1269     return OK;
1270 }
1271 
IsDotOrDotDot(const struct dirent & ent)1272 bool IsDotOrDotDot(const struct dirent& ent) {
1273     return strcmp(ent.d_name, ".") == 0 || strcmp(ent.d_name, "..") == 0;
1274 }
1275 
delete_dir_contents(DIR * dir)1276 static status_t delete_dir_contents(DIR* dir) {
1277     // Shamelessly borrowed from android::installd
1278     int dfd = dirfd(dir);
1279     if (dfd < 0) {
1280         return -errno;
1281     }
1282 
1283     status_t result = OK;
1284     struct dirent* de;
1285     while ((de = readdir(dir))) {
1286         const char* name = de->d_name;
1287         if (de->d_type == DT_DIR) {
1288             /* always skip "." and ".." */
1289             if (IsDotOrDotDot(*de)) continue;
1290 
1291             android::base::unique_fd subfd(
1292                 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1293             if (subfd.get() == -1) {
1294                 PLOG(ERROR) << "Couldn't openat " << name;
1295                 result = -errno;
1296                 continue;
1297             }
1298             std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1299                 android::base::Fdopendir(std::move(subfd)), closedir);
1300             if (!subdirp) {
1301                 PLOG(ERROR) << "Couldn't fdopendir " << name;
1302                 result = -errno;
1303                 continue;
1304             }
1305             result = delete_dir_contents(subdirp.get());
1306             if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1307                 PLOG(ERROR) << "Couldn't unlinkat " << name;
1308                 result = -errno;
1309             }
1310         } else {
1311             if (unlinkat(dfd, name, 0) < 0) {
1312                 PLOG(ERROR) << "Couldn't unlinkat " << name;
1313                 result = -errno;
1314             }
1315         }
1316     }
1317     return result;
1318 }
1319 
DeleteDirContentsAndDir(const std::string & pathname)1320 status_t DeleteDirContentsAndDir(const std::string& pathname) {
1321     status_t res = DeleteDirContents(pathname);
1322     if (res < 0) {
1323         return res;
1324     }
1325     if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
1326         PLOG(ERROR) << "rmdir failed on " << pathname;
1327         return -errno;
1328     }
1329     LOG(VERBOSE) << "Success: rmdir on " << pathname;
1330     return OK;
1331 }
1332 
DeleteDirContents(const std::string & pathname)1333 status_t DeleteDirContents(const std::string& pathname) {
1334     // Shamelessly borrowed from android::installd
1335     std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1336     if (!dirp) {
1337         if (errno == ENOENT) {
1338             return OK;
1339         }
1340         PLOG(ERROR) << "Failed to opendir " << pathname;
1341         return -errno;
1342     }
1343     return delete_dir_contents(dirp.get());
1344 }
1345 
1346 // TODO(118708649): fix duplication with init/util.h
WaitForFile(const char * filename,std::chrono::nanoseconds timeout)1347 status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1348     android::base::Timer t;
1349     while (t.duration() < timeout) {
1350         struct stat sb;
1351         if (stat(filename, &sb) != -1) {
1352             LOG(INFO) << "wait for '" << filename << "' took " << t;
1353             return 0;
1354         }
1355         std::this_thread::sleep_for(10ms);
1356     }
1357     LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1358     return -1;
1359 }
1360 
pathExists(const std::string & path)1361 bool pathExists(const std::string& path) {
1362     return access(path.c_str(), F_OK) == 0;
1363 }
1364 
FsyncDirectory(const std::string & dirname)1365 bool FsyncDirectory(const std::string& dirname) {
1366     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1367     if (fd == -1) {
1368         PLOG(ERROR) << "Failed to open " << dirname;
1369         return false;
1370     }
1371     if (fsync(fd) == -1) {
1372         if (errno == EROFS || errno == EINVAL) {
1373             PLOG(WARNING) << "Skip fsync " << dirname
1374                           << " on a file system does not support synchronization";
1375         } else {
1376             PLOG(ERROR) << "Failed to fsync " << dirname;
1377             return false;
1378         }
1379     }
1380     return true;
1381 }
1382 
FsyncParentDirectory(const std::string & path)1383 bool FsyncParentDirectory(const std::string& path) {
1384     return FsyncDirectory(android::base::Dirname(path));
1385 }
1386 
1387 // Creates all parent directories of |path| that don't already exist.  Assigns
1388 // the specified |mode| to any new directories, and also fsync()s their parent
1389 // directories so that the new directories get written to disk right away.
MkdirsSync(const std::string & path,mode_t mode)1390 bool MkdirsSync(const std::string& path, mode_t mode) {
1391     if (path[0] != '/') {
1392         LOG(ERROR) << "MkdirsSync() needs an absolute path, but got " << path;
1393         return false;
1394     }
1395     std::vector<std::string> components = android::base::Split(android::base::Dirname(path), "/");
1396 
1397     std::string current_dir = "/";
1398     for (const std::string& component : components) {
1399         if (component.empty()) continue;
1400 
1401         std::string parent_dir = current_dir;
1402         if (current_dir != "/") current_dir += "/";
1403         current_dir += component;
1404 
1405         if (!pathExists(current_dir)) {
1406             if (mkdir(current_dir.c_str(), mode) != 0) {
1407                 PLOG(ERROR) << "Failed to create " << current_dir;
1408                 return false;
1409             }
1410             if (!FsyncDirectory(parent_dir)) return false;
1411             LOG(DEBUG) << "Created directory " << current_dir;
1412         }
1413     }
1414     return true;
1415 }
1416 
writeStringToFile(const std::string & payload,const std::string & filename)1417 bool writeStringToFile(const std::string& payload, const std::string& filename) {
1418     android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1419         open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1420     if (fd == -1) {
1421         PLOG(ERROR) << "Failed to open " << filename;
1422         return false;
1423     }
1424     if (!android::base::WriteStringToFd(payload, fd)) {
1425         PLOG(ERROR) << "Failed to write to " << filename;
1426         unlink(filename.c_str());
1427         return false;
1428     }
1429     // fsync as close won't guarantee flush data
1430     // see close(2), fsync(2) and b/68901441
1431     if (fsync(fd) == -1) {
1432         if (errno == EROFS || errno == EINVAL) {
1433             PLOG(WARNING) << "Skip fsync " << filename
1434                           << " on a file system does not support synchronization";
1435         } else {
1436             PLOG(ERROR) << "Failed to fsync " << filename;
1437             unlink(filename.c_str());
1438             return false;
1439         }
1440     }
1441     return true;
1442 }
1443 
AbortFuseConnections()1444 status_t AbortFuseConnections() {
1445     namespace fs = std::filesystem;
1446 
1447     static constexpr const char* kFuseConnections = "/sys/fs/fuse/connections";
1448 
1449     std::error_code ec;
1450     for (const auto& itEntry : fs::directory_iterator(kFuseConnections, ec)) {
1451         std::string fsPath = itEntry.path().string() + "/filesystem";
1452         std::string fs;
1453 
1454         // Virtiofs is on top of fuse and there isn't any user space daemon.
1455         // Android user space doesn't manage it.
1456         if (android::base::ReadFileToString(fsPath, &fs, false) &&
1457             android::base::Trim(fs) == "virtiofs") {
1458             LOG(INFO) << "Ignore virtiofs connection entry " << itEntry.path().string();
1459             continue;
1460         }
1461 
1462         std::string abortPath = itEntry.path().string() + "/abort";
1463         LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1464         bool ret = writeStringToFile("1", abortPath);
1465         if (!ret) {
1466             LOG(WARNING) << "Failed to write to " << abortPath;
1467         }
1468     }
1469 
1470     if (ec) {
1471         LOG(WARNING) << "Failed to iterate through " << kFuseConnections << ": "  << ec.message();
1472         return -ec.value();
1473     }
1474 
1475     return OK;
1476 }
1477 
EnsureDirExists(const std::string & path,mode_t mode,uid_t uid,gid_t gid)1478 status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1479     if (access(path.c_str(), F_OK) != 0) {
1480         PLOG(WARNING) << "Dir does not exist: " << path;
1481         if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1482             return -errno;
1483         }
1484     }
1485     return OK;
1486 }
1487 
1488 // Gets the sysfs path for parameters of the backing device info (bdi)
getBdiPathForMount(const std::string & mount)1489 static std::string getBdiPathForMount(const std::string& mount) {
1490     // First figure out MAJOR:MINOR of mount. Simplest way is to stat the path.
1491     struct stat info;
1492     if (stat(mount.c_str(), &info) != 0) {
1493         PLOG(ERROR) << "Failed to stat " << mount;
1494         return "";
1495     }
1496     unsigned int maj = major(info.st_dev);
1497     unsigned int min = minor(info.st_dev);
1498 
1499     return StringPrintf("/sys/class/bdi/%u:%u", maj, min);
1500 }
1501 
1502 // Configures max_ratio for the FUSE filesystem.
ConfigureMaxDirtyRatioForFuse(const std::string & fuse_mount,unsigned int max_ratio)1503 void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio) {
1504     LOG(INFO) << "Configuring max_ratio of " << fuse_mount << " fuse filesystem to " << max_ratio;
1505     if (max_ratio > 100) {
1506         LOG(ERROR) << "Invalid max_ratio: " << max_ratio;
1507         return;
1508     }
1509     std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1510     if (fuseBdiPath == "") {
1511         return;
1512     }
1513     std::string max_ratio_file = StringPrintf("%s/max_ratio", fuseBdiPath.c_str());
1514     unique_fd fd(TEMP_FAILURE_RETRY(open(max_ratio_file.c_str(), O_WRONLY | O_CLOEXEC)));
1515     if (fd.get() == -1) {
1516         PLOG(ERROR) << "Failed to open " << max_ratio_file;
1517         return;
1518     }
1519     LOG(INFO) << "Writing " << max_ratio << " to " << max_ratio_file;
1520     if (!WriteStringToFd(std::to_string(max_ratio), fd)) {
1521         PLOG(ERROR) << "Failed to write to " << max_ratio_file;
1522     }
1523 }
1524 
1525 // Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1526 // writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
ConfigureReadAheadForFuse(const std::string & fuse_mount,size_t read_ahead_kb)1527 void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1528     LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1529               << read_ahead_kb << "kb";
1530     std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1531     if (fuseBdiPath == "") {
1532         return;
1533     }
1534     // We found the bdi path for our filesystem, time to configure read ahead!
1535     std::string read_ahead_file = StringPrintf("%s/read_ahead_kb", fuseBdiPath.c_str());
1536     unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1537     if (fd.get() == -1) {
1538         PLOG(ERROR) << "Failed to open " << read_ahead_file;
1539         return;
1540     }
1541     LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1542     if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1543         PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1544     }
1545 }
1546 
MountUserFuse(userid_t user_id,const std::string & absolute_lower_path,const std::string & relative_upper_path,android::base::unique_fd * fuse_fd)1547 status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1548                        const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1549     std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1550     std::string fuse_path(
1551             StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1552 
1553     std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1554     std::string pass_through_path(
1555             StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
1556 
1557     // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1558     // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
1559     auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
1560     if (result != android::OK) {
1561         PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1562         return -1;
1563     }
1564 
1565     // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1566     // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1567     // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1568     // These bits should be consistent with what is set in zygote in
1569     // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
1570     result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
1571                              multiuser_get_uid(user_id, AID_EVERYBODY));
1572     if (result != android::OK) {
1573         PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
1574         return -1;
1575     }
1576 
1577     result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1578     if (result != android::OK) {
1579         PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1580         return -1;
1581     }
1582 
1583     result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
1584     if (result != android::OK) {
1585         PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1586         return -1;
1587     }
1588 
1589     result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
1590     if (result != android::OK) {
1591         PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1592         return -1;
1593     }
1594 
1595     if (relative_upper_path == "emulated") {
1596         std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1597         result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
1598         if (result != android::OK) {
1599             PLOG(ERROR) << "Failed to prepare directory " << linkpath;
1600             return -1;
1601         }
1602         linkpath += "/primary";
1603         Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
1604 
1605         std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
1606         result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
1607         if (result != android::OK) {
1608             PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1609             return -1;
1610         }
1611         pass_through_linkpath += "/primary";
1612         Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
1613     }
1614 
1615     // Open fuse fd.
1616     fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1617     if (fuse_fd->get() == -1) {
1618         PLOG(ERROR) << "Failed to open /dev/fuse";
1619         return -1;
1620     }
1621 
1622     // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1623     // permission checks before routing to FUSE daemon.
1624     const auto opts = StringPrintf(
1625         "fd=%i,"
1626         "rootmode=40000,"
1627         "allow_other,"
1628         "user_id=0,group_id=0,",
1629         fuse_fd->get());
1630 
1631     result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1632                                       MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1633                                       opts.c_str()));
1634     if (result != 0) {
1635         PLOG(ERROR) << "Failed to mount " << fuse_path;
1636         return -errno;
1637     }
1638 
1639     if (IsSdcardfsUsed()) {
1640         std::string sdcardfs_path(
1641                 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1642 
1643         LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1644         return BindMount(sdcardfs_path, pass_through_path);
1645     } else {
1646         LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1647         return BindMount(absolute_lower_path, pass_through_path);
1648     }
1649 }
1650 
UnmountUserFuse(userid_t user_id,const std::string & absolute_lower_path,const std::string & relative_upper_path)1651 status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1652                          const std::string& relative_upper_path) {
1653     std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1654     std::string pass_through_path(
1655             StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1656 
1657     LOG(INFO) << "Unmounting fuse path " << fuse_path;
1658     android::status_t result = ForceUnmount(fuse_path);
1659     if (result != android::OK) {
1660         // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1661         // Figure out why we get EBUSY and remove this special casing if possible.
1662         PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1663         if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1664             errno != ENOENT) {
1665             PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1666             return -errno;
1667         }
1668         result = android::OK;
1669     }
1670     rmdir(fuse_path.c_str());
1671 
1672     LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1673     auto status = ForceUnmount(pass_through_path);
1674     if (status != android::OK) {
1675         LOG(ERROR) << "Failed to unmount " << pass_through_path;
1676     }
1677     rmdir(pass_through_path.c_str());
1678 
1679     return result;
1680 }
1681 
PrepareAndroidDirs(const std::string & volumeRoot)1682 status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1683     std::string androidDir = volumeRoot + kAndroidDir;
1684     std::string androidDataDir = volumeRoot + kAppDataDir;
1685     std::string androidObbDir = volumeRoot + kAppObbDir;
1686     std::string androidMediaDir = volumeRoot + kAppMediaDir;
1687 
1688     bool useSdcardFs = IsSdcardfsUsed();
1689 
1690     // mode 0771 + sticky bit for inheriting GIDs
1691     mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1692     if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1693         PLOG(ERROR) << "Failed to create " << androidDir;
1694         return -errno;
1695     }
1696 
1697     gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
1698     if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
1699         PLOG(ERROR) << "Failed to create " << androidDataDir;
1700         return -errno;
1701     }
1702 
1703     gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
1704     if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
1705         PLOG(ERROR) << "Failed to create " << androidObbDir;
1706         return -errno;
1707     }
1708     // Some other apps, like installers, have write access to the OBB directory
1709     // to pre-download them. To make sure newly created folders in this directory
1710     // have the right permissions, set a default ACL.
1711     SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
1712 
1713     if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1714         PLOG(ERROR) << "Failed to create " << androidMediaDir;
1715         return -errno;
1716     }
1717 
1718     return OK;
1719 }
1720 
1721 namespace ab = android::base;
1722 
openDirFd(int parentFd,const char * name)1723 static ab::unique_fd openDirFd(int parentFd, const char* name) {
1724     return ab::unique_fd{::openat(parentFd, name, O_CLOEXEC | O_DIRECTORY | O_PATH | O_NOFOLLOW)};
1725 }
1726 
openAbsolutePathFd(std::string_view path)1727 static ab::unique_fd openAbsolutePathFd(std::string_view path) {
1728     if (path.empty() || path[0] != '/') {
1729         errno = EINVAL;
1730         return {};
1731     }
1732     if (path == "/") {
1733         return openDirFd(-1, "/");
1734     }
1735 
1736     // first component is special - it includes the leading slash
1737     auto next = path.find('/', 1);
1738     auto component = std::string(path.substr(0, next));
1739     if (component == "..") {
1740         errno = EINVAL;
1741         return {};
1742     }
1743     auto fd = openDirFd(-1, component.c_str());
1744     if (!fd.ok()) {
1745         return fd;
1746     }
1747     path.remove_prefix(std::min(next + 1, path.size()));
1748     while (next != path.npos && !path.empty()) {
1749         next = path.find('/');
1750         component.assign(path.substr(0, next));
1751         fd = openDirFd(fd, component.c_str());
1752         if (!fd.ok()) {
1753             return fd;
1754         }
1755         path.remove_prefix(std::min(next + 1, path.size()));
1756     }
1757     return fd;
1758 }
1759 
OpenDirInProcfs(std::string_view path)1760 std::pair<android::base::unique_fd, std::string> OpenDirInProcfs(std::string_view path) {
1761     auto fd = openAbsolutePathFd(path);
1762     if (!fd.ok()) {
1763         return {};
1764     }
1765 
1766     auto linkPath = std::string("/proc/self/fd/") += std::to_string(fd.get());
1767     return {std::move(fd), std::move(linkPath)};
1768 }
1769 
IsPropertySet(const char * name,bool & value)1770 static bool IsPropertySet(const char* name, bool& value) {
1771     if (base::GetProperty(name, "") == "") return false;
1772 
1773     value = base::GetBoolProperty(name, false);
1774     LOG(INFO) << "fuse-bpf is " << (value ? "enabled" : "disabled") << " because of property "
1775               << name;
1776     return true;
1777 }
1778 
IsFuseBpfEnabled()1779 bool IsFuseBpfEnabled() {
1780     // This logic is reproduced in packages/providers/MediaProvider/jni/FuseDaemon.cpp
1781     // so changes made here must be reflected there
1782     bool enabled = false;
1783 
1784     if (IsPropertySet("ro.fuse.bpf.is_running", enabled)) return enabled;
1785 
1786     if (!IsPropertySet("persist.sys.fuse.bpf.override", enabled) &&
1787         !IsPropertySet("ro.fuse.bpf.enabled", enabled)) {
1788         // If the kernel has fuse-bpf, /sys/fs/fuse/features/fuse_bpf will exist and have the
1789         // contents 'supported\n' - see fs/fuse/inode.c in the kernel source
1790         std::string contents;
1791         const char* filename = "/sys/fs/fuse/features/fuse_bpf";
1792         if (!base::ReadFileToString(filename, &contents)) {
1793             LOG(INFO) << "fuse-bpf is disabled because " << filename << " cannot be read";
1794             enabled = false;
1795         } else if (contents == "supported\n") {
1796             LOG(INFO) << "fuse-bpf is enabled because " << filename << " reads 'supported'";
1797             enabled = true;
1798         } else {
1799             LOG(INFO) << "fuse-bpf is disabled because " << filename
1800                       << " does not read 'supported'";
1801             enabled = false;
1802         }
1803     }
1804 
1805     std::string value = enabled ? "true" : "false";
1806     LOG(INFO) << "Setting ro.fuse.bpf.is_running to " << value;
1807     base::SetProperty("ro.fuse.bpf.is_running", value);
1808     return enabled;
1809 }
1810 
1811 }  // namespace vold
1812 }  // namespace android
1813