VolumeManager.cpp 32.7 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 24 25
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>

26
#include <linux/kdev_t.h>
27 28 29

#define LOG_TAG "Vold"

30 31
#include <openssl/md5.h>

32 33
#include <cutils/log.h>

34 35
#include <sysutils/NetlinkEvent.h>

36
#include "VolumeManager.h"
37
#include "DirectVolume.h"
38
#include "ResponseCode.h"
39 40
#include "Loop.h"
#include "Fat.h"
41
#include "Devmapper.h"
42
#include "Process.h"
43
#include "Asec.h"
44

45 46 47 48 49 50 51 52 53
VolumeManager *VolumeManager::sInstance = NULL;

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

VolumeManager::VolumeManager() {
San Mehat's avatar
San Mehat committed
54
    mDebug = false;
55
    mVolumes = new VolumeCollection();
56
    mActiveContainers = new AsecIdCollection();
57
    mBroadcaster = NULL;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    mUsbMassStorageEnabled = false;
    mUsbConnected = false;

    readInitialState();
}

void VolumeManager::readInitialState() {
    FILE *fp;
    char state[255];

    /*
     * Read the initial mass storage enabled state
     */
    if ((fp = fopen("/sys/devices/virtual/usb_composite/usb_mass_storage/enable", "r"))) {
        if (fgets(state, sizeof(state), fp)) {
            mUsbMassStorageEnabled = !strncmp(state, "1", 1);
        } else {
            SLOGE("Failed to read usb_mass_storage enabled state (%s)", strerror(errno));
        }
        fclose(fp);
    } else {
        SLOGD("USB mass storage support is not enabled in the kernel");
    }

    /*
     * Read the initial USB connected state
     */
    if ((fp = fopen("/sys/devices/virtual/switch/usb_configuration/state", "r"))) {
        if (fgets(state, sizeof(state), fp)) {
            mUsbConnected = !strncmp(state, "1", 1);
        } else {
            SLOGE("Failed to read usb_configuration switch (%s)", strerror(errno));
        }
        fclose(fp);
    } else {
        SLOGD("usb_configuration switch is not enabled in the kernel");
    }
95 96 97
}

VolumeManager::~VolumeManager() {
98 99
    delete mVolumes;
    delete mActiveContainers;
100 101
}

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

105
    unsigned char sig[MD5_DIGEST_LENGTH];
San Mehat's avatar
San Mehat committed
106

107 108 109 110 111 112 113 114 115 116 117
    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
118 119 120
        errno = ESPIPE;
        return NULL;
    }
121 122

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

124
    char *p = buffer;
125
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
126 127
        *p++ = digits[sig[i] >> 4];
        *p++ = digits[sig[i] & 0x0F];
San Mehat's avatar
San Mehat committed
128
    }
129
    *p = '\0';
San Mehat's avatar
San Mehat committed
130 131 132 133 134 135 136 137 138 139 140 141

    return buffer;
}

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

142 143 144 145 146 147 148 149 150 151 152 153 154
int VolumeManager::start() {
    return 0;
}

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

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

155
void VolumeManager::notifyUmsAvailable(bool available) {
156 157 158
    char msg[255];

    snprintf(msg, sizeof(msg), "Share method ums now %s",
159 160
             (available ? "available" : "unavailable"));
    SLOGD(msg);
161 162 163 164 165
    getBroadcaster()->sendBroadcast(ResponseCode::ShareAvailabilityChange,
                                    msg, false);
}

