VolumeManager.cpp 54.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
#include <dirent.h>
18
#include <errno.h>
19
#include <fcntl.h>
20
#include <fts.h>
21 22 23 24 25 26
#include <mntent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
27 28
#include <sys/stat.h>
#include <sys/types.h>
29
#include <sys/wait.h>
30
#include <unistd.h>
31

32
#include <linux/kdev_t.h>
33 34 35

#define LOG_TAG "Vold"

36 37
#include <openssl/md5.h>

38 39
#include <base/logging.h>
#include <base/stringprintf.h>
Jeff Sharkey's avatar
Jeff Sharkey committed
40
#include <cutils/fs.h>
41 42
#include <cutils/log.h>

43 44
#include <selinux/android.h>

45 46
#include <sysutils/NetlinkEvent.h>

47 48
#include <private/android_filesystem_config.h>

49
#include "Benchmark.h"
50
#include "EmulatedVolume.h"
51
#include "VolumeManager.h"
52
#include "NetlinkManager.h"
53
#include "ResponseCode.h"
54
#include "Loop.h"
55 56
#include "fs/Ext4.h"
#include "fs/Vfat.h"
57
#include "Utils.h"
58
#include "Devmapper.h"
59
#include "Process.h"
60
#include "Asec.h"
61
#include "VoldUtil.h"
62
#include "cryptfs.h"
63

64 65
#define MASS_STORAGE_FILE_PATH  "/sys/class/android_usb/android0/f_mass_storage/lun/file"

66 67 68
#define ROUND_UP_POWER_OF_2(number, po2) (((!!(number & ((1U << po2) - 1))) << po2)\
                                         + (number & (~((1U << po2) - 1))))

69 70
using android::base::StringPrintf;

Jeff Sharkey's avatar
Jeff Sharkey committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/*
 * Path to external storage where *only* root can access ASEC image files
 */
const char *VolumeManager::SEC_ASECDIR_EXT   = "/mnt/secure/asec";

/*
 * Path to internal storage where *only* root can access ASEC image files
 */
const char *VolumeManager::SEC_ASECDIR_INT   = "/data/app-asec";

/*
 * Path to where secure containers are mounted
 */
const char *VolumeManager::ASECDIR           = "/mnt/asec";

/*
 * Path to where OBBs are mounted
 */
const char *VolumeManager::LOOPDIR           = "/mnt/obb";

91 92 93 94
static const char* kUserMountPath = "/mnt/user";

static const unsigned int kMajorBlockMmc = 179;

95 96
/* writes superblock at end of file or device given by name */
static int writeSuperBlock(const char* name, struct asec_superblock *sb, unsigned int numImgSectors) {
97
    int sbfd = open(name, O_RDWR | O_CLOEXEC);
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    if (sbfd < 0) {
        SLOGE("Failed to open %s for superblock write (%s)", name, strerror(errno));
        return -1;
    }

    if (lseek(sbfd, (numImgSectors * 512), SEEK_SET) < 0) {
        SLOGE("Failed to lseek for superblock (%s)", strerror(errno));
        close(sbfd);
        return -1;
    }

    if (write(sbfd, sb, sizeof(struct asec_superblock)) != sizeof(struct asec_superblock)) {
        SLOGE("Failed to write superblock (%s)", strerror(errno));
        close(sbfd);
        return -1;
    }
    close(sbfd);
    return 0;
}

static int adjustSectorNumExt4(unsigned numSectors) {
119 120 121 122 123 124
    // Ext4 started to reserve 2% or 4096 clusters, whichever is smaller for
    // preventing costly operations or unexpected ENOSPC error.
    // Ext4::format() uses default block size without clustering.
    unsigned clusterSectors = 4096 / 512;
    unsigned reservedSectors = (numSectors * 2)/100 + (numSectors % 50 > 0);
    numSectors += reservedSectors > (4096 * clusterSectors) ? (4096 * clusterSectors) : reservedSectors;
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    return ROUND_UP_POWER_OF_2(numSectors, 3);
}

static int adjustSectorNumFAT(unsigned numSectors) {
    /*
    * Add some headroom
    */
    unsigned fatSize = (((numSectors * 4) / 512) + 1) * 2;
    numSectors += fatSize + 2;
    /*
    * FAT is aligned to 32 kb with 512b sectors.
    */
    return ROUND_UP_POWER_OF_2(numSectors, 6);
}

static int setupLoopDevice(char* buffer, size_t len, const char* asecFileName, const char* idHash, bool debug) {
    if (Loop::lookupActive(idHash, buffer, len)) {
        if (Loop::create(idHash, asecFileName, buffer, len)) {
            SLOGE("ASEC loop device creation failed for %s (%s)", asecFileName, strerror(errno));
            return -1;
        }
        if (debug) {
            SLOGD("New loop device created at %s", buffer);
        }
    } else {
        if (debug) {
            SLOGD("Found active loopback for %s at %s", asecFileName, buffer);
        }
    }
    return 0;
}

static int setupDevMapperDevice(char* buffer, size_t len, const char* loopDevice, const char* asecFileName, const char* key, const char* idHash , int numImgSectors, bool* createdDMDevice, bool debug) {
    if (strcmp(key, "none")) {
        if (Devmapper::lookupActive(idHash, buffer, len)) {
            if (Devmapper::create(idHash, loopDevice, key, numImgSectors,
                                  buffer, len)) {
                SLOGE("ASEC device mapping failed for %s (%s)", asecFileName, strerror(errno));
                return -1;
            }
            if (debug) {
                SLOGD("New devmapper instance created at %s", buffer);
            }
        } else {
            if (debug) {
                SLOGD("Found active devmapper for %s at %s", asecFileName, buffer);
            }
        }
        *createdDMDevice = true;
    } else {
        strcpy(buffer, loopDevice);
        *createdDMDevice = false;
    }
    return 0;
}

static void waitForDevMapper(const char *dmDevice) {
    /*
     * Wait for the device mapper node to be created. Sometimes it takes a
     * while. Wait for up to 1 second. We could also inspect incoming uevents,
     * but that would take more effort.
     */
    int tries = 25;
    while (tries--) {
        if (!access(dmDevice, F_OK) || errno != ENOENT) {
            break;
        }
        usleep(40 * 1000);
    }
}

196 197 198 199 200 201 202 203 204
VolumeManager *VolumeManager::sInstance = NULL;

VolumeManager *VolumeManager::Instance() {
    if (!sInstance)
        sInstance = new VolumeManager();
    return sInstance;
}

VolumeManager::VolumeManager() {
San Mehat's avatar
San Mehat committed
205
    mDebug = false;
206
    mActiveContainers = new AsecIdCollection();
207
    mBroadcaster = NULL;
208 209 210 211
    mUmsSharingCount = 0;
    mSavedDirtyRatio = -1;
    // set dirty ratio to 0 when UMS is active
    mUmsDirtyRatio = 0;
212 213 214
}

VolumeManager::~VolumeManager() {
215
    delete mActiveContainers;
216 217
}

San Mehat's avatar
San Mehat committed
218
char *VolumeManager::asecHash(const char *id, char *buffer, size_t len) {
219 220
    static const char* digits = "0123456789abcdef";

221
    unsigned char sig[MD5_DIGEST_LENGTH];
San Mehat's avatar
San Mehat committed
222

223 224 225 226 227 228 229 230 231
    if (buffer == NULL) {
        SLOGE("Destination buffer is NULL");
        errno = ESPIPE;
        return NULL;
    } else if (id == NULL) {
        SLOGE("Source buffer is NULL");
        errno = ESPIPE;
        return NULL;
    } else if (len < MD5_ASCII_LENGTH_PLUS_NULL) {
Colin Cross's avatar
Colin Cross committed
232
        SLOGE("Target hash buffer size < %d bytes (%zu)",
233
                MD5_ASCII_LENGTH_PLUS_NULL, len);
San Mehat's avatar
San Mehat committed
234 235 236
        errno = ESPIPE;
        return NULL;
    }
237 238

    MD5(reinterpret_cast<const unsigned char*>(id), strlen(id), sig);
San Mehat's avatar
San Mehat committed
239

240
    char *p = buffer;
241
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
242 243
        *p++ = digits[sig[i] >> 4];
        *p++ = digits[sig[i] & 0x0F];
San Mehat's avatar
San Mehat committed
244
    }
