• 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 <limits.h>
23 #include <mntent.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/ioctl.h>
28 #include <sys/mount.h>
29 #include <sys/stat.h>
30 #include <sys/sysmacros.h>
31 #include <sys/types.h>
32 #include <sys/wait.h>
33 #include <unistd.h>
34 #include <array>
35 
36 #include <linux/kdev_t.h>
37 
38 #include <android-base/file.h>
39 #include <android-base/logging.h>
40 #include <android-base/parseint.h>
41 #include <android-base/properties.h>
42 #include <android-base/stringprintf.h>
43 #include <android-base/strings.h>
44 #include <async_safe/log.h>
45 
46 #include <cutils/fs.h>
47 #include <utils/Trace.h>
48 
49 #include <selinux/android.h>
50 
51 #include <sysutils/NetlinkEvent.h>
52 
53 #include <private/android_filesystem_config.h>
54 
55 #include <fscrypt/fscrypt.h>
56 #include <libdm/dm.h>
57 
58 #include "AppFuseUtil.h"
59 #include "FsCrypt.h"
60 #include "Loop.h"
61 #include "NetlinkManager.h"
62 #include "Process.h"
63 #include "Utils.h"
64 #include "VoldNativeService.h"
65 #include "VoldUtil.h"
66 #include "VolumeManager.h"
67 #include "fs/Ext4.h"
68 #include "fs/Vfat.h"
69 #include "model/EmulatedVolume.h"
70 #include "model/ObbVolume.h"
71 #include "model/PrivateVolume.h"
72 #include "model/PublicVolume.h"
73 #include "model/StubVolume.h"
74 
75 using android::OK;
76 using android::base::GetBoolProperty;
77 using android::base::StartsWith;
78 using android::base::StringAppendF;
79 using android::base::StringPrintf;
80 using android::base::unique_fd;
81 using android::vold::BindMount;
82 using android::vold::CreateDir;
83 using android::vold::DeleteDirContents;
84 using android::vold::DeleteDirContentsAndDir;
85 using android::vold::EnsureDirExists;
86 using android::vold::GetFuseMountPathForUser;
87 using android::vold::IsFilesystemSupported;
88 using android::vold::IsSdcardfsUsed;
89 using android::vold::IsVirtioBlkDevice;
90 using android::vold::PrepareAndroidDirs;
91 using android::vold::PrepareAppDirFromRoot;
92 using android::vold::PrivateVolume;
93 using android::vold::PublicVolume;
94 using android::vold::Symlink;
95 using android::vold::Unlink;
96 using android::vold::UnmountTree;
97 using android::vold::VoldNativeService;
98 using android::vold::VolumeBase;
99 
100 static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
101 
102 static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
103 
104 /* 512MiB is large enough for testing purposes */
105 static const unsigned int kSizeVirtualDisk = 536870912;
106 
107 static const unsigned int kMajorBlockMmc = 179;
108 
109 using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
110 
111 VolumeManager* VolumeManager::sInstance = NULL;
112 
Instance()113 VolumeManager* VolumeManager::Instance() {
114     if (!sInstance) sInstance = new VolumeManager();
115     return sInstance;
116 }
117 
VolumeManager()118 VolumeManager::VolumeManager() {
119     mDebug = false;
120     mNextObbId = 0;
121     mNextStubId = 0;
122     // For security reasons, assume that a secure keyguard is
123     // showing until we hear otherwise
124     mSecureKeyguardShowing = true;
125 }
126 
~VolumeManager()127 VolumeManager::~VolumeManager() {}
128 
updateVirtualDisk()129 int VolumeManager::updateVirtualDisk() {
130     ATRACE_NAME("VolumeManager::updateVirtualDisk");
131     if (GetBoolProperty(kPropVirtualDisk, false)) {
132         if (access(kPathVirtualDisk, F_OK) != 0) {
133             Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
134         }
135 
136         if (mVirtualDisk == nullptr) {
137             if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
138                 LOG(ERROR) << "Failed to create virtual disk";
139                 return -1;
140             }
141 
142             struct stat buf;
143             if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
144                 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
145                 return -1;
146             }
147 
148             auto disk = new android::vold::Disk(
149                 "virtual", buf.st_rdev, "virtual",
150                 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
151             mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
152             handleDiskAdded(mVirtualDisk);
153         }
154     } else {
155         if (mVirtualDisk != nullptr) {
156             dev_t device = mVirtualDisk->getDevice();
157             handleDiskRemoved(device);
158 
159             Loop::destroyByDevice(mVirtualDiskPath.c_str());
160             mVirtualDisk = nullptr;
161         }
162 
163         if (access(kPathVirtualDisk, F_OK) == 0) {
164             unlink(kPathVirtualDisk);
165         }
166     }
167     return 0;
168 }
169 
setDebug(bool enable)170 int VolumeManager::setDebug(bool enable) {
171     mDebug = enable;
172     return 0;
173 }
174 
start()175 int VolumeManager::start() {
176     ATRACE_NAME("VolumeManager::start");
177 
178     // Always start from a clean slate by unmounting everything in
179     // directories that we own, in case we crashed.
180     unmountAll();
181 
182     Loop::destroyAll();
183 
184     // Assume that we always have an emulated volume on internal
185     // storage; the framework will decide if it should be mounted.
186     CHECK(mInternalEmulatedVolumes.empty());
187 
188     auto vol = std::shared_ptr<android::vold::VolumeBase>(
189             new android::vold::EmulatedVolume("/data/media", 0));
190     vol->setMountUserId(0);
191     vol->create();
192     mInternalEmulatedVolumes.push_back(vol);
193 
194     // Consider creating a virtual disk
195     updateVirtualDisk();
196 
197     return 0;
198 }
199 
handleBlockEvent(NetlinkEvent * evt)200 void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
201     std::lock_guard<std::mutex> lock(mLock);
202 
203     if (mDebug) {
204         LOG(DEBUG) << "----------------";
205         LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
206         evt->dump();
207     }
208 
209     std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
210     std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
211 
212     if (devType != "disk") return;
213 
214     int major = std::stoi(evt->findParam("MAJOR"));
215     int minor = std::stoi(evt->findParam("MINOR"));
216     dev_t device = makedev(major, minor);
217 
218     switch (evt->getAction()) {
219         case NetlinkEvent::Action::kAdd: {
220             for (const auto& source : mDiskSources) {
221                 if (source->matches(eventPath)) {
222                     // For now, assume that MMC and virtio-blk (the latter is
223                     // specific to virtual platforms; see Utils.cpp for details)
224                     // devices are SD, and that everything else is USB
225                     int flags = source->getFlags();
226                     if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
227                         flags |= android::vold::Disk::Flags::kSd;
228                     } else {
229                         flags |= android::vold::Disk::Flags::kUsb;
230                     }
231 
232                     auto disk =
233                         new android::vold::Disk(eventPath, device, source->getNickname(), flags);
234                     handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
235                     break;
236                 }
237             }
238             break;
239         }
240         case NetlinkEvent::Action::kChange: {
241             LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
242             handleDiskChanged(device);
243             break;
244         }
245         case NetlinkEvent::Action::kRemove: {
246             handleDiskRemoved(device);
247             break;
248         }
249         default: {
250             LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
251             break;
252         }
253     }
254 }
255 
handleDiskAdded(const std::shared_ptr<android::vold::Disk> & disk)256 void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
257     // For security reasons, if secure keyguard is showing, wait
258     // until the user unlocks the device to actually touch it
259     // Additionally, wait until user 0 is actually started, since we need
260     // the user to be up before we can mount a FUSE daemon to handle the disk.
261     bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
262     if (mSecureKeyguardShowing) {
263         LOG(INFO) << "Found disk at " << disk->getEventPath()
264                   << " but delaying scan due to secure keyguard";
265         mPendingDisks.push_back(disk);
266     } else if (!userZeroStarted) {
267         LOG(INFO) << "Found disk at " << disk->getEventPath()
268                   << " but delaying scan due to user zero not having started";
269         mPendingDisks.push_back(disk);
270     } else {
271         disk->create();
272         mDisks.push_back(disk);
273     }
274 }
275 
handleDiskChanged(dev_t device)276 void VolumeManager::handleDiskChanged(dev_t device) {
277     for (const auto& disk : mDisks) {
278         if (disk->getDevice() == device) {
279             disk->readMetadata();
280             disk->readPartitions();
281         }
282     }
283 
284     // For security reasons, we ignore all pending disks, since
285     // we'll scan them once the device is unlocked
286 }
287 
handleDiskRemoved(dev_t device)288 void VolumeManager::handleDiskRemoved(dev_t device) {
289     auto i = mDisks.begin();
290     while (i != mDisks.end()) {
291         if ((*i)->getDevice() == device) {
292             (*i)->destroy();
293             i = mDisks.erase(i);
294         } else {
295             ++i;
296         }
297     }
298     auto j = mPendingDisks.begin();
299     while (j != mPendingDisks.end()) {
300         if ((*j)->getDevice() == device) {
301             j = mPendingDisks.erase(j);
302         } else {
303             ++j;
304         }
305     }
306 }
307 
addDiskSource(const std::shared_ptr<DiskSource> & diskSource)308 void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
309     std::lock_guard<std::mutex> lock(mLock);
310     mDiskSources.push_back(diskSource);
311 }
312 
findDisk(const std::string & id)313 std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
314     for (auto disk : mDisks) {
315         if (disk->getId() == id) {
316             return disk;
317         }
318     }
319     return nullptr;
320 }
321 
findVolume(const std::string & id)322 std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
323     for (const auto& vol : mInternalEmulatedVolumes) {
324         if (vol->getId() == id) {
325             return vol;
326         }
327     }
328     for (const auto& disk : mDisks) {
329         auto vol = disk->findVolume(id);
330         if (vol != nullptr) {
331             return vol;
332         }
333     }
334     for (const auto& vol : mObbVolumes) {
335         if (vol->getId() == id) {
336             return vol;
337         }
338     }
339     return nullptr;
340 }
341 
listVolumes(android::vold::VolumeBase::Type type,std::list<std::string> & list) const342 void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
343                                 std::list<std::string>& list) const {
344     list.clear();
345     for (const auto& disk : mDisks) {
346         disk->listVolumes(type, list);
347     }
348 }
349 
forgetPartition(const std::string & partGuid,const std::string & fsUuid)350 bool VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
351     std::string normalizedGuid;
352     if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
353         LOG(WARNING) << "Invalid GUID " << partGuid;
354         return false;
355     }
356 
357     std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
358     if (unlink(keyPath.c_str()) != 0) {
359         LOG(ERROR) << "Failed to unlink " << keyPath;
360         return false;
361     }
362     return true;
363 }
364 
destroyEmulatedVolumesForUser(userid_t userId)365 void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
366     // Destroy and remove all unstacked EmulatedVolumes for the user
367     auto i = mInternalEmulatedVolumes.begin();
368     while (i != mInternalEmulatedVolumes.end()) {
369         auto vol = *i;
370         if (vol->getMountUserId() == userId) {
371             vol->destroy();
372             i = mInternalEmulatedVolumes.erase(i);
373         } else {
374             i++;
375         }
376     }
377 
378     // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
379     std::list<std::string> private_vols;
380     listVolumes(VolumeBase::Type::kPrivate, private_vols);
381     for (const std::string& id : private_vols) {
382         PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
383         std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
384         if (pvol->getState() == VolumeBase::State::kMounted) {
385             for (const auto& vol : pvol->getVolumes()) {
386                 if (vol->getMountUserId() == userId) {
387                     vols_to_remove.push_back(vol);
388                 }
389             }
390             for (const auto& vol : vols_to_remove) {
391                 vol->destroy();
392                 pvol->removeVolume(vol);
393             }
394         }  // else EmulatedVolumes will be destroyed on VolumeBase#unmount
395     }
396 }
397 
createEmulatedVolumesForUser(userid_t userId)398 void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
399     // Create unstacked EmulatedVolumes for the user
400     auto vol = std::shared_ptr<android::vold::VolumeBase>(
401             new android::vold::EmulatedVolume("/data/media", userId));
402     vol->setMountUserId(userId);
403     mInternalEmulatedVolumes.push_back(vol);
404     vol->create();
405 
406     // Create stacked EmulatedVolumes for the user on each PrivateVolume
407     std::list<std::string> private_vols;
408     listVolumes(VolumeBase::Type::kPrivate, private_vols);
409     for (const std::string& id : private_vols) {
410         PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
411         if (pvol->getState() == VolumeBase::State::kMounted) {
412             auto evol =
413                     std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
414                             pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
415                             userId));
416             evol->setMountUserId(userId);
417             pvol->addVolume(evol);
418             evol->create();
419         }  // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
420     }
421 }
422 
getSharedStorageUser(userid_t userId)423 userid_t VolumeManager::getSharedStorageUser(userid_t userId) {
424     if (mSharedStorageUser.find(userId) == mSharedStorageUser.end()) {
425         return USER_UNKNOWN;
426     }
427     return mSharedStorageUser.at(userId);
428 }
429 
onUserAdded(userid_t userId,int userSerialNumber,userid_t sharesStorageWithUserId)430 int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber,
431                                userid_t sharesStorageWithUserId) {
432     LOG(INFO) << "onUserAdded: " << userId;
433 
434     mAddedUsers[userId] = userSerialNumber;
435     if (sharesStorageWithUserId != USER_UNKNOWN) {
436         mSharedStorageUser[userId] = sharesStorageWithUserId;
437     }
438     return 0;
439 }
440 
onUserRemoved(userid_t userId)441 int VolumeManager::onUserRemoved(userid_t userId) {
442     LOG(INFO) << "onUserRemoved: " << userId;
443 
444     onUserStopped(userId);
445     mAddedUsers.erase(userId);
446     mSharedStorageUser.erase(userId);
447     return 0;
448 }
449 
onUserStarted(userid_t userId)450 int VolumeManager::onUserStarted(userid_t userId) {
451     LOG(INFO) << "onUserStarted: " << userId;
452 
453     if (mStartedUsers.find(userId) == mStartedUsers.end()) {
454         createEmulatedVolumesForUser(userId);
455 
456         userid_t sharedStorageUserId = VolumeManager::Instance()->getSharedStorageUser(userId);
457         if (sharedStorageUserId != USER_UNKNOWN) {
458             std::list<std::string> public_vols;
459             listVolumes(VolumeBase::Type::kPublic, public_vols);
460             for (const std::string& id : public_vols) {
461                 PublicVolume *pvol = static_cast<PublicVolume *>(findVolume(id).get());
462                 if (pvol->getState() != VolumeBase::State::kMounted) {
463                     continue;
464                 }
465                 if (pvol->isVisible() == 0) {
466                     continue;
467                 }
468                 userid_t mountUserId = pvol->getMountUserId();
469                 if (userId == mountUserId) {
470                     // No need to bind mount for the user that owns the mount
471                     continue;
472                 }
473 
474                 if (mountUserId != sharedStorageUserId) {
475                     // No need to bind if the user does not share storage with the mount owner
476                     continue;
477                 }
478                 // Create mount directory for the user as there is a chance that no other Volume is
479                 // mounted for the user (ex: if the user is just started),
480                 // so /mnt/user/user_id  does not exist yet.
481                 auto mountDirStatus = android::vold::PrepareMountDirForUser(userId);
482                 if (mountDirStatus != OK) {
483                     LOG(ERROR) << "Failed to create Mount Directory for user " << userId;
484                 }
485                 auto bindMountStatus = pvol->bindMountForUser(userId);
486                 if (bindMountStatus != OK) {
487                     LOG(ERROR) << "Bind Mounting Public Volume: " << pvol << " for user: " << userId
488                                << "Failed. Error: " << bindMountStatus;
489                 }
490             }
491         }
492     }
493 
494     mStartedUsers.insert(userId);
495 
496     createPendingDisksIfNeeded();
497     return 0;
498 }
499 
onUserStopped(userid_t userId)500 int VolumeManager::onUserStopped(userid_t userId) {
501     LOG(VERBOSE) << "onUserStopped: " << userId;
502 
503     if (mStartedUsers.find(userId) != mStartedUsers.end()) {
504         destroyEmulatedVolumesForUser(userId);
505 
506         userid_t sharedStorageUserId = VolumeManager::Instance()->getSharedStorageUser(userId);
507         if (sharedStorageUserId != USER_UNKNOWN) {
508             std::list<std::string> public_vols;
509             listVolumes(VolumeBase::Type::kPublic, public_vols);
510             for (const std::string &id: public_vols) {
511                 PublicVolume *pvol = static_cast<PublicVolume *>(findVolume(id).get());
512                 if (pvol->getState() != VolumeBase::State::kMounted) {
513                     continue;
514                 }
515                 if (pvol->isVisible() == 0) {
516                     continue;
517                 }
518                 userid_t mountUserId = pvol->getMountUserId();
519                 if (userId == mountUserId) {
520                     // No need to remove bind mount for the user that owns the mount
521                     continue;
522                 }
523                 if (mountUserId != sharedStorageUserId) {
524                     // No need to remove bind mount
525                     // if the user does not share storage with the mount owner
526                     continue;
527                 }
528                 LOG(INFO) << "Removing Public Volume Bind Mount for: " << userId;
529                 auto mountPath = GetFuseMountPathForUser(userId, pvol->getStableName());
530                 android::vold::ForceUnmount(mountPath);
531                 rmdir(mountPath.c_str());
532             }
533         }
534 
535     }
536 
537     mStartedUsers.erase(userId);
538     return 0;
539 }
540 
createPendingDisksIfNeeded()541 void VolumeManager::createPendingDisksIfNeeded() {
542     bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
543     if (!mSecureKeyguardShowing && userZeroStarted) {
544         // Now that secure keyguard has been dismissed and user 0 has
545         // started, process any pending disks
546         for (const auto& disk : mPendingDisks) {
547             disk->create();
548             mDisks.push_back(disk);
549         }
550         mPendingDisks.clear();
551     }
552 }
553 
onSecureKeyguardStateChanged(bool isShowing)554 int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
555     mSecureKeyguardShowing = isShowing;
556     createPendingDisksIfNeeded();
557     return 0;
558 }
559 
560 // This code is executed after a fork so it's very important that the set of
561 // methods we call here is strictly limited.
562 //
563 // TODO: Get rid of this guesswork altogether and instead exec a process
564 // immediately after fork to do our bindding for us.
childProcess(const char * storageSource,const char * userSource,int nsFd,const char * name)565 static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
566                          const char* name) {
567     if (setns(nsFd, CLONE_NEWNS) != 0) {
568         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
569                               strerror(errno));
570         return false;
571     }
572 
573     // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
574     // to also protect against future changes that may cause issues across a
575     // fork.
576     if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
577         errno != ENOENT) {
578         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
579                               strerror(errno));
580         return false;
581     }
582 
583     if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
584         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
585                               storageSource, name, strerror(errno));
586         return false;
587     }
588 
589     if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
590         async_safe_format_log(ANDROID_LOG_ERROR, "vold",
591                               "Failed to set MS_SLAVE to /storage for %s :%s", name,
592                               strerror(errno));
593         return false;
594     }
595 
596     if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
597         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
598                               userSource, name, strerror(errno));
599         return false;
600     }
601 
602     return true;
603 }
604 
605 // Fork the process and remount storage
forkAndRemountChild(uid_t uid,pid_t pid,int nsFd,const char * name,void * params)606 bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
607     int32_t mountMode = *static_cast<int32_t*>(params);
608     std::string userSource;
609     std::string storageSource;
610     pid_t child;
611     // Need to fix these paths to account for when sdcardfs is gone
612     switch (mountMode) {
613         case VoldNativeService::REMOUNT_MODE_NONE:
614             return true;
615         case VoldNativeService::REMOUNT_MODE_DEFAULT:
616             storageSource = "/mnt/runtime/default";
617             break;
618         case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
619         case VoldNativeService::REMOUNT_MODE_INSTALLER:
620             storageSource = "/mnt/runtime/write";
621             break;
622         case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
623             return true;
624         default:
625             PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
626             return false;
627     }
628     LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
629 
630     // Fork a child to mount user-specific symlink helper into place
631     userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
632     if (!(child = fork())) {
633         if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
634             _exit(0);
635         } else {
636             _exit(1);
637         }
638     }
639 
640     if (child == -1) {
641         PLOG(ERROR) << "Failed to fork";
642         return false;
643     } else {
644         TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
645     }
646     return true;
647 }
648 
649 // Helper function to scan all processes in /proc and call the callback if:
650 // 1). pid belongs to an app process
651 // 2). If input uid is 0 or it matches the process uid
652 // 3). If userId is not -1 or userId matches the process userId
scanProcProcesses(uid_t uid,userid_t userId,ScanProcCallback callback,void * params)653 bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
654     DIR* dir;
655     struct dirent* de;
656     std::string rootName;
657     std::string pidName;
658     std::string exeName;
659     int pidFd;
660     int nsFd;
661     struct stat sb;
662 
663     if (!(dir = opendir("/proc"))) {
664         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
665         return false;
666     }
667 
668     // Figure out root namespace to compare against below
669     if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
670         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
671         closedir(dir);
672         return false;
673     }
674 
675     async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
676     // Poke through all running PIDs look for apps running as UID
677     while ((de = readdir(dir))) {
678         pid_t pid;
679         if (de->d_type != DT_DIR) continue;
680         if (!android::base::ParseInt(de->d_name, &pid)) continue;
681 
682         pidFd = -1;
683         nsFd = -1;
684 
685         pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
686         if (pidFd < 0) {
687             goto next;
688         }
689         if (fstat(pidFd, &sb) != 0) {
690             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
691             goto next;
692         }
693         if (uid != 0 && sb.st_uid != uid) {
694             goto next;
695         }
696         if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
697             goto next;
698         }
699 
700         // Matches so far, but refuse to touch if in root namespace
701         if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
702             async_safe_format_log(ANDROID_LOG_ERROR, "vold",
703                     "Failed to read namespacefor %s", de->d_name);
704             goto next;
705         }
706         if (rootName == pidName) {
707             goto next;
708         }
709 
710         // Some early native processes have mount namespaces that are different
711         // from that of the init. Therefore, above check can't filter them out.
712         // Since the propagation type of / is 'shared', unmounting /storage
713         // for the early native processes affects other processes including
714         // init. Filter out such processes by skipping if a process is a
715         // non-Java process whose UID is < AID_APP_START. (The UID condition
716         // is required to not filter out child processes spawned by apps.)
717         if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
718             goto next;
719         }
720         if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
721             goto next;
722         }
723 
724         // We purposefully leave the namespace open across the fork
725         // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
726         nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
727         if (nsFd < 0) {
728             async_safe_format_log(ANDROID_LOG_ERROR, "vold",
729                     "Failed to open namespace for %s", de->d_name);
730             goto next;
731         }
732 
733         if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
734             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
735         }
736 
737     next:
738         close(nsFd);
739         close(pidFd);
740     }
741     closedir(dir);
742     async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
743     return true;
744 }
745 
746 // In each app's namespace, unmount obb and data dirs
umountStorageDirs(int nsFd,const char * android_data_dir,const char * android_obb_dir,int uid,const char * targets[],int size)747 static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
748         int uid, const char* targets[], int size) {
749     // This code is executed after a fork so it's very important that the set of
750     // methods we call here is strictly limited.
751     if (setns(nsFd, CLONE_NEWNS) != 0) {
752         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
753         return false;
754     }
755 
756     // Unmount of Android/data/foo needs to be done before Android/data below.
757     bool result = true;
758     for (int i = 0; i < size; i++) {
759         if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
760                 errno != ENOENT) {
761             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
762                                   targets[i], strerror(errno));
763             result = false;
764         }
765     }
766 
767     // Mount tmpfs on Android/data and Android/obb
768     if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
769                 errno != ENOENT) {
770         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
771                         android_data_dir, strerror(errno));
772         result = false;
773     }
774     if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
775                 errno != ENOENT) {
776         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
777                 android_obb_dir, strerror(errno));
778         result = false;
779     }
780     return result;
781 }
782 
783 // In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
784 // package dirs.
remountStorageDirs(int nsFd,const char * android_data_dir,const char * android_obb_dir,int uid,const char * sources[],const char * targets[],int size)785 static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
786         int uid, const char* sources[], const char* targets[], int size) {
787     // This code is executed after a fork so it's very important that the set of
788     // methods we call here is strictly limited.
789     if (setns(nsFd, CLONE_NEWNS) != 0) {
790         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
791         return false;
792     }
793 
794     // Mount tmpfs on Android/data and Android/obb
795     if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
796             MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
797         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
798                         android_data_dir, strerror(errno));
799         return false;
800     }
801     if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
802             MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
803         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
804                 android_obb_dir, strerror(errno));
805         return false;
806     }
807 
808     for (int i = 0; i < size; i++) {
809         // Create package dir and bind mount it to the actual one.
810         if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
811             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
812                     targets[i], strerror(errno));
813             return false;
814         }
815         if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
816             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
817                                   sources[i], targets[i], strerror(errno));
818             return false;
819         }
820     }
821     return true;
822 }
823 
getStorageDirSrc(userid_t userId,const std::string & dirName,const std::string & packageName)824 static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
825         const std::string& packageName) {
826     if (IsSdcardfsUsed()) {
827         return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
828                 userId, dirName.c_str(), packageName.c_str());
829     } else {
830         return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
831                 userId, userId, dirName.c_str(), packageName.c_str());
832     }
833 }
834 
getStorageDirTarget(userid_t userId,std::string dirName,std::string packageName)835 static std::string getStorageDirTarget(userid_t userId, std::string dirName,
836         std::string packageName) {
837     return StringPrintf("/storage/emulated/%d/%s/%s",
838             userId, dirName.c_str(), packageName.c_str());
839 }
840 
841 // Fork the process and remount / unmount app data and obb dirs
forkAndRemountStorage(int uid,int pid,bool doUnmount,const std::vector<std::string> & packageNames)842 bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
843                                           const std::vector<std::string>& packageNames) {
844     userid_t userId = multiuser_get_user_id(uid);
845     std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
846     android::base::unique_fd nsFd(
847             TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
848     if (nsFd == -1) {
849         PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
850         return false;
851     }
852     // Storing both Android/obb and Android/data paths.
853     int size = packageNames.size() * 2;
854 
855     std::unique_ptr<std::string[]> sources(new std::string[size]);
856     std::unique_ptr<std::string[]> targets(new std::string[size]);
857     std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
858     std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
859     const char** sources_cstr = sources_uptr.get();
860     const char** targets_cstr = targets_uptr.get();
861 
862     for (int i = 0; i < size; i += 2) {
863         std::string const& packageName = packageNames[i/2];
864         sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
865         targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
866         sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
867         targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
868 
869         sources_cstr[i] = sources[i].c_str();
870         targets_cstr[i] = targets[i].c_str();
871         sources_cstr[i+1] = sources[i+1].c_str();
872         targets_cstr[i+1] = targets[i+1].c_str();
873     }
874 
875     for (int i = 0; i < size; i++) {
876         // Make sure /storage/emulated/... paths are setup correctly
877         // This needs to be done before EnsureDirExists to ensure Android/ is created.
878         auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
879         if (status != OK) {
880             PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
881             return false;
882         }
883         status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
884         if (status != OK) {
885             PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
886             return false;
887         }
888     }
889 
890     char android_data_dir[PATH_MAX];
891     char android_obb_dir[PATH_MAX];
892     snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
893     snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
894 
895     pid_t child;
896     // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
897     // original vold process mount namespace.
898     if (!(child = fork())) {
899         if (doUnmount) {
900             if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
901                     targets_cstr, size)) {
902                 _exit(0);
903             } else {
904                 _exit(1);
905             }
906         } else {
907             if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
908                     sources_cstr, targets_cstr, size)) {
909                 _exit(0);
910             } else {
911                 _exit(1);
912             }
913         }
914     }
915 
916     if (child == -1) {
917         PLOG(ERROR) << "Failed to fork";
918         return false;
919     } else {
920         int status;
921         if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
922             PLOG(ERROR) << "Failed to waitpid: " << child;
923             return false;
924         }
925         if (!WIFEXITED(status)) {
926             PLOG(ERROR) << "Process did not exit normally, status: " << status;
927             return false;
928         }
929         if (WEXITSTATUS(status)) {
930             PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
931             return false;
932         }
933     }
934     return true;
935 }
936 
handleAppStorageDirs(int uid,int pid,bool doUnmount,const std::vector<std::string> & packageNames)937 int VolumeManager::handleAppStorageDirs(int uid, int pid,
938         bool doUnmount, const std::vector<std::string>& packageNames) {
939     // Only run the remount if fuse is mounted for that user.
940     userid_t userId = multiuser_get_user_id(uid);
941     bool fuseMounted = false;
942     for (auto& vol : mInternalEmulatedVolumes) {
943         if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
944             auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
945             if (emulatedVol) {
946                 fuseMounted = emulatedVol->isFuseMounted();
947             }
948             break;
949         }
950     }
951     if (fuseMounted) {
952         forkAndRemountStorage(uid, pid, doUnmount, packageNames);
953     }
954     return 0;
955 }
956 
abortFuse()957 int VolumeManager::abortFuse() {
958     return android::vold::AbortFuseConnections();
959 }
960 
reset()961 int VolumeManager::reset() {
962     // Tear down all existing disks/volumes and start from a blank slate so
963     // newly connected framework hears all events.
964 
965     // Destroy StubVolume disks. This needs to be done before destroying
966     // EmulatedVolumes because in ARC (Android on ChromeOS), ChromeOS Downloads
967     // directory (which is in a StubVolume) is bind-mounted to
968     // /data/media/0/Download.
969     // We do not recreate StubVolumes here because they are managed from outside
970     // Android (e.g. from ChromeOS) and their disk recreation on reset events
971     // should be handled from outside by calling createStubVolume() again.
972     for (const auto& disk : mDisks) {
973         if (disk->isStub()) {
974             disk->destroy();
975         }
976     }
977     // Remove StubVolume from both mDisks and mPendingDisks.
978     const auto isStub = [](const auto& disk) { return disk->isStub(); };
979     mDisks.remove_if(isStub);
980     mPendingDisks.remove_if(isStub);
981 
982     for (const auto& vol : mInternalEmulatedVolumes) {
983         vol->destroy();
984     }
985     mInternalEmulatedVolumes.clear();
986 
987     // Destroy and recreate non-StubVolume disks.
988     for (const auto& disk : mDisks) {
989         disk->destroy();
990         disk->create();
991     }
992 
993     updateVirtualDisk();
994     mAddedUsers.clear();
995     mStartedUsers.clear();
996     mSharedStorageUser.clear();
997 
998     // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
999     // with FUSE fds open.
1000     abortFuse();
1001     return 0;
1002 }
1003 
1004 // Can be called twice (sequentially) during shutdown. should be safe for that.
shutdown()1005 int VolumeManager::shutdown() {
1006     if (mInternalEmulatedVolumes.empty()) {
1007         return 0;  // already shutdown
1008     }
1009     android::vold::sSleepOnUnmount = false;
1010     // Destroy StubVolume disks before destroying EmulatedVolumes (see the
1011     // comment in VolumeManager::reset()).
1012     for (const auto& disk : mDisks) {
1013         if (disk->isStub()) {
1014             disk->destroy();
1015         }
1016     }
1017     for (const auto& vol : mInternalEmulatedVolumes) {
1018         vol->destroy();
1019     }
1020     for (const auto& disk : mDisks) {
1021         if (!disk->isStub()) {
1022             disk->destroy();
1023         }
1024     }
1025 
1026     mInternalEmulatedVolumes.clear();
1027     mDisks.clear();
1028     mPendingDisks.clear();
1029     android::vold::sSleepOnUnmount = true;
1030 
1031     return 0;
1032 }
1033 
unmountAll()1034 int VolumeManager::unmountAll() {
1035     std::lock_guard<std::mutex> lock(mLock);
1036     ATRACE_NAME("VolumeManager::unmountAll()");
1037 
1038     // First, try gracefully unmounting all known devices
1039     // Unmount StubVolume disks before unmounting EmulatedVolumes (see the
1040     // comment in VolumeManager::reset()).
1041     for (const auto& disk : mDisks) {
1042         if (disk->isStub()) {
1043             disk->unmountAll();
1044         }
1045     }
1046     for (const auto& vol : mInternalEmulatedVolumes) {
1047         vol->unmount();
1048     }
1049     for (const auto& disk : mDisks) {
1050         if (!disk->isStub()) {
1051             disk->unmountAll();
1052         }
1053     }
1054 
1055     // Worst case we might have some stale mounts lurking around, so
1056     // force unmount those just to be safe.
1057     FILE* fp = setmntent("/proc/mounts", "re");
1058     if (fp == NULL) {
1059         PLOG(ERROR) << "Failed to open /proc/mounts";
1060         return -errno;
1061     }
1062 
1063     // Some volumes can be stacked on each other, so force unmount in
1064     // reverse order to give us the best chance of success.
1065     std::list<std::string> toUnmount;
1066     mntent* mentry;
1067     while ((mentry = getmntent(fp)) != NULL) {
1068         auto test = std::string(mentry->mnt_dir);
1069         if ((StartsWith(test, "/mnt/") &&
1070 #ifdef __ANDROID_DEBUGGABLE__
1071              !StartsWith(test, "/mnt/scratch") &&
1072 #endif
1073              !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
1074              !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable") &&
1075              !StartsWith(test, "/mnt/vm")) ||
1076             StartsWith(test, "/storage/")) {
1077             toUnmount.push_front(test);
1078         }
1079     }
1080     endmntent(fp);
1081 
1082     for (const auto& path : toUnmount) {
1083         LOG(DEBUG) << "Tearing down stale mount " << path;
1084         android::vold::ForceUnmount(path);
1085     }
1086 
1087     return 0;
1088 }
1089 
ensureAppDirsCreated(const std::vector<std::string> & paths,int32_t appUid)1090 int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
1091     int size = paths.size();
1092     for (int i = 0; i < size; i++) {
1093         int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1094                 true /* skipIfDirExists */);
1095         if (result != OK) {
1096             return result;
1097         }
1098     }
1099     return OK;
1100 }
1101 
setupAppDir(const std::string & path,int32_t appUid,bool fixupExistingOnly,bool skipIfDirExists)1102 int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1103         bool skipIfDirExists) {
1104     // Only offer to create directories for paths managed by vold
1105     if (!StartsWith(path, "/storage/")) {
1106         LOG(ERROR) << "Failed to find mounted volume for " << path;
1107         return -EINVAL;
1108     }
1109 
1110     // Find the volume it belongs to
1111     auto filter_fn = [&](const VolumeBase& vol) {
1112         if (vol.getState() != VolumeBase::State::kMounted) {
1113             // The volume must be mounted
1114             return false;
1115         }
1116         if (!vol.isVisibleForWrite()) {
1117             // App dirs should only be created for writable volumes.
1118             return false;
1119         }
1120         if (vol.getInternalPath().empty()) {
1121             return false;
1122         }
1123         if (vol.getMountUserId() != USER_UNKNOWN &&
1124             vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1125             // The app dir must be created on a volume with the same user-id
1126             return false;
1127         }
1128         if (!path.empty() && StartsWith(path, vol.getPath())) {
1129             return true;
1130         }
1131 
1132         return false;
1133     };
1134     auto volume = findVolumeWithFilter(filter_fn);
1135     if (volume == nullptr) {
1136         LOG(ERROR) << "Failed to find mounted volume for " << path;
1137         return -EINVAL;
1138     }
1139     // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1140     // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1141     // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1142     // on /storage/emulated/10 means /mnt/user/0/emulated/10
1143     const std::string lowerPath =
1144             volume->getInternalPath() + path.substr(volume->getPath().length());
1145 
1146     const std::string volumeRoot = volume->getRootPath();  // eg /data/media/0
1147 
1148     const int access_result = access(lowerPath.c_str(), F_OK);
1149     if (fixupExistingOnly && access_result != 0) {
1150         // Nothing to fixup
1151         return OK;
1152     }
1153 
1154     if (skipIfDirExists && access_result == 0) {
1155         // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1156         // which the dir doesn't need to have correct permission for now yet.
1157         return OK;
1158     }
1159 
1160     if (volume->getType() == VolumeBase::Type::kPublic) {
1161         // On public volumes, we don't need to setup permissions, as everything goes through
1162         // FUSE; just create the dirs and be done with it.
1163         return fs_mkdirs(lowerPath.c_str(), 0700);
1164     }
1165 
1166     // Create the app paths we need from the root
1167     return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1168 }
1169 
fixupAppDir(const std::string & path,int32_t appUid)1170 int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
1171     if (IsSdcardfsUsed()) {
1172         //sdcardfs magically does this for us
1173         return OK;
1174     }
1175     return setupAppDir(path, appUid, true /* fixupExistingOnly */);
1176 }
1177 
createObb(const std::string & sourcePath,int32_t ownerGid,std::string * outVolId)1178 int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1179                              std::string* outVolId) {
1180     int id = mNextObbId++;
1181 
1182     std::string lowerSourcePath;
1183 
1184     // Convert to lower filesystem path
1185     if (StartsWith(sourcePath, "/storage/")) {
1186         auto filter_fn = [&](const VolumeBase& vol) {
1187             if (vol.getState() != VolumeBase::State::kMounted) {
1188                 // The volume must be mounted
1189                 return false;
1190             }
1191             if (!vol.isVisibleForWrite()) {
1192                 // Obb volume should only be created for writable volumes.
1193                 return false;
1194             }
1195             if (vol.getInternalPath().empty()) {
1196                 return false;
1197             }
1198             if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1199                 return true;
1200             }
1201 
1202             return false;
1203         };
1204         auto volume = findVolumeWithFilter(filter_fn);
1205         if (volume == nullptr) {
1206             LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1207             return -EINVAL;
1208         } else {
1209             lowerSourcePath =
1210                     volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1211         }
1212     } else {
1213         lowerSourcePath = sourcePath;
1214     }
1215 
1216     auto vol = std::shared_ptr<android::vold::VolumeBase>(
1217             new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
1218     vol->create();
1219 
1220     mObbVolumes.push_back(vol);
1221     *outVolId = vol->getId();
1222     return android::OK;
1223 }
1224 
destroyObb(const std::string & volId)1225 int VolumeManager::destroyObb(const std::string& volId) {
1226     auto i = mObbVolumes.begin();
1227     while (i != mObbVolumes.end()) {
1228         if ((*i)->getId() == volId) {
1229             (*i)->destroy();
1230             i = mObbVolumes.erase(i);
1231         } else {
1232             ++i;
1233         }
1234     }
1235     return android::OK;
1236 }
1237 
createStubVolume(const std::string & sourcePath,const std::string & mountPath,const std::string & fsType,const std::string & fsUuid,const std::string & fsLabel,int32_t flags,std::string * outVolId)1238 int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1239                                     const std::string& fsType, const std::string& fsUuid,
1240                                     const std::string& fsLabel, int32_t flags,
1241                                     std::string* outVolId) {
1242     dev_t stubId = --mNextStubId;
1243     auto vol = std::shared_ptr<android::vold::StubVolume>(
1244             new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1245 
1246     int32_t passedFlags = 0;
1247     passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1248     passedFlags |= (flags & android::vold::Disk::Flags::kSd);
1249     if (flags & android::vold::Disk::Flags::kStubVisible) {
1250         passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1251     } else {
1252         passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1253     }
1254     // StubDisk doesn't have device node corresponds to it. So, a fake device
1255     // number is used.
1256     auto disk = std::shared_ptr<android::vold::Disk>(
1257             new android::vold::Disk("stub", stubId, "stub", passedFlags));
1258     disk->initializePartition(vol);
1259     handleDiskAdded(disk);
1260     *outVolId = vol->getId();
1261     return android::OK;
1262 }
1263 
destroyStubVolume(const std::string & volId)1264 int VolumeManager::destroyStubVolume(const std::string& volId) {
1265     auto tokens = android::base::Split(volId, ":");
1266     CHECK(tokens.size() == 2);
1267     dev_t stubId;
1268     CHECK(android::base::ParseUint(tokens[1], &stubId));
1269     handleDiskRemoved(stubId);
1270     return android::OK;
1271 }
1272 
mountAppFuse(uid_t uid,int mountId,unique_fd * device_fd)1273 int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
1274     return android::vold::MountAppFuse(uid, mountId, device_fd);
1275 }
1276 
unmountAppFuse(uid_t uid,int mountId)1277 int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
1278     return android::vold::UnmountAppFuse(uid, mountId);
1279 }
1280 
openAppFuseFile(uid_t uid,int mountId,int fileId,int flags)1281 int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
1282     return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
1283 }
1284 
getDeviceSize(std::string & device,int64_t * storageSize,bool isF2fsPrimary)1285 static android::status_t getDeviceSize(std::string& device, int64_t* storageSize,
1286                                        bool isF2fsPrimary) {
1287     // Follow any symbolic links
1288     std::string dataDevice;
1289     if (!android::base::Realpath(device, &dataDevice)) {
1290         dataDevice = device;
1291     }
1292 
1293     // Handle mapped volumes.
1294     auto& dm = android::dm::DeviceMapper::Instance();
1295     std::string dmPath = dataDevice;
1296     if (dm.IsDmBlockDevice(dataDevice)) {
1297         for (;;) {
1298             auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1299             if (!parent.has_value()) break;
1300             dataDevice = *parent;
1301         }
1302     } else if (isF2fsPrimary) {
1303         if (!dm.GetDmDevicePathByName(android::base::Basename(device), &dmPath)) {
1304             LOG(WARNING) << "No proper dm device for " << device;
1305             isF2fsPrimary = false;
1306         }
1307     }
1308 
1309     // Find a device name for F2FS primary partition
1310     std::string f2fsReservedBlocksSysfs;
1311     std::size_t leaf;
1312     if (isF2fsPrimary) {
1313         leaf = dmPath.rfind('/');
1314         if (leaf == std::string::npos) {
1315             LOG(WARNING) << "dm device " << dmPath << " is not a path";
1316             isF2fsPrimary = false;
1317         }
1318         f2fsReservedBlocksSysfs =
1319                 std::string() + "/sys/fs/f2fs/" + dmPath.substr(leaf + 1) + "/reserved_blocks";
1320     }
1321 
1322     // Get the potential /sys/block entry
1323     leaf = dataDevice.rfind('/');
1324     if (leaf == std::string::npos) {
1325         LOG(ERROR) << "data device " << dataDevice << " is not a path";
1326         return EINVAL;
1327     }
1328     if (dataDevice.substr(0, leaf) != "/dev/block") {
1329         LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1330         return EINVAL;
1331     }
1332     std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1333 
1334     // Look for a directory in /sys/block containing size where the name is a shortened
1335     // version of the name we now have
1336     // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1337     // Note that this directory only contains actual disks, not partitions, so this is
1338     // not going to find anything other than the disks
1339     std::string size;
1340     std::string sizeFile;
1341     for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1342         if (sysfsDir.back() == '/') {
1343             LOG(ERROR) << "Could not find valid block device from " << sysfs;
1344             return EINVAL;
1345         }
1346         sizeFile = sysfsDir + "/size";
1347         if (android::base::ReadFileToString(sizeFile, &size, true)) {
1348             break;
1349         }
1350     }
1351 
1352     // Read the size file and be done
1353     int64_t sizeNum;
1354     std::stringstream ssSize(size);
1355     ssSize >> sizeNum;
1356     if (ssSize.fail()) {
1357         LOG(ERROR) << sizeFile << " cannot be read as an integer";
1358         return EINVAL;
1359     }
1360 
1361     sizeNum *= 512;
1362     if (isF2fsPrimary) {
1363         int64_t reservedBlocksNum = 0;
1364         if (!android::base::ReadFileToString(f2fsReservedBlocksSysfs, &size, true)) {
1365             LOG(WARNING) << "Could not find valid entry from " << f2fsReservedBlocksSysfs;
1366         } else {
1367             std::stringstream reservedBlocks(size);
1368             reservedBlocks >> reservedBlocksNum;
1369             if (reservedBlocks.fail()) {
1370                 LOG(WARNING) << f2fsReservedBlocksSysfs << " cannot be read as an integer";
1371                 reservedBlocksNum = 0;
1372             }
1373         }
1374         int64_t blockSize = android::base::GetIntProperty("ro.boot.hardware.cpu.pagesize", 0);
1375         sizeNum -= reservedBlocksNum * blockSize;
1376     }
1377 
1378     *storageSize = sizeNum;
1379     return OK;
1380 }
1381 
GetStorageSize(int64_t * storageSize)1382 android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1383     android::status_t status;
1384     // Start with the /data mount point from fs_mgr
1385     auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1386     if (entry == nullptr) {
1387         LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1388         return EINVAL;
1389     }
1390 
1391     status = getDeviceSize(entry->blk_device, storageSize, entry->fs_type == "f2fs");
1392     if (status != OK) {
1393         return status;
1394     }
1395 
1396     for (auto device : entry->user_devices) {
1397         int64_t deviceStorageSize;
1398         status = getDeviceSize(device, &deviceStorageSize, false);
1399         if (status != OK) {
1400             return status;
1401         }
1402         *storageSize += deviceStorageSize;
1403     }
1404 
1405     return OK;
1406 }
1407