void VolumeManager::handleSwitchEvent(NetlinkEvent *evt) {
166
    const char *devpath = evt->findParam("DEVPATH");
167 168 169
    const char *name = evt->findParam("SWITCH_NAME");
    const char *state = evt->findParam("SWITCH_STATE");

170
    if (!name || !state) {
San Mehat's avatar
San Mehat committed
171
        SLOGW("Switch %s event missing name/state info", devpath);
172 173 174
        return;
    }

175 176 177 178 179 180 181
    bool oldAvailable = massStorageAvailable();
    if (!strcmp(name, "usb_configuration")) {
        mUsbConnected = !strcmp(state, "1");
        SLOGD("USB %s", mUsbConnected ? "connected" : "disconnected");
        bool newAvailable = massStorageAvailable();
        if (newAvailable != oldAvailable) {
            notifyUmsAvailable(newAvailable);
182 183
        }
    } else {
San Mehat's avatar
San Mehat committed
184
        SLOGW("Ignoring unknown switch '%s'", name);
185 186
    }
}
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
void VolumeManager::handleUsbCompositeEvent(NetlinkEvent *evt) {
    const char *function = evt->findParam("FUNCTION");
    const char *enabled = evt->findParam("ENABLED");

    if (!function || !enabled) {
        SLOGW("usb_composite event missing function/enabled info");
        return;
    }

    if (!strcmp(function, "usb_mass_storage")) {
        bool oldAvailable = massStorageAvailable();
        mUsbMassStorageEnabled = !strcmp(enabled, "1");
        SLOGD("usb_mass_storage function %s", mUsbMassStorageEnabled ? "enabled" : "disabled");
        bool newAvailable = massStorageAvailable();
        if (newAvailable != oldAvailable) {
            notifyUmsAvailable(newAvailable);
        }
    }
}
206

207 208
void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
    const char *devpath = evt->findParam("DEVPATH");
209

210
    /* Lookup a volume to handle this device */
211 212 213
    VolumeCollection::iterator it;
    bool hit = false;
    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
214
        if (!(*it)->handleBlockEvent(evt)) {
215
#ifdef NETLINK_DEBUG
San Mehat's avatar
San Mehat committed
216
            SLOGD("Device '%s' event handled by volume %s\n", devpath, (*it)->getLabel());
217
#endif
218 219 220 221 222 223
            hit = true;
            break;
        }
    }

    if (!hit) {
224
#ifdef NETLINK_DEBUG
San Mehat's avatar
San Mehat committed
225
        SLOGW("No volumes handled block event for '%s'", devpath);
226
#endif
227 228 229 230 231 232 233 234 235 236 237
    }
}

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

    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
        char *buffer;
        asprintf(&buffer, "%s %s %d",
                 (*i)->getLabel(), (*i)->getMountpoint(),
                 (*i)->getState());
238
        cli->sendMsg(ResponseCode::VolumeListResult, buffer, false);
239 240
        free(buffer);
    }
241
    cli->sendMsg(ResponseCode::CommandOkay, "Volumes listed.", false);
242 243
    return 0;
}
244

245 246 247 248 249 250 251 252 253 254 255
int VolumeManager::formatVolume(const char *label) {
    Volume *v = lookupVolume(label);

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

    return v->formatVol();
}

Kenny Root's avatar
Kenny Root committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
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);
    snprintf(mountPath, mountPathLen, "%s/%s", Volume::LOOPDIR, idHash);

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

    return 0;
}

274
int VolumeManager::getAsecMountPath(const char *id, char *buffer, int maxlen) {
275 276 277 278 279 280 281 282
    char asecFileName[255];
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);

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

284
    snprintf(buffer, maxlen, "%s/%s", Volume::ASECDIR, id);
285 286 287
    return 0;
}

288
int VolumeManager::createAsec(const char *id, unsigned int numSectors,
289
                              const char *fstype, const char *key, int ownerUid) {
290 291 292 293 294
    struct asec_superblock sb;
    memset(&sb, 0, sizeof(sb));

    sb.magic = ASEC_SB_MAGIC;
    sb.ver = ASEC_SB_VER;
295

296
    if (numSectors < ((1024*1024)/512)) {
San Mehat's avatar
San Mehat committed
297
        SLOGE("Invalid container size specified (%d sectors)", numSectors);
298 299 300 301
        errno = EINVAL;
        return -1;
    }

302
    if (lookupVolume(id)) {
San Mehat's avatar
San Mehat committed
303
        SLOGE("ASEC id '%s' currently exists", id);
304 305 306 307 308
        errno = EADDRINUSE;
        return -1;
    }

    char asecFileName[255];
309
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
310 311

    if (!access(asecFileName, F_OK)) {
San Mehat's avatar
San Mehat committed
312
        SLOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
313 314 315 316 317
             asecFileName, strerror(errno));
        errno = EADDRINUSE;
        return -1;
    }