245
    *p = '\0';
San Mehat's avatar
San Mehat committed
246 247 248 249

    return buffer;
}

250
int VolumeManager::setDebug(bool enable) {
San Mehat's avatar
San Mehat committed
251
    mDebug = enable;
252
    return 0;
San Mehat's avatar
San Mehat committed
253 254
}

255
int VolumeManager::start() {
256 257
    // Always start from a clean slate by unmounting everything in
    // directories that we own, in case we crashed.
258
    unmountAll();
259 260 261

    // Assume that we always have an emulated volume on internal
    // storage; the framework will decide if it should be mounted.
262
    CHECK(mInternalEmulated == nullptr);
263
    mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
264
            new android::vold::EmulatedVolume("/data/media"));
265 266
    mInternalEmulated->create();

267 268 269 270
    return 0;
}

int VolumeManager::stop() {
271
    CHECK(mInternalEmulated != nullptr);
272 273
    mInternalEmulated->destroy();
    mInternalEmulated = nullptr;
274 275 276
    return 0;
}

277
void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
278 279
    std::lock_guard<std::mutex> lock(mLock);

280 281 282 283 284
    if (mDebug) {
        LOG(VERBOSE) << "----------------";
        LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
        evt->dump();
    }
285

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    std::string eventPath(evt->findParam("DEVPATH"));
    std::string devType(evt->findParam("DEVTYPE"));

    if (devType != "disk") return;

    int major = atoi(evt->findParam("MAJOR"));
    int minor = atoi(evt->findParam("MINOR"));
    dev_t device = makedev(major, minor);

    switch (evt->getAction()) {
    case NetlinkEvent::Action::kAdd: {
        for (auto source : mDiskSources) {
            if (source->matches(eventPath)) {
                // For now, assume that MMC devices are SD, and that
                // everything else is USB
                int flags = source->getFlags();
                if (major == kMajorBlockMmc) {
                    flags |= android::vold::Disk::Flags::kSd;
                } else {
                    flags |= android::vold::Disk::Flags::kUsb;
                }

                auto disk = new android::vold::Disk(eventPath, device,
                        source->getNickname(), flags);
                disk->create();
                mDisks.push_back(std::shared_ptr<android::vold::Disk>(disk));
                break;
            }
        }
        break;
    }
    case NetlinkEvent::Action::kChange: {
Jeff Sharkey's avatar
Jeff Sharkey committed
318
        LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        for (auto disk : mDisks) {
            if (disk->getDevice() == device) {
                disk->readMetadata();
                disk->readPartitions();
            }
        }
        break;
    }
    case NetlinkEvent::Action::kRemove: {
        auto i = mDisks.begin();
        while (i != mDisks.end()) {
            if ((*i)->getDevice() == device) {
                (*i)->destroy();
                i = mDisks.erase(i);
            } else {
                ++i;
            }
336
        }
337 338 339 340 341
        break;
    }
    default: {
        LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
        break;
342
    }
343 344
    }
}
345

346 347 348 349 350 351 352 353 354
void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
    mDiskSources.push_back(diskSource);
}

std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
    for (auto disk : mDisks) {
        if (disk->getId() == id) {
            return disk;
        }
355
    }
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
    return nullptr;
}

std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
    if (mInternalEmulated->getId() == id) {
        return mInternalEmulated;
    }
    for (auto disk : mDisks) {
        auto vol = disk->findVolume(id);
        if (vol != nullptr) {
            return vol;
        }
    }
    return nullptr;
}

372 373 374 375 376 377 378 379 380
void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
        std::list<std::string>& list) {
    list.clear();
    for (auto disk : mDisks) {
        disk->listVolumes(type, list);
    }
}

nsecs_t VolumeManager::benchmarkPrivate(const std::string& id) {
381
    std::string path;
382 383 384 385 386
    if (id == "private" || id == "null") {
        path = "/data";
    } else {
        auto vol = findVolume(id);
        if (vol != nullptr && vol->getState() == android::vold::VolumeBase::State::kMounted) {
387 388 389 390 391 392 393 394 395
            path = vol->getPath();
        }
    }

    if (path.empty()) {
        LOG(WARNING) << "Failed to find volume for " << id;
        return -1;
    }

396
    return android::vold::BenchmarkPrivate(path);
397 398
}

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
int VolumeManager::forgetPartition(const std::string& partGuid) {
    std::string normalizedGuid;
    if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
        LOG(WARNING) << "Invalid GUID " << partGuid;
        return -1;
    }

    std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
    if (unlink(keyPath.c_str()) != 0) {
        LOG(ERROR) << "Failed to unlink " << keyPath;
        return -1;
    }

    return 0;
}

415 416 417 418
int VolumeManager::linkPrimary(userid_t userId) {
    std::string source(mPrimary->getPath());
    if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
        source = StringPrintf("%s/%d", source.c_str(), userId);
419
        fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
420 421 422 423 424 425 426 427
    }

    std::string target(StringPrintf("/mnt/user/%d/primary", userId));
    if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
        if (errno != ENOENT) {
            SLOGW("Failed to unlink %s: %s", target.c_str(), strerror(errno));
        }
    }
428
    LOG(DEBUG) << "Linking " << source << " to " << target;
429 430 431 432 433 434 435 436
    if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
        SLOGW("Failed to link %s to %s: %s", source.c_str(), target.c_str(),
                strerror(errno));
        return -errno;
    }
    return 0;
}

437 438 439 440 441 442 443 444 445 446 447
int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
    mAddedUsers[userId] = userSerialNumber;
    return 0;
}

int VolumeManager::onUserRemoved(userid_t userId) {
    mAddedUsers.erase(userId);
    return 0;
}

int VolumeManager::onUserStarted(userid_t userId) {
448 449 450 451 452 453
    // Note that sometimes the system will spin up processes from Zygote
    // before actually starting the user, so we're okay if Zygote
    // already created this directory.
    std::string path(StringPrintf("%s/%d", kUserMountPath, userId));
    fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);

454
    mStartedUsers.insert(userId);
455 456 457 458 459 460
    if (mPrimary) {
        linkPrimary(userId);
    }
    return 0;
}

461 462
int VolumeManager::onUserStopped(userid_t userId) {
    mStartedUsers.erase(userId);
463 464 465 466 467
    return 0;
}

int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
    mPrimary = vol;
468
    for (userid_t userId : mStartedUsers) {
469 470 471 472 473
        linkPrimary(userId);
    }
    return 0;
}

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
static int sane_readlinkat(int dirfd, const char* path, char* buf, size_t bufsiz) {
    ssize_t len = readlinkat(dirfd, path, buf, bufsiz);
    if (len < 0) {
        return -1;
    } else if (len == (ssize_t) bufsiz) {
        return -1;
    } else {
        buf[len] = '\0';
        return 0;
    }
}

static int unmount_tree(const char* path) {
    size_t path_len = strlen(path);

    FILE* fp = setmntent("/proc/mounts", "r");
    if (fp == NULL) {
        ALOGE("Error opening /proc/mounts: %s", strerror(errno));
        return -errno;
    }

    // Some volumes can be stacked on each other, so force unmount in
    // reverse order to give us the best chance of success.
    std::list<std::string> toUnmount;
    mntent* mentry;
    while ((mentry = getmntent(fp)) != NULL) {
        if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
            toUnmount.push_front(std::string(mentry->mnt_dir));
        }
    }
    endmntent(fp);

    for (auto path : toUnmount) {
        if (umount2(path.c_str(), MNT_DETACH)) {
            ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
        }
    }
    return 0;
}

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
    LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;

    DIR* dir;
    struct dirent* de;
    char rootName[PATH_MAX];
    char pidName[PATH_MAX];
    int pidFd;
    int nsFd;
    struct stat sb;
    pid_t child;

    if (!(dir = opendir("/proc"))) {
        PLOG(ERROR) << "Failed to opendir";
        return -1;
    }

    // Figure out root namespace to compare against below
