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