VolumeManager.cpp revision f5c61980969a0b49bda37b5dc94ffe675ebd5a5a
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 <cutils/log.h>
31
32#include <sysutils/NetlinkEvent.h>
33
34#include "VolumeManager.h"
35#include "DirectVolume.h"
36#include "ResponseCode.h"
37#include "Loop.h"
38#include "Fat.h"
39#include "Devmapper.h"
40
41extern "C" void KillProcessesWithOpenFiles(const char *, int, int, int);
42
43VolumeManager *VolumeManager::sInstance = NULL;
44
45VolumeManager *VolumeManager::Instance() {
46    if (!sInstance)
47        sInstance = new VolumeManager();
48    return sInstance;
49}
50
51VolumeManager::VolumeManager() {
52    mBlockDevices = new BlockDeviceCollection();
53    mVolumes = new VolumeCollection();
54    mActiveContainers = new AsecIdCollection();
55    mBroadcaster = NULL;
56    mUsbMassStorageConnected = false;
57}
58
59VolumeManager::~VolumeManager() {
60    delete mBlockDevices;
61    delete mVolumes;
62    delete mActiveContainers;
63}
64
65int VolumeManager::start() {
66    return 0;
67}
68
69int VolumeManager::stop() {
70    return 0;
71}
72
73int VolumeManager::addVolume(Volume *v) {
74    mVolumes->push_back(v);
75    return 0;
76}
77
78void VolumeManager::notifyUmsConnected(bool connected) {
79    char msg[255];
80
81    if (connected) {
82        mUsbMassStorageConnected = true;
83    } else {
84        mUsbMassStorageConnected = false;
85    }
86    snprintf(msg, sizeof(msg), "Share method ums now %s",
87             (connected ? "available" : "unavailable"));
88
89    getBroadcaster()->sendBroadcast(ResponseCode::ShareAvailabilityChange,
90                                    msg, false);
91}
92
93void VolumeManager::handleSwitchEvent(NetlinkEvent *evt) {
94    const char *devpath = evt->findParam("DEVPATH");
95    const char *name = evt->findParam("SWITCH_NAME");
96    const char *state = evt->findParam("SWITCH_STATE");
97
98    if (!name || !state) {
99        LOGW("Switch %s event missing name/state info", devpath);
100        return;
101    }
102
103    if (!strcmp(name, "usb_mass_storage")) {
104
105        if (!strcmp(state, "online"))  {
106            notifyUmsConnected(true);
107        } else {
108            notifyUmsConnected(false);
109        }
110    } else {
111        LOGW("Ignoring unknown switch '%s'", name);
112    }
113}
114
115void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
116    const char *devpath = evt->findParam("DEVPATH");
117
118    /* Lookup a volume to handle this device */
119    VolumeCollection::iterator it;
120    bool hit = false;
121    for (it = mVolumes->begin(); it != mVolumes->end(); ++it) {
122        if (!(*it)->handleBlockEvent(evt)) {
123#ifdef NETLINK_DEBUG
124            LOGD("Device '%s' event handled by volume %s\n", devpath, (*it)->getLabel());
125#endif
126            hit = true;
127            break;
128        }
129    }
130
131    if (!hit) {
132#ifdef NETLINK_DEBUG
133        LOGW("No volumes handled block event for '%s'", devpath);
134#endif
135    }
136}
137
138int VolumeManager::listVolumes(SocketClient *cli) {
139    VolumeCollection::iterator i;
140
141    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
142        char *buffer;
143        asprintf(&buffer, "%s %s %d",
144                 (*i)->getLabel(), (*i)->getMountpoint(),
145                 (*i)->getState());
146        cli->sendMsg(ResponseCode::VolumeListResult, buffer, false);
147        free(buffer);
148    }
149    cli->sendMsg(ResponseCode::CommandOkay, "Volumes listed.", false);
150    return 0;
151}
152
153int VolumeManager::formatVolume(const char *label) {
154    Volume *v = lookupVolume(label);
155
156    if (!v) {
157        errno = ENOENT;
158        return -1;
159    }
160
161    return v->formatVol();
162}
163
164int VolumeManager::getAsecMountPath(const char *id, char *buffer, int maxlen) {
165    char mountPoint[255];
166
167    snprintf(mountPoint, sizeof(mountPoint), "/asec/%s", id);
168    snprintf(buffer, maxlen, "/asec/%s", id);
169    return 0;
170}
171
172int VolumeManager::createAsec(const char *id, unsigned int numSectors,
173                              const char *fstype, const char *key, int ownerUid) {
174
175    mkdir("/sdcard/android_secure", 0777);
176
177    if (lookupVolume(id)) {
178        LOGE("ASEC volume '%s' currently exists", id);
179        errno = EADDRINUSE;
180        return -1;
181    }
182
183    char asecFileName[255];
184    snprintf(asecFileName, sizeof(asecFileName),
185             "/sdcard/android_secure/%s.asec", id);
186
187    if (!access(asecFileName, F_OK)) {
188        LOGE("ASEC file '%s' currently exists - destroy it first! (%s)",
189             asecFileName, strerror(errno));
190        errno = EADDRINUSE;
191        return -1;
192    }
193
194    if (Loop::createImageFile(asecFileName, numSectors)) {
195        LOGE("ASEC image file creation failed (%s)", strerror(errno));
196        return -1;
197    }
198
199    char loopDevice[255];
200    if (Loop::create(asecFileName, loopDevice, sizeof(loopDevice))) {
201        LOGE("ASEC loop device creation failed (%s)", strerror(errno));
202        unlink(asecFileName);
203        return -1;
204    }
205
206    char dmDevice[255];
207    bool cleanupDm = false;
208
209    if (strcmp(key, "none")) {
210        if (Devmapper::create(id, loopDevice, key, numSectors, dmDevice,
211                             sizeof(dmDevice))) {
212            LOGE("ASEC device mapping failed (%s)", strerror(errno));
213            Loop::destroyByDevice(loopDevice);
214            unlink(asecFileName);
215            return -1;
216        }
217        cleanupDm = true;
218    } else {
219        strcpy(dmDevice, loopDevice);
220    }
221
222    if (Fat::format(dmDevice)) {
223        LOGE("ASEC FAT format failed (%s)", strerror(errno));
224        if (cleanupDm) {
225            Devmapper::destroy(id);
226        }
227        Loop::destroyByDevice(loopDevice);
228        unlink(asecFileName);
229        return -1;
230    }
231
232    char mountPoint[255];
233
234    snprintf(mountPoint, sizeof(mountPoint), "/asec/%s", id);
235    if (mkdir(mountPoint, 0777)) {
236        if (errno != EEXIST) {
237            LOGE("Mountpoint creation failed (%s)", strerror(errno));
238            if (cleanupDm) {
239                Devmapper::destroy(id);
240            }
241            Loop::destroyByDevice(loopDevice);
242            unlink(asecFileName);
243            return -1;
244        }
245    }
246
247    if (Fat::doMount(dmDevice, mountPoint, false, false, ownerUid,
248                     0, 0000, false)) {
249//                     0, 0007, false)) {
250        LOGE("ASEC FAT mount failed (%s)", strerror(errno));
251        if (cleanupDm) {
252            Devmapper::destroy(id);
253        }
254        Loop::destroyByDevice(loopDevice);
255        unlink(asecFileName);
256        return -1;
257    }
258
259    mActiveContainers->push_back(strdup(id));
260    return 0;
261}
262
263int VolumeManager::finalizeAsec(const char *id) {
264    char asecFileName[255];
265    char loopDevice[255];
266    char mountPoint[255];
267
268    snprintf(asecFileName, sizeof(asecFileName),
269             "/sdcard/android_secure/%s.asec", id);
270
271    if (Loop::lookupActive(asecFileName, loopDevice, sizeof(loopDevice))) {
272        LOGE("Unable to finalize %s (%s)", id, strerror(errno));
273        return -1;
274    }
275
276    snprintf(mountPoint, sizeof(mountPoint), "/asec/%s", id);
277    // XXX:
278    if (Fat::doMount(loopDevice, mountPoint, true, true, 0, 0, 0227, false)) {
279        LOGE("ASEC finalize mount failed (%s)", strerror(errno));
280        return -1;
281    }
282
283    LOGD("ASEC %s finalized", id);
284    return 0;
285}
286
287int VolumeManager::renameAsec(const char *id1, const char *id2) {
288    char *asecFilename1;
289    char *asecFilename2;
290    char mountPoint[255];
291
292    asprintf(&asecFilename1, "/sdcard/android_secure/%s.asec", id1);
293    asprintf(&asecFilename2, "/sdcard/android_secure/%s.asec", id2);
294
295    snprintf(mountPoint, sizeof(mountPoint), "/asec/%s", id1);
296    if (isMountpointMounted(mountPoint)) {
297        LOGW("Rename attempt when src mounted");
298        errno = EBUSY;
299        goto out_err;
300    }
301
302    if (!access(asecFilename2, F_OK)) {
303        LOGE("Rename attempt when dst exists");
304        errno = EADDRINUSE;
305        goto out_err;
306    }
307
308    if (rename(asecFilename1, asecFilename2)) {
309        LOGE("Rename of '%s' to '%s' failed (%s)", asecFilename1, asecFilename2, strerror(errno));
310        goto out_err;
311    }
312
313    free(asecFilename1);
314    free(asecFilename2);
315    return 0;
316
317out_err:
318    free(asecFilename1);
319    free(asecFilename2);
320    return -1;
321}
322
323int VolumeManager::unmountAsec(const char *id) {
324    char asecFileName[255];
325    char mountPoint[255];
326
327    snprintf(asecFileName, sizeof(asecFileName),
328             "/sdcard/android_secure/%s.asec", id);
329    snprintf(mountPoint, sizeof(mountPoint), "/asec/%s", id);
330
331    if (!isMountpointMounted(mountPoint)) {
332        LOGE("Unmount request for ASEC %s when not mounted", id);
333        errno = EINVAL;
334        return -1;
335    }
336
337    int i, rc;
338    for (i = 0; i < 10; i++) {
339        rc = umount(mountPoint);
340        if (!rc) {
341            break;
342        }
343        if (rc && (errno == EINVAL || errno == ENOENT)) {
344            rc = 0;
345            break;
346        }
347        LOGW("ASEC %s unmount attempt %d failed (%s)",
348              id, i +1, strerror(errno));
349
350        if (i >= 5) {
351            KillProcessesWithOpenFiles(mountPoint, (i < 7 ? 0 : 1),
352                                       NULL, 0);
353        }
354        usleep(1000 * 250);
355    }
356
357    if (rc) {
358        LOGE("Failed to unmount ASEC %s", id);
359        return -1;
360    }
361
362    if (rmdir(mountPoint)) {
363        LOGE("Failed to rmdir mountpoint (%s)", strerror(errno));
364    }
365
366    if (Devmapper::destroy(id) && errno != ENXIO) {
367        LOGE("Failed to destroy devmapper instance (%s)", strerror(errno));
368    }
369
370    char loopDevice[255];
371    if (!Loop::lookupActive(asecFileName, loopDevice, sizeof(loopDevice))) {
372        Loop::destroyByDevice(loopDevice);
373    }
374
375    AsecIdCollection::iterator it;
376    for (it = mActiveContainers->begin(); it != mActiveContainers->end(); ++it) {
377        if (!strcmp(*it, id)) {
378            free(*it);
379            mActiveContainers->erase(it);
380            break;
381        }
382    }
383    if (it == mActiveContainers->end()) {
384        LOGW("mActiveContainers is inconsistent!");
385    }
386    return 0;
387}
388
389int VolumeManager::destroyAsec(const char *id) {
390    char asecFileName[255];
391    char mountPoint[255];
392
393    snprintf(asecFileName, sizeof(asecFileName),
394             "/sdcard/android_secure/%s.asec", id);
395    snprintf(mountPoint, sizeof(mountPoint), "/asec/%s", id);
396
397    if (isMountpointMounted(mountPoint)) {
398        LOGD("Unmounting container before destroy");
399        if (unmountAsec(id)) {
400            LOGE("Failed to unmount asec %s for destroy (%s)", id, strerror(errno));
401            return -1;
402        }
403    }
404
405    if (unlink(asecFileName)) {
406        LOGE("Failed to unlink asec '%s' (%s)", asecFileName, strerror(errno));
407        return -1;
408    }
409
410    LOGD("ASEC %s destroyed", id);
411    return 0;
412}
413
414int VolumeManager::mountAsec(const char *id, const char *key, int ownerUid) {
415    char asecFileName[255];
416    char mountPoint[255];
417
418    snprintf(asecFileName, sizeof(asecFileName),
419             "/sdcard/android_secure/%s.asec", id);
420    snprintf(mountPoint, sizeof(mountPoint), "/asec/%s", id);
421
422    if (isMountpointMounted(mountPoint)) {
423        LOGE("ASEC %s already mounted", id);
424        errno = EBUSY;
425        return -1;
426    }
427
428    char loopDevice[255];
429    if (Loop::lookupActive(asecFileName, loopDevice, sizeof(loopDevice))) {
430        if (Loop::create(asecFileName, loopDevice, sizeof(loopDevice))) {
431            LOGE("ASEC loop device creation failed (%s)", strerror(errno));
432            return -1;
433        }
434        LOGD("New loop device created at %s", loopDevice);
435    } else {
436        LOGD("Found active loopback for %s at %s", asecFileName, loopDevice);
437    }
438
439    char dmDevice[255];
440    bool cleanupDm = false;
441    if (strcmp(key, "none")) {
442        if (Devmapper::lookupActive(id, dmDevice, sizeof(dmDevice))) {
443            unsigned int nr_sec = 0;
444            int fd;
445
446            if ((fd = open(loopDevice, O_RDWR)) < 0) {
447                LOGE("Failed to open loopdevice (%s)", strerror(errno));
448                Loop::destroyByDevice(loopDevice);
449                return -1;
450            }
451
452            if (ioctl(fd, BLKGETSIZE, &nr_sec)) {
453                LOGE("Failed to get loop size (%s)", strerror(errno));
454                Loop::destroyByDevice(loopDevice);
455                close(fd);
456                return -1;
457            }
458            close(fd);
459            if (Devmapper::create(id, loopDevice, key, nr_sec,
460                                  dmDevice, sizeof(dmDevice))) {
461                LOGE("ASEC device mapping failed (%s)", strerror(errno));
462                Loop::destroyByDevice(loopDevice);
463                return -1;
464            }
465            LOGD("New devmapper instance created at %s", dmDevice);
466        } else {
467            LOGD("Found active devmapper for %s at %s", asecFileName, dmDevice);
468        }
469        cleanupDm = true;
470    } else {
471        strcpy(dmDevice, loopDevice);
472    }
473
474    if (mkdir(mountPoint, 0777)) {
475        if (errno != EEXIST) {
476            LOGE("Mountpoint creation failed (%s)", strerror(errno));
477            if (cleanupDm) {
478                Devmapper::destroy(id);
479            }
480            Loop::destroyByDevice(loopDevice);
481            return -1;
482        }
483    }
484
485    if (Fat::doMount(dmDevice, mountPoint, true, false, ownerUid, 0,
486                     0222, false)) {
487//                     0227, false)) {
488        LOGE("ASEC mount failed (%s)", strerror(errno));
489        if (cleanupDm) {
490            Devmapper::destroy(id);
491        }
492        Loop::destroyByDevice(loopDevice);
493        return -1;
494    }
495
496    mActiveContainers->push_back(strdup(id));
497    LOGD("ASEC %s mounted", id);
498    return 0;
499}
500
501int VolumeManager::mountVolume(const char *label) {
502    Volume *v = lookupVolume(label);
503
504    if (!v) {
505        errno = ENOENT;
506        return -1;
507    }
508
509    return v->mountVol();
510}
511
512int VolumeManager::shareAvailable(const char *method, bool *avail) {
513
514    if (strcmp(method, "ums")) {
515        errno = ENOSYS;
516        return -1;
517    }
518
519    if (mUsbMassStorageConnected)
520        *avail = true;
521    else
522        *avail = false;
523    return 0;
524}
525
526int VolumeManager::shareEnabled(const char *label, const char *method, bool *enabled) {
527    Volume *v = lookupVolume(label);
528
529    if (!v) {
530        errno = ENOENT;
531        return -1;
532    }
533
534    if (strcmp(method, "ums")) {
535        errno = ENOSYS;
536        return -1;
537    }
538
539    if (v->getState() != Volume::State_Shared) {
540        *enabled = true;
541    } else {
542        *enabled = false;
543    }
544    return 0;
545}
546
547int VolumeManager::simulate(const char *cmd, const char *arg) {
548
549    if (!strcmp(cmd, "ums")) {
550        if (!strcmp(arg, "connect")) {
551            notifyUmsConnected(true);
552        } else if (!strcmp(arg, "disconnect")) {
553            notifyUmsConnected(false);
554        } else {
555            errno = EINVAL;
556            return -1;
557        }
558    } else {
559        errno = EINVAL;
560        return -1;
561    }
562    return 0;
563}
564
565int VolumeManager::shareVolume(const char *label, const char *method) {
566    Volume *v = lookupVolume(label);
567
568    if (!v) {
569        errno = ENOENT;
570        return -1;
571    }
572
573    /*
574     * Eventually, we'll want to support additional share back-ends,
575     * some of which may work while the media is mounted. For now,
576     * we just support UMS
577     */
578    if (strcmp(method, "ums")) {
579        errno = ENOSYS;
580        return -1;
581    }
582
583    if (v->getState() == Volume::State_NoMedia) {
584        errno = ENODEV;
585        return -1;
586    }
587
588    if (v->getState() != Volume::State_Idle) {
589        // You need to unmount manually befoe sharing
590        errno = EBUSY;
591        return -1;
592    }
593
594    dev_t d = v->getDiskDevice();
595    if ((MAJOR(d) == 0) && (MINOR(d) == 0)) {
596        // This volume does not support raw disk access
597        errno = EINVAL;
598        return -1;
599    }
600
601    int fd;
602    char nodepath[255];
603    snprintf(nodepath,
604             sizeof(nodepath), "/dev/block/vold/%d:%d",
605             MAJOR(d), MINOR(d));
606
607    if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file",
608                   O_WRONLY)) < 0) {
609        LOGE("Unable to open ums lunfile (%s)", strerror(errno));
610        return -1;
611    }
612
613    if (write(fd, nodepath, strlen(nodepath)) < 0) {
614        LOGE("Unable to write to ums lunfile (%s)", strerror(errno));
615        close(fd);
616        return -1;
617    }
618
619    close(fd);
620    v->handleVolumeShared();
621    return 0;
622}
623
624int VolumeManager::unshareVolume(const char *label, const char *method) {
625    Volume *v = lookupVolume(label);
626
627    if (!v) {
628        errno = ENOENT;
629        return -1;
630    }
631
632    if (strcmp(method, "ums")) {
633        errno = ENOSYS;
634        return -1;
635    }
636
637    if (v->getState() != Volume::State_Shared) {
638        errno = EINVAL;
639        return -1;
640    }
641
642    dev_t d = v->getDiskDevice();
643
644    int fd;
645    char nodepath[255];
646    snprintf(nodepath,
647             sizeof(nodepath), "/dev/block/vold/%d:%d",
648             MAJOR(d), MINOR(d));
649
650    if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file", O_WRONLY)) < 0) {
651        LOGE("Unable to open ums lunfile (%s)", strerror(errno));
652        return -1;
653    }
654
655    char ch = 0;
656    if (write(fd, &ch, 1) < 0) {
657        LOGE("Unable to write to ums lunfile (%s)", strerror(errno));
658        close(fd);
659        return -1;
660    }
661
662    close(fd);
663    v->handleVolumeUnshared();
664    return 0;
665}
666
667int VolumeManager::unmountVolume(const char *label) {
668    Volume *v = lookupVolume(label);
669
670    if (!v) {
671        errno = ENOENT;
672        return -1;
673    }
674
675    if (v->getState() == Volume::State_NoMedia) {
676        errno = ENODEV;
677        return -1;
678    }
679
680    if (v->getState() != Volume::State_Mounted) {
681        LOGW("Attempt to unmount volume which isn't mounted (%d)\n",
682             v->getState());
683        errno = EBUSY;
684        return -1;
685    }
686
687    while(mActiveContainers->size()) {
688        AsecIdCollection::iterator it = mActiveContainers->begin();
689        LOGI("Unmounting ASEC %s (dependant on %s)", *it, v->getMountpoint());
690        if (unmountAsec(*it)) {
691            LOGE("Failed to unmount ASEC %s (%s) - unmount of %s may fail!", *it,
692                 strerror(errno), v->getMountpoint());
693        }
694    }
695
696    return v->unmountVol();
697}
698
699/*
700 * Looks up a volume by it's label or mount-point
701 */
702Volume *VolumeManager::lookupVolume(const char *label) {
703    VolumeCollection::iterator i;
704
705    for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
706        if (label[0] == '/') {
707            if (!strcmp(label, (*i)->getMountpoint()))
708                return (*i);
709        } else {
710            if (!strcmp(label, (*i)->getLabel()))
711                return (*i);
712        }
713    }
714    return NULL;
715}
716
717bool VolumeManager::isMountpointMounted(const char *mp)
718{
719    char device[256];
720    char mount_path[256];
721    char rest[256];
722    FILE *fp;
723    char line[1024];
724
725    if (!(fp = fopen("/proc/mounts", "r"))) {
726        LOGE("Error opening /proc/mounts (%s)", strerror(errno));
727        return false;
728    }
729
730    while(fgets(line, sizeof(line), fp)) {
731        line[strlen(line)-1] = '\0';
732        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
733        if (!strcmp(mount_path, mp)) {
734            fclose(fp);
735            return true;
736        }
737
738    }
739
740    fclose(fp);
741    return false;
742}
743
744