532
    if (sane_readlinkat(dirfd(dir), "1/ns/mnt", rootName, PATH_MAX) == -1) {
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
        PLOG(ERROR) << "Failed to readlink";
        closedir(dir);
        return -1;
    }

    // Poke through all running PIDs look for apps running as UID
    while ((de = readdir(dir))) {
        pidFd = -1;
        nsFd = -1;

        pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
        if (pidFd < 0) {
            goto next;
        }
        if (fstat(pidFd, &sb) != 0) {
            PLOG(WARNING) << "Failed to stat " << de->d_name;
            goto next;
        }
        if (sb.st_uid != uid) {
            goto next;
        }

        // Matches so far, but refuse to touch if in root namespace
        LOG(DEBUG) << "Found matching PID " << de->d_name;
557
        if (sane_readlinkat(pidFd, "ns/mnt", pidName, PATH_MAX) == -1) {
558 559 560 561 562 563 564 565 566 567 568
            PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
            goto next;
        }
        if (!strcmp(rootName, pidName)) {
            LOG(WARNING) << "Skipping due to root namespace";
            goto next;
        }

        // We purposefully leave the namespace open across the fork
        nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
        if (nsFd < 0) {
569
            PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
570 571 572 573 574
            goto next;
        }

        if (!(child = fork())) {
            if (setns(nsFd, CLONE_NEWNS) != 0) {
575
                PLOG(ERROR) << "Failed to setns for " << de->d_name;
576 577 578
                _exit(1);
            }

579
            unmount_tree("/storage");
580 581 582

            std::string storageSource;
            if (mode == "default") {
583
                storageSource = "/mnt/runtime/default";
584
            } else if (mode == "read") {
585
                storageSource = "/mnt/runtime/read";
586
            } else if (mode == "write") {
587
                storageSource = "/mnt/runtime/write";
588 589 590 591 592 593
            } else {
                // Sane default of no storage visible
                _exit(0);
            }
            if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
                    NULL, MS_BIND | MS_REC | MS_SLAVE, NULL)) == -1) {
594 595 596
                PLOG(ERROR) << "Failed to mount " << storageSource << " for "
                        << de->d_name;
                _exit(1);
597
            }
598 599 600 601 602 603 604 605 606 607 608

            // Mount user-specific symlink helper into place
            userid_t user_id = multiuser_get_user_id(uid);
            std::string userSource(StringPrintf("/mnt/user/%d", user_id));
            if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
                    NULL, MS_BIND, NULL)) == -1) {
                PLOG(ERROR) << "Failed to mount " << userSource << " for "
                        << de->d_name;
                _exit(1);
            }

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
            _exit(0);
        }

        if (child == -1) {
            PLOG(ERROR) << "Failed to fork";
            goto next;
        } else {
            TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
        }

next:
        close(nsFd);
        close(pidFd);
    }
    closedir(dir);
    return 0;
}

627 628 629 630 631 632 633 634 635
int VolumeManager::reset() {
    // Tear down all existing disks/volumes and start from a blank slate so
    // newly connected framework hears all events.
    mInternalEmulated->destroy();
    mInternalEmulated->create();
    for (auto disk : mDisks) {
        disk->destroy();
        disk->create();
    }
636 637
    mAddedUsers.clear();
    mStartedUsers.clear();
638 639 640 641
    return 0;
}

int VolumeManager::shutdown() {
642
    mInternalEmulated->destroy();
643 644 645 646 647
    for (auto disk : mDisks) {
        disk->destroy();
    }
    mDisks.clear();
    return 0;
648 649
}

650
int VolumeManager::unmountAll() {
651 652
    std::lock_guard<std::mutex> lock(mLock);

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
    // First, try gracefully unmounting all known devices
    if (mInternalEmulated != nullptr) {
        mInternalEmulated->unmount();
    }
    for (auto disk : mDisks) {
        disk->unmountAll();
    }

    // Worst case we might have some stale mounts lurking around, so
    // force unmount those just to be safe.
    FILE* fp = setmntent("/proc/mounts", "r");
    if (fp == NULL) {
        SLOGE("Error opening /proc/mounts: %s", strerror(errno));
        return -errno;
    }

    // Some volumes can be stacked on each other, so force unmount in
    // reverse order to give us the best chance of success.
    std::list<std::string> toUnmount;
    mntent* mentry;
    while ((mentry = getmntent(fp)) != NULL) {
        if (strncmp(mentry->mnt_dir, "/mnt/", 5) == 0
                || strncmp(mentry->mnt_dir, "/storage/", 9) == 0) {
            toUnmount.push_front(std::string(mentry->mnt_dir));
        }
    }
    endmntent(fp);

    for (auto path : toUnmount) {
        SLOGW("Tearing down stale mount %s", path.c_str());
        android::vold::ForceUnmount(path);
    }

    return 0;
}

Kenny Root's avatar
Kenny Root committed
689 690 691 692 693 694 695 696
int VolumeManager::getObbMountPath(const char *sourceFile, char *mountPath, int mountPathLen) {
    char idHash[33];
    if (!asecHash(sourceFile, idHash, sizeof(idHash))) {
        SLOGE("Hash of '%s' failed (%s)", sourceFile, strerror(errno));
        return -1;
    }

    memset(mountPath, 0, mountPathLen);
Jeff Sharkey's avatar
Jeff Sharkey committed
697
    int written = snprintf(mountPath, mountPathLen, "%s/%s", VolumeManager::LOOPDIR, idHash);
698 699 700 701
    if ((written < 0) || (written >= mountPathLen)) {
        errno = EINVAL;
        return -1;
    }
Kenny Root's avatar
Kenny Root committed
702 703 704 705 706 707 708 709 710

    if (access(mountPath, F_OK)) {
        errno = ENOENT;
        return -1;
    }

    return 0;
}