318 319 320 321 322 323 324 325 326 327 328 329
    /*
     * 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
330
        SLOGE("ASEC image file creation failed (%s)", strerror(errno));
331 332 333
        return -1;
    }

San Mehat's avatar
San Mehat committed
334 335
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
336
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
337 338 339 340
        unlink(asecFileName);
        return -1;
    }

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

348 349
    char dmDevice[255];
    bool cleanupDm = false;
350

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

367 368 369 370 371 372
    /*
     * 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
373
        SLOGE("Failed to open new DM device for superblock write (%s)", strerror(errno));
374
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
375
            Devmapper::destroy(idHash);
376 377 378 379 380 381 382 383
        }
        Loop::destroyByDevice(loopDevice);
        unlink(asecFileName);
        return -1;
    }

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

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

405 406
    if (strcmp(fstype, "none")) {
        if (strcmp(fstype, "fat")) {
San Mehat's avatar
San Mehat committed
407
            SLOGW("Unknown fstype '%s' specified for container", fstype);
408
        }
409

410
        if (Fat::format(dmDevice, numImgSectors)) {
San Mehat's avatar
San Mehat committed
411
            SLOGE("ASEC FAT format failed (%s)", strerror(errno));
412
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
413
                Devmapper::destroy(idHash);
414
            }
415 416 417 418
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
        }
419 420 421 422 423
        char mountPoint[255];

        snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
        if (mkdir(mountPoint, 0777)) {
            if (errno != EEXIST) {
San Mehat's avatar
San Mehat committed
424
                SLOGE("Mountpoint creation failed (%s)", strerror(errno));
425
                if (cleanupDm) {
San Mehat's avatar
San Mehat committed
426
                    Devmapper::destroy(idHash);
427 428 429 430 431 432
                }
                Loop::destroyByDevice(loopDevice);
                unlink(asecFileName);
                return -1;
            }
        }
433

434
        if (Fat::doMount(dmDevice, mountPoint, false, false, false, ownerUid,
435
                         0, 0000, false)) {
San Mehat's avatar
San Mehat committed
436
            SLOGE("ASEC FAT mount failed (%s)", strerror(errno));
437
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
438
                Devmapper::destroy(idHash);
439 440 441 442
            }
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
443
        }
444
    } else {
San Mehat's avatar
San Mehat committed
445
        SLOGI("Created raw secure container %s (no filesystem)", id);
446
    }
447

Kenny Root's avatar
Kenny Root committed
448
    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
449 450 451 452 453 454 455 456
    return 0;
}

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

457
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
458

San Mehat's avatar
San Mehat committed
459 460
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
461
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
462 463 464 465
        return -1;
    }

    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
466
        SLOGE("Unable to finalize %s (%s)", id, strerror(errno));
467 468 469
        return -1;
    }

470
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
471
    // XXX:
472
    if (Fat::doMount(loopDevice, mountPoint, true, true, true, 0, 0, 0227, false)) {
San Mehat's avatar
San Mehat committed
473
        SLOGE("ASEC finalize mount failed (%s)", strerror(errno));
474 475 476
        return -1;
    }

San Mehat's avatar
San Mehat committed
477
    if (mDebug) {
San Mehat's avatar
San Mehat committed
478
        SLOGD("ASEC %s finalized", id);
San Mehat's avatar
San Mehat committed
479
    }
480 481 482
    return 0;
}

483 484 485 486 487
int VolumeManager::renameAsec(const char *id1, const char *id2) {
    char *asecFilename1;
    char *asecFilename2;
    char mountPoint[255];

488 489
    asprintf(&asecFilename1, "%s/%s.asec", Volume::SEC_ASECDIR, id1);
    asprintf(&asecFilename2, "%s/%s.asec", Volume::SEC_ASECDIR, id2);
490

491
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id1);
492
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
493
        SLOGW("Rename attempt when src mounted");
494 495 496 497
        errno = EBUSY;
        goto out_err;
    }

498 499
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id2);
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
500
        SLOGW("Rename attempt when dst mounted");
501 502 503 504
        errno = EBUSY;
        goto out_err;
    }

505
    if (!access(asecFilename2, F_OK)) {
San Mehat's avatar
San Mehat committed
506
        SLOGE("Rename attempt when dst exists");
507 508 509 510 511
        errno = EADDRINUSE;
        goto out_err;
    }

    if (rename(asecFilename1, asecFilename2)) {
San Mehat's avatar
San Mehat committed
512
        SLOGE("Rename of '%s' to '%s' failed (%s)", asecFilename1, asecFilename2, strerror(errno));
513 514 515 516 517 518 519 520 521 522 523 524 525
        goto out_err;
    }

    free(asecFilename1);
    free(asecFilename2);
    return 0;

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

526 527
#define UNMOUNT_RETRIES 5
#define UNMOUNT_SLEEP_BETWEEN_RETRY_MS (1000 * 1000)
528
int VolumeManager::unmountAsec(const char *id, bool force) {
529 530 531
    char asecFileName[255];
    char mountPoint[255];

532 533
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
534

San Mehat's avatar
San Mehat committed
535 536
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
537
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
538 539 540
        return -1;
    }

541 542 543
    return unmountLoopImage(id, idHash, asecFileName, mountPoint, force);
}

Kenny Root's avatar
Kenny Root committed
544
int VolumeManager::unmountObb(const char *fileName, bool force) {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    char mountPoint[255];

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

    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::LOOPDIR, idHash);

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

int VolumeManager::unmountLoopImage(const char *id, const char *idHash,
        const char *fileName, const char *mountPoint, bool force) {
560
    if (!isMountpointMounted(mountPoint)) {
561
        SLOGE("Unmount request for %s when not mounted", id);
562 563 564
        errno = EINVAL;
        return -1;
    }
565

566
    int i, rc;
567
    for (i = 1; i <= UNMOUNT_RETRIES; i++) {
568 569 570
        rc = umount(mountPoint);
        if (!rc) {
            break;
571
        }
572
        if (rc && (errno == EINVAL || errno == ENOENT)) {
573
            SLOGI("Container %s unmounted OK", id);
574 575
            rc = 0;
            break;
576
        }
577
        SLOGW("%s unmount attempt %d failed (%s)",
578 579
              id, i, strerror(errno));

580 581 582
        int action = 0; // default is to just complain

        if (force) {
583
            if (i > (UNMOUNT_RETRIES - 2))
584
                action = 2; // SIGKILL
585
            else if (i > (UNMOUNT_RETRIES - 3))
586 587
                action = 1; // SIGHUP
        }
588

589
        Process::killProcessesWithOpenFiles(mountPoint, action);
590
        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
591 592 593
    }

    if (rc) {
594
        errno = EBUSY;
San Mehat's avatar
San Mehat committed
595
        SLOGE("Failed to unmount container %s (%s)", id, strerror(errno));
596 597 598
        return -1;
    }

599 600 601 602 603 604 605
    int retries = 10;

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

San Mehat's avatar
San Mehat committed
606
        SLOGW("Failed to rmdir %s (%s)", mountPoint, strerror(errno));
607
        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
608 609 610
    }

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

San Mehat's avatar
San Mehat committed
614
    if (Devmapper::destroy(idHash) && errno != ENXIO) {
San Mehat's avatar
San Mehat committed
615
        SLOGE("Failed to destroy devmapper instance (%s)", strerror(errno));
616 617 618
    }

    char loopDevice[255];
San Mehat's avatar
San Mehat committed
619
    if (!Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
620
        Loop::destroyByDevice(loopDevice);
San Mehat's avatar
San Mehat committed
621
    } else {
622
        SLOGW("Failed to find loop device for {%s} (%s)", fileName, strerror(errno));
623
    }
624 625 626

    AsecIdCollection::iterator it;
    for (it = mActiveContainers->begin(); it != mActiveContainers->end(); ++it) {
Kenny Root's avatar
Kenny Root committed
627 628
        ContainerData* cd = *it;
        if (!strcmp(cd->id, id)) {
629 630 631 632 633 634
            free(*it);
            mActiveContainers->erase(it);
            break;
        }
    }
    if (it == mActiveContainers->end()) {
San Mehat's avatar
San Mehat committed
635
        SLOGW("mActiveContainers is inconsistent!");
636
    }
637 638 639
    return 0;
}

640
int VolumeManager::destroyAsec(const char *id, bool force) {
641 642 643
    char asecFileName[255];
    char mountPoint[255];

644
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
645
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
646

647
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
648
        if (mDebug) {
San Mehat's avatar
San Mehat committed
649
            SLOGD("Unmounting container before destroy");
San Mehat's avatar
San Mehat committed
650
        }
651
        if (unmountAsec(id, force)) {
San Mehat's avatar
San Mehat committed
652
            SLOGE("Failed to unmount asec %s for destroy (%s)", id, strerror(errno));
653 654 655
            return -1;
        }
    }
656

657
    if (unlink(asecFileName)) {
San Mehat's avatar
San Mehat committed
658
        SLOGE("Failed to unlink asec '%s' (%s)", asecFileName, strerror(errno));
659 660
        return -1;
    }
661

San Mehat's avatar
San Mehat committed
662
    if (mDebug) {
San Mehat's avatar
San Mehat committed
663
        SLOGD("ASEC %s destroyed", id);
San Mehat's avatar
San Mehat committed
664
    }
665 666 667 668 669 670 671
    return 0;
}

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

672 673
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
674 675

    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
676
        SLOGE("ASEC %s already mounted", id);
677 678 679 680
        errno = EBUSY;
        return -1;
    }

San Mehat's avatar
San Mehat committed
681 682
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
683
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
684 685
        return -1;
    }
686

687
    char loopDevice[255];
San Mehat's avatar
San Mehat committed
688 689
    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
        if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
690
            SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
691 692
            return -1;
        }
San Mehat's avatar
San Mehat committed
693
        if (mDebug) {
San Mehat's avatar
San Mehat committed
694
            SLOGD("New loop device created at %s", loopDevice);
San Mehat's avatar
San Mehat committed
695
        }
696
    } else {
San Mehat's avatar
San Mehat committed
697
        if (mDebug) {
San Mehat's avatar
San Mehat committed
698
            SLOGD("Found active loopback for %s at %s", asecFileName, loopDevice);
San Mehat's avatar
San Mehat committed
699
        }
700 701 702 703
    }

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

707
    if ((fd = open(loopDevice, O_RDWR)) < 0) {
San Mehat's avatar
San Mehat committed
708
        SLOGE("Failed to open loopdevice (%s)", strerror(errno));
709 710 711
        Loop::destroyByDevice(loopDevice);
        return -1;
    }
712

713
    if (ioctl(fd, BLKGETSIZE, &nr_sec)) {
San Mehat's avatar
San Mehat committed
714
        SLOGE("Failed to get loop size (%s)", strerror(errno));
715 716 717 718 719 720 721 722 723 724 725
        Loop::destroyByDevice(loopDevice);
        close(fd);
        return -1;
    }

    /*
     * Validate superblock
     */
    struct asec_superblock sb;
    memset(&sb, 0, sizeof(sb));
    if (lseek(fd, ((nr_sec-1) * 512), SEEK_SET) < 0) {
San Mehat's avatar
San Mehat committed
726
        SLOGE("lseek failed (%s)", strerror(errno));
727 728 729 730 731
        close(fd);
        Loop::destroyByDevice(loopDevice);
        return -1;
    }
    if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
