VolumeManager.cpp 24.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 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
    mUsbMassStorageConnected = false;
59 60 61
}

VolumeManager::~VolumeManager() {
62 63
    delete mVolumes;
    delete mActiveContainers;
64 65
}

66 67
#define MD5_ASCII_LENGTH ((MD5_DIGEST_LENGTH*2)+1)

San Mehat's avatar
San Mehat committed
68
char *VolumeManager::asecHash(const char *id, char *buffer, size_t len) {
69
    unsigned char sig[MD5_DIGEST_LENGTH];
San Mehat's avatar
San Mehat committed
70

71
    if (len < MD5_ASCII_LENGTH) {
San Mehat's avatar
San Mehat committed
72
        SLOGE("Target hash buffer size < %d bytes (%d)", MD5_ASCII_LENGTH, len);
San Mehat's avatar
San Mehat committed
73 74 75
        errno = ESPIPE;
        return NULL;
    }
76 77

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

    memset(buffer, 0, len);

81
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
San Mehat's avatar
San Mehat committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        char tmp[3];
        snprintf(tmp, 3, "%.02x", sig[i]);
        strcat(buffer, tmp);
    }

    return buffer;
}

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

98 99 100 101 102 103 104 105 106 107 108 109 110
int VolumeManager::start() {
    return 0;
}

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

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

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
void VolumeManager::notifyUmsConnected(bool connected) {
    char msg[255];

    if (connected) {
        mUsbMassStorageConnected = true;
    } else {
        mUsbMassStorageConnected = false;
    }
    snprintf(msg, sizeof(msg), "Share method ums now %s",
             (connected ? "available" : "unavailable"));

    getBroadcaster()->sendBroadcast(ResponseCode::ShareAvailabilityChange,
                                    msg, false);
}

void VolumeManager::handleSwitchEvent(NetlinkEvent *evt) {
127
    const char *devpath = evt->findParam("DEVPATH");
128 129 130
    const char *name = evt->findParam("SWITCH_NAME");
    const char *state = evt->findParam("SWITCH_STATE");

131
    if (!name || !state) {
San Mehat's avatar
San Mehat committed
132
        SLOGW("Switch %s event missing name/state info", devpath);
133 134 135
        return;
    }

136 137 138 139 140 141 142 143
    if (!strcmp(name, "usb_mass_storage")) {

        if (!strcmp(state, "online"))  {
            notifyUmsConnected(true);
        } else {
            notifyUmsConnected(false);
        }
    } else {
San Mehat's avatar
San Mehat committed
144
        SLOGW("Ignoring unknown switch '%s'", name);
145 146 147
    }
}

148 149
void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
    const char *devpath = evt->findParam("DEVPATH");
150

151
    /* Lookup a volume to handle this device */
152 153 154
    VolumeCollection::iterator it;
    bool hit = false;
    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
155
        if (!(*it)->handleBlockEvent(evt)) {
156
#ifdef NETLINK_DEBUG
San Mehat's avatar
San Mehat committed
157
            SLOGD("Device '%s' event handled by volume %s\n", devpath, (*it)->getLabel());
158
#endif
159 160 161 162 163 164
            hit = true;
            break;
        }
    }

    if (!hit) {
165
#ifdef NETLINK_DEBUG
San Mehat's avatar
San Mehat committed
166
        SLOGW("No volumes handled block event for '%s'", devpath);
167
#endif
168 169 170 171 172 173 174 175 176 177 178
    }
}

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());
179
        cli->sendMsg(ResponseCode::VolumeListResult, buffer, false);
180 181
        free(buffer);
    }
182
    cli->sendMsg(ResponseCode::CommandOkay, "Volumes listed.", false);
183 184
    return 0;
}
185

186 187 188 189 190 191 192 193 194 195 196
int VolumeManager::formatVolume(const char *label) {
    Volume *v = lookupVolume(label);

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

    return v->formatVol();
}

197
int VolumeManager::getAsecMountPath(const char *id, char *buffer, int maxlen) {
198 199 200 201 202 203 204 205
    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;
    }
206

207
    snprintf(buffer, maxlen, "%s/%s", Volume::ASECDIR, id);