711
int VolumeManager::getAsecMountPath(const char *id, char *buffer, int maxlen) {
712
    char asecFileName[255];
713

Nick Kralevich's avatar
Nick Kralevich committed
714 715 716 717 718 719
    if (!isLegalAsecId(id)) {
        SLOGE("getAsecMountPath: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

720 721 722 723
    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }
724 725 726 727 728 729

    memset(buffer, 0, maxlen);
    if (access(asecFileName, F_OK)) {
        errno = ENOENT;
        return -1;
    }
730

Jeff Sharkey's avatar
Jeff Sharkey committed
731
    int written = snprintf(buffer, maxlen, "%s/%s", VolumeManager::ASECDIR, id);
732 733 734 735 736 737
    if ((written < 0) || (written >= maxlen)) {
        SLOGE("getAsecMountPath failed for %s: couldn't construct path in buffer", id);
        errno = EINVAL;
        return -1;
    }

738 739 740
    return 0;
}

741 742
int VolumeManager::getAsecFilesystemPath(const char *id, char *buffer, int maxlen) {
    char asecFileName[255];
743

Nick Kralevich's avatar
Nick Kralevich committed
744 745 746 747 748 749
    if (!isLegalAsecId(id)) {
        SLOGE("getAsecFilesystemPath: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

750 751 752 753
    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }
754 755 756 757 758 759 760

    memset(buffer, 0, maxlen);
    if (access(asecFileName, F_OK)) {
        errno = ENOENT;
        return -1;
    }

761 762 763 764 765 766
    int written = snprintf(buffer, maxlen, "%s", asecFileName);
    if ((written < 0) || (written >= maxlen)) {
        errno = EINVAL;
        return -1;
    }

767 768 769
    return 0;
}

770 771
int VolumeManager::createAsec(const char *id, unsigned int numSectors, const char *fstype,
        const char *key, const int ownerUid, bool isExternal) {
772 773 774
    struct asec_superblock sb;
    memset(&sb, 0, sizeof(sb));

Nick Kralevich's avatar
Nick Kralevich committed
775 776 777 778 779 780
    if (!isLegalAsecId(id)) {
        SLOGE("createAsec: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

781 782 783 784 785 786 787 788 789 790 791 792 793
    const bool wantFilesystem = strcmp(fstype, "none");
    bool usingExt4 = false;
    if (wantFilesystem) {
        usingExt4 = !strcmp(fstype, "ext4");
        if (usingExt4) {
            sb.c_opts |= ASEC_SB_C_OPTS_EXT4;
        } else if (strcmp(fstype, "fat")) {
            SLOGE("Invalid filesystem type %s", fstype);
            errno = EINVAL;
            return -1;
        }
    }

794 795
    sb.magic = ASEC_SB_MAGIC;
    sb.ver = ASEC_SB_VER;
796

797
    if (numSectors < ((1024*1024)/512)) {
San Mehat's avatar
San Mehat committed
798
        SLOGE("Invalid container size specified (%d sectors)", numSectors);
799 800 801 802
        errno = EINVAL;
        return -1;
    }

803
    char asecFileName[255];
804 805 806 807 808 809 810 811

    if (!findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
                asecFileName, strerror(errno));
        errno = EADDRINUSE;
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
812
    const char *asecDir = isExternal ? VolumeManager::SEC_ASECDIR_EXT : VolumeManager::SEC_ASECDIR_INT;
813

814 815 816 817 818
    int written = snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", asecDir, id);
    if ((written < 0) || (size_t(written) >= sizeof(asecFileName))) {
        errno = EINVAL;
        return -1;
    }
819 820

    if (!access(asecFileName, F_OK)) {
San Mehat's avatar
San Mehat committed
821
        SLOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
822
                asecFileName, strerror(errno));
823 824 825 826
        errno = EADDRINUSE;
        return -1;
    }

827
    unsigned numImgSectors;
828
    if (usingExt4)
829
        numImgSectors = adjustSectorNumExt4(numSectors);
830
    else
831
        numImgSectors = adjustSectorNumFAT(numSectors);
832 833 834

    // Add +1 for our superblock which is at the end
    if (Loop::createImageFile(asecFileName, numImgSectors + 1)) {
San Mehat's avatar
San Mehat committed
835
        SLOGE("ASEC image file creation failed (%s)", strerror(errno));
836 837 838
        return -1;
    }

San Mehat's avatar
San Mehat committed
839 840
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
841
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
842 843 844 845
        unlink(asecFileName);
        return -1;
    }

846
    char loopDevice[255];
San Mehat's avatar
San Mehat committed
847
    if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
848
        SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
849 850 851 852
        unlink(asecFileName);
        return -1;
    }

853 854
    char dmDevice[255];
    bool cleanupDm = false;
855

856
    if (strcmp(key, "none")) {
857 858
        // XXX: This is all we support for now
        sb.c_cipher = ASEC_SB_C_CIPHER_TWOFISH;
San Mehat's avatar
San Mehat committed
859
        if (Devmapper::create(idHash, loopDevice, key, numImgSectors, dmDevice,
860
                             sizeof(dmDevice))) {
San Mehat's avatar
San Mehat committed
861
            SLOGE("ASEC device mapping failed (%s)", strerror(errno));
862 863 864 865 866 867
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
        }
        cleanupDm = true;
    } else {
868
        sb.c_cipher = ASEC_SB_C_CIPHER_NONE;
869 870 871
        strcpy(dmDevice, loopDevice);
    }

872 873 874
    /*
     * Drop down the superblock at the end of the file
     */
875
    if (writeSuperBlock(loopDevice, &sb, numImgSectors)) {
876
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
877
            Devmapper::destroy(idHash);
878 879 880 881 882 883
        }
        Loop::destroyByDevice(loopDevice);
        unlink(asecFileName);
        return -1;
    }

884 885
    if (wantFilesystem) {
        int formatStatus;
886 887
        char mountPoint[255];

Jeff Sharkey's avatar
Jeff Sharkey committed
888
        int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id);
889 890 891 892 893 894 895 896 897
        if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
            SLOGE("ASEC fs format failed: couldn't construct mountPoint");
            if (cleanupDm) {
                Devmapper::destroy(idHash);
            }
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
        }
898

899
        if (usingExt4) {
900
            formatStatus = android::vold::ext4::Format(dmDevice, numImgSectors, mountPoint);
901
        } else {
902
            formatStatus = android::vold::vfat::Format(dmDevice, numImgSectors);
903
        }
904

905 906
        if (formatStatus < 0) {
            SLOGE("ASEC fs format failed (%s)", strerror(errno));
907
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
908
                Devmapper::destroy(idHash);
909
            }
910 911 912 913
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
        }
914 915

        if (mkdir(mountPoint, 0000)) {
916
            if (errno != EEXIST) {
San Mehat's avatar
San Mehat committed
917
                SLOGE("Mountpoint creation failed (%s)", strerror(errno));
918
                if (cleanupDm) {
San Mehat's avatar
San Mehat committed
919
                    Devmapper::destroy(idHash);
920 921 922 923 924 925
                }
                Loop::destroyByDevice(loopDevice);
                unlink(asecFileName);
                return -1;
            }
        }
926

927 928
        int mountStatus;
        if (usingExt4) {
929 930
            mountStatus = android::vold::ext4::Mount(dmDevice, mountPoint,
                    false, false, false);
931
        } else {
932 933
            mountStatus = android::vold::vfat::Mount(dmDevice, mountPoint,
                    false, false, false, ownerUid, 0, 0000, false);
934 935 936
        }

        if (mountStatus) {
San Mehat's avatar
San Mehat committed
937
            SLOGE("ASEC FAT mount failed (%s)", strerror(errno));
938
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
939
                Devmapper::destroy(idHash);
940 941 942 943
            }
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
944
        }
945 946

        if (usingExt4) {
947
            int dirfd = open(mountPoint, O_DIRECTORY | O_CLOEXEC);
948 949 950 951 952 953 954 955
            if (dirfd >= 0) {
                if (fchown(dirfd, ownerUid, AID_SYSTEM)
                        || fchmod(dirfd, S_IRUSR | S_IWUSR | S_IXUSR | S_ISGID | S_IRGRP | S_IXGRP)) {
                    SLOGI("Cannot chown/chmod new ASEC mount point %s", mountPoint);
                }
                close(dirfd);
            }
        }
956
    } else {
San Mehat's avatar
San Mehat committed
957
        SLOGI("Created raw secure container %s (no filesystem)", id);
958
    }
959

Kenny Root's avatar
Kenny Root committed
960
    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
961 962 963
    return 0;
}