San Mehat's avatar
San Mehat committed
732
        SLOGE("superblock read failed (%s)", strerror(errno));
733 734 735 736 737 738 739
        close(fd);
        Loop::destroyByDevice(loopDevice);
        return -1;
    }

    close(fd);

San Mehat's avatar
San Mehat committed
740
    if (mDebug) {
San Mehat's avatar
San Mehat committed
741
        SLOGD("Container sb magic/ver (%.8x/%.2x)", sb.magic, sb.ver);
San Mehat's avatar
San Mehat committed
742
    }
743
    if (sb.magic != ASEC_SB_MAGIC || sb.ver != ASEC_SB_VER) {
San Mehat's avatar
San Mehat committed
744
        SLOGE("Bad container magic/version (%.8x/%.2x)", sb.magic, sb.ver);
745 746 747 748 749 750 751
        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
752 753
        if (Devmapper::lookupActive(idHash, dmDevice, sizeof(dmDevice))) {
            if (Devmapper::create(idHash, loopDevice, key, nr_sec,
754
                                  dmDevice, sizeof(dmDevice))) {
San Mehat's avatar
San Mehat committed
755
                SLOGE("ASEC device mapping failed (%s)", strerror(errno));
756 757 758
                Loop::destroyByDevice(loopDevice);
                return -1;
            }
San Mehat's avatar
San Mehat committed
759
            if (mDebug) {
San Mehat's avatar
San Mehat committed
760
                SLOGD("New devmapper instance created at %s", dmDevice);
San Mehat's avatar
San Mehat committed
761
            }
762
        } else {
San Mehat's avatar
San Mehat committed
763
            if (mDebug) {
San Mehat's avatar
San Mehat committed
764
                SLOGD("Found active devmapper for %s at %s", asecFileName, dmDevice);
San Mehat's avatar
San Mehat committed
765
            }
766 767 768 769
        }
        cleanupDm = true;
    } else {
        strcpy(dmDevice, loopDevice);
770 771 772
    }

    if (mkdir(mountPoint, 0777)) {
773
        if (errno != EEXIST) {
San Mehat's avatar
San Mehat committed
774
            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
775
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
776
                Devmapper::destroy(idHash);
777 778 779 780
            }
            Loop::destroyByDevice(loopDevice);
            return -1;
        }
