VolumeManager.cpp 44.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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.
 */

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

29
#include <linux/kdev_t.h>
30 31 32

#define LOG_TAG "Vold"

33 34
#include <openssl/md5.h>

Jeff Sharkey's avatar
Jeff Sharkey committed
35
#include <cutils/fs.h>
36 37
#include <cutils/log.h>

38 39
#include <sysutils/NetlinkEvent.h>

40 41
#include <private/android_filesystem_config.h>

42
#include "VolumeManager.h"
43
#include "DirectVolume.h"
44
#include "ResponseCode.h"
45
#include "Loop.h"
46
#include "Ext4.h"
47
#include "Fat.h"
48
#include "Devmapper.h"
49
#include "Process.h"
50
#include "Asec.h"
51
#include "cryptfs.h"
52

53 54
#define MASS_STORAGE_FILE_PATH  "/sys/class/android_usb/android0/f_mass_storage/lun/file"

55 56 57 58 59 60 61 62 63
VolumeManager *VolumeManager::sInstance = NULL;

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

VolumeManager::VolumeManager() {
San Mehat's avatar
San Mehat committed
64
    mDebug = false;
65
    mVolumes = new VolumeCollection();
66
    mActiveContainers = new AsecIdCollection();
67
    mBroadcaster = NULL;
68 69 70 71
    mUmsSharingCount = 0;
    mSavedDirtyRatio = -1;
    // set dirty ratio to 0 when UMS is active
    mUmsDirtyRatio = 0;
72
    mVolManagerDisabled = 0;
73 74 75
}

VolumeManager::~VolumeManager() {
76 77
    delete mVolumes;
    delete mActiveContainers;
78 79
}

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

83
    unsigned char sig[MD5_DIGEST_LENGTH];
San Mehat's avatar
San Mehat committed
84

85 86 87 88 89 90 91 92 93 94 95
    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) {
        SLOGE("Target hash buffer size < %d bytes (%d)",
                MD5_ASCII_LENGTH_PLUS_NULL, len);
San Mehat's avatar
San Mehat committed
96 97 98
        errno = ESPIPE;
        return NULL;
    }
99 100

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

102
    char *p = buffer;
103
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
104 105
        *p++ = digits[sig[i] >> 4];
        *p++ = digits[sig[i] & 0x0F];
San Mehat's avatar
San Mehat committed
106
    }
107
    *p = '\0';
San Mehat's avatar
San Mehat committed
108 109 110 111 112 113 114 115 116 117 118 119

    return buffer;
}

void VolumeManager::setDebug(bool enable) {
    mDebug = enable;
    VolumeCollection::iterator it;
    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
        (*it)->setDebug(enable);
    }
}

120 121 122 123 124 125 126 127 128 129 130 131 132
int VolumeManager::start() {
    return 0;
}

int VolumeManager::stop() {
    return 0;
}

int VolumeManager::addVolume(Volume *v) {
    mVolumes->push_back(v);
    return 0;
}

133 134
void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
    const char *devpath = evt->findParam("DEVPATH");
135

136
    /* Lookup a volume to handle this device */
137 138 139
    VolumeCollection::iterator it;
    bool hit = false;
    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
140
        if (!(*it)->handleBlockEvent(evt)) {
141
#ifdef NETLINK_DEBUG
San Mehat's avatar
San Mehat committed
142
            SLOGD("Device '%s' event handled by volume %s\n", devpath, (*it)->getLabel());
143
#endif
144 145 146 147 148 149
            hit = true;
            break;
        }
    }

    if (!hit) {
150
#ifdef NETLINK_DEBUG
San Mehat's avatar
San Mehat committed
151
        SLOGW("No volumes handled block event for '%s'", devpath);
152
#endif
153 154 155 156 157 158 159 160 161
    }
}

int VolumeManager::listVolumes(SocketClient *cli) {
    VolumeCollection::iterator i;

    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
        char *buffer;
        asprintf(&buffer, "%s %s %d",
162
                 (*i)->getLabel(), (*i)->getFuseMountpoint(),
163
                 (*i)->getState());
164
        cli->sendMsg(ResponseCode::VolumeListResult, buffer, false);
165 166
        free(buffer);
    }
167
    cli->sendMsg(ResponseCode::CommandOkay, "Volumes listed.", false);
168 169
    return 0;
}
170

171
int VolumeManager::formatVolume(const char *label, bool wipe) {
172 173 174 175 176 177 178
    Volume *v = lookupVolume(label);

    if (!v) {
        errno = ENOENT;
        return -1;
    }

179 180 181 182 183
    if (mVolManagerDisabled) {
        errno = EBUSY;
        return -1;
    }

184
    return v->formatVol(wipe);
185 186
}

Kenny Root's avatar
Kenny Root committed
187 188 189 190 191 192 193 194
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);
195 196 197 198 199
    int written = snprintf(mountPath, mountPathLen, "%s/%s", Volume::LOOPDIR, idHash);
    if ((written < 0) || (written >= mountPathLen)) {
        errno = EINVAL;
        return -1;
    }
Kenny Root's avatar
Kenny Root committed
200 201 202 203 204 205 206 207 208

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

    return 0;
}

209
int VolumeManager::getAsecMountPath(const char *id, char *buffer, int maxlen) {
210
    char asecFileName[255];
211 212 213 214 215

    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }
216 217 218 219 220 221

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

223 224 225 226 227 228 229
    int written = snprintf(buffer, maxlen, "%s/%s", Volume::ASECDIR, id);
    if ((written < 0) || (written >= maxlen)) {
        SLOGE("getAsecMountPath failed for %s: couldn't construct path in buffer", id);
        errno = EINVAL;
        return -1;
    }

230 231 232
    return 0;
}

