VolumeManager.cpp revision 6b715592ec94f9d75ca8119ace824ff729c104c2
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24#include <sys/mount.h>
25
26#include <linux/kdev_t.h>
27
28#define LOG_TAG "Vold"
29
30#include <openssl/md5.h>
31
32#include <cutils/log.h>
33
34#include <sysutils/NetlinkEvent.h>
35
36#include "VolumeManager.h"
37#include "DirectVolume.h"
38#include "ResponseCode.h"
39#include "Loop.h"
40#include "Fat.h"
41#include "Devmapper.h"
42#include "Process.h"
43#include "Asec.h"
44#include "cryptfs.h"
45
46VolumeManager *VolumeManager::sInstance = NULL;
47
48VolumeManager *VolumeManager::Instance() {
49    if (!sInstance)
50        sInstance = new VolumeManager();
51    return sInstance;
52}
53
54VolumeManager::VolumeManager() {
55    mDebug = false;
56    mVolumes = new VolumeCollection();
57    mActiveContainers = new AsecIdCollection();
58    mBroadcaster = NULL;
59    mUmsSharingCount = 0;
60    mSavedDirtyRatio = -1;
61    // set dirty ratio to 0 when UMS is active
62    mUmsDirtyRatio = 0;
63}
64
65VolumeManager::~VolumeManager() {
66    delete mVolumes;
67    delete mActiveContainers;
68}
69
70char *VolumeManager::asecHash(const char *id, char *buffer, size_t len) {
71    static const char* digits = "0123456789abcdef";
72
73    unsigned char sig[MD5_DIGEST_LENGTH];
74
75    if (buffer == NULL) {
76        SLOGE("Destination buffer is NULL");
77        errno = ESPIPE;
78        return NULL;
79    } else if (id == NULL) {
80        SLOGE("Source buffer is NULL");
81        errno = ESPIPE;
82        return NULL;
83    } else if (len < MD5_ASCII_LENGTH_PLUS_NULL) {
84        SLOGE("Target hash buffer size < %d bytes (%d)",
85                MD5_ASCII_LENGTH_PLUS_NULL, len);
86        errno = ESPIPE;
87        return NULL;
88    }
89
90    MD5(reinterpret_cast<const unsigned char*>(id), strlen(id), sig);
91
92    char *p = buffer;
93    for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
94        *p++ = digits[sig[i] >> 4];
95        *p++ = digits[sig[i] & 0x0F];
96    }
97    *p = '\0';
98
99    return buffer;
100}
101
102void VolumeManager::setDebug(bool enable) {
103    mDebug = enable;
104    VolumeCollection::iterator it;
105    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
106        (*it)->setDebug(enable);
107    }
108}
109
110int VolumeManager::start() {
111    return 0;
112}
113
114int VolumeManager::stop() {
115    return 0;
116}
117
118int VolumeManager::addVolume(Volume *v) {
119    mVolumes->push_back(v);
120    return 0;
121}
122
123void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
124    const char *devpath = evt->findParam("DEVPATH");
125
126    /* Lookup a volume to handle this device */
127    VolumeCollection::iterator it;
128    bool hit = false;
129    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
130        if (!(*it)->handleBlockEvent(evt)) {
131#ifdef NETLINK_DEBUG
132            SLOGD("Device '%s' event handled by volume %s\n", devpath, (*it)->getLabel());
133#endif
134            hit = true;
135            break;
136        }
137    }
138
139    if (!hit) {
140#ifdef NETLINK_DEBUG
141        SLOGW("No volumes handled block event for '%s'", devpath);
142#endif
143    }
144}
145
146int VolumeManager::listVolumes(SocketClient *cli) {
147    VolumeCollection::iterator i;
148
149    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
150        char *buffer;
151        asprintf(&buffer, "%s %s %d",
152                 (*i)->getLabel(), (*i)->getMountpoint(),
153                 (*i)->getState());
154        cli->sendMsg(ResponseCode::VolumeListResult, buffer, false);
155        free(buffer);
156    }
157    cli->sendMsg(ResponseCode::CommandOkay, "Volumes listed.", false);
158    return 0;
159}
160
161int VolumeManager::formatVolume(const char *label) {
162    Volume *v = lookupVolume(label);
163
164    if (!v) {
165        errno = ENOENT;
166        return -1;
167    }
168
169    return v->formatVol();
170}
171
172int VolumeManager::getObbMountPath(const char *sourceFile, char *mountPath, int mountPathLen) {
173    char idHash[33];
174    if (!asecHash(sourceFile, idHash, sizeof(idHash))) {
175        SLOGE("Hash of '%s' failed (%s)", sourceFile, strerror(errno));
176        return -1;
177    }
178
179    memset(mountPath, 0, mountPathLen);
180    snprintf(mountPath, mountPathLen, "%s/%s", Volume::LOOPDIR, idHash);
181
182    if (access(mountPath, F_OK)) {
183        errno = ENOENT;
184        return -1;
185    }
186
187    return 0;
188}
189
190int VolumeManager::getAsecMountPath(const char *id, char *buffer, int maxlen) {
191    char asecFileName[255];
192    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
193
194    memset(buffer, 0, maxlen);
195    if (access(asecFileName, F_OK)) {
196        errno = ENOENT;
197        return -1;
198    }
199
200    snprintf(buffer, maxlen, "%s/%s", Volume::ASECDIR, id);
201    return 0;
202}
203
204int VolumeManager::createAsec(const char *id, unsigned int numSectors,
205                              const char *fstype, const char *key, int ownerUid) {
206    struct asec_superblock sb;
207    memset(&sb, 0, sizeof(sb));
208
209    sb.magic = ASEC_SB_MAGIC;
210    sb.ver = ASEC_SB_VER;
211
212    if (numSectors < ((1024*1024)/512)) {
213        SLOGE("Invalid container size specified (%d sectors)", numSectors);
214        errno = EINVAL;
215        return -1;
216    }
217
218    if (lookupVolume(id)) {
219        SLOGE("ASEC id '%s' currently exists", id);
220        errno = EADDRINUSE;
221        return -1;
222    }
223
224    char asecFileName[255];
225    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
226
227    if (!access(asecFileName, F_OK)) {
228        SLOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
229             asecFileName, strerror(errno));
230        errno = EADDRINUSE;
231        return -1;
232    }
233
234    /*
235     * Add some headroom
236     */
237    unsigned fatSize = (((numSectors * 4) / 512) + 1) * 2;
238    unsigned numImgSectors = numSectors + fatSize + 2;
239
240    if (numImgSectors % 63) {
241        numImgSectors += (63 - (numImgSectors % 63));
242    }
243
244    // Add +1 for our superblock which is at the end
245    if (Loop::createImageFile(asecFileName, numImgSectors + 1)) {
246        SLOGE("ASEC image file creation failed (%s)", strerror(errno));
247        return -1;
248    }
249
250    char idHash[33];
251    if (!asecHash(id, idHash, sizeof(idHash))) {
252        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
253        unlink(asecFileName);
254        return -1;
255    }
256
257    char loopDevice[255];
258    if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
259        SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
260        unlink(asecFileName);
261        return -1;
262    }
263
264    char dmDevice[255];
265    bool cleanupDm = false;
266
267    if (strcmp(key, "none")) {
268        // XXX: This is all we support for now
269        sb.c_cipher = ASEC_SB_C_CIPHER_TWOFISH;
270        if (Devmapper::create(idHash, loopDevice, key, numImgSectors, dmDevice,
271                             sizeof(dmDevice))) {
272            SLOGE("ASEC device mapping failed (%s)", strerror(errno));
273            Loop::destroyByDevice(loopDevice);
274            unlink(asecFileName);
275            return -1;
276        }
277        cleanupDm = true;
278    } else {
279        sb.c_cipher = ASEC_SB_C_CIPHER_NONE;
280        strcpy(dmDevice, loopDevice);
281    }
282
283    /*
284     * Drop down the superblock at the end of the file
285     */
286
287    int sbfd = open(loopDevice, O_RDWR);
288    if (sbfd < 0) {
289        SLOGE("Failed to open new DM device for superblock write (%s)", strerror(errno));
290        if (cleanupDm) {
291            Devmapper::destroy(idHash);
292        }
293        Loop::destroyByDevice(loopDevice);
294        unlink(asecFileName);
295        return -1;
296    }
297
298    if (lseek(sbfd, (numImgSectors * 512), SEEK_SET) < 0) {
299        close(sbfd);
300        SLOGE("Failed to lseek for superblock (%s)", strerror(errno));
301        if (cleanupDm) {
302            Devmapper::destroy(idHash);
303        }
304        Loop::destroyByDevice(loopDevice);
305        unlink(asecFileName);
306        return -1;
307    }
308
309    if (write(sbfd, &sb, sizeof(sb)) != sizeof(sb)) {
310        close(sbfd);
311        SLOGE("Failed to write superblock (%s)", strerror(errno));
312        if (cleanupDm) {
313            Devmapper::destroy(idHash);
314        }
315        Loop::destroyByDevice(loopDevice);
316        unlink(asecFileName);
317        return -1;
318    }
319    close(sbfd);
320
321    if (strcmp(fstype, "none")) {
322        if (strcmp(fstype, "fat")) {
323            SLOGW("Unknown fstype '%s' specified for container", fstype);
324        }
325
326        if (Fat::format(dmDevice, numImgSectors)) {
327            SLOGE("ASEC FAT format failed (%s)", strerror(errno));
328            if (cleanupDm) {
329                Devmapper::destroy(idHash);
330            }
331            Loop::destroyByDevice(loopDevice);
332            unlink(asecFileName);
333            return -1;
334        }
335        char mountPoint[255];
336
337        snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
338        if (mkdir(mountPoint, 0777)) {
339            if (errno != EEXIST) {
340                SLOGE("Mountpoint creation failed (%s)", strerror(errno));
341                if (cleanupDm) {
342                    Devmapper::destroy(idHash);
343                }
344                Loop::destroyByDevice(loopDevice);
345                unlink(asecFileName);
346                return -1;
347            }
348        }
349
350        if (Fat::doMount(dmDevice, mountPoint, false, false, false, ownerUid,
351                         0, 0000, false)) {
352            SLOGE("ASEC FAT mount failed (%s)", strerror(errno));
353            if (cleanupDm) {
354                Devmapper::destroy(idHash);
355            }
356            Loop::destroyByDevice(loopDevice);
357            unlink(asecFileName);
358            return -1;
359        }
360    } else {
361        SLOGI("Created raw secure container %s (no filesystem)", id);
362    }
363
364    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
365    return 0;
366}
367
368int VolumeManager::finalizeAsec(const char *id) {
369    char asecFileName[255];
370    char loopDevice[255];
371    char mountPoint[255];
372
373    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
374
375    char idHash[33];
376    if (!asecHash(id, idHash, sizeof(idHash))) {
377        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
378        return -1;
379    }
380
381    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
382        SLOGE("Unable to finalize %s (%s)", id, strerror(errno));
383        return -1;
384    }
385
386    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
387    // XXX:
388    if (Fat::doMount(loopDevice, mountPoint, true, true, true, 0, 0, 0227, false)) {
389        SLOGE("ASEC finalize mount failed (%s)", strerror(errno));
390        return -1;
391    }
392
393    if (mDebug) {
394        SLOGD("ASEC %s finalized", id);
395    }
396    return 0;
397}
398
399int VolumeManager::renameAsec(const char *id1, const char *id2) {
400    char *asecFilename1;
401    char *asecFilename2;
402    char mountPoint[255];
403
404    asprintf(&asecFilename1, "%s/%s.asec", Volume::SEC_ASECDIR, id1);
405    asprintf(&asecFilename2, "%s/%s.asec", Volume::SEC_ASECDIR, id2);
406
407    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id1);
408    if (isMountpointMounted(mountPoint)) {
409        SLOGW("Rename attempt when src mounted");
410        errno = EBUSY;
411        goto out_err;
412    }
413
414    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id2);
415    if (isMountpointMounted(mountPoint)) {
416        SLOGW("Rename attempt when dst mounted");
417        errno = EBUSY;
418        goto out_err;
419    }
420
421    if (!access(asecFilename2, F_OK)) {
422        SLOGE("Rename attempt when dst exists");
423        errno = EADDRINUSE;
424        goto out_err;
425    }
426
427    if (rename(asecFilename1, asecFilename2)) {
428        SLOGE("Rename of '%s' to '%s' failed (%s)", asecFilename1, asecFilename2, strerror(errno));
429        goto out_err;
430    }
431
432    free(asecFilename1);
433    free(asecFilename2);
434    return 0;
435
436out_err:
437    free(asecFilename1);
438    free(asecFilename2);
439    return -1;
440}
441
442#define UNMOUNT_RETRIES 5
443#define UNMOUNT_SLEEP_BETWEEN_RETRY_MS (1000 * 1000)
444int VolumeManager::unmountAsec(const char *id, bool force) {
445    char asecFileName[255];
446    char mountPoint[255];
447
448    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
449    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
450
451    char idHash[33];
452    if (!asecHash(id, idHash, sizeof(idHash))) {
453        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
454        return -1;
455    }
456
457    return unmountLoopImage(id, idHash, asecFileName, mountPoint, force);
458}
459
460int VolumeManager::unmountObb(const char *fileName, bool force) {
461    char mountPoint[255];
462
463    char idHash[33];
464    if (!asecHash(fileName, idHash, sizeof(idHash))) {
465        SLOGE("Hash of '%s' failed (%s)", fileName, strerror(errno));
466        return -1;
467    }
468
469    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::LOOPDIR, idHash);
470
471    return unmountLoopImage(fileName, idHash, fileName, mountPoint, force);
472}
473
474int VolumeManager::unmountLoopImage(const char *id, const char *idHash,
475        const char *fileName, const char *mountPoint, bool force) {
476    if (!isMountpointMounted(mountPoint)) {
477        SLOGE("Unmount request for %s when not mounted", id);
478        errno = ENOENT;
479        return -1;
480    }
481
482    int i, rc;
483    for (i = 1; i <= UNMOUNT_RETRIES; i++) {
484        rc = umount(mountPoint);
485        if (!rc) {
486            break;
487        }
488        if (rc && (errno == EINVAL || errno == ENOENT)) {
489            SLOGI("Container %s unmounted OK", id);
490            rc = 0;
491            break;
492        }
493        SLOGW("%s unmount attempt %d failed (%s)",
494              id, i, strerror(errno));
495
496        int action = 0; // default is to just complain
497
498        if (force) {
499            if (i > (UNMOUNT_RETRIES - 2))
500                action = 2; // SIGKILL
501            else if (i > (UNMOUNT_RETRIES - 3))
502                action = 1; // SIGHUP
503        }
504
505        Process::killProcessesWithOpenFiles(mountPoint, action);
506        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
507    }
508
509    if (rc) {
510        errno = EBUSY;
511        SLOGE("Failed to unmount container %s (%s)", id, strerror(errno));
512        return -1;
513    }
514
515    int retries = 10;
516
517    while(retries--) {
518        if (!rmdir(mountPoint)) {
519            break;
520        }
521
522        SLOGW("Failed to rmdir %s (%s)", mountPoint, strerror(errno));
523        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
524    }
525
526    if (!retries) {
527        SLOGE("Timed out trying to rmdir %s (%s)", mountPoint, strerror(errno));
528    }
529
530    if (Devmapper::destroy(idHash) && errno != ENXIO) {
531        SLOGE("Failed to destroy devmapper instance (%s)", strerror(errno));
532    }
533
534    char loopDevice[255];
535    if (!Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
536        Loop::destroyByDevice(loopDevice);
537    } else {
538        SLOGW("Failed to find loop device for {%s} (%s)", fileName, strerror(errno));
539    }
540
541    AsecIdCollection::iterator it;
542    for (it = mActiveContainers->begin(); it != mActiveContainers->end(); ++it) {
543        ContainerData* cd = *it;
544        if (!strcmp(cd->id, id)) {
545            free(*it);
546            mActiveContainers->erase(it);
547            break;
548        }
549    }
550    if (it == mActiveContainers->end()) {
551        SLOGW("mActiveContainers is inconsistent!");
552    }
553    return 0;
554}
555
556int VolumeManager::destroyAsec(const char *id, bool force) {
557    char asecFileName[255];
558    char mountPoint[255];
559
560    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
561    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
562
563    if (isMountpointMounted(mountPoint)) {
564        if (mDebug) {
565            SLOGD("Unmounting container before destroy");
566        }
567        if (unmountAsec(id, force)) {
568            SLOGE("Failed to unmount asec %s for destroy (%s)", id, strerror(errno));
569            return -1;
570        }
571    }
572
573    if (unlink(asecFileName)) {
574        SLOGE("Failed to unlink asec '%s' (%s)", asecFileName, strerror(errno));
575        return -1;
576    }
577
578    if (mDebug) {
579        SLOGD("ASEC %s destroyed", id);
580    }
581    return 0;
582}
583
584int VolumeManager::mountAsec(const char *id, const char *key, int ownerUid) {
585    char asecFileName[255];
586    char mountPoint[255];
587
588    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
589    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
590
591    if (isMountpointMounted(mountPoint)) {
592        SLOGE("ASEC %s already mounted", id);
593        errno = EBUSY;
594        return -1;
595    }
596
597    char idHash[33];
598    if (!asecHash(id, idHash, sizeof(idHash))) {
599        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
600        return -1;
601    }
602
603    char loopDevice[255];
604    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
605        if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
606            SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
607            return -1;
608        }
609        if (mDebug) {
610            SLOGD("New loop device created at %s", loopDevice);
611        }
612    } else {
613        if (mDebug) {
614            SLOGD("Found active loopback for %s at %s", asecFileName, loopDevice);
615        }
616    }
617
618    char dmDevice[255];
619    bool cleanupDm = false;
620    int fd;
621    unsigned int nr_sec = 0;
622
623    if ((fd = open(loopDevice, O_RDWR)) < 0) {
624        SLOGE("Failed to open loopdevice (%s)", strerror(errno));
625        Loop::destroyByDevice(loopDevice);
626        return -1;
627    }
628
629    if (ioctl(fd, BLKGETSIZE, &nr_sec)) {
630        SLOGE("Failed to get loop size (%s)", strerror(errno));
631        Loop::destroyByDevice(loopDevice);
632        close(fd);
633        return -1;
634    }
635
636    /*
637     * Validate superblock
638     */
639    struct asec_superblock sb;
640    memset(&sb, 0, sizeof(sb));
641    if (lseek(fd, ((nr_sec-1) * 512), SEEK_SET) < 0) {
642        SLOGE("lseek failed (%s)", strerror(errno));
643        close(fd);
644        Loop::destroyByDevice(loopDevice);
645        return -1;
646    }
647    if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
648        SLOGE("superblock read failed (%s)", strerror(errno));
649        close(fd);
650        Loop::destroyByDevice(loopDevice);
651        return -1;
652    }
653
654    close(fd);
655
656    if (mDebug) {
657        SLOGD("Container sb magic/ver (%.8x/%.2x)", sb.magic, sb.ver);
658    }
659    if (sb.magic != ASEC_SB_MAGIC || sb.ver != ASEC_SB_VER) {
660        SLOGE("Bad container magic/version (%.8x/%.2x)", sb.magic, sb.ver);
661        Loop::destroyByDevice(loopDevice);
662        errno = EMEDIUMTYPE;
663        return -1;
664    }
665    nr_sec--; // We don't want the devmapping to extend onto our superblock
666
667    if (strcmp(key, "none")) {
668        if (Devmapper::lookupActive(idHash, dmDevice, sizeof(dmDevice))) {
669            if (Devmapper::create(idHash, loopDevice, key, nr_sec,
670                                  dmDevice, sizeof(dmDevice))) {
671                SLOGE("ASEC device mapping failed (%s)", strerror(errno));
672                Loop::destroyByDevice(loopDevice);
673                return -1;
674            }
675            if (mDebug) {
676                SLOGD("New devmapper instance created at %s", dmDevice);
677            }
678        } else {
679            if (mDebug) {
680                SLOGD("Found active devmapper for %s at %s", asecFileName, dmDevice);
681            }
682        }
683        cleanupDm = true;
684    } else {
685        strcpy(dmDevice, loopDevice);
686    }
687
688    if (mkdir(mountPoint, 0777)) {
689        if (errno != EEXIST) {
690            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
691            if (cleanupDm) {
692                Devmapper::destroy(idHash);
693            }
694            Loop::destroyByDevice(loopDevice);
695            return -1;
696        }
697    }
698
699    if (Fat::doMount(dmDevice, mountPoint, true, false, true, ownerUid, 0,
700                     0222, false)) {
701//                     0227, false)) {
702        SLOGE("ASEC mount failed (%s)", strerror(errno));
703        if (cleanupDm) {
704            Devmapper::destroy(idHash);
705        }
706        Loop::destroyByDevice(loopDevice);
707        return -1;
708    }
709
710    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
711    if (mDebug) {
712        SLOGD("ASEC %s mounted", id);
713    }
714    return 0;
715}
716
717/**
718 * Mounts an image file <code>img</code>.
719 */
720int VolumeManager::mountObb(const char *img, const char *key, int ownerUid) {
721    char mountPoint[255];
722
723    char idHash[33];
724    if (!asecHash(img, idHash, sizeof(idHash))) {
725        SLOGE("Hash of '%s' failed (%s)", img, strerror(errno));
726        return -1;
727    }
728
729    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::LOOPDIR, idHash);
730
731    if (isMountpointMounted(mountPoint)) {
732        SLOGE("Image %s already mounted", img);
733        errno = EBUSY;
734        return -1;
735    }
736
737    char loopDevice[255];
738    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
739        if (Loop::create(idHash, img, loopDevice, sizeof(loopDevice))) {
740            SLOGE("Image loop device creation failed (%s)", strerror(errno));
741            return -1;
742        }
743        if (mDebug) {
744            SLOGD("New loop device created at %s", loopDevice);
745        }
746    } else {
747        if (mDebug) {
748            SLOGD("Found active loopback for %s at %s", img, loopDevice);
749        }
750    }
751
752    char dmDevice[255];
753    bool cleanupDm = false;
754    int fd;
755    unsigned int nr_sec = 0;
756
757    if ((fd = open(loopDevice, O_RDWR)) < 0) {
758        SLOGE("Failed to open loopdevice (%s)", strerror(errno));
759        Loop::destroyByDevice(loopDevice);
760        return -1;
761    }
762
763    if (ioctl(fd, BLKGETSIZE, &nr_sec)) {
764        SLOGE("Failed to get loop size (%s)", strerror(errno));
765        Loop::destroyByDevice(loopDevice);
766        close(fd);
767        return -1;
768    }
769
770    close(fd);
771
772    if (strcmp(key, "none")) {
773        if (Devmapper::lookupActive(idHash, dmDevice, sizeof(dmDevice))) {
774            if (Devmapper::create(idHash, loopDevice, key, nr_sec,
775                                  dmDevice, sizeof(dmDevice))) {
776                SLOGE("ASEC device mapping failed (%s)", strerror(errno));
777                Loop::destroyByDevice(loopDevice);
778                return -1;
779            }
780            if (mDebug) {
781                SLOGD("New devmapper instance created at %s", dmDevice);
782            }
783        } else {
784            if (mDebug) {
785                SLOGD("Found active devmapper for %s at %s", img, dmDevice);
786            }
787        }
788        cleanupDm = true;
789    } else {
790        strcpy(dmDevice, loopDevice);
791    }
792
793    if (mkdir(mountPoint, 0755)) {
794        if (errno != EEXIST) {
795            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
796            if (cleanupDm) {
797                Devmapper::destroy(idHash);
798            }
799            Loop::destroyByDevice(loopDevice);
800            return -1;
801        }
802    }
803
804    if (Fat::doMount(dmDevice, mountPoint, true, false, true, ownerUid, 0,
805                     0227, false)) {
806        SLOGE("Image mount failed (%s)", strerror(errno));
807        if (cleanupDm) {
808            Devmapper::destroy(idHash);
809        }
810        Loop::destroyByDevice(loopDevice);
811        return -1;
812    }
813
814    mActiveContainers->push_back(new ContainerData(strdup(img), OBB));
815    if (mDebug) {
816        SLOGD("Image %s mounted", img);
817    }
818    return 0;
819}
820
821int VolumeManager::mountVolume(const char *label) {
822    Volume *v = lookupVolume(label);
823
824    if (!v) {
825        errno = ENOENT;
826        return -1;
827    }
828
829    return v->mountVol();
830}
831
832int VolumeManager::listMountedObbs(SocketClient* cli) {
833    char device[256];
834    char mount_path[256];
835    char rest[256];
836    FILE *fp;
837    char line[1024];
838
839    if (!(fp = fopen("/proc/mounts", "r"))) {
840        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
841        return -1;
842    }
843
844    // Create a string to compare against that has a trailing slash
845    int loopDirLen = sizeof(Volume::LOOPDIR);
846    char loopDir[loopDirLen + 2];
847    strcpy(loopDir, Volume::LOOPDIR);
848    loopDir[loopDirLen++] = '/';
849    loopDir[loopDirLen] = '\0';
850
851    while(fgets(line, sizeof(line), fp)) {
852        line[strlen(line)-1] = '\0';
853
854        /*
855         * Should look like:
856         * /dev/block/loop0 /mnt/obb/fc99df1323fd36424f864dcb76b76d65 ...
857         */
858        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
859
860        if (!strncmp(mount_path, loopDir, loopDirLen)) {
861            int fd = open(device, O_RDONLY);
862            if (fd >= 0) {
863                struct loop_info64 li;
864                if (ioctl(fd, LOOP_GET_STATUS64, &li) >= 0) {
865                    cli->sendMsg(ResponseCode::AsecListResult,
866                            (const char*) li.lo_file_name, false);
867                }
868                close(fd);
869            }
870        }
871    }
872
873    fclose(fp);
874    return 0;
875}
876
877int VolumeManager::shareEnabled(const char *label, const char *method, bool *enabled) {
878    Volume *v = lookupVolume(label);
879
880    if (!v) {
881        errno = ENOENT;
882        return -1;
883    }
884
885    if (strcmp(method, "ums")) {
886        errno = ENOSYS;
887        return -1;
888    }
889
890    if (v->getState() != Volume::State_Shared) {
891        *enabled = false;
892    } else {
893        *enabled = true;
894    }
895    return 0;
896}
897
898int VolumeManager::shareVolume(const char *label, const char *method) {
899    Volume *v = lookupVolume(label);
900
901    if (!v) {
902        errno = ENOENT;
903        return -1;
904    }
905
906    /*
907     * Eventually, we'll want to support additional share back-ends,
908     * some of which may work while the media is mounted. For now,
909     * we just support UMS
910     */
911    if (strcmp(method, "ums")) {
912        errno = ENOSYS;
913        return -1;
914    }
915
916    if (v->getState() == Volume::State_NoMedia) {
917        errno = ENODEV;
918        return -1;
919    }
920
921    if (v->getState() != Volume::State_Idle) {
922        // You need to unmount manually befoe sharing
923        errno = EBUSY;
924        return -1;
925    }
926
927    dev_t d = v->getShareDevice();
928    if ((MAJOR(d) == 0) && (MINOR(d) == 0)) {
929        // This volume does not support raw disk access
930        errno = EINVAL;
931        return -1;
932    }
933
934    int fd;
935    char nodepath[255];
936    snprintf(nodepath,
937             sizeof(nodepath), "/dev/block/vold/%d:%d",
938             MAJOR(d), MINOR(d));
939
940    if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file",
941                   O_WRONLY)) < 0) {
942        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
943        return -1;
944    }
945
946    if (write(fd, nodepath, strlen(nodepath)) < 0) {
947        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
948        close(fd);
949        return -1;
950    }
951
952    close(fd);
953    v->handleVolumeShared();
954    if (mUmsSharingCount++ == 0) {
955        FILE* fp;
956        mSavedDirtyRatio = -1; // in case we fail
957        if ((fp = fopen("/proc/sys/vm/dirty_ratio", "r+"))) {
958            char line[16];
959            if (fgets(line, sizeof(line), fp) && sscanf(line, "%d", &mSavedDirtyRatio)) {
960                fprintf(fp, "%d\n", mUmsDirtyRatio);
961            } else {
962                SLOGE("Failed to read dirty_ratio (%s)", strerror(errno));
963            }
964            fclose(fp);
965        } else {
966            SLOGE("Failed to open /proc/sys/vm/dirty_ratio (%s)", strerror(errno));
967        }
968    }
969    return 0;
970}
971
972int VolumeManager::unshareVolume(const char *label, const char *method) {
973    Volume *v = lookupVolume(label);
974
975    if (!v) {
976        errno = ENOENT;
977        return -1;
978    }
979
980    if (strcmp(method, "ums")) {
981        errno = ENOSYS;
982        return -1;
983    }
984
985    if (v->getState() != Volume::State_Shared) {
986        errno = EINVAL;
987        return -1;
988    }
989
990    int fd;
991    if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file", O_WRONLY)) < 0) {
992        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
993        return -1;
994    }
995
996    char ch = 0;
997    if (write(fd, &ch, 1) < 0) {
998        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
999        close(fd);
1000        return -1;
1001    }
1002
1003    close(fd);
1004    v->handleVolumeUnshared();
1005    if (--mUmsSharingCount == 0 && mSavedDirtyRatio != -1) {
1006        FILE* fp;
1007        if ((fp = fopen("/proc/sys/vm/dirty_ratio", "r+"))) {
1008            fprintf(fp, "%d\n", mSavedDirtyRatio);
1009            fclose(fp);
1010        } else {
1011            SLOGE("Failed to open /proc/sys/vm/dirty_ratio (%s)", strerror(errno));
1012        }
1013        mSavedDirtyRatio = -1;
1014    }
1015    return 0;
1016}
1017
1018extern "C" int vold_unmountVol(const char *label) {
1019    VolumeManager *vm = VolumeManager::Instance();
1020    return vm->unmountVolume(label, true);
1021}
1022
1023extern "C" int vold_getNumDirectVolumes(void) {
1024    VolumeManager *vm = VolumeManager::Instance();
1025    return vm->getNumDirectVolumes();
1026}
1027
1028int VolumeManager::getNumDirectVolumes(void) {
1029    VolumeCollection::iterator i;
1030    int n=0;
1031
1032    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1033        if ((*i)->getShareDevice() != (dev_t)0) {
1034            n++;
1035        }
1036    }
1037    return n;
1038}
1039
1040extern "C" int vold_getDirectVolumeList(struct volume_info *vol_list) {
1041    VolumeManager *vm = VolumeManager::Instance();
1042    return vm->getDirectVolumeList(vol_list);
1043}
1044
1045int VolumeManager::getDirectVolumeList(struct volume_info *vol_list) {
1046    VolumeCollection::iterator i;
1047    int n=0;
1048    dev_t d;
1049
1050    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1051        if ((d=(*i)->getShareDevice()) != (dev_t)0) {
1052            (*i)->getVolInfo(&vol_list[n]);
1053            snprintf(vol_list[n].blk_dev, sizeof(vol_list[n].blk_dev),
1054                     "/dev/block/vold/%d:%d",MAJOR(d), MINOR(d));
1055            n++;
1056        }
1057    }
1058
1059    return 0;
1060}
1061
1062int VolumeManager::unmountVolume(const char *label, bool force) {
1063    Volume *v = lookupVolume(label);
1064
1065    if (!v) {
1066        errno = ENOENT;
1067        return -1;
1068    }
1069
1070    if (v->getState() == Volume::State_NoMedia) {
1071        errno = ENODEV;
1072        return -1;
1073    }
1074
1075    if (v->getState() != Volume::State_Mounted) {
1076        SLOGW("Attempt to unmount volume which isn't mounted (%d)\n",
1077             v->getState());
1078        errno = EBUSY;
1079        return UNMOUNT_NOT_MOUNTED_ERR;
1080    }
1081
1082    cleanupAsec(v, force);
1083
1084    return v->unmountVol(force);
1085}
1086
1087/*
1088 * Looks up a volume by it's label or mount-point
1089 */
1090Volume *VolumeManager::lookupVolume(const char *label) {
1091    VolumeCollection::iterator i;
1092
1093    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1094        if (label[0] == '/') {
1095            if (!strcmp(label, (*i)->getMountpoint()))
1096                return (*i);
1097        } else {
1098            if (!strcmp(label, (*i)->getLabel()))
1099                return (*i);
1100        }
1101    }
1102    return NULL;
1103}
1104
1105bool VolumeManager::isMountpointMounted(const char *mp)
1106{
1107    char device[256];
1108    char mount_path[256];
1109    char rest[256];
1110    FILE *fp;
1111    char line[1024];
1112
1113    if (!(fp = fopen("/proc/mounts", "r"))) {
1114        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
1115        return false;
1116    }
1117
1118    while(fgets(line, sizeof(line), fp)) {
1119        line[strlen(line)-1] = '\0';
1120        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
1121        if (!strcmp(mount_path, mp)) {
1122            fclose(fp);
1123            return true;
1124        }
1125    }
1126
1127    fclose(fp);
1128    return false;
1129}
1130
1131int VolumeManager::cleanupAsec(Volume *v, bool force) {
1132    while(mActiveContainers->size()) {
1133        AsecIdCollection::iterator it = mActiveContainers->begin();
1134        ContainerData* cd = *it;
1135        SLOGI("Unmounting ASEC %s (dependant on %s)", cd->id, v->getMountpoint());
1136        if (cd->type == ASEC) {
1137            if (unmountAsec(cd->id, force)) {
1138                SLOGE("Failed to unmount ASEC %s (%s)", cd->id, strerror(errno));
1139                return -1;
1140            }
1141        } else if (cd->type == OBB) {
1142            if (unmountObb(cd->id, force)) {
1143                SLOGE("Failed to unmount OBB %s (%s)", cd->id, strerror(errno));
1144                return -1;
1145            }
1146        } else {
1147            SLOGE("Unknown container type %d!", cd->type);
1148            return -1;
1149        }
1150    }
1151    return 0;
1152}
1153
1154