964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
int VolumeManager::resizeAsec(const char *id, unsigned numSectors, const char *key) {
    char asecFileName[255];
    char mountPoint[255];
    bool cleanupDm = false;

    if (!isLegalAsecId(id)) {
        SLOGE("resizeAsec: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
980
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id);
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
       SLOGE("ASEC resize failed for %s: couldn't construct mountpoint", id);
       return -1;
    }

    if (isMountpointMounted(mountPoint)) {
       SLOGE("ASEC %s mounted. Unmount before resizing", id);
       errno = EBUSY;
       return -1;
    }

    struct asec_superblock sb;
    int fd;
    unsigned int oldNumSec = 0;

996
    if ((fd = open(asecFileName, O_RDONLY | O_CLOEXEC)) < 0) {
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
        SLOGE("Failed to open ASEC file (%s)", strerror(errno));
        return -1;
    }

    struct stat info;
    if (fstat(fd, &info) < 0) {
        SLOGE("Failed to get file size (%s)", strerror(errno));
        close(fd);
        return -1;
    }

    oldNumSec = info.st_size / 512;

    unsigned numImgSectors;
    if (sb.c_opts & ASEC_SB_C_OPTS_EXT4)
        numImgSectors = adjustSectorNumExt4(numSectors);
    else
        numImgSectors = adjustSectorNumFAT(numSectors);
    /*
     *  add one block for the superblock
     */
    SLOGD("Resizing from %d sectors to %d sectors", oldNumSec, numImgSectors + 1);
1019 1020 1021 1022
    if (oldNumSec == numImgSectors + 1) {
        SLOGW("Size unchanged; ignoring resize request");
        return 0;
    } else if (oldNumSec > numImgSectors + 1) {
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
        SLOGE("Only growing is currently supported.");
        close(fd);
        return -1;
    }

    /*
     * Try to read superblock.
     */
    memset(&sb, 0, sizeof(struct asec_superblock));
    if (lseek(fd, ((oldNumSec - 1) * 512), SEEK_SET) < 0) {
        SLOGE("lseek failed (%s)", strerror(errno));
        close(fd);
        return -1;
    }
    if (read(fd, &sb, sizeof(struct asec_superblock)) != sizeof(struct asec_superblock)) {
        SLOGE("superblock read failed (%s)", strerror(errno));
        close(fd);
        return -1;
    }
    close(fd);

    if (mDebug) {
        SLOGD("Container sb magic/ver (%.8x/%.2x)", sb.magic, sb.ver);
    }
    if (sb.magic != ASEC_SB_MAGIC || sb.ver != ASEC_SB_VER) {
        SLOGE("Bad container magic/version (%.8x/%.2x)", sb.magic, sb.ver);
        errno = EMEDIUMTYPE;
        return -1;
    }

    if (!(sb.c_opts & ASEC_SB_C_OPTS_EXT4)) {
        SLOGE("Only ext4 partitions are supported for resize");
        errno = EINVAL;
        return -1;
    }

    if (Loop::resizeImageFile(asecFileName, numImgSectors + 1)) {
        SLOGE("Resize of ASEC image file failed. Could not resize %s", id);
        return -1;
    }

    /*
     * Drop down a copy of the superblock at the end of the file
     */
    if (writeSuperBlock(asecFileName, &sb, numImgSectors))
        goto fail;

    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
        goto fail;
    }

    char loopDevice[255];
    if (setupLoopDevice(loopDevice, sizeof(loopDevice), asecFileName, idHash, mDebug))
        goto fail;

    char dmDevice[255];

    if (setupDevMapperDevice(dmDevice, sizeof(dmDevice), loopDevice, asecFileName, key, idHash, numImgSectors, &cleanupDm, mDebug)) {
        Loop::destroyByDevice(loopDevice);
        goto fail;
    }

    /*
     * Wait for the device mapper node to be created.
     */
    waitForDevMapper(dmDevice);

1092
    if (android::vold::ext4::Resize(dmDevice, numImgSectors)) {
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
        SLOGE("Unable to resize %s (%s)", id, strerror(errno));
        if (cleanupDm) {
            Devmapper::destroy(idHash);
        }
        Loop::destroyByDevice(loopDevice);
        goto fail;
    }

    return 0;
fail:
    Loop::resizeImageFile(asecFileName, oldNumSec);
    return -1;
}

1107 1108 1109 1110 1111
int VolumeManager::finalizeAsec(const char *id) {
    char asecFileName[255];
    char loopDevice[255];
    char mountPoint[255];

Nick Kralevich's avatar
Nick Kralevich committed
1112 1113 1114 1115 1116 1117
    if (!isLegalAsecId(id)) {
        SLOGE("finalizeAsec: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

1118 1119 1120 1121
    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }
1122

San Mehat's avatar
San Mehat committed
1123 1124
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
1125
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
1126 1127 1128 1129
        return -1;
    }

    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
1130
        SLOGE("Unable to finalize %s (%s)", id, strerror(errno));
1131 1132 1133
        return -1;
    }

1134
    unsigned long nr_sec = 0;
1135 1136 1137 1138 1139 1140
    struct asec_superblock sb;

    if (Loop::lookupInfo(loopDevice, &sb, &nr_sec)) {
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
1141
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id);
1142 1143 1144 1145
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("ASEC finalize failed: couldn't construct mountPoint");
        return -1;
    }
1146 1147 1148

    int result = 0;
    if (sb.c_opts & ASEC_SB_C_OPTS_EXT4) {
1149 1150
        result = android::vold::ext4::Mount(loopDevice, mountPoint,
                true, true, true);
1151
    } else {
1152 1153
        result = android::vold::vfat::Mount(loopDevice, mountPoint,
                true, true, true, 0, 0, 0227, false);
1154 1155 1156
    }

    if (result) {
San Mehat's avatar
San Mehat committed
1157
        SLOGE("ASEC finalize mount failed (%s)", strerror(errno));
1158 1159 1160
        return -1;
    }

San Mehat's avatar
San Mehat committed
1161
    if (mDebug) {
San Mehat's avatar
San Mehat committed
1162
        SLOGD("ASEC %s finalized", id);
San Mehat's avatar
San Mehat committed
1163
    }
1164 1165 1166
    return 0;
}

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
int VolumeManager::fixupAsecPermissions(const char *id, gid_t gid, const char* filename) {
    char asecFileName[255];
    char loopDevice[255];
    char mountPoint[255];

    if (gid < AID_APP) {
        SLOGE("Group ID is not in application range");
        return -1;
    }

Nick Kralevich's avatar
Nick Kralevich committed
1177 1178 1179 1180 1181 1182
    if (!isLegalAsecId(id)) {
        SLOGE("fixupAsecPermissions: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }

    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
        return -1;
    }

    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
        SLOGE("Unable fix permissions during lookup on %s (%s)", id, strerror(errno));
        return -1;
    }

1199
    unsigned long nr_sec = 0;
1200 1201 1202 1203 1204 1205
    struct asec_superblock sb;

    if (Loop::lookupInfo(loopDevice, &sb, &nr_sec)) {
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
1206
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id);
1207 1208 1209 1210
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("Unable remount to fix permissions for %s: couldn't construct mountpoint", id);
        return -1;
    }
1211 1212 1213 1214 1215 1216

    int result = 0;
    if ((sb.c_opts & ASEC_SB_C_OPTS_EXT4) == 0) {
        return 0;
    }

1217
    int ret = android::vold::ext4::Mount(loopDevice, mountPoint,
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
            false /* read-only */,
            true  /* remount */,
            false /* executable */);
    if (ret) {
        SLOGE("Unable remount to fix permissions for %s (%s)", id, strerror(errno));
        return -1;
    }

    char *paths[] = { mountPoint, NULL };

    FTS *fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL);
    if (fts) {
        // Traverse the entire hierarchy and chown to system UID.
        for (FTSENT *ftsent = fts_read(fts); ftsent != NULL; ftsent = fts_read(fts)) {
            // We don't care about the lost+found directory.
            if (!strcmp(ftsent->fts_name, "lost+found")) {
                continue;
            }

            /*
             * There can only be one file marked as private right now.
             * This should be more robust, but it satisfies the requirements
             * we have for right now.
             */
            const bool privateFile = !strcmp(ftsent->fts_name, filename);

1244
            int fd = open(ftsent->fts_accpath, O_NOFOLLOW | O_CLOEXEC);
1245 1246 1247 1248 1249 1250 1251 1252 1253
            if (fd < 0) {
                SLOGE("Couldn't open file %s: %s", ftsent->fts_accpath, strerror(errno));
                result = -1;
                continue;
            }

            result |= fchown(fd, AID_SYSTEM, privateFile? gid : AID_SYSTEM);

            if (ftsent->fts_info & FTS_D) {
1254
                result |= fchmod(fd, 0755);
1255
            } else if (ftsent->fts_info & FTS_F) {
1256 1257
                result |= fchmod(fd, privateFile ? 0640 : 0644);
            }
1258

1259
            if (selinux_android_restorecon(ftsent->fts_path, 0) < 0) {
1260 1261 1262 1263
                SLOGE("restorecon failed for %s: %s\n", ftsent->fts_path, strerror(errno));
                result |= -1;
            }

1264 1265 1266 1267 1268
            close(fd);
        }
        fts_close(fts);

        // Finally make the directory readable by everyone.
1269
        int dirfd = open(mountPoint, O_DIRECTORY | O_CLOEXEC);
1270 1271 1272 1273 1274 1275 1276 1277 1278
        if (dirfd < 0 || fchmod(dirfd, 0755)) {
            SLOGE("Couldn't change owner of existing directory %s: %s", mountPoint, strerror(errno));
            result |= -1;
        }
        close(dirfd);
    } else {
        result |= -1;
    }