233 234
int VolumeManager::getAsecFilesystemPath(const char *id, char *buffer, int maxlen) {
    char asecFileName[255];
235 236 237 238 239

    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
        SLOGE("Couldn't find ASEC %s", id);
        return -1;
    }
240 241 242 243 244 245 246

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

247 248 249 250 251 252
    int written = snprintf(buffer, maxlen, "%s", asecFileName);
    if ((written < 0) || (written >= maxlen)) {
        errno = EINVAL;
        return -1;
    }

253 254 255
    return 0;
}

256 257
int VolumeManager::createAsec(const char *id, unsigned int numSectors, const char *fstype,
        const char *key, const int ownerUid, bool isExternal) {
258 259 260
    struct asec_superblock sb;
    memset(&sb, 0, sizeof(sb));

261 262 263 264 265 266 267 268 269 270 271 272 273
    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;
        }
    }

274 275
    sb.magic = ASEC_SB_MAGIC;
    sb.ver = ASEC_SB_VER;
276

277
    if (numSectors < ((1024*1024)/512)) {
San Mehat's avatar
San Mehat committed
278
        SLOGE("Invalid container size specified (%d sectors)", numSectors);
279 280 281 282
        errno = EINVAL;
        return -1;
    }

283
    if (lookupVolume(id)) {
San Mehat's avatar
San Mehat committed
284
        SLOGE("ASEC id '%s' currently exists", id);
285 286 287 288 289
        errno = EADDRINUSE;
        return -1;
    }

    char asecFileName[255];
290 291 292 293 294 295 296 297 298 299

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

    const char *asecDir = isExternal ? Volume::SEC_ASECDIR_EXT : Volume::SEC_ASECDIR_INT;

300 301 302 303 304
    int written = snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", asecDir, id);
    if ((written < 0) || (size_t(written) >= sizeof(asecFileName))) {
        errno = EINVAL;
        return -1;
    }
305 306

    if (!access(asecFileName, F_OK)) {
San Mehat's avatar
San Mehat committed
307
        SLOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
308
                asecFileName, strerror(errno));
309 310 311 312
        errno = EADDRINUSE;
        return -1;
    }

313 314 315 316 317 318 319 320 321 322 323 324
    /*
     * Add some headroom
     */
    unsigned fatSize = (((numSectors * 4) / 512) + 1) * 2;
    unsigned numImgSectors = numSectors + fatSize + 2;

    if (numImgSectors % 63) {
        numImgSectors += (63 - (numImgSectors % 63));
    }

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

San Mehat's avatar
San Mehat committed
329 330
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
331
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
332 333 334 335
        unlink(asecFileName);
        return -1;
    }

336
    char loopDevice[255];
San Mehat's avatar
San Mehat committed
337
    if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
338
        SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
339 340 341 342
        unlink(asecFileName);
        return -1;
    }

343 344
    char dmDevice[255];
    bool cleanupDm = false;
345

346
    if (strcmp(key, "none")) {
347 348
        // XXX: This is all we support for now
        sb.c_cipher = ASEC_SB_C_CIPHER_TWOFISH;
San Mehat's avatar
San Mehat committed
349
        if (Devmapper::create(idHash, loopDevice, key, numImgSectors, dmDevice,
350
                             sizeof(dmDevice))) {
San Mehat's avatar
San Mehat committed
351
            SLOGE("ASEC device mapping failed (%s)", strerror(errno));
352 353 354 355 356 357
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
        }
        cleanupDm = true;
    } else {
358
        sb.c_cipher = ASEC_SB_C_CIPHER_NONE;
359 360 361
        strcpy(dmDevice, loopDevice);
    }

362 363 364 365 366 367
    /*
     * Drop down the superblock at the end of the file
     */

    int sbfd = open(loopDevice, O_RDWR);
    if (sbfd < 0) {
San Mehat's avatar
San Mehat committed
368
        SLOGE("Failed to open new DM device for superblock write (%s)", strerror(errno));
369
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
370
            Devmapper::destroy(idHash);
371 372 373 374 375 376 377 378
        }
        Loop::destroyByDevice(loopDevice);
        unlink(asecFileName);
        return -1;
    }

    if (lseek(sbfd, (numImgSectors * 512), SEEK_SET) < 0) {
        close(sbfd);
San Mehat's avatar
San Mehat committed
379
        SLOGE("Failed to lseek for superblock (%s)", strerror(errno));
380
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
381
            Devmapper::destroy(idHash);
382 383 384 385 386 387 388 389
        }
        Loop::destroyByDevice(loopDevice);
        unlink(asecFileName);
        return -1;
    }

    if (write(sbfd, &sb, sizeof(sb)) != sizeof(sb)) {
        close(sbfd);
San Mehat's avatar
San Mehat committed
390
        SLOGE("Failed to write superblock (%s)", strerror(errno));
391
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
392
            Devmapper::destroy(idHash);
393 394 395 396 397 398 399
        }
        Loop::destroyByDevice(loopDevice);
        unlink(asecFileName);
        return -1;
    }
    close(sbfd);

400 401
    if (wantFilesystem) {
        int formatStatus;
402 403
        char mountPoint[255];

404 405 406 407 408 409 410 411 412 413
        int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
        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;
        }
414

415
        if (usingExt4) {
416
            formatStatus = Ext4::format(dmDevice, mountPoint);
417
        } else {
418
            formatStatus = Fat::format(dmDevice, numImgSectors, 0);
419
        }
420

421 422
        if (formatStatus < 0) {
            SLOGE("ASEC fs format failed (%s)", strerror(errno));
423
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
424
                Devmapper::destroy(idHash);
425
            }
426 427 428 429
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
        }
