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 std::list<std::string> public_vols;
456 listVolumes(VolumeBase::Type::kPublic, public_vols);
457 for (const std::string& id : public_vols) {
458 PublicVolume* pvol = static_cast<PublicVolume*>(findVolume(id).get());
459 if (pvol->getState() != VolumeBase::State::kMounted) {
460 continue;
461 }
462 if (pvol->isVisible() == 0) {
463 continue;
464 }
465 userid_t mountUserId = pvol->getMountUserId();
466 if (userId == mountUserId) {
467 // No need to bind mount for the user that owns the mount
468 continue;
469 }
470 if (mountUserId != VolumeManager::Instance()->getSharedStorageUser(userId)) {
471 // No need to bind if the user does not share storage with the mount owner
472 continue;
473 }
474 // Create mount directory for the user as there is a chance that no other Volume is
475 // mounted for the user (ex: if the user is just started), so /mnt/user/user_id does
476 // not exist yet.
477 auto mountDirStatus = android::vold::PrepareMountDirForUser(userId);
478 if (mountDirStatus != OK) {
479 LOG(ERROR) << "Failed to create Mount Directory for user " << userId;
480 }
481 auto bindMountStatus = pvol->bindMountForUser(userId);
482 if (bindMountStatus != OK) {
483 LOG(ERROR) << "Bind Mounting Public Volume: " << pvol << " for user: " << userId
484 << "Failed. Error: " << bindMountStatus;
485 }
486 }
487 }
488
489 mStartedUsers.insert(userId);
490
491 createPendingDisksIfNeeded();
492 return 0;
493 }
494
onUserStopped(userid_t userId)495 int VolumeManager::onUserStopped(userid_t userId) {
496 LOG(VERBOSE) << "onUserStopped: " << userId;
497
498 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
499 destroyEmulatedVolumesForUser(userId);
500 }
501
502 mStartedUsers.erase(userId);
503 return 0;
504 }
505
createPendingDisksIfNeeded()506 void VolumeManager::createPendingDisksIfNeeded() {
507 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
508 if (!mSecureKeyguardShowing && userZeroStarted) {
509 // Now that secure keyguard has been dismissed and user 0 has
510 // started, process any pending disks
511 for (const auto& disk : mPendingDisks) {
512 disk->create();
513 mDisks.push_back(disk);
514 }
515 mPendingDisks.clear();
516 }
517 }
518
onSecureKeyguardStateChanged(bool isShowing)519 int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
520 mSecureKeyguardShowing = isShowing;
521 createPendingDisksIfNeeded();
522 return 0;
523 }
524
525 // This code is executed after a fork so it's very important that the set of
526 // methods we call here is strictly limited.
527 //
528 // TODO: Get rid of this guesswork altogether and instead exec a process
529 // immediately after fork to do our bindding for us.
childProcess(const char * storageSource,const char * userSource,int nsFd,const char * name)530 static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
531 const char* name) {
532 if (setns(nsFd, CLONE_NEWNS) != 0) {
533 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
534 strerror(errno));
535 return false;
536 }
537
538 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
539 // to also protect against future changes that may cause issues across a
540 // fork.
541 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
542 errno != ENOENT) {
543 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
544 strerror(errno));
545 return false;
546 }
547
548 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
549 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
550 storageSource, name, strerror(errno));
551 return false;
552 }
553
554 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
555 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
556 "Failed to set MS_SLAVE to /storage for %s :%s", name,
557 strerror(errno));
558 return false;
559 }
560
561 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
562 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
563 userSource, name, strerror(errno));
564 return false;
565 }
566
567 return true;
568 }
569
570 // Fork the process and remount storage
forkAndRemountChild(uid_t uid,pid_t pid,int nsFd,const char * name,void * params)571 bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
572 int32_t mountMode = *static_cast<int32_t*>(params);
573 std::string userSource;
574 std::string storageSource;
575 pid_t child;
576 // Need to fix these paths to account for when sdcardfs is gone
577 switch (mountMode) {
578 case VoldNativeService::REMOUNT_MODE_NONE:
579 return true;
580 case VoldNativeService::REMOUNT_MODE_DEFAULT:
581 storageSource = "/mnt/runtime/default";
582 break;
583 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
584 case VoldNativeService::REMOUNT_MODE_INSTALLER:
585 storageSource = "/mnt/runtime/write";
586 break;
587 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
588 return true;
589 default:
590 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
591 return false;
592 }
593 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
594
595 // Fork a child to mount user-specific symlink helper into place
596 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
597 if (!(child = fork())) {
598 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
599 _exit(0);
600 } else {
601 _exit(1);
602 }
603 }
604
605 if (child == -1) {
606 PLOG(ERROR) << "Failed to fork";
607 return false;
608 } else {
609 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
610 }
611 return true;
612 }
613
614 // Helper function to scan all processes in /proc and call the callback if:
615 // 1). pid belongs to an app process
616 // 2). If input uid is 0 or it matches the process uid
617 // 3). If userId is not -1 or userId matches the process userId
scanProcProcesses(uid_t uid,userid_t userId,ScanProcCallback callback,void * params)618 bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
619 DIR* dir;
620 struct dirent* de;
621 std::string rootName;
622 std::string pidName;
623 std::string exeName;
624 int pidFd;
625 int nsFd;
626 struct stat sb;
627
628 if (!(dir = opendir("/proc"))) {
629 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
630 return false;
631 }
632
633 // Figure out root namespace to compare against below
634 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
635 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
636 closedir(dir);
637 return false;
638 }
639
640 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
641 // Poke through all running PIDs look for apps running as UID
642 while ((de = readdir(dir))) {
643 pid_t pid;
644 if (de->d_type != DT_DIR) continue;
645 if (!android::base::ParseInt(de->d_name, &pid)) continue;
646
647 pidFd = -1;
648 nsFd = -1;
649
650 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
651 if (pidFd < 0) {
652 goto next;
653 }
654 if (fstat(pidFd, &sb) != 0) {
655 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
656 goto next;
657 }
658 if (uid != 0 && sb.st_uid != uid) {
659 goto next;
660 }
661 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
662 goto next;
663 }
664
665 // Matches so far, but refuse to touch if in root namespace
666 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
667 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
668 "Failed to read namespacefor %s", de->d_name);
669 goto next;
670 }
671 if (rootName == pidName) {
672 goto next;
673 }
674
675 // Some early native processes have mount namespaces that are different
676 // from that of the init. Therefore, above check can't filter them out.
677 // Since the propagation type of / is 'shared', unmounting /storage
678 // for the early native processes affects other processes including
679 // init. Filter out such processes by skipping if a process is a
680 // non-Java process whose UID is < AID_APP_START. (The UID condition
681 // is required to not filter out child processes spawned by apps.)
682 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
683 goto next;
684 }
685 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
686 goto next;
687 }
688
689 // We purposefully leave the namespace open across the fork
690 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
691 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
692 if (nsFd < 0) {
693 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
694 "Failed to open namespace for %s", de->d_name);
695 goto next;
696 }
697
698 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
699 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
700 }
701
702 next:
703 close(nsFd);
704 close(pidFd);
705 }
706 closedir(dir);
707 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
708 return true;
709 }
710
711 // 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)712 static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
713 int uid, const char* targets[], int size) {
714 // This code is executed after a fork so it's very important that the set of
715 // methods we call here is strictly limited.
716 if (setns(nsFd, CLONE_NEWNS) != 0) {
717 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
718 return false;
719 }
720
721 // Unmount of Android/data/foo needs to be done before Android/data below.
722 bool result = true;
723 for (int i = 0; i < size; i++) {
724 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
725 errno != ENOENT) {
726 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
727 targets[i], strerror(errno));
728 result = false;
729 }
730 }
731
732 // Mount tmpfs on Android/data and Android/obb
733 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
734 errno != ENOENT) {
735 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
736 android_data_dir, strerror(errno));
737 result = false;
738 }
739 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
740 errno != ENOENT) {
741 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
742 android_obb_dir, strerror(errno));
743 result = false;
744 }
745 return result;
746 }
747
748 // In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
749 // 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)750 static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
751 int uid, const char* sources[], const char* targets[], int size) {
752 // This code is executed after a fork so it's very important that the set of
753 // methods we call here is strictly limited.
754 if (setns(nsFd, CLONE_NEWNS) != 0) {
755 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
756 return false;
757 }
758
759 // Mount tmpfs on Android/data and Android/obb
760 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
761 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
762 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
763 android_data_dir, strerror(errno));
764 return false;
765 }
766 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
767 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
768 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
769 android_obb_dir, strerror(errno));
770 return false;
771 }
772
773 for (int i = 0; i < size; i++) {
774 // Create package dir and bind mount it to the actual one.
775 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
776 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
777 targets[i], strerror(errno));
778 return false;
779 }
780 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
781 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
782 sources[i], targets[i], strerror(errno));
783 return false;
784 }
785 }
786 return true;
787 }
788
getStorageDirSrc(userid_t userId,const std::string & dirName,const std::string & packageName)789 static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
790 const std::string& packageName) {
791 if (IsSdcardfsUsed()) {
792 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
793 userId, dirName.c_str(), packageName.c_str());
794 } else {
795 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
796 userId, userId, dirName.c_str(), packageName.c_str());
797 }
798 }
799
getStorageDirTarget(userid_t userId,std::string dirName,std::string packageName)800 static std::string getStorageDirTarget(userid_t userId, std::string dirName,
801 std::string packageName) {
802 return StringPrintf("/storage/emulated/%d/%s/%s",
803 userId, dirName.c_str(), packageName.c_str());
804 }
805
806 // Fork the process and remount / unmount app data and obb dirs
forkAndRemountStorage(int uid,int pid,bool doUnmount,const std::vector<std::string> & packageNames)807 bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
808 const std::vector<std::string>& packageNames) {
809 userid_t userId = multiuser_get_user_id(uid);
810 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
811 android::base::unique_fd nsFd(
812 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
813 if (nsFd == -1) {
814 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
815 return false;
816 }
817 // Storing both Android/obb and Android/data paths.
818 int size = packageNames.size() * 2;
819
820 std::unique_ptr<std::string[]> sources(new std::string[size]);
821 std::unique_ptr<std::string[]> targets(new std::string[size]);
822 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
823 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
824 const char** sources_cstr = sources_uptr.get();
825 const char** targets_cstr = targets_uptr.get();
826
827 for (int i = 0; i < size; i += 2) {
828 std::string const& packageName = packageNames[i/2];
829 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
830 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
831 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
832 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
833
834 sources_cstr[i] = sources[i].c_str();
835 targets_cstr[i] = targets[i].c_str();
836 sources_cstr[i+1] = sources[i+1].c_str();
837 targets_cstr[i+1] = targets[i+1].c_str();
838 }
839
840 for (int i = 0; i < size; i++) {
841 // Make sure /storage/emulated/... paths are setup correctly
842 // This needs to be done before EnsureDirExists to ensure Android/ is created.
843 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
844 if (status != OK) {
845 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
846 return false;
847 }
848 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
849 if (status != OK) {
850 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
851 return false;
852 }
853 }
854
855 char android_data_dir[PATH_MAX];
856 char android_obb_dir[PATH_MAX];
857 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
858 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
859
860 pid_t child;
861 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
862 // original vold process mount namespace.
863 if (!(child = fork())) {
864 if (doUnmount) {
865 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
866 targets_cstr, size)) {
867 _exit(0);
868 } else {
869 _exit(1);
870 }
871 } else {
872 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
873 sources_cstr, targets_cstr, size)) {
874 _exit(0);
875 } else {
876 _exit(1);
877 }
878 }
879 }
880
881 if (child == -1) {
882 PLOG(ERROR) << "Failed to fork";
883 return false;
884 } else {
885 int status;
886 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
887 PLOG(ERROR) << "Failed to waitpid: " << child;
888 return false;
889 }
890 if (!WIFEXITED(status)) {
891 PLOG(ERROR) << "Process did not exit normally, status: " << status;
892 return false;
893 }
894 if (WEXITSTATUS(status)) {
895 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
896 return false;
897 }
898 }
899 return true;
900 }
901
handleAppStorageDirs(int uid,int pid,bool doUnmount,const std::vector<std::string> & packageNames)902 int VolumeManager::handleAppStorageDirs(int uid, int pid,
903 bool doUnmount, const std::vector<std::string>& packageNames) {
904 // Only run the remount if fuse is mounted for that user.
905 userid_t userId = multiuser_get_user_id(uid);
906 bool fuseMounted = false;
907 for (auto& vol : mInternalEmulatedVolumes) {
908 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
909 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
910 if (emulatedVol) {
911 fuseMounted = emulatedVol->isFuseMounted();
912 }
913 break;
914 }
915 }
916 if (fuseMounted) {
917 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
918 }
919 return 0;
920 }
921
abortFuse()922 int VolumeManager::abortFuse() {
923 return android::vold::AbortFuseConnections();
924 }
925
reset()926 int VolumeManager::reset() {
927 // Tear down all existing disks/volumes and start from a blank slate so
928 // newly connected framework hears all events.
929
930 // Destroy StubVolume disks. This needs to be done before destroying
931 // EmulatedVolumes because in ARC (Android on ChromeOS), ChromeOS Downloads
932 // directory (which is in a StubVolume) is bind-mounted to
933 // /data/media/0/Download.
934 // We do not recreate StubVolumes here because they are managed from outside
935 // Android (e.g. from ChromeOS) and their disk recreation on reset events
936 // should be handled from outside by calling createStubVolume() again.
937 for (const auto& disk : mDisks) {
938 if (disk->isStub()) {
939 disk->destroy();
940 }
941 }
942 // Remove StubVolume from both mDisks and mPendingDisks.
943 const auto isStub = [](const auto& disk) { return disk->isStub(); };
944 mDisks.remove_if(isStub);
945 mPendingDisks.remove_if(isStub);
946
947 for (const auto& vol : mInternalEmulatedVolumes) {
948 vol->destroy();
949 }
950 mInternalEmulatedVolumes.clear();
951
952 // Destroy and recreate non-StubVolume disks.
953 for (const auto& disk : mDisks) {
954 disk->destroy();
955 disk->create();
956 }
957
958 updateVirtualDisk();
959 mAddedUsers.clear();
960 mStartedUsers.clear();
961 mSharedStorageUser.clear();
962
963 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
964 // with FUSE fds open.
965 abortFuse();
966 return 0;
967 }
968
969 // Can be called twice (sequentially) during shutdown. should be safe for that.
shutdown()970 int VolumeManager::shutdown() {
971 if (mInternalEmulatedVolumes.empty()) {
972 return 0; // already shutdown
973 }
974 android::vold::sSleepOnUnmount = false;
975 // Destroy StubVolume disks before destroying EmulatedVolumes (see the
976 // comment in VolumeManager::reset()).
977 for (const auto& disk : mDisks) {
978 if (disk->isStub()) {
979 disk->destroy();
980 }
981 }
982 for (const auto& vol : mInternalEmulatedVolumes) {
983 vol->destroy();
984 }
985 for (const auto& disk : mDisks) {
986 if (!disk->isStub()) {
987 disk->destroy();
988 }
989 }
990
991 mInternalEmulatedVolumes.clear();
992 mDisks.clear();
993 mPendingDisks.clear();
994 android::vold::sSleepOnUnmount = true;
995
996 return 0;
997 }
998
unmountAll()999 int VolumeManager::unmountAll() {
1000 std::lock_guard<std::mutex> lock(mLock);
1001 ATRACE_NAME("VolumeManager::unmountAll()");
1002
1003 // First, try gracefully unmounting all known devices
1004 // Unmount StubVolume disks before unmounting EmulatedVolumes (see the
1005 // comment in VolumeManager::reset()).
1006 for (const auto& disk : mDisks) {
1007 if (disk->isStub()) {
1008 disk->unmountAll();
1009 }
1010 }
1011 for (const auto& vol : mInternalEmulatedVolumes) {
1012 vol->unmount();
1013 }
1014 for (const auto& disk : mDisks) {
1015 if (!disk->isStub()) {
1016 disk->unmountAll();
1017 }
1018 }
1019
1020 // Worst case we might have some stale mounts lurking around, so
1021 // force unmount those just to be safe.
1022 FILE* fp = setmntent("/proc/mounts", "re");
1023 if (fp == NULL) {
1024 PLOG(ERROR) << "Failed to open /proc/mounts";
1025 return -errno;
1026 }
1027
1028 // Some volumes can be stacked on each other, so force unmount in
1029 // reverse order to give us the best chance of success.
1030 std::list<std::string> toUnmount;
1031 mntent* mentry;
1032 while ((mentry = getmntent(fp)) != NULL) {
1033 auto test = std::string(mentry->mnt_dir);
1034 if ((StartsWith(test, "/mnt/") &&
1035 #ifdef __ANDROID_DEBUGGABLE__
1036 !StartsWith(test, "/mnt/scratch") &&
1037 #endif
1038 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
1039 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable") &&
1040 !StartsWith(test, "/mnt/vm")) ||
1041 StartsWith(test, "/storage/")) {
1042 toUnmount.push_front(test);
1043 }
1044 }
1045 endmntent(fp);
1046
1047 for (const auto& path : toUnmount) {
1048 LOG(DEBUG) << "Tearing down stale mount " << path;
1049 android::vold::ForceUnmount(path);
1050 }
1051
1052 return 0;
1053 }
1054
ensureAppDirsCreated(const std::vector<std::string> & paths,int32_t appUid)1055 int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
1056 int size = paths.size();
1057 for (int i = 0; i < size; i++) {
1058 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1059 true /* skipIfDirExists */);
1060 if (result != OK) {
1061 return result;
1062 }
1063 }
1064 return OK;
1065 }
1066
setupAppDir(const std::string & path,int32_t appUid,bool fixupExistingOnly,bool skipIfDirExists)1067 int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1068 bool skipIfDirExists) {
1069 // Only offer to create directories for paths managed by vold
1070 if (!StartsWith(path, "/storage/")) {
1071 LOG(ERROR) << "Failed to find mounted volume for " << path;
1072 return -EINVAL;
1073 }
1074
1075 // Find the volume it belongs to
1076 auto filter_fn = [&](const VolumeBase& vol) {
1077 if (vol.getState() != VolumeBase::State::kMounted) {
1078 // The volume must be mounted
1079 return false;
1080 }
1081 if (!vol.isVisibleForWrite()) {
1082 // App dirs should only be created for writable volumes.
1083 return false;
1084 }
1085 if (vol.getInternalPath().empty()) {
1086 return false;
1087 }
1088 if (vol.getMountUserId() != USER_UNKNOWN &&
1089 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1090 // The app dir must be created on a volume with the same user-id
1091 return false;
1092 }
1093 if (!path.empty() && StartsWith(path, vol.getPath())) {
1094 return true;
1095 }
1096
1097 return false;
1098 };
1099 auto volume = findVolumeWithFilter(filter_fn);
1100 if (volume == nullptr) {
1101 LOG(ERROR) << "Failed to find mounted volume for " << path;
1102 return -EINVAL;
1103 }
1104 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1105 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1106 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1107 // on /storage/emulated/10 means /mnt/user/0/emulated/10
1108 const std::string lowerPath =
1109 volume->getInternalPath() + path.substr(volume->getPath().length());
1110
1111 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1112
1113 const int access_result = access(lowerPath.c_str(), F_OK);
1114 if (fixupExistingOnly && access_result != 0) {
1115 // Nothing to fixup
1116 return OK;
1117 }
1118
1119 if (skipIfDirExists && access_result == 0) {
1120 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1121 // which the dir doesn't need to have correct permission for now yet.
1122 return OK;
1123 }
1124
1125 if (volume->getType() == VolumeBase::Type::kPublic) {
1126 // On public volumes, we don't need to setup permissions, as everything goes through
1127 // FUSE; just create the dirs and be done with it.
1128 return fs_mkdirs(lowerPath.c_str(), 0700);
1129 }
1130
1131 // Create the app paths we need from the root
1132 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1133 }
1134
fixupAppDir(const std::string & path,int32_t appUid)1135 int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
1136 if (IsSdcardfsUsed()) {
1137 //sdcardfs magically does this for us
1138 return OK;
1139 }
1140 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
1141 }
1142
createObb(const std::string & sourcePath,int32_t ownerGid,std::string * outVolId)1143 int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1144 std::string* outVolId) {
1145 int id = mNextObbId++;
1146
1147 std::string lowerSourcePath;
1148
1149 // Convert to lower filesystem path
1150 if (StartsWith(sourcePath, "/storage/")) {
1151 auto filter_fn = [&](const VolumeBase& vol) {
1152 if (vol.getState() != VolumeBase::State::kMounted) {
1153 // The volume must be mounted
1154 return false;
1155 }
1156 if (!vol.isVisibleForWrite()) {
1157 // Obb volume should only be created for writable volumes.
1158 return false;
1159 }
1160 if (vol.getInternalPath().empty()) {
1161 return false;
1162 }
1163 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1164 return true;
1165 }
1166
1167 return false;
1168 };
1169 auto volume = findVolumeWithFilter(filter_fn);
1170 if (volume == nullptr) {
1171 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1172 return -EINVAL;
1173 } else {
1174 lowerSourcePath =
1175 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1176 }
1177 } else {
1178 lowerSourcePath = sourcePath;
1179 }
1180
1181 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1182 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
1183 vol->create();
1184
1185 mObbVolumes.push_back(vol);
1186 *outVolId = vol->getId();
1187 return android::OK;
1188 }
1189
destroyObb(const std::string & volId)1190 int VolumeManager::destroyObb(const std::string& volId) {
1191 auto i = mObbVolumes.begin();
1192 while (i != mObbVolumes.end()) {
1193 if ((*i)->getId() == volId) {
1194 (*i)->destroy();
1195 i = mObbVolumes.erase(i);
1196 } else {
1197 ++i;
1198 }
1199 }
1200 return android::OK;
1201 }
1202
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)1203 int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1204 const std::string& fsType, const std::string& fsUuid,
1205 const std::string& fsLabel, int32_t flags,
1206 std::string* outVolId) {
1207 dev_t stubId = --mNextStubId;
1208 auto vol = std::shared_ptr<android::vold::StubVolume>(
1209 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1210
1211 int32_t passedFlags = 0;
1212 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1213 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
1214 if (flags & android::vold::Disk::Flags::kStubVisible) {
1215 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1216 } else {
1217 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1218 }
1219 // StubDisk doesn't have device node corresponds to it. So, a fake device
1220 // number is used.
1221 auto disk = std::shared_ptr<android::vold::Disk>(
1222 new android::vold::Disk("stub", stubId, "stub", passedFlags));
1223 disk->initializePartition(vol);
1224 handleDiskAdded(disk);
1225 *outVolId = vol->getId();
1226 return android::OK;
1227 }
1228
destroyStubVolume(const std::string & volId)1229 int VolumeManager::destroyStubVolume(const std::string& volId) {
1230 auto tokens = android::base::Split(volId, ":");
1231 CHECK(tokens.size() == 2);
1232 dev_t stubId;
1233 CHECK(android::base::ParseUint(tokens[1], &stubId));
1234 handleDiskRemoved(stubId);
1235 return android::OK;
1236 }
1237
mountAppFuse(uid_t uid,int mountId,unique_fd * device_fd)1238 int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
1239 return android::vold::MountAppFuse(uid, mountId, device_fd);
1240 }
1241
unmountAppFuse(uid_t uid,int mountId)1242 int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
1243 return android::vold::UnmountAppFuse(uid, mountId);
1244 }
1245
openAppFuseFile(uid_t uid,int mountId,int fileId,int flags)1246 int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
1247 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
1248 }
1249
getDeviceSize(std::string & device,int64_t * storageSize)1250 static android::status_t getDeviceSize(std::string& device, int64_t* storageSize) {
1251 // Follow any symbolic links
1252 std::string dataDevice;
1253 if (!android::base::Realpath(device, &dataDevice)) {
1254 dataDevice = device;
1255 }
1256
1257 // Handle mapped volumes.
1258 auto& dm = android::dm::DeviceMapper::Instance();
1259 for (;;) {
1260 auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1261 if (!parent.has_value()) break;
1262 dataDevice = *parent;
1263 }
1264
1265 // Get the potential /sys/block entry
1266 std::size_t leaf = dataDevice.rfind('/');
1267 if (leaf == std::string::npos) {
1268 LOG(ERROR) << "data device " << dataDevice << " is not a path";
1269 return EINVAL;
1270 }
1271 if (dataDevice.substr(0, leaf) != "/dev/block") {
1272 LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1273 return EINVAL;
1274 }
1275 std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1276
1277 // Look for a directory in /sys/block containing size where the name is a shortened
1278 // version of the name we now have
1279 // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1280 // Note that this directory only contains actual disks, not partitions, so this is
1281 // not going to find anything other than the disks
1282 std::string size;
1283 std::string sizeFile;
1284 for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1285 if (sysfsDir.back() == '/') {
1286 LOG(ERROR) << "Could not find valid block device from " << sysfs;
1287 return EINVAL;
1288 }
1289 sizeFile = sysfsDir + "/size";
1290 if (android::base::ReadFileToString(sizeFile, &size, true)) {
1291 break;
1292 }
1293 }
1294
1295 // Read the size file and be done
1296 std::stringstream ssSize(size);
1297 ssSize >> *storageSize;
1298 if (ssSize.fail()) {
1299 LOG(ERROR) << sizeFile << " cannot be read as an integer";
1300 return EINVAL;
1301 }
1302
1303 *storageSize *= 512;
1304 return OK;
1305 }
1306
GetStorageSize(int64_t * storageSize)1307 android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1308 android::status_t status;
1309 // Start with the /data mount point from fs_mgr
1310 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1311 if (entry == nullptr) {
1312 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1313 return EINVAL;
1314 }
1315
1316 status = getDeviceSize(entry->blk_device, storageSize);
1317 if (status != OK) {
1318 return status;
1319 }
1320
1321 for (auto device : entry->user_devices) {
1322 int64_t deviceStorageSize;
1323 status = getDeviceSize(device, &deviceStorageSize);
1324 if (status != OK) {
1325 return status;
1326 }
1327 *storageSize += deviceStorageSize;
1328 }
1329
1330 return OK;
1331 }
1332