1279
    result |= android::vold::ext4::Mount(loopDevice, mountPoint,
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
            true /* read-only */,
            true /* remount */,
            true /* execute */);

    if (result) {
        SLOGE("ASEC fix permissions failed (%s)", strerror(errno));
        return -1;
    }

    if (mDebug) {
        SLOGD("ASEC %s permissions fixed", id);
    }
    return 0;
}

1295
int VolumeManager::renameAsec(const char *id1, const char *id2) {
1296
    char asecFilename1[255];
1297 1298 1299
    char *asecFilename2;
    char mountPoint[255];

1300 1301
    const char *dir;

Nick Kralevich's avatar
Nick Kralevich committed
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    if (!isLegalAsecId(id1)) {
        SLOGE("renameAsec: Invalid asec id1 \"%s\"", id1);
        errno = EINVAL;
        return -1;
    }

    if (!isLegalAsecId(id2)) {
        SLOGE("renameAsec: Invalid asec id2 \"%s\"", id2);
        errno = EINVAL;
        return -1;
    }

1314 1315 1316 1317 1318 1319
    if (findAsec(id1, asecFilename1, sizeof(asecFilename1), &dir)) {
        SLOGE("Couldn't find ASEC %s", id1);
        return -1;
    }

    asprintf(&asecFilename2, "%s/%s.asec", dir, id2);
1320

Jeff Sharkey's avatar
Jeff Sharkey committed
1321
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id1);
1322 1323 1324 1325 1326
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("Rename failed: couldn't construct mountpoint");
        goto out_err;
    }

1327
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
1328
        SLOGW("Rename attempt when src mounted");
1329 1330 1331 1332
        errno = EBUSY;
        goto out_err;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
1333
    written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id2);
1334 1335 1336 1337 1338
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("Rename failed: couldn't construct mountpoint2");
        goto out_err;
    }

1339
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
1340
        SLOGW("Rename attempt when dst mounted");
1341 1342 1343 1344
        errno = EBUSY;
        goto out_err;
    }

1345
    if (!access(asecFilename2, F_OK)) {
San Mehat's avatar
San Mehat committed
1346
        SLOGE("Rename attempt when dst exists");
1347 1348 1349 1350 1351
        errno = EADDRINUSE;
        goto out_err;
    }

    if (rename(asecFilename1, asecFilename2)) {
San Mehat's avatar
San Mehat committed
1352
        SLOGE("Rename of '%s' to '%s' failed (%s)", asecFilename1, asecFilename2, strerror(errno));
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
        goto out_err;
    }

    free(asecFilename2);
    return 0;

out_err:
    free(asecFilename2);
    return -1;
}

1364 1365
#define UNMOUNT_RETRIES 5
#define UNMOUNT_SLEEP_BETWEEN_RETRY_MS (1000 * 1000)
1366
int VolumeManager::unmountAsec(const char *id, bool force) {
1367 1368 1369
    char asecFileName[255];
    char mountPoint[255];

Nick Kralevich's avatar
Nick Kralevich committed
1370 1371 1372 1373 1374 1375
    if (!isLegalAsecId(id)) {
        SLOGE("unmountAsec: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

1376 1377 1378 1379 1380
    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
1381
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id);
1382 1383 1384 1385
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("ASEC unmount failed for %s: couldn't construct mountpoint", id);
        return -1;
    }
1386

San Mehat's avatar
San Mehat committed
1387 1388
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
1389
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
1390 1391 1392
        return -1;
    }

1393 1394 1395
    return unmountLoopImage(id, idHash, asecFileName, mountPoint, force);
}

Kenny Root's avatar
Kenny Root committed
1396
int VolumeManager::unmountObb(const char *fileName, bool force) {
1397 1398 1399 1400 1401 1402 1403 1404
    char mountPoint[255];

    char idHash[33];
    if (!asecHash(fileName, idHash, sizeof(idHash))) {
        SLOGE("Hash of '%s' failed (%s)", fileName, strerror(errno));
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
1405
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::LOOPDIR, idHash);
1406 1407 1408 1409
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("OBB unmount failed for %s: couldn't construct mountpoint", fileName);
        return -1;
    }
1410 1411 1412 1413 1414 1415

    return unmountLoopImage(fileName, idHash, fileName, mountPoint, force);
}

int VolumeManager::unmountLoopImage(const char *id, const char *idHash,
        const char *fileName, const char *mountPoint, bool force) {
1416
    if (!isMountpointMounted(mountPoint)) {
1417
        SLOGE("Unmount request for %s when not mounted", id);
1418
        errno = ENOENT;
1419 1420
        return -1;
    }
1421

1422
    int i, rc;
1423
    for (i = 1; i <= UNMOUNT_RETRIES; i++) {
1424 1425 1426
        rc = umount(mountPoint);
        if (!rc) {
            break;
1427
        }
1428
        if (rc && (errno == EINVAL || errno == ENOENT)) {
1429
            SLOGI("Container %s unmounted OK", id);
1430 1431
            rc = 0;
            break;
1432
        }
1433
        SLOGW("%s unmount attempt %d failed (%s)",
1434 1435
              id, i, strerror(errno));

1436
        int signal = 0; // default is to just complain
1437 1438

        if (force) {
1439
            if (i > (UNMOUNT_RETRIES - 2))
1440
                signal = SIGKILL;
1441
            else if (i > (UNMOUNT_RETRIES - 3))
1442
                signal = SIGTERM;
1443
        }
1444

1445
        Process::killProcessesWithOpenFiles(mountPoint, signal);
1446
        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
1447 1448 1449
    }

    if (rc) {
1450
        errno = EBUSY;
San Mehat's avatar
San Mehat committed
1451
        SLOGE("Failed to unmount container %s (%s)", id, strerror(errno));
1452 1453 1454
        return -1;
    }

1455 1456 1457 1458 1459 1460 1461
    int retries = 10;

    while(retries--) {
        if (!rmdir(mountPoint)) {
            break;
        }

San Mehat's avatar
San Mehat committed
1462
        SLOGW("Failed to rmdir %s (%s)", mountPoint, strerror(errno));
1463
        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
1464 1465 1466
    }

    if (!retries) {
San Mehat's avatar
San Mehat committed
1467
        SLOGE("Timed out trying to rmdir %s (%s)", mountPoint, strerror(errno));
1468
    }
1469

1470 1471 1472 1473 1474 1475 1476 1477
    for (i=1; i <= UNMOUNT_RETRIES; i++) {
        if (Devmapper::destroy(idHash) && errno != ENXIO) {
            SLOGE("Failed to destroy devmapper instance (%s)", strerror(errno));
            usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
            continue;
        } else {
          break;
        }
1478 1479 1480
    }

    char loopDevice[255];
San Mehat's avatar
San Mehat committed
1481
    if (!Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
1482
        Loop::destroyByDevice(loopDevice);
San Mehat's avatar
San Mehat committed
1483
    } else {
1484
        SLOGW("Failed to find loop device for {%s} (%s)", fileName, strerror(errno));
1485
    }
1486 1487 1488

    AsecIdCollection::iterator it;
    for (it = mActiveContainers->begin(); it != mActiveContainers->end(); ++it) {
Kenny Root's avatar
Kenny Root committed
1489 1490
        ContainerData* cd = *it;
        if (!strcmp(cd->id, id)) {
1491 1492 1493 1494 1495 1496
            free(*it);
            mActiveContainers->erase(it);
            break;
        }
    }
    if (it == mActiveContainers->end()) {
San Mehat's avatar
San Mehat committed
1497
        SLOGW("mActiveContainers is inconsistent!");
1498
    }
1499 1500 1501
    return 0;
}