430 431

        if (mkdir(mountPoint, 0000)) {
432
            if (errno != EEXIST) {
San Mehat's avatar
San Mehat committed
433
                SLOGE("Mountpoint creation failed (%s)", strerror(errno));
434
                if (cleanupDm) {
San Mehat's avatar
San Mehat committed
435
                    Devmapper::destroy(idHash);
436 437 438 439 440 441
                }
                Loop::destroyByDevice(loopDevice);
                unlink(asecFileName);
                return -1;
            }
        }
442

443 444 445 446 447 448 449 450 451
        int mountStatus;
        if (usingExt4) {
            mountStatus = Ext4::doMount(dmDevice, mountPoint, false, false, false);
        } else {
            mountStatus = Fat::doMount(dmDevice, mountPoint, false, false, false, ownerUid, 0, 0000,
                    false);
        }

        if (mountStatus) {
San Mehat's avatar
San Mehat committed
452
            SLOGE("ASEC FAT mount failed (%s)", strerror(errno));
453
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
454
                Devmapper::destroy(idHash);
455 456 457 458
            }
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
459
        }
460 461 462 463 464 465 466 467 468 469 470

        if (usingExt4) {
            int dirfd = open(mountPoint, O_DIRECTORY);
            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);
            }
        }
471
    } else {
San Mehat's avatar
San Mehat committed
472
        SLOGI("Created raw secure container %s (no filesystem)", id);
473
    }
474

Kenny Root's avatar
Kenny Root committed
475
    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
476 477 478 479 480 481 482 483
    return 0;
}

int VolumeManager::finalizeAsec(const char *id) {
    char asecFileName[255];
    char loopDevice[255];
    char mountPoint[255];

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

San Mehat's avatar
San Mehat committed
489 490
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
491
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
492 493 494 495
        return -1;
    }

    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
496
        SLOGE("Unable to finalize %s (%s)", id, strerror(errno));
497 498 499
        return -1;
    }

500 501 502 503 504 505 506
    unsigned int nr_sec = 0;
    struct asec_superblock sb;

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

507 508 509 510 511
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("ASEC finalize failed: couldn't construct mountPoint");
        return -1;
    }
512 513 514 515 516 517 518 519 520

    int result = 0;
    if (sb.c_opts & ASEC_SB_C_OPTS_EXT4) {
        result = Ext4::doMount(loopDevice, mountPoint, true, true, true);
    } else {
        result = Fat::doMount(loopDevice, mountPoint, true, true, true, 0, 0, 0227, false);
    }

    if (result) {
San Mehat's avatar
San Mehat committed
521
        SLOGE("ASEC finalize mount failed (%s)", strerror(errno));
522 523 524
        return -1;
    }

San Mehat's avatar
San Mehat committed
525
    if (mDebug) {
San Mehat's avatar
San Mehat committed
526
        SLOGD("ASEC %s finalized", id);
San Mehat's avatar
San Mehat committed
527
    }
528 529 530
    return 0;
}

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
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;
    }

    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;
    }

    unsigned int nr_sec = 0;
    struct asec_superblock sb;

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

564 565 566 567 568
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("Unable remount to fix permissions for %s: couldn't construct mountpoint", id);
        return -1;
    }
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

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

    int ret = Ext4::doMount(loopDevice, mountPoint,
            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);

            int fd = open(ftsent->fts_accpath, O_NOFOLLOW);
            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) {
612
                result |= fchmod(fd, 0755);
613
            } else if (ftsent->fts_info & FTS_F) {
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
                result |= fchmod(fd, privateFile ? 0640 : 0644);
            }
            close(fd);
        }
        fts_close(fts);

        // Finally make the directory readable by everyone.
        int dirfd = open(mountPoint, O_DIRECTORY);
        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;
    }

    result |= Ext4::doMount(loopDevice, mountPoint,
            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;
}

647
int VolumeManager::renameAsec(const char *id1, const char *id2) {
648
    char asecFilename1[255];
649 650 651
    char *asecFilename2;
    char mountPoint[255];

652 653 654 655 656 657 658 659
    const char *dir;

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

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

661 662 663 664 665 666
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id1);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("Rename failed: couldn't construct mountpoint");
        goto out_err;
    }

667
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
668
        SLOGW("Rename attempt when src mounted");
669 670 671 672
        errno = EBUSY;
        goto out_err;
    }

673 674 675 676 677 678
    written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id2);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("Rename failed: couldn't construct mountpoint2");
        goto out_err;
    }

679
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
680
        SLOGW("Rename attempt when dst mounted");
681 682 683 684
        errno = EBUSY;
        goto out_err;
    }

685
    if (!access(asecFilename2, F_OK)) {
San Mehat's avatar
San Mehat committed
686
        SLOGE("Rename attempt when dst exists");
687 688 689 690 691
        errno = EADDRINUSE;
        goto out_err;
    }

    if (rename(asecFilename1, asecFilename2)) {
San Mehat's avatar
San Mehat committed
692
        SLOGE("Rename of '%s' to '%s' failed (%s)", asecFilename1, asecFilename2, strerror(errno));
693 694 695 696 697 698 699 700 701 702 703
        goto out_err;
    }

    free(asecFilename2);
    return 0;

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

704 705
#define UNMOUNT_RETRIES 5
#define UNMOUNT_SLEEP_BETWEEN_RETRY_MS (1000 * 1000)
706
int VolumeManager::unmountAsec(const char *id, bool force) {
707 708 709
    char asecFileName[255];
    char mountPoint[255];

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

715 716 717 718 719
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("ASEC unmount failed for %s: couldn't construct mountpoint", id);
        return -1;
    }
720

San Mehat's avatar
San Mehat committed
721 722
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
723
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
724 725 726
        return -1;
    }

727 728 729
    return unmountLoopImage(id, idHash, asecFileName, mountPoint, force);
}

