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 <ApexProperties.sysprop.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 
57 #include "AppFuseUtil.h"
58 #include "Devmapper.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/StubVolume.h"
73 
74 using android::OK;
75 using android::base::GetBoolProperty;
76 using android::base::StartsWith;
77 using android::base::StringAppendF;
78 using android::base::StringPrintf;
79 using android::base::unique_fd;
80 using android::vold::BindMount;
81 using android::vold::CreateDir;
82 using android::vold::DeleteDirContents;
83 using android::vold::DeleteDirContentsAndDir;
84 using android::vold::EnsureDirExists;
85 using android::vold::IsFilesystemSupported;
86 using android::vold::IsSdcardfsUsed;
87 using android::vold::IsVirtioBlkDevice;
88 using android::vold::PrepareAndroidDirs;
89 using android::vold::PrepareAppDirFromRoot;
90 using android::vold::PrivateVolume;
91 using android::vold::Symlink;
92 using android::vold::Unlink;
93 using android::vold::UnmountTree;
94 using android::vold::VoldNativeService;
95 using android::vold::VolumeBase;
96 
97 static const char* kPathUserMount = "/mnt/user";
98 static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
99 
100 static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
101 
102 static const std::string kEmptyString("");
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     Devmapper::destroyAll();
183     Loop::destroyAll();
184 
185     // Assume that we always have an emulated volume on internal
186     // storage; the framework will decide if it should be mounted.
187     CHECK(mInternalEmulatedVolumes.empty());
188 
189     auto vol = std::shared_ptr<android::vold::VolumeBase>(
190             new android::vold::EmulatedVolume("/data/media", 0));
191     vol->setMountUserId(0);
192     vol->create();
193     mInternalEmulatedVolumes.push_back(vol);
194 
195     // Consider creating a virtual disk
196     updateVirtualDisk();
197 
198     return 0;
199 }
200 
handleBlockEvent(NetlinkEvent * evt)201 void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
202     std::lock_guard<std::mutex> lock(mLock);
203 
204     if (mDebug) {
205         LOG(DEBUG) << "----------------";
206         LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
207         evt->dump();
208     }
209 
210     std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
211     std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
212 
213     if (devType != "disk") return;
214 
215     int major = std::stoi(evt->findParam("MAJOR"));
216     int minor = std::stoi(evt->findParam("MINOR"));
217     dev_t device = makedev(major, minor);
218 
219     switch (evt->getAction()) {
220         case NetlinkEvent::Action::kAdd: {
221             for (const auto& source : mDiskSources) {
222                 if (source->matches(eventPath)) {
223                     // For now, assume that MMC and virtio-blk (the latter is
224                     // specific to virtual platforms; see Utils.cpp for details)
225                     // devices are SD, and that everything else is USB
226                     int flags = source->getFlags();
227                     if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
228                         flags |= android::vold::Disk::Flags::kSd;
229                     } else {
230                         flags |= android::vold::Disk::Flags::kUsb;
231                     }
232 
233                     auto disk =
234                         new android::vold::Disk(eventPath, device, source->getNickname(), flags);
235                     handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
236                     break;
237                 }
238             }
239             break;
240         }
241         case NetlinkEvent::Action::kChange: {
242             LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
243             handleDiskChanged(device);
244             break;
245         }
246         case NetlinkEvent::Action::kRemove: {
247             handleDiskRemoved(device);
248             break;
249         }
250         default: {
251             LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
252             break;
253         }
254     }
255 }
256 
handleDiskAdded(const std::shared_ptr<android::vold::Disk> & disk)257 void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
258     // For security reasons, if secure keyguard is showing, wait
259     // until the user unlocks the device to actually touch it
260     // Additionally, wait until user 0 is actually started, since we need
261     // the user to be up before we can mount a FUSE daemon to handle the disk.
262     bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
263     if (mSecureKeyguardShowing) {
264         LOG(INFO) << "Found disk at " << disk->getEventPath()
265                   << " but delaying scan due to secure keyguard";
266         mPendingDisks.push_back(disk);
267     } else if (!userZeroStarted) {
268         LOG(INFO) << "Found disk at " << disk->getEventPath()
269                   << " but delaying scan due to user zero not having started";
270         mPendingDisks.push_back(disk);
271     } else {
272         disk->create();
273         mDisks.push_back(disk);
274     }
275 }
276 
handleDiskChanged(dev_t device)277 void VolumeManager::handleDiskChanged(dev_t device) {
278     for (const auto& disk : mDisks) {
279         if (disk->getDevice() == device) {
280             disk->readMetadata();
281             disk->readPartitions();
282         }
283     }
284 
285     // For security reasons, we ignore all pending disks, since
286     // we'll scan them once the device is unlocked
287 }
288 
handleDiskRemoved(dev_t device)289 void VolumeManager::handleDiskRemoved(dev_t device) {
290     auto i = mDisks.begin();
291     while (i != mDisks.end()) {
292         if ((*i)->getDevice() == device) {
293             (*i)->destroy();
294             i = mDisks.erase(i);
295         } else {
296             ++i;
297         }
298     }
299     auto j = mPendingDisks.begin();
300     while (j != mPendingDisks.end()) {
301         if ((*j)->getDevice() == device) {
302             j = mPendingDisks.erase(j);
303         } else {
304             ++j;
305         }
306     }
307 }
308 
addDiskSource(const std::shared_ptr<DiskSource> & diskSource)309 void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
310     std::lock_guard<std::mutex> lock(mLock);
311     mDiskSources.push_back(diskSource);
312 }
313 
findDisk(const std::string & id)314 std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
315     for (auto disk : mDisks) {
316         if (disk->getId() == id) {
317             return disk;
318         }
319     }
320     return nullptr;
321 }
322 
findVolume(const std::string & id)323 std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
324     for (const auto& vol : mInternalEmulatedVolumes) {
325         if (vol->getId() == id) {
326             return vol;
327         }
328     }
329     for (const auto& disk : mDisks) {
330         auto vol = disk->findVolume(id);
331         if (vol != nullptr) {
332             return vol;
333         }
334     }
335     for (const auto& vol : mObbVolumes) {
336         if (vol->getId() == id) {
337             return vol;
338         }
339     }
340     return nullptr;
341 }
342 
listVolumes(android::vold::VolumeBase::Type type,std::list<std::string> & list) const343 void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
344                                 std::list<std::string>& list) const {
345     list.clear();
346     for (const auto& disk : mDisks) {
347         disk->listVolumes(type, list);
348     }
349 }
350 
forgetPartition(const std::string & partGuid,const std::string & fsUuid)351 int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
352     std::string normalizedGuid;
353     if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
354         LOG(WARNING) << "Invalid GUID " << partGuid;
355         return -1;
356     }
357 
358     bool success = true;
359     std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
360     if (unlink(keyPath.c_str()) != 0) {
361         LOG(ERROR) << "Failed to unlink " << keyPath;
362         success = false;
363     }
364     if (fscrypt_is_native()) {
365         if (!fscrypt_destroy_volume_keys(fsUuid)) {
366             success = false;
367         }
368     }
369     return success ? 0 : -1;
370 }
371 
destroyEmulatedVolumesForUser(userid_t userId)372 void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
373     // Destroy and remove all unstacked EmulatedVolumes for the user
374     auto i = mInternalEmulatedVolumes.begin();
375     while (i != mInternalEmulatedVolumes.end()) {
376         auto vol = *i;
377         if (vol->getMountUserId() == userId) {
378             vol->destroy();
379             i = mInternalEmulatedVolumes.erase(i);
380         } else {
381             i++;
382         }
383     }
384 
385     // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
386     std::list<std::string> private_vols;
387     listVolumes(VolumeBase::Type::kPrivate, private_vols);
388     for (const std::string& id : private_vols) {
389         PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
390         std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
391         if (pvol->getState() == VolumeBase::State::kMounted) {
392             for (const auto& vol : pvol->getVolumes()) {
393                 if (vol->getMountUserId() == userId) {
394                     vols_to_remove.push_back(vol);
395                 }
396             }
397             for (const auto& vol : vols_to_remove) {
398                 vol->destroy();
399                 pvol->removeVolume(vol);
400             }
401         }  // else EmulatedVolumes will be destroyed on VolumeBase#unmount
402     }
403 }
404 
createEmulatedVolumesForUser(userid_t userId)405 void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
406     // Create unstacked EmulatedVolumes for the user
407     auto vol = std::shared_ptr<android::vold::VolumeBase>(
408             new android::vold::EmulatedVolume("/data/media", userId));
409     vol->setMountUserId(userId);
410     mInternalEmulatedVolumes.push_back(vol);
411     vol->create();
412 
413     // Create stacked EmulatedVolumes for the user on each PrivateVolume
414     std::list<std::string> private_vols;
415     listVolumes(VolumeBase::Type::kPrivate, private_vols);
416     for (const std::string& id : private_vols) {
417         PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
418         if (pvol->getState() == VolumeBase::State::kMounted) {
419             auto evol =
420                     std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
421                             pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
422                             userId));
423             evol->setMountUserId(userId);
424             pvol->addVolume(evol);
425             evol->create();
426         }  // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
427     }
428 }
429 
onUserAdded(userid_t userId,int userSerialNumber)430 int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
431     LOG(INFO) << "onUserAdded: " << userId;
432 
433     mAddedUsers[userId] = userSerialNumber;
434     return 0;
435 }
436 
onUserRemoved(userid_t userId)437 int VolumeManager::onUserRemoved(userid_t userId) {
438     LOG(INFO) << "onUserRemoved: " << userId;
439 
440     onUserStopped(userId);
441     mAddedUsers.erase(userId);
442     return 0;
443 }
444 
onUserStarted(userid_t userId)445 int VolumeManager::onUserStarted(userid_t userId) {
446     LOG(INFO) << "onUserStarted: " << userId;
447 
448     if (mStartedUsers.find(userId) == mStartedUsers.end()) {
449         createEmulatedVolumesForUser(userId);
450     }
451 
452     mStartedUsers.insert(userId);
453 
454     createPendingDisksIfNeeded();
455     return 0;
456 }
457 
onUserStopped(userid_t userId)458 int VolumeManager::onUserStopped(userid_t userId) {
459     LOG(VERBOSE) << "onUserStopped: " << userId;
460 
461     if (mStartedUsers.find(userId) != mStartedUsers.end()) {
462         destroyEmulatedVolumesForUser(userId);
463     }
464 
465     mStartedUsers.erase(userId);
466     return 0;
467 }
468 
createPendingDisksIfNeeded()469 void VolumeManager::createPendingDisksIfNeeded() {
470     bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
471     if (!mSecureKeyguardShowing && userZeroStarted) {
472         // Now that secure keyguard has been dismissed and user 0 has
473         // started, process any pending disks
474         for (const auto& disk : mPendingDisks) {
475             disk->create();
476             mDisks.push_back(disk);
477         }
478         mPendingDisks.clear();
479     }
480 }
481 
onSecureKeyguardStateChanged(bool isShowing)482 int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
483     mSecureKeyguardShowing = isShowing;
484     createPendingDisksIfNeeded();
485     return 0;
486 }
487 
488 // This code is executed after a fork so it's very important that the set of
489 // methods we call here is strictly limited.
490 //
491 // TODO: Get rid of this guesswork altogether and instead exec a process
492 // immediately after fork to do our bindding for us.
childProcess(const char * storageSource,const char * userSource,int nsFd,const char * name)493 static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
494                          const char* name) {
495     if (setns(nsFd, CLONE_NEWNS) != 0) {
496         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
497                               strerror(errno));
498         return false;
499     }
500 
501     // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
502     // to also protect against future changes that may cause issues across a
503     // fork.
504     if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
505         errno != ENOENT) {
506         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
507                               strerror(errno));
508         return false;
509     }
510 
511     if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
512         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
513                               storageSource, name, strerror(errno));
514         return false;
515     }
516 
517     if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
518         async_safe_format_log(ANDROID_LOG_ERROR, "vold",
519                               "Failed to set MS_SLAVE to /storage for %s :%s", name,
520                               strerror(errno));
521         return false;
522     }
523 
524     if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
525         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
526                               userSource, name, strerror(errno));
527         return false;
528     }
529 
530     return true;
531 }
532 
533 // Fork the process and remount storage
forkAndRemountChild(uid_t uid,pid_t pid,int nsFd,const char * name,void * params)534 bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
535     int32_t mountMode = *static_cast<int32_t*>(params);
536     std::string userSource;
537     std::string storageSource;
538     pid_t child;
539     // Need to fix these paths to account for when sdcardfs is gone
540     switch (mountMode) {
541         case VoldNativeService::REMOUNT_MODE_NONE:
542             return true;
543         case VoldNativeService::REMOUNT_MODE_DEFAULT:
544             storageSource = "/mnt/runtime/default";
545             break;
546         case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
547         case VoldNativeService::REMOUNT_MODE_INSTALLER:
548             storageSource = "/mnt/runtime/write";
549             break;
550         case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
551             return true;
552         default:
553             PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
554             return false;
555     }
556     LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
557 
558     // Fork a child to mount user-specific symlink helper into place
559     userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
560     if (!(child = fork())) {
561         if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
562             _exit(0);
563         } else {
564             _exit(1);
565         }
566     }
567 
568     if (child == -1) {
569         PLOG(ERROR) << "Failed to fork";
570         return false;
571     } else {
572         TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
573     }
574     return true;
575 }
576 
577 // Helper function to scan all processes in /proc and call the callback if:
578 // 1). pid belongs to an app process
579 // 2). If input uid is 0 or it matches the process uid
580 // 3). If userId is not -1 or userId matches the process userId
scanProcProcesses(uid_t uid,userid_t userId,ScanProcCallback callback,void * params)581 bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
582     DIR* dir;
583     struct dirent* de;
584     std::string rootName;
585     std::string pidName;
586     int pidFd;
587     int nsFd;
588     struct stat sb;
589 
590     static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
591 
592     if (!(dir = opendir("/proc"))) {
593         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
594         return false;
595     }
596 
597     // Figure out root namespace to compare against below
598     if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
599         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
600         closedir(dir);
601         return false;
602     }
603 
604     async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
605     // Poke through all running PIDs look for apps running as UID
606     while ((de = readdir(dir))) {
607         pid_t pid;
608         if (de->d_type != DT_DIR) continue;
609         if (!android::base::ParseInt(de->d_name, &pid)) continue;
610 
611         pidFd = -1;
612         nsFd = -1;
613 
614         pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
615         if (pidFd < 0) {
616             goto next;
617         }
618         if (fstat(pidFd, &sb) != 0) {
619             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
620             goto next;
621         }
622         if (uid != 0 && sb.st_uid != uid) {
623             goto next;
624         }
625         if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
626             goto next;
627         }
628 
629         // Matches so far, but refuse to touch if in root namespace
630         if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
631             async_safe_format_log(ANDROID_LOG_ERROR, "vold",
632                     "Failed to read namespacefor %s", de->d_name);
633             goto next;
634         }
635         if (rootName == pidName) {
636             goto next;
637         }
638 
639         if (apexUpdatable) {
640             std::string exeName;
641             // When ro.apex.bionic_updatable is set to true,
642             // some early native processes have mount namespaces that are different
643             // from that of the init. Therefore, above check can't filter them out.
644             // Since the propagation type of / is 'shared', unmounting /storage
645             // for the early native processes affects other processes including
646             // init. Filter out such processes by skipping if a process is a
647             // non-Java process whose UID is < AID_APP_START. (The UID condition
648             // is required to not filter out child processes spawned by apps.)
649             if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
650                 goto next;
651             }
652             if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
653                 goto next;
654             }
655         }
656 
657         // We purposefully leave the namespace open across the fork
658         // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
659         nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
660         if (nsFd < 0) {
661             async_safe_format_log(ANDROID_LOG_ERROR, "vold",
662                     "Failed to open namespace for %s", de->d_name);
663             goto next;
664         }
665 
666         if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
667             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
668         }
669 
670     next:
671         close(nsFd);
672         close(pidFd);
673     }
674     closedir(dir);
675     async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
676     return true;
677 }
678 
679 // 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)680 static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
681         int uid, const char* targets[], int size) {
682     // This code is executed after a fork so it's very important that the set of
683     // methods we call here is strictly limited.
684     if (setns(nsFd, CLONE_NEWNS) != 0) {
685         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
686         return false;
687     }
688 
689     // Unmount of Android/data/foo needs to be done before Android/data below.
690     bool result = true;
691     for (int i = 0; i < size; i++) {
692         if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
693                 errno != ENOENT) {
694             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
695                                   targets[i], strerror(errno));
696             result = false;
697         }
698     }
699 
700     // Mount tmpfs on Android/data and Android/obb
701     if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
702                 errno != ENOENT) {
703         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
704                         android_data_dir, strerror(errno));
705         result = false;
706     }
707     if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
708                 errno != ENOENT) {
709         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
710                 android_obb_dir, strerror(errno));
711         result = false;
712     }
713     return result;
714 }
715 
716 // In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
717 // 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)718 static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
719         int uid, const char* sources[], const char* targets[], int size) {
720     // This code is executed after a fork so it's very important that the set of
721     // methods we call here is strictly limited.
722     if (setns(nsFd, CLONE_NEWNS) != 0) {
723         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
724         return false;
725     }
726 
727     // Mount tmpfs on Android/data and Android/obb
728     if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
729             MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
730         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
731                         android_data_dir, strerror(errno));
732         return false;
733     }
734     if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
735             MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
736         async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
737                 android_obb_dir, strerror(errno));
738         return false;
739     }
740 
741     for (int i = 0; i < size; i++) {
742         // Create package dir and bind mount it to the actual one.
743         if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
744             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
745                     targets[i], strerror(errno));
746             return false;
747         }
748         if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
749             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
750                                   sources[i], targets[i], strerror(errno));
751             return false;
752         }
753     }
754     return true;
755 }
756 
getStorageDirSrc(userid_t userId,const std::string & dirName,const std::string & packageName)757 static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
758         const std::string& packageName) {
759     if (IsSdcardfsUsed()) {
760         return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
761                 userId, dirName.c_str(), packageName.c_str());
762     } else {
763         return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
764                 userId, userId, dirName.c_str(), packageName.c_str());
765     }
766 }
767 
getStorageDirTarget(userid_t userId,std::string dirName,std::string packageName)768 static std::string getStorageDirTarget(userid_t userId, std::string dirName,
769         std::string packageName) {
770     return StringPrintf("/storage/emulated/%d/%s/%s",
771             userId, dirName.c_str(), packageName.c_str());
772 }
773 
774 // Fork the process and remount / unmount app data and obb dirs
forkAndRemountStorage(int uid,int pid,bool doUnmount,const std::vector<std::string> & packageNames)775 bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
776                                           const std::vector<std::string>& packageNames) {
777     userid_t userId = multiuser_get_user_id(uid);
778     std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
779     android::base::unique_fd nsFd(
780             TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
781     if (nsFd == -1) {
782         PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
783         return false;
784     }
785     // Storing both Android/obb and Android/data paths.
786     int size = packageNames.size() * 2;
787 
788     std::unique_ptr<std::string[]> sources(new std::string[size]);
789     std::unique_ptr<std::string[]> targets(new std::string[size]);
790     std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
791     std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
792     const char** sources_cstr = sources_uptr.get();
793     const char** targets_cstr = targets_uptr.get();
794 
795     for (int i = 0; i < size; i += 2) {
796         std::string const& packageName = packageNames[i/2];
797         sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
798         targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
799         sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
800         targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
801 
802         sources_cstr[i] = sources[i].c_str();
803         targets_cstr[i] = targets[i].c_str();
804         sources_cstr[i+1] = sources[i+1].c_str();
805         targets_cstr[i+1] = targets[i+1].c_str();
806     }
807 
808     for (int i = 0; i < size; i++) {
809         // Make sure /storage/emulated/... paths are setup correctly
810         // This needs to be done before EnsureDirExists to ensure Android/ is created.
811         auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
812         if (status != OK) {
813             PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
814             return false;
815         }
816         status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
817         if (status != OK) {
818             PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
819             return false;
820         }
821     }
822 
823     char android_data_dir[PATH_MAX];
824     char android_obb_dir[PATH_MAX];
825     snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
826     snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
827 
828     pid_t child;
829     // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
830     // original vold process mount namespace.
831     if (!(child = fork())) {
832         if (doUnmount) {
833             if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
834                     targets_cstr, size)) {
835                 _exit(0);
836             } else {
837                 _exit(1);
838             }
839         } else {
840             if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
841                     sources_cstr, targets_cstr, size)) {
842                 _exit(0);
843             } else {
844                 _exit(1);
845             }
846         }
847     }
848 
849     if (child == -1) {
850         PLOG(ERROR) << "Failed to fork";
851         return false;
852     } else {
853         int status;
854         if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
855             PLOG(ERROR) << "Failed to waitpid: " << child;
856             return false;
857         }
858         if (!WIFEXITED(status)) {
859             PLOG(ERROR) << "Process did not exit normally, status: " << status;
860             return false;
861         }
862         if (WEXITSTATUS(status)) {
863             PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
864             return false;
865         }
866     }
867     return true;
868 }
869 
handleAppStorageDirs(int uid,int pid,bool doUnmount,const std::vector<std::string> & packageNames)870 int VolumeManager::handleAppStorageDirs(int uid, int pid,
871         bool doUnmount, const std::vector<std::string>& packageNames) {
872     // Only run the remount if fuse is mounted for that user.
873     userid_t userId = multiuser_get_user_id(uid);
874     bool fuseMounted = false;
875     for (auto& vol : mInternalEmulatedVolumes) {
876         if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
877             auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
878             if (emulatedVol) {
879                 fuseMounted = emulatedVol->isFuseMounted();
880             }
881             break;
882         }
883     }
884     if (fuseMounted) {
885         forkAndRemountStorage(uid, pid, doUnmount, packageNames);
886     }
887     return 0;
888 }
889 
abortFuse()890 int VolumeManager::abortFuse() {
891     return android::vold::AbortFuseConnections();
892 }
893 
reset()894 int VolumeManager::reset() {
895     // Tear down all existing disks/volumes and start from a blank slate so
896     // newly connected framework hears all events.
897     for (const auto& vol : mInternalEmulatedVolumes) {
898         vol->destroy();
899     }
900     mInternalEmulatedVolumes.clear();
901 
902     for (const auto& disk : mDisks) {
903         disk->destroy();
904         disk->create();
905     }
906     updateVirtualDisk();
907     mAddedUsers.clear();
908     mStartedUsers.clear();
909     return 0;
910 }
911 
912 // Can be called twice (sequentially) during shutdown. should be safe for that.
shutdown()913 int VolumeManager::shutdown() {
914     if (mInternalEmulatedVolumes.empty()) {
915         return 0;  // already shutdown
916     }
917     android::vold::sSleepOnUnmount = false;
918     for (const auto& vol : mInternalEmulatedVolumes) {
919         vol->destroy();
920     }
921     for (const auto& disk : mDisks) {
922         disk->destroy();
923     }
924 
925     mInternalEmulatedVolumes.clear();
926     mDisks.clear();
927     mPendingDisks.clear();
928     android::vold::sSleepOnUnmount = true;
929 
930     return 0;
931 }
932 
unmountAll()933 int VolumeManager::unmountAll() {
934     std::lock_guard<std::mutex> lock(mLock);
935     ATRACE_NAME("VolumeManager::unmountAll()");
936 
937     // First, try gracefully unmounting all known devices
938     for (const auto& vol : mInternalEmulatedVolumes) {
939         vol->unmount();
940     }
941     for (const auto& disk : mDisks) {
942         disk->unmountAll();
943     }
944 
945     // Worst case we might have some stale mounts lurking around, so
946     // force unmount those just to be safe.
947     FILE* fp = setmntent("/proc/mounts", "re");
948     if (fp == NULL) {
949         PLOG(ERROR) << "Failed to open /proc/mounts";
950         return -errno;
951     }
952 
953     // Some volumes can be stacked on each other, so force unmount in
954     // reverse order to give us the best chance of success.
955     std::list<std::string> toUnmount;
956     mntent* mentry;
957     while ((mentry = getmntent(fp)) != NULL) {
958         auto test = std::string(mentry->mnt_dir);
959         if ((StartsWith(test, "/mnt/") &&
960 #ifdef __ANDROID_DEBUGGABLE__
961              !StartsWith(test, "/mnt/scratch") &&
962 #endif
963              !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
964              !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
965             StartsWith(test, "/storage/")) {
966             toUnmount.push_front(test);
967         }
968     }
969     endmntent(fp);
970 
971     for (const auto& path : toUnmount) {
972         LOG(DEBUG) << "Tearing down stale mount " << path;
973         android::vold::ForceUnmount(path);
974     }
975 
976     return 0;
977 }
978 
ensureAppDirsCreated(const std::vector<std::string> & paths,int32_t appUid)979 int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
980     int size = paths.size();
981     for (int i = 0; i < size; i++) {
982         int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
983                 true /* skipIfDirExists */);
984         if (result != OK) {
985             return result;
986         }
987     }
988     return OK;
989 }
990 
setupAppDir(const std::string & path,int32_t appUid,bool fixupExistingOnly,bool skipIfDirExists)991 int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
992         bool skipIfDirExists) {
993     // Only offer to create directories for paths managed by vold
994     if (!StartsWith(path, "/storage/")) {
995         LOG(ERROR) << "Failed to find mounted volume for " << path;
996         return -EINVAL;
997     }
998 
999     // Find the volume it belongs to
1000     auto filter_fn = [&](const VolumeBase& vol) {
1001         if (vol.getState() != VolumeBase::State::kMounted) {
1002             // The volume must be mounted
1003             return false;
1004         }
1005         if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
1006             // and visible
1007             return false;
1008         }
1009         if (vol.getInternalPath().empty()) {
1010             return false;
1011         }
1012         if (vol.getMountUserId() != USER_UNKNOWN &&
1013             vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1014             // The app dir must be created on a volume with the same user-id
1015             return false;
1016         }
1017         if (!path.empty() && StartsWith(path, vol.getPath())) {
1018             return true;
1019         }
1020 
1021         return false;
1022     };
1023     auto volume = findVolumeWithFilter(filter_fn);
1024     if (volume == nullptr) {
1025         LOG(ERROR) << "Failed to find mounted volume for " << path;
1026         return -EINVAL;
1027     }
1028     // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1029     // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1030     // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1031     // on /storage/emulated/10 means /mnt/user/0/emulated/10
1032     const std::string lowerPath =
1033             volume->getInternalPath() + path.substr(volume->getPath().length());
1034 
1035     const std::string volumeRoot = volume->getRootPath();  // eg /data/media/0
1036 
1037     const int access_result = access(lowerPath.c_str(), F_OK);
1038     if (fixupExistingOnly && access_result != 0) {
1039         // Nothing to fixup
1040         return OK;
1041     }
1042 
1043     if (skipIfDirExists && access_result == 0) {
1044         // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1045         // which the dir doesn't need to have correct permission for now yet.
1046         return OK;
1047     }
1048 
1049     if (volume->getType() == VolumeBase::Type::kPublic) {
1050         // On public volumes, we don't need to setup permissions, as everything goes through
1051         // FUSE; just create the dirs and be done with it.
1052         return fs_mkdirs(lowerPath.c_str(), 0700);
1053     }
1054 
1055     // Create the app paths we need from the root
1056     return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1057 }
1058 
fixupAppDir(const std::string & path,int32_t appUid)1059 int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
1060     if (IsSdcardfsUsed()) {
1061         //sdcardfs magically does this for us
1062         return OK;
1063     }
1064     return setupAppDir(path, appUid, true /* fixupExistingOnly */);
1065 }
1066 
createObb(const std::string & sourcePath,const std::string & sourceKey,int32_t ownerGid,std::string * outVolId)1067 int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
1068                              int32_t ownerGid, std::string* outVolId) {
1069     int id = mNextObbId++;
1070 
1071     std::string lowerSourcePath;
1072 
1073     // Convert to lower filesystem path
1074     if (StartsWith(sourcePath, "/storage/")) {
1075         auto filter_fn = [&](const VolumeBase& vol) {
1076             if (vol.getState() != VolumeBase::State::kMounted) {
1077                 // The volume must be mounted
1078                 return false;
1079             }
1080             if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
1081                 // and visible
1082                 return false;
1083             }
1084             if (vol.getInternalPath().empty()) {
1085                 return false;
1086             }
1087             if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1088                 return true;
1089             }
1090 
1091             return false;
1092         };
1093         auto volume = findVolumeWithFilter(filter_fn);
1094         if (volume == nullptr) {
1095             LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1096             return -EINVAL;
1097         } else {
1098             lowerSourcePath =
1099                     volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1100         }
1101     } else {
1102         lowerSourcePath = sourcePath;
1103     }
1104 
1105     auto vol = std::shared_ptr<android::vold::VolumeBase>(
1106             new android::vold::ObbVolume(id, lowerSourcePath, sourceKey, ownerGid));
1107     vol->create();
1108 
1109     mObbVolumes.push_back(vol);
1110     *outVolId = vol->getId();
1111     return android::OK;
1112 }
1113 
destroyObb(const std::string & volId)1114 int VolumeManager::destroyObb(const std::string& volId) {
1115     auto i = mObbVolumes.begin();
1116     while (i != mObbVolumes.end()) {
1117         if ((*i)->getId() == volId) {
1118             (*i)->destroy();
1119             i = mObbVolumes.erase(i);
1120         } else {
1121             ++i;
1122         }
1123     }
1124     return android::OK;
1125 }
1126 
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)1127 int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1128                                     const std::string& fsType, const std::string& fsUuid,
1129                                     const std::string& fsLabel, int32_t flags,
1130                                     std::string* outVolId) {
1131     dev_t stubId = --mNextStubId;
1132     auto vol = std::shared_ptr<android::vold::StubVolume>(
1133             new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1134 
1135     int32_t passedFlags = 0;
1136     passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1137     passedFlags |= (flags & android::vold::Disk::Flags::kSd);
1138     if (flags & android::vold::Disk::Flags::kStubVisible) {
1139         passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1140     } else {
1141         passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1142     }
1143     // StubDisk doesn't have device node corresponds to it. So, a fake device
1144     // number is used.
1145     auto disk = std::shared_ptr<android::vold::Disk>(
1146             new android::vold::Disk("stub", stubId, "stub", passedFlags));
1147     disk->initializePartition(vol);
1148     handleDiskAdded(disk);
1149     *outVolId = vol->getId();
1150     return android::OK;
1151 }
1152 
destroyStubVolume(const std::string & volId)1153 int VolumeManager::destroyStubVolume(const std::string& volId) {
1154     auto tokens = android::base::Split(volId, ":");
1155     CHECK(tokens.size() == 2);
1156     dev_t stubId;
1157     CHECK(android::base::ParseUint(tokens[1], &stubId));
1158     handleDiskRemoved(stubId);
1159     return android::OK;
1160 }
1161 
mountAppFuse(uid_t uid,int mountId,unique_fd * device_fd)1162 int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
1163     return android::vold::MountAppFuse(uid, mountId, device_fd);
1164 }
1165 
unmountAppFuse(uid_t uid,int mountId)1166 int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
1167     return android::vold::UnmountAppFuse(uid, mountId);
1168 }
1169 
openAppFuseFile(uid_t uid,int mountId,int fileId,int flags)1170 int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
1171     return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
1172 }
1173