781 782
    }

783
    if (Fat::doMount(dmDevice, mountPoint, true, false, true, ownerUid, 0,
784 785
                     0222, false)) {
//                     0227, false)) {
San Mehat's avatar
San Mehat committed
786
        SLOGE("ASEC mount failed (%s)", strerror(errno));
787
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
788
            Devmapper::destroy(idHash);
789 790
        }
        Loop::destroyByDevice(loopDevice);
791 792 793
        return -1;
    }

Kenny Root's avatar
Kenny Root committed
794
    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
San Mehat's avatar
San Mehat committed
795
    if (mDebug) {
San Mehat's avatar
San Mehat committed
796
        SLOGD("ASEC %s mounted", id);
San Mehat's avatar
San Mehat committed
797
    }
798 799 800
    return 0;
}

801 802 803
/**
 * Mounts an image file <code>img</code>.
 */
Kenny Root's avatar
Kenny Root committed
804
int VolumeManager::mountObb(const char *img, const char *key, int ownerUid) {
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
    char mountPoint[255];

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

    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::LOOPDIR, idHash);

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

888
    if (Fat::doMount(dmDevice, mountPoint, true, false, true, ownerUid, 0,
889 890 891 892 893 894 895 896 897
                     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
898
    mActiveContainers->push_back(new ContainerData(strdup(img), OBB));
899 900 901 902 903 904
    if (mDebug) {
        SLOGD("Image %s mounted", img);
    }
    return 0;
}

905 906 907 908 909 910 911 912
int VolumeManager::mountVolume(const char *label) {
    Volume *v = lookupVolume(label);

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

913 914 915
    return v->mountVol();
}

Kenny Root's avatar
Kenny Root committed
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
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
    int loopDirLen = sizeof(Volume::LOOPDIR);
    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;
}