Kenny Root's avatar
Kenny Root committed
730
int VolumeManager::unmountObb(const char *fileName, bool force) {
731 732 733 734 735 736 737 738
    char mountPoint[255];

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

739 740 741 742 743
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::LOOPDIR, idHash);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("OBB unmount failed for %s: couldn't construct mountpoint", fileName);
        return -1;
    }
744 745 746 747 748 749

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

int VolumeManager::unmountLoopImage(const char *id, const char *idHash,
        const char *fileName, const char *mountPoint, bool force) {
750
    if (!isMountpointMounted(mountPoint)) {
751
        SLOGE("Unmount request for %s when not mounted", id);
752
        errno = ENOENT;
753 754
        return -1;
    }
755

756
    int i, rc;
757
    for (i = 1; i <= UNMOUNT_RETRIES; i++) {
758 759 760
        rc = umount(mountPoint);
        if (!rc) {
            break;
761
        }
762
        if (rc && (errno == EINVAL || errno == ENOENT)) {
763
            SLOGI("Container %s unmounted OK", id);
764 765
            rc = 0;
            break;
766
        }
767
        SLOGW("%s unmount attempt %d failed (%s)",
768 769
              id, i, strerror(errno));

770 771 772
        int action = 0; // default is to just complain

        if (force) {
773
            if (i > (UNMOUNT_RETRIES - 2))
774
                action = 2; // SIGKILL
775
            else if (i > (UNMOUNT_RETRIES - 3))
776 777
                action = 1; // SIGHUP
        }
778

779
        Process::killProcessesWithOpenFiles(mountPoint, action);
780
        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
781 782 783
    }

    if (rc) {
784
        errno = EBUSY;
San Mehat's avatar
San Mehat committed
785
        SLOGE("Failed to unmount container %s (%s)", id, strerror(errno));
786 787 788
        return -1;
    }

789 790 791 792 793 794 795
    int retries = 10;

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

San Mehat's avatar
San Mehat committed
796
        SLOGW("Failed to rmdir %s (%s)", mountPoint, strerror(errno));
797
        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
798 799 800
    }

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

San Mehat's avatar
San Mehat committed
804
    if (Devmapper::destroy(idHash) && errno != ENXIO) {
San Mehat's avatar
San Mehat committed
805
        SLOGE("Failed to destroy devmapper instance (%s)", strerror(errno));
806 807 808
    }

    char loopDevice[255];
San Mehat's avatar
San Mehat committed
809
    if (!Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
810
        Loop::destroyByDevice(loopDevice);
San Mehat's avatar
San Mehat committed
811
    } else {
812
        SLOGW("Failed to find loop device for {%s} (%s)", fileName, strerror(errno));
813
    }
814 815 816

    AsecIdCollection::iterator it;
    for (it = mActiveContainers->begin(); it != mActiveContainers->end(); ++it) {
Kenny Root's avatar
Kenny Root committed
817 818
        ContainerData* cd = *it;
        if (!strcmp(cd->id, id)) {
819 820 821 822 823 824
            free(*it);
            mActiveContainers->erase(it);
            break;
        }
    }
    if (it == mActiveContainers->end()) {
San Mehat's avatar
San Mehat committed
825
        SLOGW("mActiveContainers is inconsistent!");
826
    }
827 828 829
    return 0;
}

830
int VolumeManager::destroyAsec(const char *id, bool force) {
831 832 833
    char asecFileName[255];
    char mountPoint[255];

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

839 840 841 842 843
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("ASEC destroy failed for %s: couldn't construct mountpoint", id);
        return -1;
    }
844

845
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
846
        if (mDebug) {
San Mehat's avatar
San Mehat committed
847
            SLOGD("Unmounting container before destroy");
San Mehat's avatar
San Mehat committed
848
        }
849
        if (unmountAsec(id, force)) {
San Mehat's avatar
San Mehat committed
850
            SLOGE("Failed to unmount asec %s for destroy (%s)", id, strerror(errno));
851 852 853
            return -1;
        }
    }
854

855
    if (unlink(asecFileName)) {
San Mehat's avatar
San Mehat committed
856
        SLOGE("Failed to unlink asec '%s' (%s)", asecFileName, strerror(errno));
857 858
        return -1;
    }
859

San Mehat's avatar
San Mehat committed
860
    if (mDebug) {
San Mehat's avatar
San Mehat committed
861
        SLOGD("ASEC %s destroyed", id);
San Mehat's avatar
San Mehat committed
862
    }
863 864 865
    return 0;
}

866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
bool VolumeManager::isAsecInDirectory(const char *dir, const char *asecName) const {
    int dirfd = open(dir, O_DIRECTORY);
    if (dirfd < 0) {
        SLOGE("Couldn't open internal ASEC dir (%s)", strerror(errno));
        return -1;
    }

    bool ret = false;

    if (!faccessat(dirfd, asecName, F_OK, AT_SYMLINK_NOFOLLOW)) {
        ret = true;
    }

    close(dirfd);

    return ret;
}

int VolumeManager::findAsec(const char *id, char *asecPath, size_t asecPathLen,
        const char **directory) const {
    int dirfd, fd;
    const int idLen = strlen(id);
    char *asecName;

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

    const char *dir;
    if (isAsecInDirectory(Volume::SEC_ASECDIR_INT, asecName)) {
        dir = Volume::SEC_ASECDIR_INT;
    } else if (isAsecInDirectory(Volume::SEC_ASECDIR_EXT, asecName)) {
        dir = Volume::SEC_ASECDIR_EXT;
    } else {
        free(asecName);
        return -1;
    }

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

    if (asecPath != NULL) {
        int written = snprintf(asecPath, asecPathLen, "%s/%s", dir, asecName);
911 912
        if ((written < 0) || (size_t(written) >= asecPathLen)) {
            SLOGE("findAsec failed for %s: couldn't construct ASEC path", id);
913 914 915 916 917 918 919 920 921
            free(asecName);
            return -1;
        }
    }

    free(asecName);
    return 0;
}

