VolumeManager.cpp 24 KB

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