• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18 
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <mntent.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/ioctl.h>
27 #include <sys/mount.h>
28 #include <sys/stat.h>
29 #include <sys/sysmacros.h>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 #include <array>
34 
35 #include <linux/kdev_t.h>
36 
37 #include <ApexProperties.sysprop.h>
38 #include <android-base/logging.h>
39 #include <android-base/parseint.h>
40 #include <android-base/properties.h>
41 #include <android-base/stringprintf.h>
42 #include <android-base/strings.h>
43 
44 #include <cutils/fs.h>
45 #include <utils/Trace.h>
46 
47 #include <selinux/android.h>
48 
49 #include <sysutils/NetlinkEvent.h>
50 
51 #include <private/android_filesystem_config.h>
52 
53 #include <fscrypt/fscrypt.h>
54 
55 #include "AppFuseUtil.h"
56 #include "Devmapper.h"
57 #include "FsCrypt.h"
58 #include "Loop.h"
59 #include "NetlinkManager.h"
60 #include "Process.h"
61 #include "Utils.h"
62 #include "VoldNativeService.h"
63 #include "VoldUtil.h"
64 #include "VolumeManager.h"
65 #include "cryptfs.h"
66 #include "fs/Ext4.h"
67 #include "fs/Vfat.h"
68 #include "model/EmulatedVolume.h"
69 #include "model/ObbVolume.h"
70 #include "model/StubVolume.h"
71 
72 using android::OK;
73 using android::base::GetBoolProperty;
74 using android::base::StartsWith;
75 using android::base::StringAppendF;
76 using android::base::StringPrintf;
77 using android::base::unique_fd;
78 using android::vold::BindMount;
79 using android::vold::CreateDir;
80 using android::vold::DeleteDirContents;
81 using android::vold::DeleteDirContentsAndDir;
82 using android::vold::Symlink;
83 using android::vold::Unlink;
84 using android::vold::UnmountTree;
85 using android::vold::VoldNativeService;
86 
87 static const char* kPathUserMount = "/mnt/user";
88 static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
89 
90 static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
91 
92 static const std::string kEmptyString("");
93 
94 /* 512MiB is large enough for testing purposes */
95 static const unsigned int kSizeVirtualDisk = 536870912;
96 
97 static const unsigned int kMajorBlockMmc = 179;
98 static const unsigned int kMajorBlockExperimentalMin = 240;
99 static const unsigned int kMajorBlockExperimentalMax = 254;
100 
101 VolumeManager* VolumeManager::sInstance = NULL;
102 
Instance()103 VolumeManager* VolumeManager::Instance() {
104     if (!sInstance) sInstance = new VolumeManager();
105     return sInstance;
106 }
107 
VolumeManager()108 VolumeManager::VolumeManager() {
109     mDebug = false;
110     mNextObbId = 0;
111     mNextStubVolumeId = 0;
112     // For security reasons, assume that a secure keyguard is
113     // showing until we hear otherwise
114     mSecureKeyguardShowing = true;
115 }
116 
~VolumeManager()117 VolumeManager::~VolumeManager() {}
118 
updateVirtualDisk()119 int VolumeManager::updateVirtualDisk() {
120     ATRACE_NAME("VolumeManager::updateVirtualDisk");
121     if (GetBoolProperty(kPropVirtualDisk, false)) {
122         if (access(kPathVirtualDisk, F_OK) != 0) {
123             Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
124         }
125 
126         if (mVirtualDisk == nullptr) {
127             if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
128                 LOG(ERROR) << "Failed to create virtual disk";
129                 return -1;
130             }
131 
132             struct stat buf;
133             if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
134                 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
135                 return -1;
136             }
137 
138             auto disk = new android::vold::Disk(
139                 "virtual", buf.st_rdev, "virtual",
140                 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
141             mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
142             handleDiskAdded(mVirtualDisk);
143         }
144     } else {
145         if (mVirtualDisk != nullptr) {
146             dev_t device = mVirtualDisk->getDevice();
147             handleDiskRemoved(device);
148 
149             Loop::destroyByDevice(mVirtualDiskPath.c_str());
150             mVirtualDisk = nullptr;
151         }
152 
153         if (access(kPathVirtualDisk, F_OK) == 0) {
154             unlink(kPathVirtualDisk);
155         }
156     }
157     return 0;
158 }
159 
setDebug(bool enable)160 int VolumeManager::setDebug(bool enable) {
161     mDebug = enable;
162     return 0;
163 }
164 
start()165 int VolumeManager::start() {
166     ATRACE_NAME("VolumeManager::start");
167 
168     // Always start from a clean slate by unmounting everything in
169     // directories that we own, in case we crashed.
170     unmountAll();
171 
172     Devmapper::destroyAll();
173     Loop::destroyAll();
174 
175     // Assume that we always have an emulated volume on internal
176     // storage; the framework will decide if it should be mounted.
177     CHECK(mInternalEmulated == nullptr);
178     mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
179         new android::vold::EmulatedVolume("/data/media"));
180     mInternalEmulated->create();
181 
182     // Consider creating a virtual disk
183     updateVirtualDisk();
184 
185     return 0;
186 }
187 
stop()188 int VolumeManager::stop() {
189     CHECK(mInternalEmulated != nullptr);
190     mInternalEmulated->destroy();
191     mInternalEmulated = nullptr;
192     return 0;
193 }
194 
handleBlockEvent(NetlinkEvent * evt)195 void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
196     std::lock_guard<std::mutex> lock(mLock);
197 
198     if (mDebug) {
199         LOG(DEBUG) << "----------------";
200         LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
201         evt->dump();
202     }
203 
204     std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
205     std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
206 
207     if (devType != "disk") return;
208 
209     int major = std::stoi(evt->findParam("MAJOR"));
210     int minor = std::stoi(evt->findParam("MINOR"));
211     dev_t device = makedev(major, minor);
212 
213     switch (evt->getAction()) {
214         case NetlinkEvent::Action::kAdd: {
215             for (const auto& source : mDiskSources) {
216                 if (source->matches(eventPath)) {
217                     // For now, assume that MMC and virtio-blk (the latter is
218                     // emulator-specific; see Disk.cpp for details) devices are SD,
219                     // and that everything else is USB
220                     int flags = source->getFlags();
221                     if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
222                                                     major >= (int)kMajorBlockExperimentalMin &&
223                                                     major <= (int)kMajorBlockExperimentalMax)) {
224                         flags |= android::vold::Disk::Flags::kSd;
225                     } else {
226                         flags |= android::vold::Disk::Flags::kUsb;
227                     }
228 
229                     auto disk =
230                         new android::vold::Disk(eventPath, device, source->getNickname(), flags);
231                     handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
232                     break;
233                 }
234             }
235             break;
236         }
237         case NetlinkEvent::Action::kChange: {
238             LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
239             handleDiskChanged(device);
240             break;
241         }
242         case NetlinkEvent::Action::kRemove: {
243             handleDiskRemoved(device);
244             break;
245         }
246         default: {
247             LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
248             break;
249         }
250     }
251 }
252 
handleDiskAdded(const std::shared_ptr<android::vold::Disk> & disk)253 void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
254     // For security reasons, if secure keyguard is showing, wait
255     // until the user unlocks the device to actually touch it
256     if (mSecureKeyguardShowing) {
257         LOG(INFO) << "Found disk at " << disk->getEventPath()
258                   << " but delaying scan due to secure keyguard";
259         mPendingDisks.push_back(disk);
260     } else {
261         disk->create();
262         mDisks.push_back(disk);
263     }
264 }
265 
handleDiskChanged(dev_t device)266 void VolumeManager::handleDiskChanged(dev_t device) {
267     for (const auto& disk : mDisks) {
268         if (disk->getDevice() == device) {
269             disk->readMetadata();
270             disk->readPartitions();
271         }
272     }
273 
274     // For security reasons, we ignore all pending disks, since
275     // we'll scan them once the device is unlocked
276 }
277 
handleDiskRemoved(dev_t device)278 void VolumeManager::handleDiskRemoved(dev_t device) {
279     auto i = mDisks.begin();
280     while (i != mDisks.end()) {
281         if ((*i)->getDevice() == device) {
282             (*i)->destroy();
283             i = mDisks.erase(i);
284         } else {
285             ++i;
286         }
287     }
288     auto j = mPendingDisks.begin();
289     while (j != mPendingDisks.end()) {
290         if ((*j)->getDevice() == device) {
291             j = mPendingDisks.erase(j);
292         } else {
293             ++j;
294         }
295     }
296 }
297 
addDiskSource(const std::shared_ptr<DiskSource> & diskSource)298 void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
299     std::lock_guard<std::mutex> lock(mLock);
300     mDiskSources.push_back(diskSource);
301 }
302 
findDisk(const std::string & id)303 std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
304     for (auto disk : mDisks) {
305         if (disk->getId() == id) {
306             return disk;
307         }
308     }
309     return nullptr;
310 }
311 
findVolume(const std::string & id)312 std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
313     // Vold could receive "mount" after "shutdown" command in the extreme case.
314     // If this happens, mInternalEmulated will equal nullptr and
315     // we need to deal with it in order to avoid null pointer crash.
316     if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
317         return mInternalEmulated;
318     }
319     for (const auto& disk : mDisks) {
320         auto vol = disk->findVolume(id);
321         if (vol != nullptr) {
322             return vol;
323         }
324     }
325     for (const auto& vol : mStubVolumes) {
326         if (vol->getId() == id) {
327             return vol;
328         }
329     }
330     for (const auto& vol : mObbVolumes) {
331         if (vol->getId() == id) {
332             return vol;
333         }
334     }
335     return nullptr;
336 }
337 
listVolumes(android::vold::VolumeBase::Type type,std::list<std::string> & list) const338 void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
339                                 std::list<std::string>& list) const {
340     list.clear();
341     for (const auto& disk : mDisks) {
342         disk->listVolumes(type, list);
343     }
344 }
345 
forgetPartition(const std::string & partGuid,const std::string & fsUuid)346 int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
347     std::string normalizedGuid;
348     if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
349         LOG(WARNING) << "Invalid GUID " << partGuid;
350         return -1;
351     }
352 
353     bool success = true;
354     std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
355     if (unlink(keyPath.c_str()) != 0) {
356         LOG(ERROR) << "Failed to unlink " << keyPath;
357         success = false;
358     }
359     if (fscrypt_is_native()) {
360         if (!fscrypt_destroy_volume_keys(fsUuid)) {
361             success = false;
362         }
363     }
364     return success ? 0 : -1;
365 }
366 
linkPrimary(userid_t userId)367 int VolumeManager::linkPrimary(userid_t userId) {
368     std::string source(mPrimary->getPath());
369     if (mPrimary->isEmulated()) {
370         source = StringPrintf("%s/%d", source.c_str(), userId);
371         fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
372     }
373 
374     std::string target(StringPrintf("/mnt/user/%d/primary", userId));
375     LOG(DEBUG) << "Linking " << source << " to " << target;
376     Symlink(source, target);
377     return 0;
378 }
379 
onUserAdded(userid_t userId,int userSerialNumber)380 int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
381     mAddedUsers[userId] = userSerialNumber;
382     return 0;
383 }
384 
onUserRemoved(userid_t userId)385 int VolumeManager::onUserRemoved(userid_t userId) {
386     mAddedUsers.erase(userId);
387     return 0;
388 }
389 
onUserStarted(userid_t userId)390 int VolumeManager::onUserStarted(userid_t userId) {
391     LOG(VERBOSE) << "onUserStarted: " << userId;
392     // Note that sometimes the system will spin up processes from Zygote
393     // before actually starting the user, so we're okay if Zygote
394     // already created this directory.
395     std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
396     fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
397 
398     mStartedUsers.insert(userId);
399     if (mPrimary) {
400         linkPrimary(userId);
401     }
402     return 0;
403 }
404 
onUserStopped(userid_t userId)405 int VolumeManager::onUserStopped(userid_t userId) {
406     LOG(VERBOSE) << "onUserStopped: " << userId;
407     mStartedUsers.erase(userId);
408     return 0;
409 }
410 
onSecureKeyguardStateChanged(bool isShowing)411 int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
412     mSecureKeyguardShowing = isShowing;
413     if (!mSecureKeyguardShowing) {
414         // Now that secure keyguard has been dismissed, process
415         // any pending disks
416         for (const auto& disk : mPendingDisks) {
417             disk->create();
418             mDisks.push_back(disk);
419         }
420         mPendingDisks.clear();
421     }
422     return 0;
423 }
424 
setPrimary(const std::shared_ptr<android::vold::VolumeBase> & vol)425 int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
426     mPrimary = vol;
427     for (userid_t userId : mStartedUsers) {
428         linkPrimary(userId);
429     }
430     return 0;
431 }
432 
remountUid(uid_t uid,int32_t mountMode)433 int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
434     std::string mode;
435     switch (mountMode) {
436         case VoldNativeService::REMOUNT_MODE_NONE:
437             mode = "none";
438             break;
439         case VoldNativeService::REMOUNT_MODE_DEFAULT:
440             mode = "default";
441             break;
442         case VoldNativeService::REMOUNT_MODE_READ:
443             mode = "read";
444             break;
445         case VoldNativeService::REMOUNT_MODE_WRITE:
446         case VoldNativeService::REMOUNT_MODE_LEGACY:
447         case VoldNativeService::REMOUNT_MODE_INSTALLER:
448             mode = "write";
449             break;
450         case VoldNativeService::REMOUNT_MODE_FULL:
451             mode = "full";
452             break;
453         default:
454             PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
455             return -1;
456     }
457     LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
458 
459     DIR* dir;
460     struct dirent* de;
461     std::string rootName;
462     std::string pidName;
463     int pidFd;
464     int nsFd;
465     struct stat sb;
466     pid_t child;
467 
468     static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
469 
470     if (!(dir = opendir("/proc"))) {
471         PLOG(ERROR) << "Failed to opendir";
472         return -1;
473     }
474 
475     // Figure out root namespace to compare against below
476     if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
477         PLOG(ERROR) << "Failed to read root namespace";
478         closedir(dir);
479         return -1;
480     }
481 
482     // Poke through all running PIDs look for apps running as UID
483     while ((de = readdir(dir))) {
484         pid_t pid;
485         if (de->d_type != DT_DIR) continue;
486         if (!android::base::ParseInt(de->d_name, &pid)) continue;
487 
488         pidFd = -1;
489         nsFd = -1;
490 
491         pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
492         if (pidFd < 0) {
493             goto next;
494         }
495         if (fstat(pidFd, &sb) != 0) {
496             PLOG(WARNING) << "Failed to stat " << de->d_name;
497             goto next;
498         }
499         if (sb.st_uid != uid) {
500             goto next;
501         }
502 
503         // Matches so far, but refuse to touch if in root namespace
504         LOG(DEBUG) << "Found matching PID " << de->d_name;
505         if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
506             PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
507             goto next;
508         }
509         if (rootName == pidName) {
510             LOG(WARNING) << "Skipping due to root namespace";
511             goto next;
512         }
513 
514         if (apexUpdatable) {
515             std::string exeName;
516             // When ro.apex.bionic_updatable is set to true,
517             // some early native processes have mount namespaces that are different
518             // from that of the init. Therefore, above check can't filter them out.
519             // Since the propagation type of / is 'shared', unmounting /storage
520             // for the early native processes affects other processes including
521             // init. Filter out such processes by skipping if a process is a
522             // non-Java process whose UID is < AID_APP_START. (The UID condition
523             // is required to not filter out child processes spawned by apps.)
524             if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
525                 PLOG(WARNING) << "Failed to read exe name for " << de->d_name;
526                 goto next;
527             }
528             if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
529                 LOG(WARNING) << "Skipping due to native system process";
530                 goto next;
531             }
532         }
533 
534         // We purposefully leave the namespace open across the fork
535         // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
536         nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
537         if (nsFd < 0) {
538             PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
539             goto next;
540         }
541 
542         if (!(child = fork())) {
543             if (setns(nsFd, CLONE_NEWNS) != 0) {
544                 PLOG(ERROR) << "Failed to setns for " << de->d_name;
545                 _exit(1);
546             }
547 
548             android::vold::UnmountTree("/storage/");
549 
550             std::string storageSource;
551             if (mode == "default") {
552                 storageSource = "/mnt/runtime/default";
553             } else if (mode == "read") {
554                 storageSource = "/mnt/runtime/read";
555             } else if (mode == "write") {
556                 storageSource = "/mnt/runtime/write";
557             } else if (mode == "full") {
558                 storageSource = "/mnt/runtime/full";
559             } else {
560                 // Sane default of no storage visible
561                 _exit(0);
562             }
563             if (TEMP_FAILURE_RETRY(
564                     mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
565                 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
566                 _exit(1);
567             }
568             if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
569                 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
570                 _exit(1);
571             }
572 
573             // Mount user-specific symlink helper into place
574             userid_t user_id = multiuser_get_user_id(uid);
575             std::string userSource(StringPrintf("/mnt/user/%d", user_id));
576             if (TEMP_FAILURE_RETRY(
577                     mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
578                 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
579                 _exit(1);
580             }
581 
582             _exit(0);
583         }
584 
585         if (child == -1) {
586             PLOG(ERROR) << "Failed to fork";
587             goto next;
588         } else {
589             TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
590         }
591 
592     next:
593         close(nsFd);
594         close(pidFd);
595     }
596     closedir(dir);
597     return 0;
598 }
599 
reset()600 int VolumeManager::reset() {
601     // Tear down all existing disks/volumes and start from a blank slate so
602     // newly connected framework hears all events.
603     if (mInternalEmulated != nullptr) {
604         mInternalEmulated->destroy();
605         mInternalEmulated->create();
606     }
607     for (const auto& disk : mDisks) {
608         disk->destroy();
609         disk->create();
610     }
611     updateVirtualDisk();
612     mAddedUsers.clear();
613     mStartedUsers.clear();
614     return 0;
615 }
616 
617 // Can be called twice (sequentially) during shutdown. should be safe for that.
shutdown()618 int VolumeManager::shutdown() {
619     if (mInternalEmulated == nullptr) {
620         return 0;  // already shutdown
621     }
622     android::vold::sSleepOnUnmount = false;
623     mInternalEmulated->destroy();
624     mInternalEmulated = nullptr;
625     for (const auto& disk : mDisks) {
626         disk->destroy();
627     }
628     mStubVolumes.clear();
629     mDisks.clear();
630     mPendingDisks.clear();
631     android::vold::sSleepOnUnmount = true;
632     return 0;
633 }
634 
unmountAll()635 int VolumeManager::unmountAll() {
636     std::lock_guard<std::mutex> lock(mLock);
637     ATRACE_NAME("VolumeManager::unmountAll()");
638 
639     // First, try gracefully unmounting all known devices
640     if (mInternalEmulated != nullptr) {
641         mInternalEmulated->unmount();
642     }
643     for (const auto& stub : mStubVolumes) {
644         stub->unmount();
645     }
646     for (const auto& disk : mDisks) {
647         disk->unmountAll();
648     }
649 
650     // Worst case we might have some stale mounts lurking around, so
651     // force unmount those just to be safe.
652     FILE* fp = setmntent("/proc/mounts", "re");
653     if (fp == NULL) {
654         PLOG(ERROR) << "Failed to open /proc/mounts";
655         return -errno;
656     }
657 
658     // Some volumes can be stacked on each other, so force unmount in
659     // reverse order to give us the best chance of success.
660     std::list<std::string> toUnmount;
661     mntent* mentry;
662     while ((mentry = getmntent(fp)) != NULL) {
663         auto test = std::string(mentry->mnt_dir);
664         if ((StartsWith(test, "/mnt/") &&
665 #ifdef __ANDROID_DEBUGGABLE__
666              !StartsWith(test, "/mnt/scratch") &&
667 #endif
668              !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
669             StartsWith(test, "/storage/")) {
670             toUnmount.push_front(test);
671         }
672     }
673     endmntent(fp);
674 
675     for (const auto& path : toUnmount) {
676         LOG(DEBUG) << "Tearing down stale mount " << path;
677         android::vold::ForceUnmount(path);
678     }
679 
680     return 0;
681 }
682 
mkdirs(const std::string & path)683 int VolumeManager::mkdirs(const std::string& path) {
684     // Only offer to create directories for paths managed by vold
685     if (StartsWith(path, "/storage/")) {
686         // fs_mkdirs() does symlink checking and relative path enforcement
687         return fs_mkdirs(path.c_str(), 0700);
688     } else {
689         LOG(ERROR) << "Failed to find mounted volume for " << path;
690         return -EINVAL;
691     }
692 }
693 
createObb(const std::string & sourcePath,const std::string & sourceKey,int32_t ownerGid,std::string * outVolId)694 int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
695                              int32_t ownerGid, std::string* outVolId) {
696     int id = mNextObbId++;
697 
698     auto vol = std::shared_ptr<android::vold::VolumeBase>(
699         new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
700     vol->create();
701 
702     mObbVolumes.push_back(vol);
703     *outVolId = vol->getId();
704     return android::OK;
705 }
706 
destroyObb(const std::string & volId)707 int VolumeManager::destroyObb(const std::string& volId) {
708     auto i = mObbVolumes.begin();
709     while (i != mObbVolumes.end()) {
710         if ((*i)->getId() == volId) {
711             (*i)->destroy();
712             i = mObbVolumes.erase(i);
713         } else {
714             ++i;
715         }
716     }
717     return android::OK;
718 }
719 
createStubVolume(const std::string & sourcePath,const std::string & mountPath,const std::string & fsType,const std::string & fsUuid,const std::string & fsLabel,std::string * outVolId)720 int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
721                                     const std::string& fsType, const std::string& fsUuid,
722                                     const std::string& fsLabel, std::string* outVolId) {
723     int id = mNextStubVolumeId++;
724     auto vol = std::shared_ptr<android::vold::VolumeBase>(
725         new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
726     vol->create();
727 
728     mStubVolumes.push_back(vol);
729     *outVolId = vol->getId();
730     return android::OK;
731 }
732 
destroyStubVolume(const std::string & volId)733 int VolumeManager::destroyStubVolume(const std::string& volId) {
734     auto i = mStubVolumes.begin();
735     while (i != mStubVolumes.end()) {
736         if ((*i)->getId() == volId) {
737             (*i)->destroy();
738             i = mStubVolumes.erase(i);
739         } else {
740             ++i;
741         }
742     }
743     return android::OK;
744 }
745 
mountAppFuse(uid_t uid,int mountId,unique_fd * device_fd)746 int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
747     return android::vold::MountAppFuse(uid, mountId, device_fd);
748 }
749 
unmountAppFuse(uid_t uid,int mountId)750 int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
751     return android::vold::UnmountAppFuse(uid, mountId);
752 }
753 
openAppFuseFile(uid_t uid,int mountId,int fileId,int flags)754 int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
755     return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
756 }
757