922 923 924 925
int VolumeManager::mountAsec(const char *id, const char *key, int ownerUid) {
    char asecFileName[255];
    char mountPoint[255];

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

931 932 933 934 935
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("ASEC mount failed: couldn't construct mountpoint", id);
        return -1;
    }
936 937

    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
938
        SLOGE("ASEC %s already mounted", id);
939 940 941 942
        errno = EBUSY;
        return -1;
    }

San Mehat's avatar
San Mehat committed
943 944
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
945
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
946 947
        return -1;
    }
948

949
    char loopDevice[255];
San Mehat's avatar
San Mehat committed
950 951
    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
        if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
952
            SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
953 954
            return -1;
        }
San Mehat's avatar
San Mehat committed
955
        if (mDebug) {
San Mehat's avatar
San Mehat committed
956
            SLOGD("New loop device created at %s", loopDevice);
San Mehat's avatar
San Mehat committed
957
        }
958
    } else {
San Mehat's avatar
San Mehat committed
959
        if (mDebug) {
San Mehat's avatar
San Mehat committed
960
            SLOGD("Found active loopback for %s at %s", asecFileName, loopDevice);
San Mehat's avatar
San Mehat committed
961
        }
962 963 964 965
    }

    char dmDevice[255];
    bool cleanupDm = false;
966 967 968
    int fd;
    unsigned int nr_sec = 0;
    struct asec_superblock sb;
969 970

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

San Mehat's avatar
San Mehat committed
974
    if (mDebug) {
San Mehat's avatar
San Mehat committed
975
        SLOGD("Container sb magic/ver (%.8x/%.2x)", sb.magic, sb.ver);
San Mehat's avatar
San Mehat committed
976
    }
977
    if (sb.magic != ASEC_SB_MAGIC || sb.ver != ASEC_SB_VER) {
San Mehat's avatar
San Mehat committed
978
        SLOGE("Bad container magic/version (%.8x/%.2x)", sb.magic, sb.ver);
979 980 981 982 983 984 985
        Loop::destroyByDevice(loopDevice);
        errno = EMEDIUMTYPE;
        return -1;
    }
    nr_sec--; // We don't want the devmapping to extend onto our superblock

    if (strcmp(key, "none")) {
San Mehat's avatar
San Mehat committed
986 987
        if (Devmapper::lookupActive(idHash, dmDevice, sizeof(dmDevice))) {
            if (Devmapper::create(idHash, loopDevice, key, nr_sec,
988
                                  dmDevice, sizeof(dmDevice))) {
San Mehat's avatar
San Mehat committed
989
                SLOGE("ASEC device mapping failed (%s)", strerror(errno));
990 991 992
                Loop::destroyByDevice(loopDevice);
                return -1;
            }
San Mehat's avatar
San Mehat committed
993
            if (mDebug) {
San Mehat's avatar
San Mehat committed
994
                SLOGD("New devmapper instance created at %s", dmDevice);
San Mehat's avatar
San Mehat committed
995
            }
996
        } else {
San Mehat's avatar
San Mehat committed
997
            if (mDebug) {
San Mehat's avatar
San Mehat committed
998
                SLOGD("Found active devmapper for %s at %s", asecFileName, dmDevice);
San Mehat's avatar
San Mehat committed
999
            }
1000 1001 1002 1003
        }
        cleanupDm = true;
    } else {
        strcpy(dmDevice, loopDevice);
1004 1005
    }

1006
    if (mkdir(mountPoint, 0000)) {
1007
        if (errno != EEXIST) {
San Mehat's avatar
San Mehat committed
1008
            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
1009
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
1010
                Devmapper::destroy(idHash);
1011 1012 1013 1014
            }
            Loop::destroyByDevice(loopDevice);
            return -1;
        }
1015 1016
    }

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    /*
     * The device mapper node needs 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);
    }

1030 1031 1032 1033 1034 1035 1036 1037
    int result;
    if (sb.c_opts & ASEC_SB_C_OPTS_EXT4) {
        result = Ext4::doMount(dmDevice, mountPoint, true, false, true);
    } else {
        result = Fat::doMount(dmDevice, mountPoint, true, false, true, ownerUid, 0, 0222, false);
    }

    if (result) {
San Mehat's avatar
San Mehat committed
1038
        SLOGE("ASEC mount failed (%s)", strerror(errno));
1039
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
1040
            Devmapper::destroy(idHash);
1041 1042
        }
        Loop::destroyByDevice(loopDevice);
1043 1044 1045
        return -1;
    }

Kenny Root's avatar
Kenny Root committed
1046
    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
San Mehat's avatar
San Mehat committed
1047
    if (mDebug) {
San Mehat's avatar
San Mehat committed
1048
        SLOGD("ASEC %s mounted", id);
San Mehat's avatar
San Mehat committed
1049
    }
1050 1051 1052
    return 0;
}

1053 1054 1055 1056
Volume* VolumeManager::getVolumeForFile(const char *fileName) {
    VolumeCollection::iterator i;

    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1057
        const char* mountPoint = (*i)->getFuseMountpoint();
1058 1059 1060 1061 1062 1063 1064 1065
        if (!strncmp(fileName, mountPoint, strlen(mountPoint))) {
            return *i;
        }
    }

    return NULL;
}

1066 1067 1068
/**
 * Mounts an image file <code>img</code>.
 */