1502
int VolumeManager::destroyAsec(const char *id, bool force) {
1503 1504 1505
    char asecFileName[255];
    char mountPoint[255];

Nick Kralevich's avatar
Nick Kralevich committed
1506 1507 1508 1509 1510 1511
    if (!isLegalAsecId(id)) {
        SLOGE("destroyAsec: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

1512 1513 1514 1515 1516
    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
1517
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id);
1518 1519 1520 1521
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("ASEC destroy failed for %s: couldn't construct mountpoint", id);
        return -1;
    }
1522

1523
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
1524
        if (mDebug) {
San Mehat's avatar
San Mehat committed
1525
            SLOGD("Unmounting container before destroy");
San Mehat's avatar
San Mehat committed
1526
        }
1527
        if (unmountAsec(id, force)) {
San Mehat's avatar
San Mehat committed
1528
            SLOGE("Failed to unmount asec %s for destroy (%s)", id, strerror(errno));
1529 1530 1531
            return -1;
        }
    }
1532

1533
    if (unlink(asecFileName)) {
San Mehat's avatar
San Mehat committed
1534
        SLOGE("Failed to unlink asec '%s' (%s)", asecFileName, strerror(errno));
1535 1536
        return -1;
    }
1537

San Mehat's avatar
San Mehat committed
1538
    if (mDebug) {
San Mehat's avatar
San Mehat committed
1539
        SLOGD("ASEC %s destroyed", id);
San Mehat's avatar
San Mehat committed
1540
    }
1541 1542 1543
    return 0;
}

Nick Kralevich's avatar
Nick Kralevich committed
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
/*
 * Legal ASEC ids consist of alphanumeric characters, '-',
 * '_', or '.'. ".." is not allowed. The first or last character
 * of the ASEC id cannot be '.' (dot).
 */
bool VolumeManager::isLegalAsecId(const char *id) const {
    size_t i;
    size_t len = strlen(id);

    if (len == 0) {
        return false;
    }
    if ((id[0] == '.') || (id[len - 1] == '.')) {
        return false;
    }

    for (i = 0; i < len; i++) {
        if (id[i] == '.') {
            // i=0 is guaranteed never to have a dot. See above.
            if (id[i-1] == '.') return false;
            continue;
        }
        if (id[i] == '_' || id[i] == '-') continue;
        if (id[i] >= 'a' && id[i] <= 'z') continue;
        if (id[i] >= 'A' && id[i] <= 'Z') continue;
        if (id[i] >= '0' && id[i] <= '9') continue;
        return false;
    }

    return true;
}

1576
bool VolumeManager::isAsecInDirectory(const char *dir, const char *asecName) const {
1577
    int dirfd = open(dir, O_DIRECTORY | O_CLOEXEC);
1578 1579
    if (dirfd < 0) {
        SLOGE("Couldn't open internal ASEC dir (%s)", strerror(errno));
1580
        return false;
1581 1582
    }

1583 1584 1585
    struct stat sb;
    bool ret = (fstatat(dirfd, asecName, &sb, AT_SYMLINK_NOFOLLOW) == 0)
        && S_ISREG(sb.st_mode);
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595

    close(dirfd);

    return ret;
}

int VolumeManager::findAsec(const char *id, char *asecPath, size_t asecPathLen,
        const char **directory) const {
    char *asecName;

Nick Kralevich's avatar
Nick Kralevich committed
1596 1597 1598 1599 1600 1601
    if (!isLegalAsecId(id)) {
        SLOGE("findAsec: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

1602 1603 1604 1605 1606 1607
    if (asprintf(&asecName, "%s.asec", id) < 0) {
        SLOGE("Couldn't allocate string to write ASEC name");
        return -1;
    }

    const char *dir;
Jeff Sharkey's avatar
Jeff Sharkey committed
1608 1609 1610 1611
    if (isAsecInDirectory(VolumeManager::SEC_ASECDIR_INT, asecName)) {
        dir = VolumeManager::SEC_ASECDIR_INT;
    } else if (isAsecInDirectory(VolumeManager::SEC_ASECDIR_EXT, asecName)) {
        dir = VolumeManager::SEC_ASECDIR_EXT;
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    } else {
        free(asecName);
        return -1;
    }

    if (directory != NULL) {
        *directory = dir;
    }

    if (asecPath != NULL) {
        int written = snprintf(asecPath, asecPathLen, "%s/%s", dir, asecName);
1623 1624
        if ((written < 0) || (size_t(written) >= asecPathLen)) {
            SLOGE("findAsec failed for %s: couldn't construct ASEC path", id);
1625 1626 1627 1628 1629 1630 1631 1632 1633
            free(asecName);
            return -1;
        }
    }

    free(asecName);
    return 0;
}

1634
int VolumeManager::mountAsec(const char *id, const char *key, int ownerUid, bool readOnly) {
1635 1636 1637
    char asecFileName[255];
    char mountPoint[255];

Nick Kralevich's avatar
Nick Kralevich committed
1638 1639 1640 1641 1642 1643
    if (!isLegalAsecId(id)) {
        SLOGE("mountAsec: Invalid asec id \"%s\"", id);
        errno = EINVAL;
        return -1;
    }

1644 1645 1646 1647 1648
    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
1649
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::ASECDIR, id);
1650
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
Colin Cross's avatar
Colin Cross committed
1651
        SLOGE("ASEC mount failed for %s: couldn't construct mountpoint", id);
1652 1653
        return -1;
    }
1654 1655

    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
1656
        SLOGE("ASEC %s already mounted", id);
1657 1658 1659 1660
        errno = EBUSY;
        return -1;
    }

San Mehat's avatar
San Mehat committed
1661 1662
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
1663
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
1664 1665
        return -1;
    }
1666

1667
    char loopDevice[255];
1668 1669
    if (setupLoopDevice(loopDevice, sizeof(loopDevice), asecFileName, idHash, mDebug))
        return -1;
1670 1671 1672

    char dmDevice[255];
    bool cleanupDm = false;
1673

1674
    unsigned long nr_sec = 0;
1675
    struct asec_superblock sb;
1676 1677

    if (Loop::lookupInfo(loopDevice, &sb, &nr_sec)) {
1678 1679 1680
        return -1;
    }

San Mehat's avatar
San Mehat committed
1681
    if (mDebug) {
San Mehat's avatar
San Mehat committed
1682
        SLOGD("Container sb magic/ver (%.8x/%.2x)", sb.magic, sb.ver);
San Mehat's avatar
San Mehat committed
1683
    }
1684
    if (sb.magic != ASEC_SB_MAGIC || sb.ver != ASEC_SB_VER) {
San Mehat's avatar
San Mehat committed
1685
        SLOGE("Bad container magic/version (%.8x/%.2x)", sb.magic, sb.ver);
1686 1687 1688 1689 1690 1691
        Loop::destroyByDevice(loopDevice);
        errno = EMEDIUMTYPE;
        return -1;
    }
    nr_sec--; // We don't want the devmapping to extend onto our superblock

1692 1693 1694
    if (setupDevMapperDevice(dmDevice, sizeof(dmDevice), loopDevice, asecFileName, key, idHash , nr_sec, &cleanupDm, mDebug)) {
        Loop::destroyByDevice(loopDevice);
        return -1;
1695 1696
    }