208 209 210
    return 0;
}

211
int VolumeManager::createAsec(const char *id, unsigned int numSectors,
212
                              const char *fstype, const char *key, int ownerUid) {
213 214 215 216 217
    struct asec_superblock sb;
    memset(&sb, 0, sizeof(sb));

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

219
    if (numSectors < ((1024*1024)/512)) {
San Mehat's avatar
San Mehat committed
220
        SLOGE("Invalid container size specified (%d sectors)", numSectors);
221 222 223 224
        errno = EINVAL;
        return -1;
    }

225
    if (lookupVolume(id)) {
San Mehat's avatar
San Mehat committed
226
        SLOGE("ASEC id '%s' currently exists", id);
227 228 229 230 231
        errno = EADDRINUSE;
        return -1;
    }

    char asecFileName[255];
232
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
233 234

    if (!access(asecFileName, F_OK)) {
San Mehat's avatar
San Mehat committed
235
        SLOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
236 237 238 239 240
             asecFileName, strerror(errno));
        errno = EADDRINUSE;
        return -1;
    }

241 242 243 244 245 246 247 248 249 250 251 252
    /*
     * 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
253
        SLOGE("ASEC image file creation failed (%s)", strerror(errno));
254 255 256
        return -1;
    }

San Mehat's avatar
San Mehat committed
257 258
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
259
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
260 261 262 263
        unlink(asecFileName);
        return -1;
    }

264
    char loopDevice[255];
San Mehat's avatar
San Mehat committed
265
    if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
266
        SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
267 268 269 270
        unlink(asecFileName);
        return -1;
    }

271 272
    char dmDevice[255];
    bool cleanupDm = false;
273

274
    if (strcmp(key, "none")) {
275 276
        // XXX: This is all we support for now
        sb.c_cipher = ASEC_SB_C_CIPHER_TWOFISH;
San Mehat's avatar
San Mehat committed
277
        if (Devmapper::create(idHash, loopDevice, key, numImgSectors, dmDevice,
278
                             sizeof(dmDevice))) {
San Mehat's avatar
San Mehat committed
279
            SLOGE("ASEC device mapping failed (%s)", strerror(errno));
280 281 282 283 284 285
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
        }
        cleanupDm = true;
    } else {
286
        sb.c_cipher = ASEC_SB_C_CIPHER_NONE;
287 288 289
        strcpy(dmDevice, loopDevice);
    }

290 291 292 293 294 295
    /*
     * 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
296
        SLOGE("Failed to open new DM device for superblock write (%s)", strerror(errno));
297
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
298
            Devmapper::destroy(idHash);
299 300 301 302 303 304 305 306
        }
        Loop::destroyByDevice(loopDevice);
        unlink(asecFileName);
        return -1;
    }

    if (lseek(sbfd, (numImgSectors * 512), SEEK_SET) < 0) {
        close(sbfd);
San Mehat's avatar
San Mehat committed
307
        SLOGE("Failed to lseek for superblock (%s)", strerror(errno));
308
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
309
            Devmapper::destroy(idHash);
310 311 312 313 314 315 316 317
        }
        Loop::destroyByDevice(loopDevice);
        unlink(asecFileName);
        return -1;
    }

    if (write(sbfd, &sb, sizeof(sb)) != sizeof(sb)) {
        close(sbfd);
San Mehat's avatar
San Mehat committed
318
        SLOGE("Failed to write superblock (%s)", strerror(errno));
319
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
320
            Devmapper::destroy(idHash);
321 322 323 324 325 326 327
        }
        Loop::destroyByDevice(loopDevice);
        unlink(asecFileName);
        return -1;
    }
    close(sbfd);

328 329
    if (strcmp(fstype, "none")) {
        if (strcmp(fstype, "fat")) {
San Mehat's avatar
San Mehat committed
330
            SLOGW("Unknown fstype '%s' specified for container", fstype);
331
        }
332

333
        if (Fat::format(dmDevice, numImgSectors)) {
San Mehat's avatar
San Mehat committed
334
            SLOGE("ASEC FAT format failed (%s)", strerror(errno));
335
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
336
                Devmapper::destroy(idHash);
337
            }
338 339 340 341
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
        }
342 343 344 345 346
        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
347
                SLOGE("Mountpoint creation failed (%s)", strerror(errno));
348
                if (cleanupDm) {
San Mehat's avatar
San Mehat committed
349
                    Devmapper::destroy(idHash);
350 351 352 353 354 355
                }
                Loop::destroyByDevice(loopDevice);
                unlink(asecFileName);
                return -1;
            }
        }
356

357 358
        if (Fat::doMount(dmDevice, mountPoint, false, false, ownerUid,
                         0, 0000, false)) {
San Mehat's avatar
San Mehat committed
359
            SLOGE("ASEC FAT mount failed (%s)", strerror(errno));
360
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
361
                Devmapper::destroy(idHash);
362 363 364 365
            }
            Loop::destroyByDevice(loopDevice);
            unlink(asecFileName);
            return -1;
366
        }
367
    } else {
San Mehat's avatar
San Mehat committed
368
        SLOGI("Created raw secure container %s (no filesystem)", id);
369
    }
370 371

    mActiveContainers->push_back(strdup(id));
372 373 374 375 376 377 378 379
    return 0;
}

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

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

San Mehat's avatar
San Mehat committed
382 383
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
384
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
385 386 387 388
        return -1;
    }

    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
389
        SLOGE("Unable to finalize %s (%s)", id, strerror(errno));
390 391 392
        return -1;
    }

393
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
394 395
    // XXX:
    if (Fat::doMount(loopDevice, mountPoint, true, true, 0, 0, 0227, false)) {
San Mehat's avatar
San Mehat committed
396
        SLOGE("ASEC finalize mount failed (%s)", strerror(errno));
397 398 399
        return -1;
    }

San Mehat's avatar
San Mehat committed
400
    if (mDebug) {
San Mehat's avatar
San Mehat committed
401
        SLOGD("ASEC %s finalized", id);
San Mehat's avatar
San Mehat committed
402
    }
403 404 405
    return 0;
}

406 407 408 409 410
int VolumeManager::renameAsec(const char *id1, const char *id2) {
    char *asecFilename1;
    char *asecFilename2;
    char mountPoint[255];

411 412
    asprintf(&asecFilename1, "%s/%s.asec", Volume::SEC_ASECDIR, id1);
    asprintf(&asecFilename2, "%s/%s.asec", Volume::SEC_ASECDIR, id2);
413

414
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id1);
415
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
416
        SLOGW("Rename attempt when src mounted");
417 418 419 420
        errno = EBUSY;
        goto out_err;
    }

421 422
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id2);
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
423
        SLOGW("Rename attempt when dst mounted");
424 425 426 427
        errno = EBUSY;
        goto out_err;
    }

428
    if (!access(asecFilename2, F_OK)) {
San Mehat's avatar
San Mehat committed
429
        SLOGE("Rename attempt when dst exists");
430 431 432 433 434
        errno = EADDRINUSE;
        goto out_err;
    }

    if (rename(asecFilename1, asecFilename2)) {
San Mehat's avatar
San Mehat committed
435
        SLOGE("Rename of '%s' to '%s' failed (%s)", asecFilename1, asecFilename2, strerror(errno));
436 437 438 439 440 441 442 443 444 445 446 447 448
        goto out_err;
    }

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

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

449 450
#define ASEC_UNMOUNT_RETRIES 5
int VolumeManager::unmountAsec(const char *id, bool force) {
451 452 453
    char asecFileName[255];
    char mountPoint[255];

454 455
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
456

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

463
    if (!isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
464
        SLOGE("Unmount request for ASEC %s when not mounted", id);
465 466 467
        errno = EINVAL;
        return -1;
    }
468

469
    int i, rc;
470
    for (i = 1; i <= ASEC_UNMOUNT_RETRIES; i++) {
471 472 473
        rc = umount(mountPoint);
        if (!rc) {
            break;
474
        }
475
        if (rc && (errno == EINVAL || errno == ENOENT)) {
San Mehat's avatar
San Mehat committed
476
            SLOGI("Secure container %s unmounted OK", id);
477 478
            rc = 0;
            break;
479
        }
San Mehat's avatar
San Mehat committed
480
        SLOGW("ASEC %s unmount attempt %d failed (%s)",
481 482
              id, i, strerror(errno));

483 484 485 486 487 488 489 490
        int action = 0; // default is to just complain

        if (force) {
            if (i > (ASEC_UNMOUNT_RETRIES - 2))
                action = 2; // SIGKILL
            else if (i > (ASEC_UNMOUNT_RETRIES - 3))
                action = 1; // SIGHUP
        }
491

492
        Process::killProcessesWithOpenFiles(mountPoint, action);
493
        usleep(1000 * 1000);
494 495 496
    }

    if (rc) {
497
        errno = EBUSY;
San Mehat's avatar
San Mehat committed
498
        SLOGE("Failed to unmount container %s (%s)", id, strerror(errno));
499 500 501
        return -1;
    }

502 503 504 505 506 507 508
    int retries = 10;

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

San Mehat's avatar
San Mehat committed
509
        SLOGW("Failed to rmdir %s (%s)", mountPoint, strerror(errno));
510 511 512 513
        usleep(1000 * 1000);
    }

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

San Mehat's avatar
San Mehat committed
517
    if (Devmapper::destroy(idHash) && errno != ENXIO) {
San Mehat's avatar
San Mehat committed
518
        SLOGE("Failed to destroy devmapper instance (%s)", strerror(errno));
519 520 521
    }

    char loopDevice[255];
San Mehat's avatar
San Mehat committed
522
    if (!Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
523
        Loop::destroyByDevice(loopDevice);
San Mehat's avatar
San Mehat committed
524
    } else {
San Mehat's avatar
San Mehat committed
525
        SLOGW("Failed to find loop device for {%s} (%s)", asecFileName, strerror(errno));
526
    }
527 528 529 530 531 532 533 534 535 536

    AsecIdCollection::iterator it;
    for (it = mActiveContainers->begin(); it != mActiveContainers->end(); ++it) {
        if (!strcmp(*it, id)) {
            free(*it);
            mActiveContainers->erase(it);
            break;
        }
    }
    if (it == mActiveContainers->end()) {
San Mehat's avatar
San Mehat committed
537
        SLOGW("mActiveContainers is inconsistent!");
538
    }
539 540 541
    return 0;
}

542
int VolumeManager::destroyAsec(const char *id, bool force) {
543 544 545
    char asecFileName[255];
    char mountPoint[255];

546
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
547
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
548

549
    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
550
        if (mDebug) {
San Mehat's avatar
San Mehat committed
551
            SLOGD("Unmounting container before destroy");
San Mehat's avatar
San Mehat committed
552
        }
553
        if (unmountAsec(id, force)) {
San Mehat's avatar
San Mehat committed
554
            SLOGE("Failed to unmount asec %s for destroy (%s)", id, strerror(errno));
555 556 557
            return -1;
        }
    }
558

559
    if (unlink(asecFileName)) {
San Mehat's avatar
San Mehat committed
560
        SLOGE("Failed to unlink asec '%s' (%s)", asecFileName, strerror(errno));
561 562
        return -1;
    }
563

San Mehat's avatar
San Mehat committed
564
    if (mDebug) {
San Mehat's avatar
San Mehat committed
565
        SLOGD("ASEC %s destroyed", id);
San Mehat's avatar
San Mehat committed
566
    }
567 568 569 570 571 572 573
    return 0;
}

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

574 575
    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
576 577

    if (isMountpointMounted(mountPoint)) {
San Mehat's avatar
San Mehat committed
578
        SLOGE("ASEC %s already mounted", id);
579 580 581 582
        errno = EBUSY;
        return -1;
    }

San Mehat's avatar
San Mehat committed
583 584
    char idHash[33];
    if (!asecHash(id, idHash, sizeof(idHash))) {
San Mehat's avatar
San Mehat committed
585
        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
San Mehat's avatar
San Mehat committed
586 587
        return -1;
    }
588

589
    char loopDevice[255];
San Mehat's avatar
San Mehat committed
590 591
    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
        if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
San Mehat's avatar
San Mehat committed
592
            SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
593 594
            return -1;
        }
San Mehat's avatar
San Mehat committed
595
        if (mDebug) {
San Mehat's avatar
San Mehat committed
596
            SLOGD("New loop device created at %s", loopDevice);
San Mehat's avatar
San Mehat committed
597
        }
598
    } else {
San Mehat's avatar
San Mehat committed
599
        if (mDebug) {
San Mehat's avatar
San Mehat committed
600
            SLOGD("Found active loopback for %s at %s", asecFileName, loopDevice);
San Mehat's avatar
San Mehat committed
601
        }
602 603 604 605
    }

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

609
    if ((fd = open(loopDevice, O_RDWR)) < 0) {
San Mehat's avatar
San Mehat committed
610
        SLOGE("Failed to open loopdevice (%s)", strerror(errno));
611 612 613
        Loop::destroyByDevice(loopDevice);
        return -1;
    }
614

615
    if (ioctl(fd, BLKGETSIZE, &nr_sec)) {
San Mehat's avatar
San Mehat committed
616
        SLOGE("Failed to get loop size (%s)", strerror(errno));
617 618 619 620 621 622 623 624 625 626 627
        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
628
        SLOGE("lseek failed (%s)", strerror(errno));
629 630 631 632 633
        close(fd);
        Loop::destroyByDevice(loopDevice);
        return -1;
    }
    if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
San Mehat's avatar
San Mehat committed
634
        SLOGE("superblock read failed (%s)", strerror(errno));
635 636 637 638 639 640 641
        close(fd);
        Loop::destroyByDevice(loopDevice);
        return -1;
    }

    close(fd);

San Mehat's avatar
San Mehat committed
642
    if (mDebug) {
San Mehat's avatar
San Mehat committed
643
        SLOGD("Container sb magic/ver (%.8x/%.2x)", sb.magic, sb.ver);
San Mehat's avatar
San Mehat committed
644
    }
645
    if (sb.magic != ASEC_SB_MAGIC || sb.ver != ASEC_SB_VER) {
San Mehat's avatar
San Mehat committed
646
        SLOGE("Bad container magic/version (%.8x/%.2x)", sb.magic, sb.ver);
647 648 649 650 651 652 653
        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
654 655
        if (Devmapper::lookupActive(idHash, dmDevice, sizeof(dmDevice))) {
            if (Devmapper::create(idHash, loopDevice, key, nr_sec,
656
                                  dmDevice, sizeof(dmDevice))) {
San Mehat's avatar
San Mehat committed
657
                SLOGE("ASEC device mapping failed (%s)", strerror(errno));
658 659 660
                Loop::destroyByDevice(loopDevice);
                return -1;
            }
San Mehat's avatar
San Mehat committed
661
            if (mDebug) {
San Mehat's avatar
San Mehat committed
662
                SLOGD("New devmapper instance created at %s", dmDevice);
San Mehat's avatar
San Mehat committed
663
            }
664
        } else {
San Mehat's avatar
San Mehat committed
665
            if (mDebug) {
San Mehat's avatar
San Mehat committed
666
                SLOGD("Found active devmapper for %s at %s", asecFileName, dmDevice);
San Mehat's avatar
San Mehat committed
667
            }
668 669 670 671
        }
        cleanupDm = true;
    } else {
        strcpy(dmDevice, loopDevice);
672 673 674
    }

    if (mkdir(mountPoint, 0777)) {
675
        if (errno != EEXIST) {
San Mehat's avatar
San Mehat committed
676
            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
677
            if (cleanupDm) {
San Mehat's avatar
San Mehat committed
678
                Devmapper::destroy(idHash);
679 680 681 682
            }
            Loop::destroyByDevice(loopDevice);
            return -1;
        }
683 684
    }

685
    if (Fat::doMount(dmDevice, mountPoint, true, false, ownerUid, 0,
686 687
                     0222, false)) {
//                     0227, false)) {
San Mehat's avatar
San Mehat committed
688
        SLOGE("ASEC mount failed (%s)", strerror(errno));
689
        if (cleanupDm) {
San Mehat's avatar
San Mehat committed
690
            Devmapper::destroy(idHash);
691 692
        }
        Loop::destroyByDevice(loopDevice);
693 694 695
        return -1;
    }

696
    mActiveContainers->push_back(strdup(id));
San Mehat's avatar
San Mehat committed
697
    if (mDebug) {
San Mehat's avatar
San Mehat committed
698
        SLOGD("ASEC %s mounted", id);
San Mehat's avatar
San Mehat committed
699
    }
700 701 702
    return 0;
}

703 704 705 706 707 708 709 710
int VolumeManager::mountVolume(const char *label) {
    Volume *v = lookupVolume(label);

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

711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
    return v->mountVol();
}

int VolumeManager::shareAvailable(const char *method, bool *avail) {

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

    if (mUsbMassStorageConnected)
        *avail = true;
    else
        *avail = false;
    return 0;
}

San Mehat's avatar
San Mehat committed
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
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
743 744
    } else {
        *enabled = true;
San Mehat's avatar
San Mehat committed
745 746 747 748
    }
    return 0;
}

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
int VolumeManager::simulate(const char *cmd, const char *arg) {

    if (!strcmp(cmd, "ums")) {
        if (!strcmp(arg, "connect")) {
            notifyUmsConnected(true);
        } else if (!strcmp(arg, "disconnect")) {
            notifyUmsConnected(false);
        } 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;
    }

790
    if (v->getState() != Volume::State_Idle) {
791
        // You need to unmount manually befoe sharing
792 793 794 795
        errno = EBUSY;
        return -1;
    }

796 797 798 799 800 801 802 803 804 805 806 807 808
    dev_t d = v->getDiskDevice();
    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));

809 810
    if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file",
                   O_WRONLY)) < 0) {
San Mehat's avatar
San Mehat committed
811
        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
812 813 814 815
        return -1;
    }

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

    dev_t d = v->getDiskDevice();

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

852
    if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file", O_WRONLY)) < 0) {
San Mehat's avatar
San Mehat committed
853
        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
854 855 856 857 858
        return -1;
    }

    char ch = 0;
    if (write(fd, &ch, 1) < 0) {
San Mehat's avatar
San Mehat committed
859
        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
860 861 862 863 864 865 866
        close(fd);
        return -1;
    }

    close(fd);
    v->handleVolumeUnshared();
    return 0;
867 868
}

869
int VolumeManager::unmountVolume(const char *label, bool force) {
870 871 872 873 874 875 876
    Volume *v = lookupVolume(label);

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

877 878 879 880 881
    if (v->getState() == Volume::State_NoMedia) {
        errno = ENODEV;
        return -1;
    }

882
    if (v->getState() != Volume::State_Mounted) {
San Mehat's avatar
San Mehat committed
883
        SLOGW("Attempt to unmount volume which isn't mounted (%d)\n",
884
             v->getState());
885 886 887 888
        errno = EBUSY;
        return -1;
    }

889 890
    while(mActiveContainers->size()) {
        AsecIdCollection::iterator it = mActiveContainers->begin();
San Mehat's avatar
San Mehat committed
891
        SLOGI("Unmounting ASEC %s (dependant on %s)", *it, v->getMountpoint());
892
        if (unmountAsec(*it, force)) {
San Mehat's avatar
San Mehat committed
893
            SLOGE("Failed to unmount ASEC %s (%s)", *it, strerror(errno));
894
            return -1;
895 896 897
        }
    }

898
    return v->unmountVol(force);
899 900
}

901 902 903
/*
 * Looks up a volume by it's label or mount-point
 */
904 905 906 907
Volume *VolumeManager::lookupVolume(const char *label) {
    VolumeCollection::iterator i;

    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
908 909 910 911 912 913 914
        if (label[0] == '/') {
            if (!strcmp(label, (*i)->getMountpoint()))
                return (*i);
        } else {
            if (!strcmp(label, (*i)->getLabel()))
                return (*i);
        }
915 916 917
    }
    return NULL;
}
918 919 920 921 922 923 924 925 926 927

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
928
        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
        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;
}