1069
int VolumeManager::mountObb(const char *img, const char *key, int ownerGid) {
1070 1071 1072 1073 1074 1075 1076 1077
    char mountPoint[255];

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

1078 1079 1080 1081 1082
    int written = snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::LOOPDIR, idHash);
    if ((written < 0) || (size_t(written) >= sizeof(mountPoint))) {
        SLOGE("OBB mount failed: couldn't construct mountpoint", img);
        return -1;
    }
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156

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

    char loopDevice[255];
    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
        if (Loop::create(idHash, img, loopDevice, sizeof(loopDevice))) {
            SLOGE("Image loop device creation failed (%s)", strerror(errno));
            return -1;
        }
        if (mDebug) {
            SLOGD("New loop device created at %s", loopDevice);
        }
    } else {
        if (mDebug) {
            SLOGD("Found active loopback for %s at %s", img, loopDevice);
        }
    }

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

    if ((fd = open(loopDevice, O_RDWR)) < 0) {
        SLOGE("Failed to open loopdevice (%s)", strerror(errno));
        Loop::destroyByDevice(loopDevice);
        return -1;
    }

    if (ioctl(fd, BLKGETSIZE, &nr_sec)) {
        SLOGE("Failed to get loop size (%s)", strerror(errno));
        Loop::destroyByDevice(loopDevice);
        close(fd);
        return -1;
    }

    close(fd);

    if (strcmp(key, "none")) {
        if (Devmapper::lookupActive(idHash, dmDevice, sizeof(dmDevice))) {
            if (Devmapper::create(idHash, loopDevice, key, nr_sec,
                                  dmDevice, sizeof(dmDevice))) {
                SLOGE("ASEC device mapping failed (%s)", strerror(errno));
                Loop::destroyByDevice(loopDevice);
                return -1;
            }
            if (mDebug) {
                SLOGD("New devmapper instance created at %s", dmDevice);
            }
        } else {
            if (mDebug) {
                SLOGD("Found active devmapper for %s at %s", img, dmDevice);
            }
        }
        cleanupDm = true;
    } else {
        strcpy(dmDevice, loopDevice);
    }

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

1157
    if (Fat::doMount(dmDevice, mountPoint, true, false, true, 0, ownerGid,
1158 1159 1160 1161 1162 1163 1164 1165 1166
                     0227, false)) {
        SLOGE("Image mount failed (%s)", strerror(errno));
        if (cleanupDm) {
            Devmapper::destroy(idHash);
        }
        Loop::destroyByDevice(loopDevice);
        return -1;
    }

Kenny Root's avatar
Kenny Root committed
1167
    mActiveContainers->push_back(new ContainerData(strdup(img), OBB));
1168 1169 1170 1171 1172 1173
    if (mDebug) {
        SLOGD("Image %s mounted", img);
    }
    return 0;
}

1174 1175 1176 1177 1178 1179 1180 1181
int VolumeManager::mountVolume(const char *label) {
    Volume *v = lookupVolume(label);

    if (!v) {
        errno = ENOENT;
        return -1;
    }

1182 1183 1184
    return v->mountVol();
}

Kenny Root's avatar
Kenny Root committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
int VolumeManager::listMountedObbs(SocketClient* cli) {
    char device[256];
    char mount_path[256];
    char rest[256];
    FILE *fp;
    char line[1024];

    if (!(fp = fopen("/proc/mounts", "r"))) {
        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
        return -1;
    }

    // Create a string to compare against that has a trailing slash
1198
    int loopDirLen = strlen(Volume::LOOPDIR);
Kenny Root's avatar
Kenny Root committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    char loopDir[loopDirLen + 2];
    strcpy(loopDir, Volume::LOOPDIR);
    loopDir[loopDirLen++] = '/';
    loopDir[loopDirLen] = '\0';

    while(fgets(line, sizeof(line), fp)) {
        line[strlen(line)-1] = '\0';

        /*
         * Should look like:
         * /dev/block/loop0 /mnt/obb/fc99df1323fd36424f864dcb76b76d65 ...
         */
        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);

        if (!strncmp(mount_path, loopDir, loopDirLen)) {
            int fd = open(device, O_RDONLY);
            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);
            }
        }
    }

    fclose(fp);
    return 0;
}

San Mehat's avatar
San Mehat committed
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
int VolumeManager::shareEnabled(const char *label, const char *method, bool *enabled) {
    Volume *v = lookupVolume(label);

    if (!v) {
        errno = ENOENT;
        return -1;
    }

    if (strcmp(method, "ums")) {
        errno = ENOSYS;
        return -1;
    }

    if (v->getState() != Volume::State_Shared) {
        *enabled = false;
San Mehat's avatar
San Mehat committed
1245 1246
    } else {
        *enabled = true;
San Mehat's avatar
San Mehat committed
1247 1248 1249 1250
    }
    return 0;
}

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
int VolumeManager::shareVolume(const char *label, const char *method) {
    Volume *v = lookupVolume(label);

    if (!v) {
        errno = ENOENT;
        return -1;
    }

    /*
     * Eventually, we'll want to support additional share back-ends,
     * some of which may work while the media is mounted. For now,
     * we just support UMS
     */
    if (strcmp(method, "ums")) {
        errno = ENOSYS;
        return -1;
    }

    if (v->getState() == Volume::State_NoMedia) {
        errno = ENODEV;
        return -1;
    }

1274
    if (v->getState() != Volume::State_Idle) {
1275
        // You need to unmount manually befoe sharing
1276 1277 1278 1279
        errno = EBUSY;
        return -1;
    }

1280 1281 1282 1283 1284
    if (mVolManagerDisabled) {
        errno = EBUSY;
        return -1;
    }

1285
    dev_t d = v->getShareDevice();
1286 1287 1288 1289 1290 1291 1292 1293
    if ((MAJOR(d) == 0) && (MINOR(d) == 0)) {
        // This volume does not support raw disk access
        errno = EINVAL;
        return -1;
    }

    int fd;
    char nodepath[255];
1294
    int written = snprintf(nodepath,
1295
             sizeof(nodepath), "/dev/block/vold/%d:%d",
Colin Cross's avatar
Colin Cross committed
1296
             major(d), minor(d));
1297

1298 1299 1300 1301 1302
    if ((written < 0) || (size_t(written) >= sizeof(nodepath))) {
        SLOGE("shareVolume failed: couldn't construct nodepath");
        return -1;
    }

1303
    if ((fd = open(MASS_STORAGE_FILE_PATH, O_WRONLY)) < 0) {
San Mehat's avatar
San Mehat committed
1304
        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
1305 1306 1307 1308
        return -1;
    }

    if (write(fd, nodepath, strlen(nodepath)) < 0) {
San Mehat's avatar
San Mehat committed
1309
        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
1310 1311 1312 1313 1314 1315
        close(fd);
        return -1;
    }

    close(fd);
    v->handleVolumeShared();
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    if (mUmsSharingCount++ == 0) {
        FILE* fp;
        mSavedDirtyRatio = -1; // in case we fail
        if ((fp = fopen("/proc/sys/vm/dirty_ratio", "r+"))) {
            char line[16];
            if (fgets(line, sizeof(line), fp) && sscanf(line, "%d", &mSavedDirtyRatio)) {
                fprintf(fp, "%d\n", mUmsDirtyRatio);
            } else {
                SLOGE("Failed to read dirty_ratio (%s)", strerror(errno));
            }
            fclose(fp);
        } else {
            SLOGE("Failed to open /proc/sys/vm/dirty_ratio (%s)", strerror(errno));
        }
    }
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
    return 0;
}

