VolumeManager.cpp revision cdc2a1c83575a349ee44035de8c3b38b8b401003
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 <fts.h>
23#include <unistd.h>
24#include <sys/stat.h>
25#include <sys/types.h>
26#include <sys/mount.h>
27
28#include <linux/kdev_t.h>
29
30#define LOG_TAG "Vold"
31
32#include <openssl/md5.h>
33
34#include <cutils/log.h>
35
36#include <sysutils/NetlinkEvent.h>
37
38#include <private/android_filesystem_config.h>
39
40#include "VolumeManager.h"
41#include "DirectVolume.h"
42#include "ResponseCode.h"
43#include "Loop.h"
44#include "Ext4.h"
45#include "Fat.h"
46#include "Devmapper.h"
47#include "Process.h"
48#include "Asec.h"
49#include "cryptfs.h"
50
51#define MASS_STORAGE_FILE_PATH  "/sys/class/android_usb/android0/f_mass_storage/lun/file"
52
53VolumeManager *VolumeManager::sInstance = NULL;
54
55VolumeManager *VolumeManager::Instance() {
56    if (!sInstance)
57        sInstance = new VolumeManager();
58    return sInstance;
59}
60
61VolumeManager::VolumeManager() {
62    mDebug = false;
63    mVolumes = new VolumeCollection();
64    mActiveContainers = new AsecIdCollection();
65    mBroadcaster = NULL;
66    mUmsSharingCount = 0;
67    mSavedDirtyRatio = -1;
68    // set dirty ratio to 0 when UMS is active
69    mUmsDirtyRatio = 0;
70    mVolManagerDisabled = 0;
71}
72
73VolumeManager::~VolumeManager() {
74    delete mVolumes;
75    delete mActiveContainers;
76}
77
78char *VolumeManager::asecHash(const char *id, char *buffer, size_t len) {
79    static const char* digits = "0123456789abcdef";
80
81    unsigned char sig[MD5_DIGEST_LENGTH];
82
83    if (buffer == NULL) {
84        SLOGE("Destination buffer is NULL");
85        errno = ESPIPE;
86        return NULL;
87    } else if (id == NULL) {
88        SLOGE("Source buffer is NULL");
89        errno = ESPIPE;
90        return NULL;
91    } else if (len < MD5_ASCII_LENGTH_PLUS_NULL) {
92        SLOGE("Target hash buffer size < %d bytes (%d)",
93                MD5_ASCII_LENGTH_PLUS_NULL, len);
94        errno = ESPIPE;
95        return NULL;
96    }
97
98    MD5(reinterpret_cast<const unsigned char*>(id), strlen(id), sig);
99
100    char *p = buffer;
101    for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
102        *p++ = digits[sig[i] >> 4];
103        *p++ = digits[sig[i] & 0x0F];
104    }
105    *p = '\0';
106
107    return buffer;
108}
109
110void VolumeManager::setDebug(bool enable) {
111    mDebug = enable;
112    VolumeCollection::iterator it;
113    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
114        (*it)->setDebug(enable);
115    }
116}
117
118int VolumeManager::start() {
119    return 0;
120}
121
122int VolumeManager::stop() {
123    return 0;
124}
125
126int VolumeManager::addVolume(Volume *v) {
127    mVolumes->push_back(v);
128    return 0;
129}
130
131void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
132    const char *devpath = evt->findParam("DEVPATH");
133
134    /* Lookup a volume to handle this device */
135    VolumeCollection::iterator it;
136    bool hit = false;
137    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
138        if (!(*it)->handleBlockEvent(evt)) {
139#ifdef NETLINK_DEBUG
140            SLOGD("Device '%s' event handled by volume %s\n", devpath, (*it)->getLabel());
141#endif
142            hit = true;
143            break;
144        }
145    }
146
147    if (!hit) {
148#ifdef NETLINK_DEBUG
149        SLOGW("No volumes handled block event for '%s'", devpath);
150#endif
151    }
152}
153
154int VolumeManager::listVolumes(SocketClient *cli) {
155    VolumeCollection::iterator i;
156
157    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
158        char *buffer;
159        asprintf(&buffer, "%s %s %d",
160                 (*i)->getLabel(), (*i)->getMountpoint(),
161                 (*i)->getState());
162        cli->sendMsg(ResponseCode::VolumeListResult, buffer, false);
163        free(buffer);
164    }
165    cli->sendMsg(ResponseCode::CommandOkay, "Volumes listed.", false);
166    return 0;
167}
168
169int VolumeManager::formatVolume(const char *label) {
170    Volume *v = lookupVolume(label);
171
172    if (!v) {
173        errno = ENOENT;
174        return -1;
175    }
176
177    if (mVolManagerDisabled) {
178        errno = EBUSY;
179        return -1;
180    }
181
182    return v->formatVol();
183}
184
185int VolumeManager::getObbMountPath(const char *sourceFile, char *mountPath, int mountPathLen) {
186    char idHash[33];
187    if (!asecHash(sourceFile, idHash, sizeof(idHash))) {
188        SLOGE("Hash of '%s' failed (%s)", sourceFile, strerror(errno));
189        return -1;
190    }
191
192    memset(mountPath, 0, mountPathLen);
193    snprintf(mountPath, mountPathLen, "%s/%s", Volume::LOOPDIR, idHash);
194
195    if (access(mountPath, F_OK)) {
196        errno = ENOENT;
197        return -1;
198    }
199
200    return 0;
201}
202
203int VolumeManager::getAsecMountPath(const char *id, char *buffer, int maxlen) {
204    char asecFileName[255];
205
206    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
207        SLOGE("Couldn't find ASEC %s", id);
208        return -1;
209    }
210
211    memset(buffer, 0, maxlen);
212    if (access(asecFileName, F_OK)) {
213        errno = ENOENT;
214        return -1;
215    }
216
217    snprintf(buffer, maxlen, "%s/%s", Volume::ASECDIR, id);
218    return 0;
219}
220
221int VolumeManager::getAsecFilesystemPath(const char *id, char *buffer, int maxlen) {
222    char asecFileName[255];
223
224    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
225        SLOGE("Couldn't find ASEC %s", id);
226        return -1;
227    }
228
229    memset(buffer, 0, maxlen);
230    if (access(asecFileName, F_OK)) {
231        errno = ENOENT;
232        return -1;
233    }
234
235    snprintf(buffer, maxlen, "%s", asecFileName);
236    return 0;
237}
238
239int VolumeManager::createAsec(const char *id, unsigned int numSectors, const char *fstype,
240        const char *key, const int ownerUid, bool isExternal) {
241    struct asec_superblock sb;
242    memset(&sb, 0, sizeof(sb));
243
244    const bool wantFilesystem = strcmp(fstype, "none");
245    bool usingExt4 = false;
246    if (wantFilesystem) {
247        usingExt4 = !strcmp(fstype, "ext4");
248        if (usingExt4) {
249            sb.c_opts |= ASEC_SB_C_OPTS_EXT4;
250        } else if (strcmp(fstype, "fat")) {
251            SLOGE("Invalid filesystem type %s", fstype);
252            errno = EINVAL;
253            return -1;
254        }
255    }
256
257    sb.magic = ASEC_SB_MAGIC;
258    sb.ver = ASEC_SB_VER;
259
260    if (numSectors < ((1024*1024)/512)) {
261        SLOGE("Invalid container size specified (%d sectors)", numSectors);
262        errno = EINVAL;
263        return -1;
264    }
265
266    if (lookupVolume(id)) {
267        SLOGE("ASEC id '%s' currently exists", id);
268        errno = EADDRINUSE;
269        return -1;
270    }
271
272    char asecFileName[255];
273
274    if (!findAsec(id, asecFileName, sizeof(asecFileName))) {
275        SLOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
276                asecFileName, strerror(errno));
277        errno = EADDRINUSE;
278        return -1;
279    }
280
281    const char *asecDir = isExternal ? Volume::SEC_ASECDIR_EXT : Volume::SEC_ASECDIR_INT;
282
283    snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", asecDir, id);
284
285    if (!access(asecFileName, F_OK)) {
286        SLOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
287                asecFileName, strerror(errno));
288        errno = EADDRINUSE;
289        return -1;
290    }
291
292    /*
293     * Add some headroom
294     */
295    unsigned fatSize = (((numSectors * 4) / 512) + 1) * 2;
296    unsigned numImgSectors = numSectors + fatSize + 2;
297
298    if (numImgSectors % 63) {
299        numImgSectors += (63 - (numImgSectors % 63));
300    }
301
302    // Add +1 for our superblock which is at the end
303    if (Loop::createImageFile(asecFileName, numImgSectors + 1)) {
304        SLOGE("ASEC image file creation failed (%s)", strerror(errno));
305        return -1;
306    }
307
308    char idHash[33];
309    if (!asecHash(id, idHash, sizeof(idHash))) {
310        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
311        unlink(asecFileName);
312        return -1;
313    }
314
315    char loopDevice[255];
316    if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
317        SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
318        unlink(asecFileName);
319        return -1;
320    }
321
322    char dmDevice[255];
323    bool cleanupDm = false;
324
325    if (strcmp(key, "none")) {
326        // XXX: This is all we support for now
327        sb.c_cipher = ASEC_SB_C_CIPHER_TWOFISH;
328        if (Devmapper::create(idHash, loopDevice, key, numImgSectors, dmDevice,
329                             sizeof(dmDevice))) {
330            SLOGE("ASEC device mapping failed (%s)", strerror(errno));
331            Loop::destroyByDevice(loopDevice);
332            unlink(asecFileName);
333            return -1;
334        }
335        cleanupDm = true;
336    } else {
337        sb.c_cipher = ASEC_SB_C_CIPHER_NONE;
338        strcpy(dmDevice, loopDevice);
339    }
340
341    /*
342     * Drop down the superblock at the end of the file
343     */
344
345    int sbfd = open(loopDevice, O_RDWR);
346    if (sbfd < 0) {
347        SLOGE("Failed to open new DM device for superblock write (%s)", strerror(errno));
348        if (cleanupDm) {
349            Devmapper::destroy(idHash);
350        }
351        Loop::destroyByDevice(loopDevice);
352        unlink(asecFileName);
353        return -1;
354    }
355
356    if (lseek(sbfd, (numImgSectors * 512), SEEK_SET) < 0) {
357        close(sbfd);
358        SLOGE("Failed to lseek for superblock (%s)", strerror(errno));
359        if (cleanupDm) {
360            Devmapper::destroy(idHash);
361        }
362        Loop::destroyByDevice(loopDevice);
363        unlink(asecFileName);
364        return -1;
365    }
366
367    if (write(sbfd, &sb, sizeof(sb)) != sizeof(sb)) {
368        close(sbfd);
369        SLOGE("Failed to write superblock (%s)", strerror(errno));
370        if (cleanupDm) {
371            Devmapper::destroy(idHash);
372        }
373        Loop::destroyByDevice(loopDevice);
374        unlink(asecFileName);
375        return -1;
376    }
377    close(sbfd);
378
379    if (wantFilesystem) {
380        int formatStatus;
381        if (usingExt4) {
382            formatStatus = Ext4::format(dmDevice);
383        } else {
384            formatStatus = Fat::format(dmDevice, numImgSectors);
385        }
386
387        if (formatStatus < 0) {
388            SLOGE("ASEC fs format failed (%s)", strerror(errno));
389            if (cleanupDm) {
390                Devmapper::destroy(idHash);
391            }
392            Loop::destroyByDevice(loopDevice);
393            unlink(asecFileName);
394            return -1;
395        }
396
397        char mountPoint[255];
398
399        snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
400        if (mkdir(mountPoint, 0000)) {
401            if (errno != EEXIST) {
402                SLOGE("Mountpoint creation failed (%s)", strerror(errno));
403                if (cleanupDm) {
404                    Devmapper::destroy(idHash);
405                }
406                Loop::destroyByDevice(loopDevice);
407                unlink(asecFileName);
408                return -1;
409            }
410        }
411
412        int mountStatus;
413        if (usingExt4) {
414            mountStatus = Ext4::doMount(dmDevice, mountPoint, false, false, false);
415        } else {
416            mountStatus = Fat::doMount(dmDevice, mountPoint, false, false, false, ownerUid, 0, 0000,
417                    false);
418        }
419
420        if (mountStatus) {
421            SLOGE("ASEC FAT mount failed (%s)", strerror(errno));
422            if (cleanupDm) {
423                Devmapper::destroy(idHash);
424            }
425            Loop::destroyByDevice(loopDevice);
426            unlink(asecFileName);
427            return -1;
428        }
429
430        if (usingExt4) {
431            int dirfd = open(mountPoint, O_DIRECTORY);
432            if (dirfd >= 0) {
433                if (fchown(dirfd, ownerUid, AID_SYSTEM)
434                        || fchmod(dirfd, S_IRUSR | S_IWUSR | S_IXUSR | S_ISGID | S_IRGRP | S_IXGRP)) {
435                    SLOGI("Cannot chown/chmod new ASEC mount point %s", mountPoint);
436                }
437                close(dirfd);
438            }
439        }
440    } else {
441        SLOGI("Created raw secure container %s (no filesystem)", id);
442    }
443
444    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
445    return 0;
446}
447
448int VolumeManager::finalizeAsec(const char *id) {
449    char asecFileName[255];
450    char loopDevice[255];
451    char mountPoint[255];
452
453    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
454        SLOGE("Couldn't find ASEC %s", id);
455        return -1;
456    }
457
458    char idHash[33];
459    if (!asecHash(id, idHash, sizeof(idHash))) {
460        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
461        return -1;
462    }
463
464    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
465        SLOGE("Unable to finalize %s (%s)", id, strerror(errno));
466        return -1;
467    }
468
469    unsigned int nr_sec = 0;
470    struct asec_superblock sb;
471
472    if (Loop::lookupInfo(loopDevice, &sb, &nr_sec)) {
473        return -1;
474    }
475
476    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
477
478    int result = 0;
479    if (sb.c_opts & ASEC_SB_C_OPTS_EXT4) {
480        result = Ext4::doMount(loopDevice, mountPoint, true, true, true);
481    } else {
482        result = Fat::doMount(loopDevice, mountPoint, true, true, true, 0, 0, 0227, false);
483    }
484
485    if (result) {
486        SLOGE("ASEC finalize mount failed (%s)", strerror(errno));
487        return -1;
488    }
489
490    if (mDebug) {
491        SLOGD("ASEC %s finalized", id);
492    }
493    return 0;
494}
495
496int VolumeManager::fixupAsecPermissions(const char *id, gid_t gid, const char* filename) {
497    char asecFileName[255];
498    char loopDevice[255];
499    char mountPoint[255];
500
501    if (gid < AID_APP) {
502        SLOGE("Group ID is not in application range");
503        return -1;
504    }
505
506    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
507        SLOGE("Couldn't find ASEC %s", id);
508        return -1;
509    }
510
511    char idHash[33];
512    if (!asecHash(id, idHash, sizeof(idHash))) {
513        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
514        return -1;
515    }
516
517    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
518        SLOGE("Unable fix permissions during lookup on %s (%s)", id, strerror(errno));
519        return -1;
520    }
521
522    unsigned int nr_sec = 0;
523    struct asec_superblock sb;
524
525    if (Loop::lookupInfo(loopDevice, &sb, &nr_sec)) {
526        return -1;
527    }
528
529    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
530
531    int result = 0;
532    if ((sb.c_opts & ASEC_SB_C_OPTS_EXT4) == 0) {
533        return 0;
534    }
535
536    int ret = Ext4::doMount(loopDevice, mountPoint,
537            false /* read-only */,
538            true  /* remount */,
539            false /* executable */);
540    if (ret) {
541        SLOGE("Unable remount to fix permissions for %s (%s)", id, strerror(errno));
542        return -1;
543    }
544
545    char *paths[] = { mountPoint, NULL };
546
547    FTS *fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL);
548    if (fts) {
549        // Traverse the entire hierarchy and chown to system UID.
550        for (FTSENT *ftsent = fts_read(fts); ftsent != NULL; ftsent = fts_read(fts)) {
551            // We don't care about the lost+found directory.
552            if (!strcmp(ftsent->fts_name, "lost+found")) {
553                continue;
554            }
555
556            /*
557             * There can only be one file marked as private right now.
558             * This should be more robust, but it satisfies the requirements
559             * we have for right now.
560             */
561            const bool privateFile = !strcmp(ftsent->fts_name, filename);
562
563            int fd = open(ftsent->fts_accpath, O_NOFOLLOW);
564            if (fd < 0) {
565                SLOGE("Couldn't open file %s: %s", ftsent->fts_accpath, strerror(errno));
566                result = -1;
567                continue;
568            }
569
570            result |= fchown(fd, AID_SYSTEM, privateFile? gid : AID_SYSTEM);
571
572            if (ftsent->fts_info & FTS_D) {
573                result |= fchmod(fd, 0711);
574            } else {
575                result |= fchmod(fd, privateFile ? 0640 : 0644);
576            }
577            close(fd);
578        }
579        fts_close(fts);
580
581        // Finally make the directory readable by everyone.
582        int dirfd = open(mountPoint, O_DIRECTORY);
583        if (dirfd < 0 || fchmod(dirfd, 0755)) {
584            SLOGE("Couldn't change owner of existing directory %s: %s", mountPoint, strerror(errno));
585            result |= -1;
586        }
587        close(dirfd);
588    } else {
589        result |= -1;
590    }
591
592    result |= Ext4::doMount(loopDevice, mountPoint,
593            true /* read-only */,
594            true /* remount */,
595            true /* execute */);
596
597    if (result) {
598        SLOGE("ASEC fix permissions failed (%s)", strerror(errno));
599        return -1;
600    }
601
602    if (mDebug) {
603        SLOGD("ASEC %s permissions fixed", id);
604    }
605    return 0;
606}
607
608int VolumeManager::renameAsec(const char *id1, const char *id2) {
609    char asecFilename1[255];
610    char *asecFilename2;
611    char mountPoint[255];
612
613    const char *dir;
614
615    if (findAsec(id1, asecFilename1, sizeof(asecFilename1), &dir)) {
616        SLOGE("Couldn't find ASEC %s", id1);
617        return -1;
618    }
619
620    asprintf(&asecFilename2, "%s/%s.asec", dir, id2);
621
622    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id1);
623    if (isMountpointMounted(mountPoint)) {
624        SLOGW("Rename attempt when src mounted");
625        errno = EBUSY;
626        goto out_err;
627    }
628
629    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id2);
630    if (isMountpointMounted(mountPoint)) {
631        SLOGW("Rename attempt when dst mounted");
632        errno = EBUSY;
633        goto out_err;
634    }
635
636    if (!access(asecFilename2, F_OK)) {
637        SLOGE("Rename attempt when dst exists");
638        errno = EADDRINUSE;
639        goto out_err;
640    }
641
642    if (rename(asecFilename1, asecFilename2)) {
643        SLOGE("Rename of '%s' to '%s' failed (%s)", asecFilename1, asecFilename2, strerror(errno));
644        goto out_err;
645    }
646
647    free(asecFilename2);
648    return 0;
649
650out_err:
651    free(asecFilename2);
652    return -1;
653}
654
655#define UNMOUNT_RETRIES 5
656#define UNMOUNT_SLEEP_BETWEEN_RETRY_MS (1000 * 1000)
657int VolumeManager::unmountAsec(const char *id, bool force) {
658    char asecFileName[255];
659    char mountPoint[255];
660
661    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
662        SLOGE("Couldn't find ASEC %s", id);
663        return -1;
664    }
665
666    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
667
668    char idHash[33];
669    if (!asecHash(id, idHash, sizeof(idHash))) {
670        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
671        return -1;
672    }
673
674    return unmountLoopImage(id, idHash, asecFileName, mountPoint, force);
675}
676
677int VolumeManager::unmountObb(const char *fileName, bool force) {
678    char mountPoint[255];
679
680    char idHash[33];
681    if (!asecHash(fileName, idHash, sizeof(idHash))) {
682        SLOGE("Hash of '%s' failed (%s)", fileName, strerror(errno));
683        return -1;
684    }
685
686    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::LOOPDIR, idHash);
687
688    return unmountLoopImage(fileName, idHash, fileName, mountPoint, force);
689}
690
691int VolumeManager::unmountLoopImage(const char *id, const char *idHash,
692        const char *fileName, const char *mountPoint, bool force) {
693    if (!isMountpointMounted(mountPoint)) {
694        SLOGE("Unmount request for %s when not mounted", id);
695        errno = ENOENT;
696        return -1;
697    }
698
699    int i, rc;
700    for (i = 1; i <= UNMOUNT_RETRIES; i++) {
701        rc = umount(mountPoint);
702        if (!rc) {
703            break;
704        }
705        if (rc && (errno == EINVAL || errno == ENOENT)) {
706            SLOGI("Container %s unmounted OK", id);
707            rc = 0;
708            break;
709        }
710        SLOGW("%s unmount attempt %d failed (%s)",
711              id, i, strerror(errno));
712
713        int action = 0; // default is to just complain
714
715        if (force) {
716            if (i > (UNMOUNT_RETRIES - 2))
717                action = 2; // SIGKILL
718            else if (i > (UNMOUNT_RETRIES - 3))
719                action = 1; // SIGHUP
720        }
721
722        Process::killProcessesWithOpenFiles(mountPoint, action);
723        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
724    }
725
726    if (rc) {
727        errno = EBUSY;
728        SLOGE("Failed to unmount container %s (%s)", id, strerror(errno));
729        return -1;
730    }
731
732    int retries = 10;
733
734    while(retries--) {
735        if (!rmdir(mountPoint)) {
736            break;
737        }
738
739        SLOGW("Failed to rmdir %s (%s)", mountPoint, strerror(errno));
740        usleep(UNMOUNT_SLEEP_BETWEEN_RETRY_MS);
741    }
742
743    if (!retries) {
744        SLOGE("Timed out trying to rmdir %s (%s)", mountPoint, strerror(errno));
745    }
746
747    if (Devmapper::destroy(idHash) && errno != ENXIO) {
748        SLOGE("Failed to destroy devmapper instance (%s)", strerror(errno));
749    }
750
751    char loopDevice[255];
752    if (!Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
753        Loop::destroyByDevice(loopDevice);
754    } else {
755        SLOGW("Failed to find loop device for {%s} (%s)", fileName, strerror(errno));
756    }
757
758    AsecIdCollection::iterator it;
759    for (it = mActiveContainers->begin(); it != mActiveContainers->end(); ++it) {
760        ContainerData* cd = *it;
761        if (!strcmp(cd->id, id)) {
762            free(*it);
763            mActiveContainers->erase(it);
764            break;
765        }
766    }
767    if (it == mActiveContainers->end()) {
768        SLOGW("mActiveContainers is inconsistent!");
769    }
770    return 0;
771}
772
773int VolumeManager::destroyAsec(const char *id, bool force) {
774    char asecFileName[255];
775    char mountPoint[255];
776
777    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
778        SLOGE("Couldn't find ASEC %s", id);
779        return -1;
780    }
781
782    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
783
784    if (isMountpointMounted(mountPoint)) {
785        if (mDebug) {
786            SLOGD("Unmounting container before destroy");
787        }
788        if (unmountAsec(id, force)) {
789            SLOGE("Failed to unmount asec %s for destroy (%s)", id, strerror(errno));
790            return -1;
791        }
792    }
793
794    if (unlink(asecFileName)) {
795        SLOGE("Failed to unlink asec '%s' (%s)", asecFileName, strerror(errno));
796        return -1;
797    }
798
799    if (mDebug) {
800        SLOGD("ASEC %s destroyed", id);
801    }
802    return 0;
803}
804
805bool VolumeManager::isAsecInDirectory(const char *dir, const char *asecName) const {
806    int dirfd = open(dir, O_DIRECTORY);
807    if (dirfd < 0) {
808        SLOGE("Couldn't open internal ASEC dir (%s)", strerror(errno));
809        return -1;
810    }
811
812    bool ret = false;
813
814    if (!faccessat(dirfd, asecName, F_OK, AT_SYMLINK_NOFOLLOW)) {
815        ret = true;
816    }
817
818    close(dirfd);
819
820    return ret;
821}
822
823int VolumeManager::findAsec(const char *id, char *asecPath, size_t asecPathLen,
824        const char **directory) const {
825    int dirfd, fd;
826    const int idLen = strlen(id);
827    char *asecName;
828
829    if (asprintf(&asecName, "%s.asec", id) < 0) {
830        SLOGE("Couldn't allocate string to write ASEC name");
831        return -1;
832    }
833
834    const char *dir;
835    if (isAsecInDirectory(Volume::SEC_ASECDIR_INT, asecName)) {
836        dir = Volume::SEC_ASECDIR_INT;
837    } else if (isAsecInDirectory(Volume::SEC_ASECDIR_EXT, asecName)) {
838        dir = Volume::SEC_ASECDIR_EXT;
839    } else {
840        free(asecName);
841        return -1;
842    }
843
844    if (directory != NULL) {
845        *directory = dir;
846    }
847
848    if (asecPath != NULL) {
849        int written = snprintf(asecPath, asecPathLen, "%s/%s", dir, asecName);
850        if (written < 0 || static_cast<size_t>(written) >= asecPathLen) {
851            free(asecName);
852            return -1;
853        }
854    }
855
856    free(asecName);
857    return 0;
858}
859
860int VolumeManager::mountAsec(const char *id, const char *key, int ownerUid) {
861    char asecFileName[255];
862    char mountPoint[255];
863
864    if (findAsec(id, asecFileName, sizeof(asecFileName))) {
865        SLOGE("Couldn't find ASEC %s", id);
866        return -1;
867    }
868
869    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::ASECDIR, id);
870
871    if (isMountpointMounted(mountPoint)) {
872        SLOGE("ASEC %s already mounted", id);
873        errno = EBUSY;
874        return -1;
875    }
876
877    char idHash[33];
878    if (!asecHash(id, idHash, sizeof(idHash))) {
879        SLOGE("Hash of '%s' failed (%s)", id, strerror(errno));
880        return -1;
881    }
882
883    char loopDevice[255];
884    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
885        if (Loop::create(idHash, asecFileName, loopDevice, sizeof(loopDevice))) {
886            SLOGE("ASEC loop device creation failed (%s)", strerror(errno));
887            return -1;
888        }
889        if (mDebug) {
890            SLOGD("New loop device created at %s", loopDevice);
891        }
892    } else {
893        if (mDebug) {
894            SLOGD("Found active loopback for %s at %s", asecFileName, loopDevice);
895        }
896    }
897
898    char dmDevice[255];
899    bool cleanupDm = false;
900    int fd;
901    unsigned int nr_sec = 0;
902    struct asec_superblock sb;
903
904    if (Loop::lookupInfo(loopDevice, &sb, &nr_sec)) {
905        return -1;
906    }
907
908    if (mDebug) {
909        SLOGD("Container sb magic/ver (%.8x/%.2x)", sb.magic, sb.ver);
910    }
911    if (sb.magic != ASEC_SB_MAGIC || sb.ver != ASEC_SB_VER) {
912        SLOGE("Bad container magic/version (%.8x/%.2x)", sb.magic, sb.ver);
913        Loop::destroyByDevice(loopDevice);
914        errno = EMEDIUMTYPE;
915        return -1;
916    }
917    nr_sec--; // We don't want the devmapping to extend onto our superblock
918
919    if (strcmp(key, "none")) {
920        if (Devmapper::lookupActive(idHash, dmDevice, sizeof(dmDevice))) {
921            if (Devmapper::create(idHash, loopDevice, key, nr_sec,
922                                  dmDevice, sizeof(dmDevice))) {
923                SLOGE("ASEC device mapping failed (%s)", strerror(errno));
924                Loop::destroyByDevice(loopDevice);
925                return -1;
926            }
927            if (mDebug) {
928                SLOGD("New devmapper instance created at %s", dmDevice);
929            }
930        } else {
931            if (mDebug) {
932                SLOGD("Found active devmapper for %s at %s", asecFileName, dmDevice);
933            }
934        }
935        cleanupDm = true;
936    } else {
937        strcpy(dmDevice, loopDevice);
938    }
939
940    if (mkdir(mountPoint, 0000)) {
941        if (errno != EEXIST) {
942            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
943            if (cleanupDm) {
944                Devmapper::destroy(idHash);
945            }
946            Loop::destroyByDevice(loopDevice);
947            return -1;
948        }
949    }
950
951    /*
952     * The device mapper node needs to be created. Sometimes it takes a
953     * while. Wait for up to 1 second. We could also inspect incoming uevents,
954     * but that would take more effort.
955     */
956    int tries = 25;
957    while (tries--) {
958        if (!access(dmDevice, F_OK) || errno != ENOENT) {
959            break;
960        }
961        usleep(40 * 1000);
962    }
963
964    int result;
965    if (sb.c_opts & ASEC_SB_C_OPTS_EXT4) {
966        result = Ext4::doMount(dmDevice, mountPoint, true, false, true);
967    } else {
968        result = Fat::doMount(dmDevice, mountPoint, true, false, true, ownerUid, 0, 0222, false);
969    }
970
971    if (result) {
972        SLOGE("ASEC mount failed (%s)", strerror(errno));
973        if (cleanupDm) {
974            Devmapper::destroy(idHash);
975        }
976        Loop::destroyByDevice(loopDevice);
977        return -1;
978    }
979
980    mActiveContainers->push_back(new ContainerData(strdup(id), ASEC));
981    if (mDebug) {
982        SLOGD("ASEC %s mounted", id);
983    }
984    return 0;
985}
986
987/**
988 * Mounts an image file <code>img</code>.
989 */
990int VolumeManager::mountObb(const char *img, const char *key, int ownerUid) {
991    char mountPoint[255];
992
993    char idHash[33];
994    if (!asecHash(img, idHash, sizeof(idHash))) {
995        SLOGE("Hash of '%s' failed (%s)", img, strerror(errno));
996        return -1;
997    }
998
999    snprintf(mountPoint, sizeof(mountPoint), "%s/%s", Volume::LOOPDIR, idHash);
1000
1001    if (isMountpointMounted(mountPoint)) {
1002        SLOGE("Image %s already mounted", img);
1003        errno = EBUSY;
1004        return -1;
1005    }
1006
1007    char loopDevice[255];
1008    if (Loop::lookupActive(idHash, loopDevice, sizeof(loopDevice))) {
1009        if (Loop::create(idHash, img, loopDevice, sizeof(loopDevice))) {
1010            SLOGE("Image loop device creation failed (%s)", strerror(errno));
1011            return -1;
1012        }
1013        if (mDebug) {
1014            SLOGD("New loop device created at %s", loopDevice);
1015        }
1016    } else {
1017        if (mDebug) {
1018            SLOGD("Found active loopback for %s at %s", img, loopDevice);
1019        }
1020    }
1021
1022    char dmDevice[255];
1023    bool cleanupDm = false;
1024    int fd;
1025    unsigned int nr_sec = 0;
1026
1027    if ((fd = open(loopDevice, O_RDWR)) < 0) {
1028        SLOGE("Failed to open loopdevice (%s)", strerror(errno));
1029        Loop::destroyByDevice(loopDevice);
1030        return -1;
1031    }
1032
1033    if (ioctl(fd, BLKGETSIZE, &nr_sec)) {
1034        SLOGE("Failed to get loop size (%s)", strerror(errno));
1035        Loop::destroyByDevice(loopDevice);
1036        close(fd);
1037        return -1;
1038    }
1039
1040    close(fd);
1041
1042    if (strcmp(key, "none")) {
1043        if (Devmapper::lookupActive(idHash, dmDevice, sizeof(dmDevice))) {
1044            if (Devmapper::create(idHash, loopDevice, key, nr_sec,
1045                                  dmDevice, sizeof(dmDevice))) {
1046                SLOGE("ASEC device mapping failed (%s)", strerror(errno));
1047                Loop::destroyByDevice(loopDevice);
1048                return -1;
1049            }
1050            if (mDebug) {
1051                SLOGD("New devmapper instance created at %s", dmDevice);
1052            }
1053        } else {
1054            if (mDebug) {
1055                SLOGD("Found active devmapper for %s at %s", img, dmDevice);
1056            }
1057        }
1058        cleanupDm = true;
1059    } else {
1060        strcpy(dmDevice, loopDevice);
1061    }
1062
1063    if (mkdir(mountPoint, 0755)) {
1064        if (errno != EEXIST) {
1065            SLOGE("Mountpoint creation failed (%s)", strerror(errno));
1066            if (cleanupDm) {
1067                Devmapper::destroy(idHash);
1068            }
1069            Loop::destroyByDevice(loopDevice);
1070            return -1;
1071        }
1072    }
1073
1074    if (Fat::doMount(dmDevice, mountPoint, true, false, true, ownerUid, 0,
1075                     0227, false)) {
1076        SLOGE("Image mount failed (%s)", strerror(errno));
1077        if (cleanupDm) {
1078            Devmapper::destroy(idHash);
1079        }
1080        Loop::destroyByDevice(loopDevice);
1081        return -1;
1082    }
1083
1084    mActiveContainers->push_back(new ContainerData(strdup(img), OBB));
1085    if (mDebug) {
1086        SLOGD("Image %s mounted", img);
1087    }
1088    return 0;
1089}
1090
1091int VolumeManager::mountVolume(const char *label) {
1092    Volume *v = lookupVolume(label);
1093
1094    if (!v) {
1095        errno = ENOENT;
1096        return -1;
1097    }
1098
1099    return v->mountVol();
1100}
1101
1102int VolumeManager::listMountedObbs(SocketClient* cli) {
1103    char device[256];
1104    char mount_path[256];
1105    char rest[256];
1106    FILE *fp;
1107    char line[1024];
1108
1109    if (!(fp = fopen("/proc/mounts", "r"))) {
1110        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
1111        return -1;
1112    }
1113
1114    // Create a string to compare against that has a trailing slash
1115    int loopDirLen = sizeof(Volume::LOOPDIR);
1116    char loopDir[loopDirLen + 2];
1117    strcpy(loopDir, Volume::LOOPDIR);
1118    loopDir[loopDirLen++] = '/';
1119    loopDir[loopDirLen] = '\0';
1120
1121    while(fgets(line, sizeof(line), fp)) {
1122        line[strlen(line)-1] = '\0';
1123
1124        /*
1125         * Should look like:
1126         * /dev/block/loop0 /mnt/obb/fc99df1323fd36424f864dcb76b76d65 ...
1127         */
1128        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
1129
1130        if (!strncmp(mount_path, loopDir, loopDirLen)) {
1131            int fd = open(device, O_RDONLY);
1132            if (fd >= 0) {
1133                struct loop_info64 li;
1134                if (ioctl(fd, LOOP_GET_STATUS64, &li) >= 0) {
1135                    cli->sendMsg(ResponseCode::AsecListResult,
1136                            (const char*) li.lo_file_name, false);
1137                }
1138                close(fd);
1139            }
1140        }
1141    }
1142
1143    fclose(fp);
1144    return 0;
1145}
1146
1147int VolumeManager::shareEnabled(const char *label, const char *method, bool *enabled) {
1148    Volume *v = lookupVolume(label);
1149
1150    if (!v) {
1151        errno = ENOENT;
1152        return -1;
1153    }
1154
1155    if (strcmp(method, "ums")) {
1156        errno = ENOSYS;
1157        return -1;
1158    }
1159
1160    if (v->getState() != Volume::State_Shared) {
1161        *enabled = false;
1162    } else {
1163        *enabled = true;
1164    }
1165    return 0;
1166}
1167
1168int VolumeManager::shareVolume(const char *label, const char *method) {
1169    Volume *v = lookupVolume(label);
1170
1171    if (!v) {
1172        errno = ENOENT;
1173        return -1;
1174    }
1175
1176    /*
1177     * Eventually, we'll want to support additional share back-ends,
1178     * some of which may work while the media is mounted. For now,
1179     * we just support UMS
1180     */
1181    if (strcmp(method, "ums")) {
1182        errno = ENOSYS;
1183        return -1;
1184    }
1185
1186    if (v->getState() == Volume::State_NoMedia) {
1187        errno = ENODEV;
1188        return -1;
1189    }
1190
1191    if (v->getState() != Volume::State_Idle) {
1192        // You need to unmount manually befoe sharing
1193        errno = EBUSY;
1194        return -1;
1195    }
1196
1197    if (mVolManagerDisabled) {
1198        errno = EBUSY;
1199        return -1;
1200    }
1201
1202    dev_t d = v->getShareDevice();
1203    if ((MAJOR(d) == 0) && (MINOR(d) == 0)) {
1204        // This volume does not support raw disk access
1205        errno = EINVAL;
1206        return -1;
1207    }
1208
1209    int fd;
1210    char nodepath[255];
1211    snprintf(nodepath,
1212             sizeof(nodepath), "/dev/block/vold/%d:%d",
1213             MAJOR(d), MINOR(d));
1214
1215    if ((fd = open(MASS_STORAGE_FILE_PATH, O_WRONLY)) < 0) {
1216        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
1217        return -1;
1218    }
1219
1220    if (write(fd, nodepath, strlen(nodepath)) < 0) {
1221        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
1222        close(fd);
1223        return -1;
1224    }
1225
1226    close(fd);
1227    v->handleVolumeShared();
1228    if (mUmsSharingCount++ == 0) {
1229        FILE* fp;
1230        mSavedDirtyRatio = -1; // in case we fail
1231        if ((fp = fopen("/proc/sys/vm/dirty_ratio", "r+"))) {
1232            char line[16];
1233            if (fgets(line, sizeof(line), fp) && sscanf(line, "%d", &mSavedDirtyRatio)) {
1234                fprintf(fp, "%d\n", mUmsDirtyRatio);
1235            } else {
1236                SLOGE("Failed to read dirty_ratio (%s)", strerror(errno));
1237            }
1238            fclose(fp);
1239        } else {
1240            SLOGE("Failed to open /proc/sys/vm/dirty_ratio (%s)", strerror(errno));
1241        }
1242    }
1243    return 0;
1244}
1245
1246int VolumeManager::unshareVolume(const char *label, const char *method) {
1247    Volume *v = lookupVolume(label);
1248
1249    if (!v) {
1250        errno = ENOENT;
1251        return -1;
1252    }
1253
1254    if (strcmp(method, "ums")) {
1255        errno = ENOSYS;
1256        return -1;
1257    }
1258
1259    if (v->getState() != Volume::State_Shared) {
1260        errno = EINVAL;
1261        return -1;
1262    }
1263
1264    int fd;
1265    if ((fd = open(MASS_STORAGE_FILE_PATH, O_WRONLY)) < 0) {
1266        SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
1267        return -1;
1268    }
1269
1270    char ch = 0;
1271    if (write(fd, &ch, 1) < 0) {
1272        SLOGE("Unable to write to ums lunfile (%s)", strerror(errno));
1273        close(fd);
1274        return -1;
1275    }
1276
1277    close(fd);
1278    v->handleVolumeUnshared();
1279    if (--mUmsSharingCount == 0 && mSavedDirtyRatio != -1) {
1280        FILE* fp;
1281        if ((fp = fopen("/proc/sys/vm/dirty_ratio", "r+"))) {
1282            fprintf(fp, "%d\n", mSavedDirtyRatio);
1283            fclose(fp);
1284        } else {
1285            SLOGE("Failed to open /proc/sys/vm/dirty_ratio (%s)", strerror(errno));
1286        }
1287        mSavedDirtyRatio = -1;
1288    }
1289    return 0;
1290}
1291
1292extern "C" int vold_disableVol(const char *label) {
1293    VolumeManager *vm = VolumeManager::Instance();
1294    vm->disableVolumeManager();
1295    vm->unshareVolume(label, "ums");
1296    return vm->unmountVolume(label, true, false);
1297}
1298
1299extern "C" int vold_getNumDirectVolumes(void) {
1300    VolumeManager *vm = VolumeManager::Instance();
1301    return vm->getNumDirectVolumes();
1302}
1303
1304int VolumeManager::getNumDirectVolumes(void) {
1305    VolumeCollection::iterator i;
1306    int n=0;
1307
1308    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1309        if ((*i)->getShareDevice() != (dev_t)0) {
1310            n++;
1311        }
1312    }
1313    return n;
1314}
1315
1316extern "C" int vold_getDirectVolumeList(struct volume_info *vol_list) {
1317    VolumeManager *vm = VolumeManager::Instance();
1318    return vm->getDirectVolumeList(vol_list);
1319}
1320
1321int VolumeManager::getDirectVolumeList(struct volume_info *vol_list) {
1322    VolumeCollection::iterator i;
1323    int n=0;
1324    dev_t d;
1325
1326    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1327        if ((d=(*i)->getShareDevice()) != (dev_t)0) {
1328            (*i)->getVolInfo(&vol_list[n]);
1329            snprintf(vol_list[n].blk_dev, sizeof(vol_list[n].blk_dev),
1330                     "/dev/block/vold/%d:%d",MAJOR(d), MINOR(d));
1331            n++;
1332        }
1333    }
1334
1335    return 0;
1336}
1337
1338int VolumeManager::unmountVolume(const char *label, bool force, bool revert) {
1339    Volume *v = lookupVolume(label);
1340
1341    if (!v) {
1342        errno = ENOENT;
1343        return -1;
1344    }
1345
1346    if (v->getState() == Volume::State_NoMedia) {
1347        errno = ENODEV;
1348        return -1;
1349    }
1350
1351    if (v->getState() != Volume::State_Mounted) {
1352        SLOGW("Attempt to unmount volume which isn't mounted (%d)\n",
1353             v->getState());
1354        errno = EBUSY;
1355        return UNMOUNT_NOT_MOUNTED_ERR;
1356    }
1357
1358    cleanupAsec(v, force);
1359
1360    return v->unmountVol(force, revert);
1361}
1362
1363/*
1364 * Looks up a volume by it's label or mount-point
1365 */
1366Volume *VolumeManager::lookupVolume(const char *label) {
1367    VolumeCollection::iterator i;
1368
1369    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
1370        if (label[0] == '/') {
1371            if (!strcmp(label, (*i)->getMountpoint()))
1372                return (*i);
1373        } else {
1374            if (!strcmp(label, (*i)->getLabel()))
1375                return (*i);
1376        }
1377    }
1378    return NULL;
1379}
1380
1381bool VolumeManager::isMountpointMounted(const char *mp)
1382{
1383    char device[256];
1384    char mount_path[256];
1385    char rest[256];
1386    FILE *fp;
1387    char line[1024];
1388
1389    if (!(fp = fopen("/proc/mounts", "r"))) {
1390        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
1391        return false;
1392    }
1393
1394    while(fgets(line, sizeof(line), fp)) {
1395        line[strlen(line)-1] = '\0';
1396        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
1397        if (!strcmp(mount_path, mp)) {
1398            fclose(fp);
1399            return true;
1400        }
1401    }
1402
1403    fclose(fp);
1404    return false;
1405}
1406
1407int VolumeManager::cleanupAsec(Volume *v, bool force) {
1408    while(mActiveContainers->size()) {
1409        AsecIdCollection::iterator it = mActiveContainers->begin();
1410        ContainerData* cd = *it;
1411        SLOGI("Unmounting ASEC %s (dependant on %s)", cd->id, v->getMountpoint());
1412        if (cd->type == ASEC) {
1413            if (unmountAsec(cd->id, force)) {
1414                SLOGE("Failed to unmount ASEC %s (%s)", cd->id, strerror(errno));
1415                return -1;
1416            }
1417        } else if (cd->type == OBB) {
1418            if (unmountObb(cd->id, force)) {
1419                SLOGE("Failed to unmount OBB %s (%s)", cd->id, strerror(errno));
1420                return -1;
1421            }
1422        } else {
1423            SLOGE("Unknown container type %d!", cd->type);
1424            return -1;
1425        }
1426    }
1427    return 0;
1428}
1429
1430