961 962 963 964 965 966 967
int VolumeManager::shareAvailable(const char *method, bool *avail) {

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

968
    *avail = massStorageAvailable();
969 970 971
    return 0;
}

San Mehat's avatar
San Mehat committed
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
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
987 988
    } else {
        *enabled = true;
San Mehat's avatar
San Mehat committed
989 990 991 992
    }
    return 0;
}

993 994 995 996
int VolumeManager::simulate(const char *cmd, const char *arg) {

    if (!strcmp(cmd, "ums")) {
        if (!strcmp(arg, "connect")) {
997
            notifyUmsAvailable(true);
998
        } else if (!strcmp(arg, "disconnect")) {
999
            notifyUmsAvailable(false);
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        } else {
            errno = EINVAL;
            return -1;
        }
    } else {
        errno = EINVAL;
        return -1;
    }
    return 0;
}

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

1034
    if (v->getState() != Volume::State_Idle) {
1035
        // You need to unmount manually befoe sharing
1036 1037 1038 1039
        errno = EBUSY;
        return -1;
    }

1040
    dev_t d = v->getShareDevice();
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    if ((MAJOR(d) == 0) && (MINOR(d) == 0)) {
        // This volume does not support raw disk access
        errno = EINVAL;
        return -1;
    }

    int fd;
    char nodepath[255];
    snprintf(nodepath,
             sizeof(nodepath), "/dev/block/vold/%d:%d",
             MAJOR(d), MINOR(d));