int VolumeManager::unshareVolume(const char *label, const char *method) {
    Volume *v = lookupVolume(label);

    if (!v) {
        errno = ENOENT;
        return -1;
    }

    if (strcmp(method, "ums")) {
        errno = ENOSYS;
        return -1;
    }

    if (v->getState() != Volume::State_Shared) {
        errno = EINVAL;
        return -1;
    }

    int fd;
1353
    if ((fd = open(MASS_STORAGE_FILE_PATH, O_WRONLY)) < 0) {
San Mehat's avatar
San Mehat committed
1354
        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
1355 1356 1357 1358 1359
        return -1;
    }

    char ch = 0;
    if (write(fd, &ch, 1) < 0) {
San Mehat's avatar
San Mehat committed
1360
        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
1361 1362 1363 1364 1365 1366
        close(fd);
        return -1;
    }

    close(fd);
    v->handleVolumeUnshared();
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    if (--mUmsSharingCount == 0 && mSavedDirtyRatio != -1) {
        FILE* fp;
        if ((fp = fopen("/proc/sys/vm/dirty_ratio", "r+"))) {
            fprintf(fp, "%d\n", mSavedDirtyRatio);
            fclose(fp);
        } else {
            SLOGE("Failed to open /proc/sys/vm/dirty_ratio (%s)", strerror(errno));
        }
        mSavedDirtyRatio = -1;
    }
1377
    return 0;
1378 1379
}

1380
extern "C" int vold_disableVol(const char *label) {
1381
    VolumeManager *vm = VolumeManager::Instance();
1382 1383
    vm->disableVolumeManager();
    vm->unshareVolume(label, "ums");
1384
    return vm->unmountVolume(label, true, false);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
}

extern "C" int vold_getNumDirectVolumes(void) {
    VolumeManager *vm = VolumeManager::Instance();
    return vm->getNumDirectVolumes();
}

int VolumeManager::getNumDirectVolumes(void) {
    VolumeCollection::iterator i;
    int n=0;

    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
        if ((*i)->getShareDevice() != (dev_t)0) {
            n++;
        }
    }
    return n;
}

extern "C" int vold_getDirectVolumeList(struct volume_info *vol_list) {
    VolumeManager *vm = VolumeManager::Instance();
    return vm->getDirectVolumeList(vol_list);
}

int VolumeManager::getDirectVolumeList(struct volume_info *vol_list) {
    VolumeCollection::iterator i;
    int n=0;
    dev_t d;

    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
        if ((d=(*i)->getShareDevice()) != (dev_t)0) {
            (*i)->getVolInfo(&vol_list[n]);
            snprintf(vol_list[n].blk_dev, sizeof(vol_list[n].blk_dev),
Colin Cross's avatar
Colin Cross committed
1418
                     "/dev/block/vold/%d:%d", major(d), minor(d));
1419 1420 1421 1422 1423 1424 1425
            n++;
        }
    }

    return 0;
}

1426
int VolumeManager::unmountVolume(const char *label, bool force, bool revert) {
1427 1428 1429 1430 1431 1432 1433
    Volume *v = lookupVolume(label);

    if (!v) {
        errno = ENOENT;
        return -1;
    }

1434 1435 1436 1437 1438
    if (v->getState() == Volume::State_NoMedia) {
        errno = ENODEV;
        return -1;
    }

1439
    if (v->getState() != Volume::State_Mounted) {
San Mehat's avatar
San Mehat committed
1440
        SLOGW("Attempt to unmount volume which isn't mounted (%d)\n",
1441
             v->getState());
1442
        errno = EBUSY;
1443
        return UNMOUNT_NOT_MOUNTED_ERR;
1444 1445
    }

1446
    cleanupAsec(v, force);
1447

1448
    return v->unmountVol(force, revert);
1449 1450
}

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
extern "C" int vold_unmountAllAsecs(void) {
    int rc;

    VolumeManager *vm = VolumeManager::Instance();
    rc = vm->unmountAllAsecsInDir(Volume::SEC_ASECDIR_EXT);
    if (vm->unmountAllAsecsInDir(Volume::SEC_ASECDIR_INT)) {
        rc = -1;
    }
    return rc;
}