1697
    if (mkdir(mountPoint, 0000)) {
1698
        if (errno != EEXIST) {
San Mehat's avatar
San Mehat committed
1699
            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
1700
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
1701
                Devmapper::destroy(idHash);
1702 1703 1704 1705
            }
            Loop::destroyByDevice(loopDevice);
            return -1;
        }
1706 1707
    }

1708
    /*
1709
     * Wait for the device mapper node to be created.
1710
     */
1711
    waitForDevMapper(dmDevice);
1712

1713 1714
    int result;
    if (sb.c_opts & ASEC_SB_C_OPTS_EXT4) {
1715 1716
        result = android::vold::ext4::Mount(dmDevice, mountPoint,
                readOnly, false, readOnly);
1717
    } else {
1718 1719
        result = android::vold::vfat::Mount(dmDevice, mountPoint,
                readOnly, false, readOnly, ownerUid, 0, 0222, false);
1720 1721 1722
    }

    if (result) {
San Mehat's avatar
San Mehat committed
1723
        SLOGE("ASEC mount failed (%s)", strerror(errno));
1724
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
1725
            Devmapper::destroy(idHash);
1726 1727
        }
        Loop::destroyByDevice(loopDevice);
1728 1729 1730
        return -1;
    }

Kenny Root's avatar
Kenny Root committed
1731
    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
San Mehat's avatar
San Mehat committed
1732
    if (mDebug) {
San Mehat's avatar
San Mehat committed
1733
        SLOGD("ASEC %s mounted", id);
San Mehat's avatar
San Mehat committed
1734
    }
1735 1736 1737
    return 0;
}

1738 1739 1740
/**
 * Mounts an image file <code>img</code>.
 */
1741
int VolumeManager::mountObb(const char *img, const char *key, int ownerGid) {
1742 1743 1744 1745 1746 1747 1748 1749
    char mountPoint[255];

    char idHash[33];
    if (!asecHash(img, idHash, sizeof(idHash))) {
        SLOGE("Hash of '%s' failed (%s)", img, strerror(errno));
        return -1;
    }

Jeff Sharkey's avatar
Jeff Sharkey committed
1750
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", VolumeManager::LOOPDIR, idHash);
1751
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
Colin Cross's avatar
Colin Cross committed
1752
        SLOGE("OBB mount failed for %s: couldn't construct mountpoint", img);
1753 1754
        return -1;
    }
1755 1756 1757 1758 1759 1760 1761 1762

    if (isMountpointMounted(mountPoint)) {
        SLOGE("Image %s already mounted", img);
        errno = EBUSY;
        return -1;
    }

    char loopDevice[255];
1763 1764
    if (setupLoopDevice(loopDevice, sizeof(loopDevice), img, idHash, mDebug))
        return -1;
1765 1766 1767 1768

    char dmDevice[255];
    bool cleanupDm = false;
    int fd;
1769
    unsigned long nr_sec = 0;
1770

1771
    if ((fd = open(loopDevice, O_RDWR | O_CLOEXEC)) < 0) {
1772 1773 1774 1775 1776
        SLOGE("Failed to open loopdevice (%s)", strerror(errno));
        Loop::destroyByDevice(loopDevice);
        return -1;
    }

1777 1778
    get_blkdev_size(fd, &nr_sec);
    if (nr_sec == 0) {
1779 1780 1781 1782 1783 1784 1785 1786
        SLOGE("Failed to get loop size (%s)", strerror(errno));
        Loop::destroyByDevice(loopDevice);
        close(fd);
        return -1;
    }

    close(fd);

1787
    if (setupDevMapperDevice(dmDevice, sizeof(loopDevice), loopDevice, img,key, idHash, nr_sec, &cleanupDm, mDebug)) {
1788 1789
        Loop::destroyByDevice(loopDevice);
        return -1;
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
    }

    if (mkdir(mountPoint, 0755)) {
        if (errno != EEXIST) {
            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
            if (cleanupDm) {
                Devmapper::destroy(idHash);
            }
            Loop::destroyByDevice(loopDevice);
            return -1;
        }
    }

1803 1804 1805 1806 1807
    /*
     * Wait for the device mapper node to be created.
     */
    waitForDevMapper(dmDevice);

1808 1809
    if (android::vold::vfat::Mount(dmDevice, mountPoint,
            true, false, true, 0, ownerGid, 0227, false)) {
1810 1811 1812 1813 1814 1815 1816 1817
        SLOGE("Image mount failed (%s)", strerror(errno));
        if (cleanupDm) {
            Devmapper::destroy(idHash);
        }
        Loop::destroyByDevice(loopDevice);
        return -1;
    }

Kenny Root's avatar
Kenny Root committed
1818
    mActiveContainers->push_back(new ContainerData(strdup(img), OBB));
1819 1820 1821 1822 1823 1824
    if (mDebug) {
        SLOGD("Image %s mounted", img);
    }
    return 0;
}

Kenny Root's avatar
Kenny Root committed
1825
int VolumeManager::listMountedObbs(SocketClient* cli) {
1826 1827
    FILE *fp = setmntent("/proc/mounts", "r");
    if (fp == NULL) {
Kenny Root's avatar
Kenny Root committed
1828 1829 1830 1831 1832
        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
        return -1;
    }

    // Create a string to compare against that has a trailing slash
Jeff Sharkey's avatar
Jeff Sharkey committed
1833
    int loopDirLen = strlen(VolumeManager::LOOPDIR);
Kenny Root's avatar
Kenny Root committed
1834
    char loopDir[loopDirLen + 2];
Jeff Sharkey's avatar
Jeff Sharkey committed
1835
    strcpy(loopDir, VolumeManager::LOOPDIR);
Kenny Root's avatar
Kenny Root committed
1836 1837 1838
    loopDir[loopDirLen++] = '/';
    loopDir[loopDirLen] = '\0';

1839 1840 1841
    mntent* mentry;
    while ((mentry = getmntent(fp)) != NULL) {
        if (!strncmp(mentry->mnt_dir, loopDir, loopDirLen)) {
1842
            int fd = open(mentry->mnt_fsname, O_RDONLY | O_CLOEXEC);
Kenny Root's avatar
Kenny Root committed
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
            if (fd >= 0) {
                struct loop_info64 li;
                if (ioctl(fd, LOOP_GET_STATUS64, &li) >= 0) {
                    cli->sendMsg(ResponseCode::AsecListResult,
                            (const char*) li.lo_file_name, false);
                }
                close(fd);
            }
        }
    }
1853
    endmntent(fp);
Kenny Root's avatar
Kenny Root committed
1854 1855 1856
    return 0;
}

1857
extern "C" int vold_unmountAll(void) {
1858
    VolumeManager *vm = VolumeManager::Instance();
1859
    return vm->unmountAll();
1860 1861
}

1862 1863
bool VolumeManager::isMountpointMounted(const char *mp)
{
1864 1865
    FILE *fp = setmntent("/proc/mounts", "r");
    if (fp == NULL) {
San Mehat's avatar
San Mehat committed
1866
        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
1867 1868 1869
        return false;
    }

1870 1871 1872 1873 1874 1875
    bool found_mp = false;
    mntent* mentry;
    while ((mentry = getmntent(fp)) != NULL) {
        if (strcmp(mentry->mnt_dir, mp) == 0) {
            found_mp = true;
            break;
1876 1877
        }
    }
1878 1879
    endmntent(fp);
    return found_mp;
1880 1881
}

Jeff Sharkey's avatar
Jeff Sharkey committed
1882
int VolumeManager::mkdirs(char* path) {
1883 1884 1885 1886
    // Only offer to create directories for paths managed by vold
    if (strncmp(path, "/storage/", 9) == 0) {
        // fs_mkdirs() does symlink checking and relative path enforcement
        return fs_mkdirs(path, 0700);
Jeff Sharkey's avatar
Jeff Sharkey committed
1887
    } else {
1888
        SLOGE("Failed to find mounted volume for %s", path);
Jeff Sharkey's avatar
Jeff Sharkey committed
1889 1890 1891
        return -EINVAL;
    }
}