• 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/stringprintf.h>
27 #include <android-base/strings.h>
28 #include <android-base/unique_fd.h>
29 #include <cutils/fs.h>
30 #include <logwrap/logwrap.h>
31 #include <private/android_filesystem_config.h>
32 #include <private/android_projectid_config.h>
33 
34 #include <dirent.h>
35 #include <fcntl.h>
36 #include <linux/fs.h>
37 #include <linux/posix_acl.h>
38 #include <linux/posix_acl_xattr.h>
39 #include <mntent.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <sys/mount.h>
43 #include <sys/stat.h>
44 #include <sys/statvfs.h>
45 #include <sys/sysmacros.h>
46 #include <sys/types.h>
47 #include <sys/wait.h>
48 #include <sys/xattr.h>
49 #include <unistd.h>
50 
51 #include <filesystem>
52 #include <list>
53 #include <mutex>
54 #include <regex>
55 #include <thread>
56 
57 #ifndef UMOUNT_NOFOLLOW
58 #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
59 #endif
60 
61 using namespace std::chrono_literals;
62 using android::base::EndsWith;
63 using android::base::ReadFileToString;
64 using android::base::StartsWith;
65 using android::base::StringPrintf;
66 using android::base::unique_fd;
67 
68 namespace android {
69 namespace vold {
70 
71 security_context_t sBlkidContext = nullptr;
72 security_context_t sBlkidUntrustedContext = nullptr;
73 security_context_t sFsckContext = nullptr;
74 security_context_t sFsckUntrustedContext = nullptr;
75 
76 bool sSleepOnUnmount = true;
77 
78 static const char* kBlkidPath = "/system/bin/blkid";
79 static const char* kKeyPath = "/data/misc/vold";
80 
81 static const char* kProcDevices = "/proc/devices";
82 static const char* kProcFilesystems = "/proc/filesystems";
83 
84 static const char* kAndroidDir = "/Android/";
85 static const char* kAppDataDir = "/Android/data/";
86 static const char* kAppMediaDir = "/Android/media/";
87 static const char* kAppObbDir = "/Android/obb/";
88 
89 static const char* kMediaProviderCtx = "u:r:mediaprovider:";
90 static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
91 
92 // Lock used to protect process-level SELinux changes from racing with each
93 // other between multiple threads.
94 static std::mutex kSecurityLock;
95 
GetFuseMountPathForUser(userid_t user_id,const std::string & relative_upper_path)96 std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path) {
97     return StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str());
98 }
99 
CreateDeviceNode(const std::string & path,dev_t dev)100 status_t CreateDeviceNode(const std::string& path, dev_t dev) {
101     std::lock_guard<std::mutex> lock(kSecurityLock);
102     const char* cpath = path.c_str();
103     status_t res = 0;
104 
105     char* secontext = nullptr;
106     if (sehandle) {
107         if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
108             setfscreatecon(secontext);
109         }
110     }
111 
112     mode_t mode = 0660 | S_IFBLK;
113     if (mknod(cpath, mode, dev) < 0) {
114         if (errno != EEXIST) {
115             PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
116                         << " at " << path;
117             res = -errno;
118         }
119     }
120 
121     if (secontext) {
122         setfscreatecon(nullptr);
123         freecon(secontext);
124     }
125 
126     return res;
127 }
128 
DestroyDeviceNode(const std::string & path)129 status_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 
138 // 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)139 int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
140                   std::vector<gid_t> additionalGids) {
141     if (IsSdcardfsUsed()) {
142         // sdcardfs magically takes care of this
143         return OK;
144     }
145 
146     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);
148     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 
156     int tag_index = 0;
157 
158     entry[tag_index].e_tag = ACL_USER_OBJ;
159     // 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
165     entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
166     entry[tag_index].e_id = uid;
167     tag_index++;
168 
169     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++;
173 
174     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;
191 
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 
SetQuotaInherit(const std::string & path)201 int SetQuotaInherit(const std::string& path) {
202     unsigned long flags;
203 
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 
SetQuotaProjectId(const std::string & path,long projectId)227 int SetQuotaProjectId(const std::string& path, long projectId) {
228     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;
243     return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
244 }
245 
PrepareDirWithProjectId(const std::string & path,mode_t mode,uid_t uid,gid_t gid,long projectId)246 int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
247                             long projectId) {
248     int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
249 
250     if (ret != 0) {
251         return ret;
252     }
253 
254     if (!IsSdcardfsUsed()) {
255         ret = SetQuotaProjectId(path, projectId);
256     }
257 
258     return ret;
259 }
260 
FixupAppDir(const std::string & path,mode_t mode,uid_t uid,gid_t gid,long projectId)261 static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
262     namespace fs = std::filesystem;
263 
264     // Setup the directory itself correctly
265     int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
266     if (ret != OK) {
267         return ret;
268     }
269 
270     // Fixup all of its file entries
271     for (const auto& itEntry : fs::directory_iterator(path)) {
272         ret = lchown(itEntry.path().c_str(), uid, gid);
273         if (ret != 0) {
274             return ret;
275         }
276 
277         ret = chmod(itEntry.path().c_str(), mode);
278         if (ret != 0) {
279             return ret;
280         }
281 
282         if (!IsSdcardfsUsed()) {
283             ret = SetQuotaProjectId(itEntry.path(), projectId);
284             if (ret != 0) {
285                 return ret;
286             }
287         }
288     }
289 
290     return OK;
291 }
292 
PrepareAppDirFromRoot(const std::string & path,const std::string & root,int appUid,bool fixupExisting)293 int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
294                           bool fixupExisting) {
295     long projectId;
296     size_t pos;
297     int ret = 0;
298     bool sdcardfsSupport = IsSdcardfsUsed();
299 
300     // Make sure the Android/ directories exist and are setup correctly
301     ret = PrepareAndroidDirs(root);
302     if (ret != 0) {
303         LOG(ERROR) << "Failed to prepare Android/ directories.";
304         return ret;
305     }
306 
307     // Now create the application-specific subdir(s)
308     // path is something like /data/media/0/Android/data/com.foo/files
309     // First, chop off the volume root, eg /data/media/0
310     std::string pathFromRoot = path.substr(root.length());
311 
312     uid_t uid = appUid;
313     gid_t gid = AID_MEDIA_RW;
314     std::vector<gid_t> additionalGids;
315     std::string appDir;
316 
317     // Check that the next part matches one of the allowed Android/ dirs
318     if (StartsWith(pathFromRoot, kAppDataDir)) {
319         appDir = kAppDataDir;
320         if (!sdcardfsSupport) {
321             gid = AID_EXT_DATA_RW;
322             // Also add the app's own UID as a group; since apps belong to a group
323             // that matches their UID, this ensures that they will always have access to
324             // the files created in these dirs, even if they are created by other processes
325             additionalGids.push_back(uid);
326         }
327     } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
328         appDir = kAppMediaDir;
329         if (!sdcardfsSupport) {
330             gid = AID_MEDIA_RW;
331         }
332     } else if (StartsWith(pathFromRoot, kAppObbDir)) {
333         appDir = kAppObbDir;
334         if (!sdcardfsSupport) {
335             gid = AID_EXT_OBB_RW;
336             // See comments for kAppDataDir above
337             additionalGids.push_back(uid);
338         }
339     } else {
340         LOG(ERROR) << "Invalid application directory: " << path;
341         return -EINVAL;
342     }
343 
344     // mode = 770, plus sticky bit on directory to inherit GID when apps
345     // create subdirs
346     mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
347     // the project ID for application-specific directories is directly
348     // derived from their uid
349 
350     // Chop off the generic application-specific part, eg /Android/data/
351     // this leaves us with something like com.foo/files/
352     std::string leftToCreate = pathFromRoot.substr(appDir.length());
353     if (!EndsWith(leftToCreate, "/")) {
354         leftToCreate += "/";
355     }
356     std::string pathToCreate = root + appDir;
357     int depth = 0;
358     // Derive initial project ID
359     if (appDir == kAppDataDir || appDir == kAppMediaDir) {
360         projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
361     } else if (appDir == kAppObbDir) {
362         projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
363     }
364 
365     while ((pos = leftToCreate.find('/')) != std::string::npos) {
366         std::string component = leftToCreate.substr(0, pos + 1);
367         leftToCreate = leftToCreate.erase(0, pos + 1);
368         pathToCreate = pathToCreate + component;
369 
370         if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
371             // All dirs use the "app" project ID, except for the cache dirs in
372             // Android/data, eg Android/data/com.foo/cache
373             // Note that this "sticks" - eg subdirs of this dir need the same
374             // project ID.
375             projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
376         }
377 
378         if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
379             // Fixup all files in this existing directory with the correct UID/GID
380             // and project ID.
381             ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
382         } else {
383             ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
384         }
385 
386         if (ret != 0) {
387             return ret;
388         }
389 
390         if (depth == 0) {
391             // Set the default ACL on the top-level application-specific directories,
392             // to ensure that even if applications run with a umask of 0077,
393             // new directories within these directories will allow the GID
394             // specified here to write; this is necessary for apps like
395             // installers and MTP, that require access here.
396             //
397             // See man (5) acl for more details.
398             ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
399             if (ret != 0) {
400                 return ret;
401             }
402 
403             if (!sdcardfsSupport) {
404                 // Set project ID inheritance, so that future subdirectories inherit the
405                 // same project ID
406                 ret = SetQuotaInherit(pathToCreate);
407                 if (ret != 0) {
408                     return ret;
409                 }
410             }
411         }
412 
413         depth++;
414     }
415 
416     return OK;
417 }
418 
SetAttrs(const std::string & path,unsigned int attrs)419 int SetAttrs(const std::string& path, unsigned int attrs) {
420     unsigned long flags;
421     android::base::unique_fd fd(
422             TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
423 
424     if (fd == -1) {
425         PLOG(ERROR) << "Failed to open " << path;
426         return -1;
427     }
428 
429     if (ioctl(fd, FS_IOC_GETFLAGS, (void*)&flags)) {
430         PLOG(ERROR) << "Failed to get flags for " << path;
431         return -1;
432     }
433 
434     if ((flags & attrs) == attrs) return 0;
435     flags |= attrs;
436     if (ioctl(fd, FS_IOC_SETFLAGS, (void*)&flags)) {
437         PLOG(ERROR) << "Failed to set flags for " << path << "(0x" << std::hex << attrs << ")";
438         return -1;
439     }
440     return 0;
441 }
442 
PrepareDir(const std::string & path,mode_t mode,uid_t uid,gid_t gid,unsigned int attrs)443 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
444                     unsigned int attrs) {
445     std::lock_guard<std::mutex> lock(kSecurityLock);
446     const char* cpath = path.c_str();
447 
448     char* secontext = nullptr;
449     if (sehandle) {
450         if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
451             setfscreatecon(secontext);
452         }
453     }
454 
455     int res = fs_prepare_dir(cpath, mode, uid, gid);
456 
457     if (secontext) {
458         setfscreatecon(nullptr);
459         freecon(secontext);
460     }
461 
462     if (res) return -errno;
463     if (attrs) res = SetAttrs(path, attrs);
464 
465     if (res == 0) {
466         return OK;
467     } else {
468         return -errno;
469     }
470 }
471 
ForceUnmount(const std::string & path)472 status_t ForceUnmount(const std::string& path) {
473     const char* cpath = path.c_str();
474     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
475         return OK;
476     }
477     // Apps might still be handling eject request, so wait before
478     // we start sending signals
479     if (sSleepOnUnmount) sleep(5);
480 
481     KillProcessesWithOpenFiles(path, SIGINT);
482     if (sSleepOnUnmount) sleep(5);
483     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
484         return OK;
485     }
486 
487     KillProcessesWithOpenFiles(path, SIGTERM);
488     if (sSleepOnUnmount) sleep(5);
489     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
490         return OK;
491     }
492 
493     KillProcessesWithOpenFiles(path, SIGKILL);
494     if (sSleepOnUnmount) sleep(5);
495     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
496         return OK;
497     }
498     PLOG(INFO) << "ForceUnmount failed";
499     return -errno;
500 }
501 
KillProcessesWithMountPrefix(const std::string & path)502 status_t KillProcessesWithMountPrefix(const std::string& path) {
503     if (KillProcessesWithMounts(path, SIGINT) == 0) {
504         return OK;
505     }
506     if (sSleepOnUnmount) sleep(5);
507 
508     if (KillProcessesWithMounts(path, SIGTERM) == 0) {
509         return OK;
510     }
511     if (sSleepOnUnmount) sleep(5);
512 
513     if (KillProcessesWithMounts(path, SIGKILL) == 0) {
514         return OK;
515     }
516     if (sSleepOnUnmount) sleep(5);
517 
518     // Send SIGKILL a second time to determine if we've
519     // actually killed everyone mount
520     if (KillProcessesWithMounts(path, SIGKILL) == 0) {
521         return OK;
522     }
523     PLOG(ERROR) << "Failed to kill processes using " << path;
524     return -EBUSY;
525 }
526 
KillProcessesUsingPath(const std::string & path)527 status_t KillProcessesUsingPath(const std::string& path) {
528     if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
529         return OK;
530     }
531     if (sSleepOnUnmount) sleep(5);
532 
533     if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
534         return OK;
535     }
536     if (sSleepOnUnmount) sleep(5);
537 
538     if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
539         return OK;
540     }
541     if (sSleepOnUnmount) sleep(5);
542 
543     // Send SIGKILL a second time to determine if we've
544     // actually killed everyone with open files
545     if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
546         return OK;
547     }
548     PLOG(ERROR) << "Failed to kill processes using " << path;
549     return -EBUSY;
550 }
551 
BindMount(const std::string & source,const std::string & target)552 status_t BindMount(const std::string& source, const std::string& target) {
553     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) {
557         PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
558         return -errno;
559     }
560     return OK;
561 }
562 
Symlink(const std::string & target,const std::string & linkpath)563 status_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 
Unlink(const std::string & linkpath)574 status_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 
CreateDir(const std::string & dir,mode_t mode)582 status_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     }
595     if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
596         PLOG(ERROR) << "Failed to mkdir " << dir;
597         return -errno;
598     }
599     return OK;
600 }
601 
FindValue(const std::string & raw,const std::string & key,std::string * value)602 bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
603     auto qual = key + "=\"";
604     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;
612     }
613     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 
readMetadata(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel,bool untrusted)622 static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
623                              std::string* fsLabel, bool untrusted) {
624     fsType->clear();
625     fsUuid->clear();
626     fsLabel->clear();
627 
628     std::vector<std::string> cmd;
629     cmd.push_back(kBlkidPath);
630     cmd.push_back("-c");
631     cmd.push_back("/dev/null");
632     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");
638     cmd.push_back(path);
639 
640     std::vector<std::string> output;
641     status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
642     if (res != OK) {
643         LOG(WARNING) << "blkid failed to identify " << path;
644         return res;
645     }
646 
647     for (const auto& line : output) {
648         // Extract values from blkid output, if defined
649         FindValue(line, "TYPE", fsType);
650         FindValue(line, "UUID", fsUuid);
651         FindValue(line, "LABEL", fsLabel);
652     }
653 
654     return OK;
655 }
656 
ReadMetadata(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel)657 status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
658                       std::string* fsLabel) {
659     return readMetadata(path, fsType, fsUuid, fsLabel, false);
660 }
661 
ReadMetadataUntrusted(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel)662 status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
663                                std::string* fsLabel) {
664     return readMetadata(path, fsType, fsUuid, fsLabel, true);
665 }
666 
ConvertToArgv(const std::vector<std::string> & args)667 static 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;
673         } else {
674             LOG(DEBUG) << "    " << arg;
675         }
676         argv.emplace_back(arg.data());
677     }
678     argv.emplace_back(nullptr);
679     return argv;
680 }
681 
ReadLinesFromFdAndLog(std::vector<std::string> * output,android::base::unique_fd ufd)682 static 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);
685     if (!fp) {
686         PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
687         return -errno;
688     }
689     if (output) output->clear();
690     char line[1024];
691     while (fgets(line, sizeof(line), fp.get()) != nullptr) {
692         LOG(DEBUG) << line;
693         if (output) output->emplace_back(line);
694     }
695     return OK;
696 }
697 
ForkExecvp(const std::vector<std::string> & args,std::vector<std::string> * output,security_context_t context)698 status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
699                     security_context_t context) {
700     auto argv = ConvertToArgv(args);
701 
702     android::base::unique_fd pipe_read, pipe_write;
703     if (!android::base::Pipe(&pipe_read, &pipe_write)) {
704         PLOG(ERROR) << "Pipe in ForkExecvp";
705         return -errno;
706     }
707 
708     pid_t pid = fork();
709     if (pid == 0) {
710         if (context) {
711             if (setexeccon(context)) {
712                 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
713                 abort();
714             }
715         }
716         pipe_read.reset();
717         if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
718             PLOG(ERROR) << "dup2 in ForkExecvp";
719             _exit(EXIT_FAILURE);
720         }
721         pipe_write.reset();
722         execvp(argv[0], const_cast<char**>(argv.data()));
723         PLOG(ERROR) << "exec in ForkExecvp";
724         _exit(EXIT_FAILURE);
725     }
726     if (pid == -1) {
727         PLOG(ERROR) << "fork in ForkExecvp";
728         return -errno;
729     }
730 
731     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     }
748     return OK;
749 }
750 
ForkExecvpAsync(const std::vector<std::string> & args)751 pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
752     auto argv = ConvertToArgv(args);
753 
754     pid_t pid = fork();
755     if (pid == 0) {
756         close(STDIN_FILENO);
757         close(STDOUT_FILENO);
758         close(STDERR_FILENO);
759 
760         execvp(argv[0], const_cast<char**>(argv.data()));
761         PLOG(ERROR) << "exec in ForkExecvpAsync";
762         _exit(EXIT_FAILURE);
763     }
764     if (pid == -1) {
765         PLOG(ERROR) << "fork in ForkExecvpAsync";
766         return -1;
767     }
768     return pid;
769 }
770 
ReadRandomBytes(size_t bytes,std::string & out)771 status_t ReadRandomBytes(size_t bytes, std::string& out) {
772     out.resize(bytes);
773     return ReadRandomBytes(bytes, &out[0]);
774 }
775 
ReadRandomBytes(size_t bytes,char * buf)776 status_t ReadRandomBytes(size_t bytes, char* buf) {
777     int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
778     if (fd == -1) {
779         return -errno;
780     }
781 
782     ssize_t n;
783     while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
784         bytes -= n;
785         buf += n;
786     }
787     close(fd);
788 
789     if (bytes == 0) {
790         return OK;
791     } else {
792         return -EIO;
793     }
794 }
795 
GenerateRandomUuid(std::string & out)796 status_t GenerateRandomUuid(std::string& out) {
797     status_t res = ReadRandomBytes(16, out);
798     if (res == OK) {
799         out[6] &= 0x0f; /* clear version        */
800         out[6] |= 0x40; /* set to version 4     */
801         out[8] &= 0x3f; /* clear variant        */
802         out[8] |= 0x80; /* set to IETF variant  */
803     }
804     return res;
805 }
806 
HexToStr(const std::string & hex,std::string & str)807 status_t HexToStr(const std::string& hex, std::string& str) {
808     str.clear();
809     bool even = true;
810     char cur = 0;
811     for (size_t i = 0; i < hex.size(); i++) {
812         int val = 0;
813         switch (hex[i]) {
814             // clang-format off
815             case ' ': case '-': case ':': continue;
816             case 'f': case 'F': val = 15; break;
817             case 'e': case 'E': val = 14; break;
818             case 'd': case 'D': val = 13; break;
819             case 'c': case 'C': val = 12; break;
820             case 'b': case 'B': val = 11; break;
821             case 'a': case 'A': val = 10; break;
822             case '9': val = 9; break;
823             case '8': val = 8; break;
824             case '7': val = 7; break;
825             case '6': val = 6; break;
826             case '5': val = 5; break;
827             case '4': val = 4; break;
828             case '3': val = 3; break;
829             case '2': val = 2; break;
830             case '1': val = 1; break;
831             case '0': val = 0; break;
832             default: return -EINVAL;
833                 // clang-format on
834         }
835 
836         if (even) {
837             cur = val << 4;
838         } else {
839             cur += val;
840             str.push_back(cur);
841             cur = 0;
842         }
843         even = !even;
844     }
845     return even ? OK : -EINVAL;
846 }
847 
848 static const char* kLookup = "0123456789abcdef";
849 
StrToHex(const std::string & str,std::string & hex)850 status_t StrToHex(const std::string& str, std::string& hex) {
851     hex.clear();
852     for (size_t i = 0; i < str.size(); i++) {
853         hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
854         hex.push_back(kLookup[str[i] & 0x0F]);
855     }
856     return OK;
857 }
858 
StrToHex(const KeyBuffer & str,KeyBuffer & hex)859 status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
860     hex.clear();
861     for (size_t i = 0; i < str.size(); i++) {
862         hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
863         hex.push_back(kLookup[str.data()[i] & 0x0F]);
864     }
865     return OK;
866 }
867 
NormalizeHex(const std::string & in,std::string & out)868 status_t NormalizeHex(const std::string& in, std::string& out) {
869     std::string tmp;
870     if (HexToStr(in, tmp)) {
871         return -EINVAL;
872     }
873     return StrToHex(tmp, out);
874 }
875 
GetBlockDevSize(int fd,uint64_t * size)876 status_t GetBlockDevSize(int fd, uint64_t* size) {
877     if (ioctl(fd, BLKGETSIZE64, size)) {
878         return -errno;
879     }
880 
881     return OK;
882 }
883 
GetBlockDevSize(const std::string & path,uint64_t * size)884 status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
885     int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
886     status_t res = OK;
887 
888     if (fd < 0) {
889         return -errno;
890     }
891 
892     res = GetBlockDevSize(fd, size);
893 
894     close(fd);
895 
896     return res;
897 }
898 
GetBlockDev512Sectors(const std::string & path,uint64_t * nr_sec)899 status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
900     uint64_t size;
901     status_t res = GetBlockDevSize(path, &size);
902 
903     if (res != OK) {
904         return res;
905     }
906 
907     *nr_sec = size / 512;
908 
909     return OK;
910 }
911 
GetFreeBytes(const std::string & path)912 uint64_t GetFreeBytes(const std::string& path) {
913     struct statvfs sb;
914     if (statvfs(path.c_str(), &sb) == 0) {
915         return (uint64_t)sb.f_bavail * sb.f_frsize;
916     } else {
917         return -1;
918     }
919 }
920 
921 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
922 // eventually be migrated into system/
stat_size(struct stat * s)923 static int64_t stat_size(struct stat* s) {
924     int64_t blksize = s->st_blksize;
925     // count actual blocks used instead of nominal file size
926     int64_t size = s->st_blocks * 512;
927 
928     if (blksize) {
929         /* round up to filesystem block size */
930         size = (size + blksize - 1) & (~(blksize - 1));
931     }
932 
933     return size;
934 }
935 
936 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
937 // eventually be migrated into system/
calculate_dir_size(int dfd)938 int64_t calculate_dir_size(int dfd) {
939     int64_t size = 0;
940     struct stat s;
941     DIR* d;
942     struct dirent* de;
943 
944     d = fdopendir(dfd);
945     if (d == NULL) {
946         close(dfd);
947         return 0;
948     }
949 
950     while ((de = readdir(d))) {
951         const char* name = de->d_name;
952         if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
953             size += stat_size(&s);
954         }
955         if (de->d_type == DT_DIR) {
956             int subfd;
957 
958             /* always skip "." and ".." */
959             if (name[0] == '.') {
960                 if (name[1] == 0) continue;
961                 if ((name[1] == '.') && (name[2] == 0)) continue;
962             }
963 
964             subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
965             if (subfd >= 0) {
966                 size += calculate_dir_size(subfd);
967             }
968         }
969     }
970     closedir(d);
971     return size;
972 }
973 
GetTreeBytes(const std::string & path)974 uint64_t GetTreeBytes(const std::string& path) {
975     int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
976     if (dirfd < 0) {
977         PLOG(WARNING) << "Failed to open " << path;
978         return -1;
979     } else {
980         return calculate_dir_size(dirfd);
981     }
982 }
983 
984 // TODO: Use a better way to determine if it's media provider app.
IsFuseDaemon(const pid_t pid)985 bool IsFuseDaemon(const pid_t pid) {
986     auto path = StringPrintf("/proc/%d/mounts", pid);
987     char* tmp;
988     if (lgetfilecon(path.c_str(), &tmp) < 0) {
989         return false;
990     }
991     bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
992             || android::base::StartsWith(tmp, kMediaProviderCtx);
993     freecon(tmp);
994     return result;
995 }
996 
IsFilesystemSupported(const std::string & fsType)997 bool IsFilesystemSupported(const std::string& fsType) {
998     std::string supported;
999     if (!ReadFileToString(kProcFilesystems, &supported)) {
1000         PLOG(ERROR) << "Failed to read supported filesystems";
1001         return false;
1002     }
1003     return supported.find(fsType + "\n") != std::string::npos;
1004 }
1005 
IsSdcardfsUsed()1006 bool IsSdcardfsUsed() {
1007     return IsFilesystemSupported("sdcardfs") &&
1008            base::GetBoolProperty(kExternalStorageSdcardfs, true);
1009 }
1010 
WipeBlockDevice(const std::string & path)1011 status_t WipeBlockDevice(const std::string& path) {
1012     status_t res = -1;
1013     const char* c_path = path.c_str();
1014     uint64_t range[2] = {0, 0};
1015 
1016     int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
1017     if (fd == -1) {
1018         PLOG(ERROR) << "Failed to open " << path;
1019         goto done;
1020     }
1021 
1022     if (GetBlockDevSize(fd, &range[1]) != OK) {
1023         PLOG(ERROR) << "Failed to determine size of " << path;
1024         goto done;
1025     }
1026 
1027     LOG(INFO) << "About to discard " << range[1] << " on " << path;
1028     if (ioctl(fd, BLKDISCARD, &range) == 0) {
1029         LOG(INFO) << "Discard success on " << path;
1030         res = 0;
1031     } else {
1032         PLOG(ERROR) << "Discard failure on " << path;
1033     }
1034 
1035 done:
1036     close(fd);
1037     return res;
1038 }
1039 
isValidFilename(const std::string & name)1040 static bool isValidFilename(const std::string& name) {
1041     if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
1042         return false;
1043     } else {
1044         return true;
1045     }
1046 }
1047 
BuildKeyPath(const std::string & partGuid)1048 std::string BuildKeyPath(const std::string& partGuid) {
1049     return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1050 }
1051 
BuildDataSystemLegacyPath(userid_t userId)1052 std::string BuildDataSystemLegacyPath(userid_t userId) {
1053     return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
1054 }
1055 
BuildDataSystemCePath(userid_t userId)1056 std::string BuildDataSystemCePath(userid_t userId) {
1057     return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
1058 }
1059 
BuildDataSystemDePath(userid_t userId)1060 std::string BuildDataSystemDePath(userid_t userId) {
1061     return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
1062 }
1063 
BuildDataMiscLegacyPath(userid_t userId)1064 std::string BuildDataMiscLegacyPath(userid_t userId) {
1065     return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
1066 }
1067 
BuildDataMiscCePath(userid_t userId)1068 std::string BuildDataMiscCePath(userid_t userId) {
1069     return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
1070 }
1071 
BuildDataMiscDePath(userid_t userId)1072 std::string BuildDataMiscDePath(userid_t userId) {
1073     return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
1074 }
1075 
1076 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
BuildDataProfilesDePath(userid_t userId)1077 std::string BuildDataProfilesDePath(userid_t userId) {
1078     return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
1079 }
1080 
BuildDataVendorCePath(userid_t userId)1081 std::string BuildDataVendorCePath(userid_t userId) {
1082     return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1083 }
1084 
BuildDataVendorDePath(userid_t userId)1085 std::string BuildDataVendorDePath(userid_t userId) {
1086     return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1087 }
1088 
BuildDataPath(const std::string & volumeUuid)1089 std::string BuildDataPath(const std::string& volumeUuid) {
1090     // TODO: unify with installd path generation logic
1091     if (volumeUuid.empty()) {
1092         return "/data";
1093     } else {
1094         CHECK(isValidFilename(volumeUuid));
1095         return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
1096     }
1097 }
1098 
BuildDataMediaCePath(const std::string & volumeUuid,userid_t userId)1099 std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
1100     // TODO: unify with installd path generation logic
1101     std::string data(BuildDataPath(volumeUuid));
1102     return StringPrintf("%s/media/%u", data.c_str(), userId);
1103 }
1104 
BuildDataUserCePath(const std::string & volumeUuid,userid_t userId)1105 std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
1106     // TODO: unify with installd path generation logic
1107     std::string data(BuildDataPath(volumeUuid));
1108     if (volumeUuid.empty() && userId == 0) {
1109         std::string legacy = StringPrintf("%s/data", data.c_str());
1110         struct stat sb;
1111         if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1112             /* /data/data is dir, return /data/data for legacy system */
1113             return legacy;
1114         }
1115     }
1116     return StringPrintf("%s/user/%u", data.c_str(), userId);
1117 }
1118 
BuildDataUserDePath(const std::string & volumeUuid,userid_t userId)1119 std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
1120     // TODO: unify with installd path generation logic
1121     std::string data(BuildDataPath(volumeUuid));
1122     return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1123 }
1124 
GetDevice(const std::string & path)1125 dev_t GetDevice(const std::string& path) {
1126     struct stat sb;
1127     if (stat(path.c_str(), &sb)) {
1128         PLOG(WARNING) << "Failed to stat " << path;
1129         return 0;
1130     } else {
1131         return sb.st_dev;
1132     }
1133 }
1134 
RestoreconRecursive(const std::string & path)1135 status_t RestoreconRecursive(const std::string& path) {
1136     LOG(DEBUG) << "Starting restorecon of " << path;
1137 
1138     static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
1139 
1140     android::base::SetProperty(kRestoreconString, "");
1141     android::base::SetProperty(kRestoreconString, path);
1142 
1143     android::base::WaitForProperty(kRestoreconString, path);
1144 
1145     LOG(DEBUG) << "Finished restorecon of " << path;
1146     return OK;
1147 }
1148 
Readlinkat(int dirfd,const std::string & path,std::string * result)1149 bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1150     // Shamelessly borrowed from android::base::Readlink()
1151     result->clear();
1152 
1153     // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1154     // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1155     // waste memory to just start there. We add 1 so that we can recognize
1156     // whether it actually fit (rather than being truncated to 4095).
1157     std::vector<char> buf(4095 + 1);
1158     while (true) {
1159         ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1160         // Unrecoverable error?
1161         if (size == -1) return false;
1162         // It fit! (If size == buf.size(), it may have been truncated.)
1163         if (static_cast<size_t>(size) < buf.size()) {
1164             result->assign(&buf[0], size);
1165             return true;
1166         }
1167         // Double our buffer and try again.
1168         buf.resize(buf.size() * 2);
1169     }
1170 }
1171 
GetMajorBlockVirtioBlk()1172 static unsigned int GetMajorBlockVirtioBlk() {
1173     std::string devices;
1174     if (!ReadFileToString(kProcDevices, &devices)) {
1175         PLOG(ERROR) << "Unable to open /proc/devices";
1176         return 0;
1177     }
1178 
1179     bool blockSection = false;
1180     for (auto line : android::base::Split(devices, "\n")) {
1181         if (line == "Block devices:") {
1182             blockSection = true;
1183         } else if (line == "Character devices:") {
1184             blockSection = false;
1185         } else if (blockSection) {
1186             auto tokens = android::base::Split(line, " ");
1187             if (tokens.size() == 2 && tokens[1] == "virtblk") {
1188                 return std::stoul(tokens[0]);
1189             }
1190         }
1191     }
1192 
1193     return 0;
1194 }
1195 
IsVirtioBlkDevice(unsigned int major)1196 bool IsVirtioBlkDevice(unsigned int major) {
1197     // Most virtualized platforms expose block devices with the virtio-blk
1198     // block device driver. Unfortunately, this driver does not use a fixed
1199     // major number, but relies on the kernel to assign one from a specific
1200     // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1201     // per Documentation/devices.txt. This is true even for the latest Linux
1202     // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1203     static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1204     return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
1205 }
1206 
findMountPointsWithPrefix(const std::string & prefix,std::list<std::string> & mountPoints)1207 static status_t findMountPointsWithPrefix(const std::string& prefix,
1208                                           std::list<std::string>& mountPoints) {
1209     // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1210     // when the prefix is /foo/bar
1211     std::string prefixWithSlash(prefix);
1212     if (prefix.back() != '/') {
1213         android::base::StringAppendF(&prefixWithSlash, "/");
1214     }
1215 
1216     std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1217     if (!mnts) {
1218         PLOG(ERROR) << "Unable to open /proc/mounts";
1219         return -errno;
1220     }
1221 
1222     // Some volumes can be stacked on each other, so force unmount in
1223     // reverse order to give us the best chance of success.
1224     struct mntent* mnt;  // getmntent returns a thread local, so it's safe.
1225     while ((mnt = getmntent(mnts.get())) != nullptr) {
1226         auto mountPoint = std::string(mnt->mnt_dir) + "/";
1227         if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1228             mountPoints.push_front(mountPoint);
1229         }
1230     }
1231     return OK;
1232 }
1233 
1234 // Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
UnmountTreeWithPrefix(const std::string & prefix)1235 status_t UnmountTreeWithPrefix(const std::string& prefix) {
1236     std::list<std::string> toUnmount;
1237     status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1238     if (result < 0) {
1239         return result;
1240     }
1241     for (const auto& path : toUnmount) {
1242         if (umount2(path.c_str(), MNT_DETACH)) {
1243             PLOG(ERROR) << "Failed to unmount " << path;
1244             result = -errno;
1245         }
1246     }
1247     return result;
1248 }
1249 
UnmountTree(const std::string & mountPoint)1250 status_t UnmountTree(const std::string& mountPoint) {
1251     if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1252         errno != ENOENT) {
1253         PLOG(ERROR) << "Failed to unmount " << mountPoint;
1254         return -errno;
1255     }
1256     return OK;
1257 }
1258 
delete_dir_contents(DIR * dir)1259 static status_t delete_dir_contents(DIR* dir) {
1260     // Shamelessly borrowed from android::installd
1261     int dfd = dirfd(dir);
1262     if (dfd < 0) {
1263         return -errno;
1264     }
1265 
1266     status_t result = OK;
1267     struct dirent* de;
1268     while ((de = readdir(dir))) {
1269         const char* name = de->d_name;
1270         if (de->d_type == DT_DIR) {
1271             /* always skip "." and ".." */
1272             if (name[0] == '.') {
1273                 if (name[1] == 0) continue;
1274                 if ((name[1] == '.') && (name[2] == 0)) continue;
1275             }
1276 
1277             android::base::unique_fd subfd(
1278                 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1279             if (subfd.get() == -1) {
1280                 PLOG(ERROR) << "Couldn't openat " << name;
1281                 result = -errno;
1282                 continue;
1283             }
1284             std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1285                 android::base::Fdopendir(std::move(subfd)), closedir);
1286             if (!subdirp) {
1287                 PLOG(ERROR) << "Couldn't fdopendir " << name;
1288                 result = -errno;
1289                 continue;
1290             }
1291             result = delete_dir_contents(subdirp.get());
1292             if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1293                 PLOG(ERROR) << "Couldn't unlinkat " << name;
1294                 result = -errno;
1295             }
1296         } else {
1297             if (unlinkat(dfd, name, 0) < 0) {
1298                 PLOG(ERROR) << "Couldn't unlinkat " << name;
1299                 result = -errno;
1300             }
1301         }
1302     }
1303     return result;
1304 }
1305 
DeleteDirContentsAndDir(const std::string & pathname)1306 status_t DeleteDirContentsAndDir(const std::string& pathname) {
1307     status_t res = DeleteDirContents(pathname);
1308     if (res < 0) {
1309         return res;
1310     }
1311     if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
1312         PLOG(ERROR) << "rmdir failed on " << pathname;
1313         return -errno;
1314     }
1315     LOG(VERBOSE) << "Success: rmdir on " << pathname;
1316     return OK;
1317 }
1318 
DeleteDirContents(const std::string & pathname)1319 status_t DeleteDirContents(const std::string& pathname) {
1320     // Shamelessly borrowed from android::installd
1321     std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1322     if (!dirp) {
1323         if (errno == ENOENT) {
1324             return OK;
1325         }
1326         PLOG(ERROR) << "Failed to opendir " << pathname;
1327         return -errno;
1328     }
1329     return delete_dir_contents(dirp.get());
1330 }
1331 
1332 // TODO(118708649): fix duplication with init/util.h
WaitForFile(const char * filename,std::chrono::nanoseconds timeout)1333 status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1334     android::base::Timer t;
1335     while (t.duration() < timeout) {
1336         struct stat sb;
1337         if (stat(filename, &sb) != -1) {
1338             LOG(INFO) << "wait for '" << filename << "' took " << t;
1339             return 0;
1340         }
1341         std::this_thread::sleep_for(10ms);
1342     }
1343     LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1344     return -1;
1345 }
1346 
FsyncDirectory(const std::string & dirname)1347 bool FsyncDirectory(const std::string& dirname) {
1348     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1349     if (fd == -1) {
1350         PLOG(ERROR) << "Failed to open " << dirname;
1351         return false;
1352     }
1353     if (fsync(fd) == -1) {
1354         if (errno == EROFS || errno == EINVAL) {
1355             PLOG(WARNING) << "Skip fsync " << dirname
1356                           << " on a file system does not support synchronization";
1357         } else {
1358             PLOG(ERROR) << "Failed to fsync " << dirname;
1359             return false;
1360         }
1361     }
1362     return true;
1363 }
1364 
writeStringToFile(const std::string & payload,const std::string & filename)1365 bool writeStringToFile(const std::string& payload, const std::string& filename) {
1366     android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1367         open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1368     if (fd == -1) {
1369         PLOG(ERROR) << "Failed to open " << filename;
1370         return false;
1371     }
1372     if (!android::base::WriteStringToFd(payload, fd)) {
1373         PLOG(ERROR) << "Failed to write to " << filename;
1374         unlink(filename.c_str());
1375         return false;
1376     }
1377     // fsync as close won't guarantee flush data
1378     // see close(2), fsync(2) and b/68901441
1379     if (fsync(fd) == -1) {
1380         if (errno == EROFS || errno == EINVAL) {
1381             PLOG(WARNING) << "Skip fsync " << filename
1382                           << " on a file system does not support synchronization";
1383         } else {
1384             PLOG(ERROR) << "Failed to fsync " << filename;
1385             unlink(filename.c_str());
1386             return false;
1387         }
1388     }
1389     return true;
1390 }
1391 
AbortFuseConnections()1392 status_t AbortFuseConnections() {
1393     namespace fs = std::filesystem;
1394 
1395     for (const auto& itEntry : fs::directory_iterator("/sys/fs/fuse/connections")) {
1396         std::string abortPath = itEntry.path().string() + "/abort";
1397         LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1398         bool ret = writeStringToFile("1", abortPath);
1399         if (!ret) {
1400             LOG(WARNING) << "Failed to write to " << abortPath;
1401         }
1402     }
1403 
1404     return OK;
1405 }
1406 
EnsureDirExists(const std::string & path,mode_t mode,uid_t uid,gid_t gid)1407 status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1408     if (access(path.c_str(), F_OK) != 0) {
1409         PLOG(WARNING) << "Dir does not exist: " << path;
1410         if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1411             return -errno;
1412         }
1413     }
1414     return OK;
1415 }
1416 
1417 // Gets the sysfs path for parameters of the backing device info (bdi)
getBdiPathForMount(const std::string & mount)1418 static std::string getBdiPathForMount(const std::string& mount) {
1419     // First figure out MAJOR:MINOR of mount. Simplest way is to stat the path.
1420     struct stat info;
1421     if (stat(mount.c_str(), &info) != 0) {
1422         PLOG(ERROR) << "Failed to stat " << mount;
1423         return "";
1424     }
1425     unsigned int maj = major(info.st_dev);
1426     unsigned int min = minor(info.st_dev);
1427 
1428     return StringPrintf("/sys/class/bdi/%u:%u", maj, min);
1429 }
1430 
1431 // Configures max_ratio for the FUSE filesystem.
ConfigureMaxDirtyRatioForFuse(const std::string & fuse_mount,unsigned int max_ratio)1432 void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio) {
1433     LOG(INFO) << "Configuring max_ratio of " << fuse_mount << " fuse filesystem to " << max_ratio;
1434     if (max_ratio > 100) {
1435         LOG(ERROR) << "Invalid max_ratio: " << max_ratio;
1436         return;
1437     }
1438     std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1439     if (fuseBdiPath == "") {
1440         return;
1441     }
1442     std::string max_ratio_file = StringPrintf("%s/max_ratio", fuseBdiPath.c_str());
1443     unique_fd fd(TEMP_FAILURE_RETRY(open(max_ratio_file.c_str(), O_WRONLY | O_CLOEXEC)));
1444     if (fd.get() == -1) {
1445         PLOG(ERROR) << "Failed to open " << max_ratio_file;
1446         return;
1447     }
1448     LOG(INFO) << "Writing " << max_ratio << " to " << max_ratio_file;
1449     if (!WriteStringToFd(std::to_string(max_ratio), fd)) {
1450         PLOG(ERROR) << "Failed to write to " << max_ratio_file;
1451     }
1452 }
1453 
1454 // Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1455 // 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)1456 void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1457     LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1458               << read_ahead_kb << "kb";
1459     std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1460     if (fuseBdiPath == "") {
1461         return;
1462     }
1463     // We found the bdi path for our filesystem, time to configure read ahead!
1464     std::string read_ahead_file = StringPrintf("%s/read_ahead_kb", fuseBdiPath.c_str());
1465     unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1466     if (fd.get() == -1) {
1467         PLOG(ERROR) << "Failed to open " << read_ahead_file;
1468         return;
1469     }
1470     LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1471     if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1472         PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1473     }
1474 }
1475 
MountUserFuse(userid_t user_id,const std::string & absolute_lower_path,const std::string & relative_upper_path,android::base::unique_fd * fuse_fd)1476 status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1477                        const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1478     std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1479     std::string fuse_path(
1480             StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1481 
1482     std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1483     std::string pass_through_path(
1484             StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
1485 
1486     // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1487     // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
1488     auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
1489     if (result != android::OK) {
1490         PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1491         return -1;
1492     }
1493 
1494     // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1495     // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1496     // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1497     // These bits should be consistent with what is set in zygote in
1498     // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
1499     result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
1500                              multiuser_get_uid(user_id, AID_EVERYBODY));
1501     if (result != android::OK) {
1502         PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
1503         return -1;
1504     }
1505 
1506     result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1507     if (result != android::OK) {
1508         PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1509         return -1;
1510     }
1511 
1512     result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
1513     if (result != android::OK) {
1514         PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1515         return -1;
1516     }
1517 
1518     result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
1519     if (result != android::OK) {
1520         PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1521         return -1;
1522     }
1523 
1524     if (relative_upper_path == "emulated") {
1525         std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1526         result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
1527         if (result != android::OK) {
1528             PLOG(ERROR) << "Failed to prepare directory " << linkpath;
1529             return -1;
1530         }
1531         linkpath += "/primary";
1532         Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
1533 
1534         std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
1535         result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
1536         if (result != android::OK) {
1537             PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1538             return -1;
1539         }
1540         pass_through_linkpath += "/primary";
1541         Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
1542     }
1543 
1544     // Open fuse fd.
1545     fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1546     if (fuse_fd->get() == -1) {
1547         PLOG(ERROR) << "Failed to open /dev/fuse";
1548         return -1;
1549     }
1550 
1551     // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1552     // permission checks before routing to FUSE daemon.
1553     const auto opts = StringPrintf(
1554         "fd=%i,"
1555         "rootmode=40000,"
1556         "allow_other,"
1557         "user_id=0,group_id=0,",
1558         fuse_fd->get());
1559 
1560     result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1561                                       MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1562                                       opts.c_str()));
1563     if (result != 0) {
1564         PLOG(ERROR) << "Failed to mount " << fuse_path;
1565         return -errno;
1566     }
1567 
1568     if (IsSdcardfsUsed()) {
1569         std::string sdcardfs_path(
1570                 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1571 
1572         LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1573         return BindMount(sdcardfs_path, pass_through_path);
1574     } else {
1575         LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1576         return BindMount(absolute_lower_path, pass_through_path);
1577     }
1578 }
1579 
UnmountUserFuse(userid_t user_id,const std::string & absolute_lower_path,const std::string & relative_upper_path)1580 status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1581                          const std::string& relative_upper_path) {
1582     std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1583     std::string pass_through_path(
1584             StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1585 
1586     // Best effort unmount pass_through path
1587     sSleepOnUnmount = false;
1588     LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1589     auto status = ForceUnmount(pass_through_path);
1590     if (status != android::OK) {
1591         LOG(ERROR) << "Failed to unmount " << pass_through_path;
1592     }
1593     rmdir(pass_through_path.c_str());
1594 
1595     LOG(INFO) << "Unmounting fuse path " << fuse_path;
1596     android::status_t result = ForceUnmount(fuse_path);
1597     sSleepOnUnmount = true;
1598     if (result != android::OK) {
1599         // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1600         // Figure out why we get EBUSY and remove this special casing if possible.
1601         PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1602         if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1603             errno != ENOENT) {
1604             PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1605             return -errno;
1606         }
1607         result = android::OK;
1608     }
1609     rmdir(fuse_path.c_str());
1610 
1611     return result;
1612 }
1613 
PrepareAndroidDirs(const std::string & volumeRoot)1614 status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1615     std::string androidDir = volumeRoot + kAndroidDir;
1616     std::string androidDataDir = volumeRoot + kAppDataDir;
1617     std::string androidObbDir = volumeRoot + kAppObbDir;
1618     std::string androidMediaDir = volumeRoot + kAppMediaDir;
1619 
1620     bool useSdcardFs = IsSdcardfsUsed();
1621 
1622     // mode 0771 + sticky bit for inheriting GIDs
1623     mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1624     if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1625         PLOG(ERROR) << "Failed to create " << androidDir;
1626         return -errno;
1627     }
1628 
1629     gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
1630     if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
1631         PLOG(ERROR) << "Failed to create " << androidDataDir;
1632         return -errno;
1633     }
1634 
1635     gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
1636     if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
1637         PLOG(ERROR) << "Failed to create " << androidObbDir;
1638         return -errno;
1639     }
1640     // Some other apps, like installers, have write access to the OBB directory
1641     // to pre-download them. To make sure newly created folders in this directory
1642     // have the right permissions, set a default ACL.
1643     SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
1644 
1645     if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1646         PLOG(ERROR) << "Failed to create " << androidMediaDir;
1647         return -errno;
1648     }
1649 
1650     return OK;
1651 }
1652 }  // namespace vold
1653 }  // namespace android
1654