#define ID_BUF_LEN 256
#define ASEC_SUFFIX ".asec"
#define ASEC_SUFFIX_LEN (sizeof(ASEC_SUFFIX) - 1)
int VolumeManager::unmountAllAsecsInDir(const char *directory) {
    DIR *d = opendir(directory);
    int rc = 0;

    if (!d) {
        SLOGE("Could not open asec dir %s", directory);
        return -1;
    }

    size_t dirent_len = offsetof(struct dirent, d_name) +
1475
            fpathconf(dirfd(d), _PC_NAME_MAX) + 1;
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506

    struct dirent *dent = (struct dirent *) malloc(dirent_len);
    if (dent == NULL) {
        SLOGE("Failed to allocate memory for asec dir");
        return -1;
    }

    struct dirent *result;
    while (!readdir_r(d, dent, &result) && result != NULL) {
        if (dent->d_name[0] == '.')
            continue;
        if (dent->d_type != DT_REG)
            continue;
        size_t name_len = strlen(dent->d_name);
        if (name_len > 5 && name_len < (ID_BUF_LEN + ASEC_SUFFIX_LEN - 1) &&
                !strcmp(&dent->d_name[name_len - 5], ASEC_SUFFIX)) {
            char id[ID_BUF_LEN];
            strlcpy(id, dent->d_name, name_len - 4);
            if (unmountAsec(id, true)) {
                /* Register the error, but try to unmount more asecs */
                rc = -1;
            }
        }
    }
    closedir(d);

    free(dent);

    return rc;
}

1507 1508 1509
/*
 * Looks up a volume by it's label or mount-point
 */
1510 1511 1512 1513
Volume *VolumeManager::lookupVolume(const char *label) {
    VolumeCollection::iterator i;

    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1514
        if (label[0] == '/') {
1515
            if (!strcmp(label, (*i)->getFuseMountpoint()))
1516 1517 1518 1519 1520
                return (*i);
        } else {
            if (!strcmp(label, (*i)->getLabel()))
                return (*i);
        }
1521 1522 1523
    }
    return NULL;
}
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533

bool VolumeManager::isMountpointMounted(const char *mp)
{
    char device[256];
    char mount_path[256];
    char rest[256];
    FILE *fp;
    char line[1024];

    if (!(fp = fopen("/proc/mounts", "r"))) {
San Mehat's avatar
San Mehat committed
1534
        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
        return false;
    }

    while(fgets(line, sizeof(line), fp)) {
        line[strlen(line)-1] = '\0';
        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
        if (!strcmp(mount_path, mp)) {
            fclose(fp);
            return true;
        }
    }

    fclose(fp);
    return false;
}

1551
int VolumeManager::cleanupAsec(Volume *v, bool force) {
1552 1553 1554 1555 1556 1557
    int rc = 0;

    char asecFileName[255];

    AsecIdCollection removeAsec;
    AsecIdCollection removeObb;
1558 1559 1560

    for (AsecIdCollection::iterator it = mActiveContainers->begin(); it != mActiveContainers->end();
            ++it) {
Kenny Root's avatar
Kenny Root committed
1561
        ContainerData* cd = *it;
1562

Kenny Root's avatar
Kenny Root committed
1563
        if (cd->type == ASEC) {
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
            if (findAsec(cd->id, asecFileName, sizeof(asecFileName))) {
                SLOGE("Couldn't find ASEC %s; cleaning up", cd->id);
                removeAsec.push_back(cd);
            } else {
                SLOGD("Found ASEC at path %s", asecFileName);
                if (!strncmp(asecFileName, Volume::SEC_ASECDIR_EXT,
                        strlen(Volume::SEC_ASECDIR_EXT))) {
                    removeAsec.push_back(cd);
                }
            }
Kenny Root's avatar
Kenny Root committed
1574
        } else if (cd->type == OBB) {
1575
            if (v == getVolumeForFile(cd->id)) {
1576
                removeObb.push_back(cd);
Kenny Root's avatar
Kenny Root committed
1577 1578 1579
            }
        } else {
            SLOGE("Unknown container type %d!", cd->type);
1580 1581
        }
    }
1582

1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    for (AsecIdCollection::iterator it = removeAsec.begin(); it != removeAsec.end(); ++it) {
        ContainerData *cd = *it;
        SLOGI("Unmounting ASEC %s (dependent on %s)", cd->id, v->getLabel());
        if (unmountAsec(cd->id, force)) {
            SLOGE("Failed to unmount ASEC %s (%s)", cd->id, strerror(errno));
            rc = -1;
        }
    }

    for (AsecIdCollection::iterator it = removeObb.begin(); it != removeObb.end(); ++it) {
1593
        ContainerData *cd = *it;
1594
        SLOGI("Unmounting OBB %s (dependent on %s)", cd->id, v->getLabel());
1595 1596 1597 1598 1599 1600 1601
        if (unmountObb(cd->id, force)) {
            SLOGE("Failed to unmount OBB %s (%s)", cd->id, strerror(errno));
            rc = -1;
        }
    }

    return rc;
1602 1603
}

Jeff Sharkey's avatar
Jeff Sharkey committed
1604 1605 1606 1607
int VolumeManager::mkdirs(char* path) {
    // Require that path lives under a volume we manage
    const char* emulated_source = getenv("EMULATED_STORAGE_SOURCE");
    const char* root = NULL;
1608
    if (emulated_source && !strncmp(path, emulated_source, strlen(emulated_source))) {
Jeff Sharkey's avatar
Jeff Sharkey committed
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
        root = emulated_source;
    } else {
        Volume* vol = getVolumeForFile(path);
        if (vol) {
            root = vol->getMountpoint();
        }
    }

    if (!root) {
        SLOGE("Failed to find volume for %s", path);
        return -EINVAL;
    }

    /* fs_mkdirs() does symlink checking and relative path enforcement */
    return fs_mkdirs(path, 0700);
}