1053 1054
    if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file",
                   O_WRONLY)) < 0) {
San Mehat's avatar
San Mehat committed
1055
        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
1056 1057 1058 1059
        return -1;
    }

    if (write(fd, nodepath, strlen(nodepath)) < 0) {
San Mehat's avatar
San Mehat committed
1060
        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
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
        close(fd);
        return -1;
    }

    close(fd);
    v->handleVolumeShared();
    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;
1089
    if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file", O_WRONLY)) < 0) {
San Mehat's avatar
San Mehat committed
1090
        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
1091 1092 1093 1094 1095
        return -1;
    }

    char ch = 0;
    if (write(fd, &ch, 1) < 0) {
San Mehat's avatar
San Mehat committed
1096
        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
1097 1098 1099 1100 1101 1102 1103
        close(fd);
        return -1;
    }

    close(fd);
    v->handleVolumeUnshared();
    return 0;
1104 1105
}

1106
int VolumeManager::unmountVolume(const char *label, bool force) {
1107 1108 1109 1110 1111 1112 1113
    Volume *v = lookupVolume(label);

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

1114 1115 1116 1117 1118
    if (v->getState() == Volume::State_NoMedia) {
        errno = ENODEV;
        return -1;
    }

1119
    if (v->getState() != Volume::State_Mounted) {
San Mehat's avatar
San Mehat committed
1120
        SLOGW("Attempt to unmount volume which isn't mounted (%d)\n",
1121
             v->getState());
1122 1123 1124 1125
        errno = EBUSY;
        return -1;
    }

1126
    cleanupAsec(v, force);
1127

1128
    return v->unmountVol(force);
1129 1130
}

1131 1132 1133
/*
 * Looks up a volume by it's label or mount-point
 */
1134 1135 1136 1137
Volume *VolumeManager::lookupVolume(const char *label) {
    VolumeCollection::iterator i;

    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1138 1139 1140 1141 1142 1143 1144
        if (label[0] == '/') {
            if (!strcmp(label, (*i)->getMountpoint()))
                return (*i);
        } else {
            if (!strcmp(label, (*i)->getLabel()))
                return (*i);
        }
1145 1146 1147
    }
    return NULL;
}
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

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
1158
        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
        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;
}

1175 1176 1177
int VolumeManager::cleanupAsec(Volume *v, bool force) {
    while(mActiveContainers->size()) {
        AsecIdCollection::iterator it = mActiveContainers->begin();
Kenny Root's avatar
Kenny Root committed
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
        ContainerData* cd = *it;
        SLOGI("Unmounting ASEC %s (dependant on %s)", cd->id, v->getMountpoint());
        if (cd->type == ASEC) {
            if (unmountAsec(cd->id, force)) {
                SLOGE("Failed to unmount ASEC %s (%s)", cd->id, strerror(errno));
                return -1;
            }
        } else if (cd->type == OBB) {
            if (unmountObb(cd->id, force)) {
                SLOGE("Failed to unmount OBB %s (%s)", cd->id, strerror(errno));
                return -1;
            }
        } else {
            SLOGE("Unknown container type %d!", cd->type);
1192 1193 1194 1195 1196 1197
            return -1;
        }
    }
    return 0;
}