Volume.cpp revision 2dfe297ec47559dbe2297a72bea71cf515c03797
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 <stdlib.h>
18#include <string.h>
19#include <dirent.h>
20#include <errno.h>
21#include <fcntl.h>
22
23#include <sys/types.h>
24#include <sys/stat.h>
25#include <sys/types.h>
26#include <sys/mman.h>
27#include <sys/mount.h>
28
29#include <linux/kdev_t.h>
30
31#include <cutils/properties.h>
32
33#include <diskconfig/diskconfig.h>
34
35#define LOG_TAG "Vold"
36
37#include <cutils/log.h>
38
39#include "Volume.h"
40#include "VolumeManager.h"
41#include "ResponseCode.h"
42#include "Fat.h"
43#include "Process.h"
44
45extern "C" void dos_partition_dec(void const *pp, struct dos_partition *d);
46extern "C" void dos_partition_enc(void *pp, struct dos_partition *d);
47
48
49/*
50 * Secure directory - stuff that only root can see
51 */
52const char *Volume::SECDIR            = "/mnt/secure";
53
54/*
55 * Secure staging directory - where media is mounted for preparation
56 */
57const char *Volume::SEC_STGDIR        = "/mnt/secure/staging";
58
59/*
60 * Path to the directory on the media which contains publicly accessable
61 * asec imagefiles. This path will be obscured before the mount is
62 * exposed to non priviledged users.
63 */
64const char *Volume::SEC_STG_SECIMGDIR = "/mnt/secure/staging/.android_secure";
65
66/*
67 * Path to where *only* root can access asec imagefiles
68 */
69const char *Volume::SEC_ASECDIR       = "/mnt/secure/asec";
70
71/*
72 * Path to where secure containers are mounted
73 */
74const char *Volume::ASECDIR           = "/mnt/asec";
75
76/*
77 * Path to where OBBs are mounted
78 */
79const char *Volume::LOOPDIR           = "/mnt/obb";
80
81static const char *stateToStr(int state) {
82    if (state == Volume::State_Init)
83        return "Initializing";
84    else if (state == Volume::State_NoMedia)
85        return "No-Media";
86    else if (state == Volume::State_Idle)
87        return "Idle-Unmounted";
88    else if (state == Volume::State_Pending)
89        return "Pending";
90    else if (state == Volume::State_Mounted)
91        return "Mounted";
92    else if (state == Volume::State_Unmounting)
93        return "Unmounting";
94    else if (state == Volume::State_Checking)
95        return "Checking";
96    else if (state == Volume::State_Formatting)
97        return "Formatting";
98    else if (state == Volume::State_Shared)
99        return "Shared-Unmounted";
100    else if (state == Volume::State_SharedMnt)
101        return "Shared-Mounted";
102    else
103        return "Unknown-Error";
104}
105
106Volume::Volume(VolumeManager *vm, const char *label, const char *mount_point) {
107    mVm = vm;
108    mDebug = false;
109    mLabel = strdup(label);
110    mMountpoint = strdup(mount_point);
111    mState = Volume::State_Init;
112    mCurrentlyMountedKdev = -1;
113}
114
115Volume::~Volume() {
116    free(mLabel);
117    free(mMountpoint);
118}
119
120void Volume::protectFromAutorunStupidity() {
121    char filename[255];
122
123    snprintf(filename, sizeof(filename), "%s/autorun.inf", SEC_STGDIR);
124    if (!access(filename, F_OK)) {
125        SLOGW("Volume contains an autorun.inf! - removing");
126        /*
127         * Ensure the filename is all lower-case so
128         * the process killer can find the inode.
129         * Probably being paranoid here but meh.
130         */
131        rename(filename, filename);
132        Process::killProcessesWithOpenFiles(filename, 2);
133        if (unlink(filename)) {
134            SLOGE("Failed to remove %s (%s)", filename, strerror(errno));
135        }
136    }
137}
138
139void Volume::setDebug(bool enable) {
140    mDebug = enable;
141}
142
143dev_t Volume::getDiskDevice() {
144    return MKDEV(0, 0);
145};
146
147dev_t Volume::getShareDevice() {
148    return getDiskDevice();
149}
150
151void Volume::handleVolumeShared() {
152}
153
154void Volume::handleVolumeUnshared() {
155}
156
157int Volume::handleBlockEvent(NetlinkEvent *evt) {
158    errno = ENOSYS;
159    return -1;
160}
161
162void Volume::setState(int state) {
163    char msg[255];
164    int oldState = mState;
165
166    if (oldState == state) {
167        SLOGW("Duplicate state (%d)\n", state);
168        return;
169    }
170
171    mState = state;
172
173    SLOGD("Volume %s state changing %d (%s) -> %d (%s)", mLabel,
174         oldState, stateToStr(oldState), mState, stateToStr(mState));
175    snprintf(msg, sizeof(msg),
176             "Volume %s %s state changed from %d (%s) to %d (%s)", getLabel(),
177             getMountpoint(), oldState, stateToStr(oldState), mState,
178             stateToStr(mState));
179
180    mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeStateChange,
181                                         msg, false);
182}
183
184int Volume::createDeviceNode(const char *path, int major, int minor) {
185    mode_t mode = 0660 | S_IFBLK;
186    dev_t dev = (major << 8) | minor;
187    if (mknod(path, mode, dev) < 0) {
188        if (errno != EEXIST) {
189            return -1;
190        }
191    }
192    return 0;
193}
194
195int Volume::formatVol() {
196
197    if (getState() == Volume::State_NoMedia) {
198        errno = ENODEV;
199        return -1;
200    } else if (getState() != Volume::State_Idle) {
201        errno = EBUSY;
202        return -1;
203    }
204
205    if (isMountpointMounted(getMountpoint())) {
206        SLOGW("Volume is idle but appears to be mounted - fixing");
207        setState(Volume::State_Mounted);
208        // mCurrentlyMountedKdev = XXX
209        errno = EBUSY;
210        return -1;
211    }
212
213    char devicePath[255];
214    dev_t diskNode = getDiskDevice();
215    dev_t partNode = MKDEV(MAJOR(diskNode), 1); // XXX: Hmmm
216
217    sprintf(devicePath, "/dev/block/vold/%d:%d",
218            MAJOR(diskNode), MINOR(diskNode));
219
220    if (mDebug) {
221        SLOGI("Formatting volume %s (%s)", getLabel(), devicePath);
222    }
223    setState(Volume::State_Formatting);
224
225    if (initializeMbr(devicePath)) {
226        SLOGE("Failed to initialize MBR (%s)", strerror(errno));
227//        goto err;
228// don't treat this as a fatal error
229// lets continue on and format the partition
230    }
231
232    sprintf(devicePath, "/dev/block/vold/%d:%d",
233            MAJOR(partNode), MINOR(partNode));
234
235    if (Fat::format(devicePath, 0)) {
236        SLOGE("Failed to format (%s)", strerror(errno));
237        goto err;
238    }
239
240    setState(Volume::State_Idle);
241    return 0;
242err:
243    return -1;
244}
245
246bool Volume::isMountpointMounted(const char *path) {
247    char device[256];
248    char mount_path[256];
249    char rest[256];
250    FILE *fp;
251    char line[1024];
252
253    if (!(fp = fopen("/proc/mounts", "r"))) {
254        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
255        return false;
256    }
257
258    while(fgets(line, sizeof(line), fp)) {
259        line[strlen(line)-1] = '\0';
260        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
261        if (!strcmp(mount_path, path)) {
262            fclose(fp);
263            return true;
264        }
265
266    }
267
268    fclose(fp);
269    return false;
270}
271
272int Volume::mountVol() {
273    dev_t deviceNodes[4];
274    int n, i, rc = 0;
275    char errmsg[255];
276
277    if (getState() == Volume::State_NoMedia) {
278        snprintf(errmsg, sizeof(errmsg),
279                 "Volume %s %s mount failed - no media",
280                 getLabel(), getMountpoint());
281        mVm->getBroadcaster()->sendBroadcast(
282                                         ResponseCode::VolumeMountFailedNoMedia,
283                                         errmsg, false);
284        errno = ENODEV;
285        return -1;
286    } else if (getState() != Volume::State_Idle) {
287        errno = EBUSY;
288        return -1;
289    }
290
291    if (isMountpointMounted(getMountpoint())) {
292        SLOGW("Volume is idle but appears to be mounted - fixing");
293        setState(Volume::State_Mounted);
294        // mCurrentlyMountedKdev = XXX
295        return 0;
296    }
297
298    n = getDeviceNodes((dev_t *) &deviceNodes, 4);
299    if (!n) {
300        SLOGE("Failed to get device nodes (%s)\n", strerror(errno));
301        return -1;
302    }
303
304    for (i = 0; i < n; i++) {
305        char devicePath[255];
306
307        sprintf(devicePath, "/dev/block/vold/%d:%d", MAJOR(deviceNodes[i]),
308                MINOR(deviceNodes[i]));
309
310        SLOGI("%s being considered for volume %s\n", devicePath, getLabel());
311
312        errno = 0;
313        setState(Volume::State_Checking);
314
315        if (Fat::check(devicePath)) {
316            if (errno == ENODATA) {
317                SLOGW("%s does not contain a FAT filesystem\n", devicePath);
318                continue;
319            }
320            errno = EIO;
321            /* Badness - abort the mount */
322            SLOGE("%s failed FS checks (%s)", devicePath, strerror(errno));
323            setState(Volume::State_Idle);
324            return -1;
325        }
326
327        /*
328         * Mount the device on our internal staging mountpoint so we can
329         * muck with it before exposing it to non priviledged users.
330         */
331        errno = 0;
332        if (Fat::doMount(devicePath, "/mnt/secure/staging", false, false, false,
333                1000, 1015, 0702, true)) {
334            SLOGE("%s failed to mount via VFAT (%s)\n", devicePath, strerror(errno));
335            continue;
336        }
337
338        SLOGI("Device %s, target %s mounted @ /mnt/secure/staging", devicePath, getMountpoint());
339
340        protectFromAutorunStupidity();
341
342        if (createBindMounts()) {
343            SLOGE("Failed to create bindmounts (%s)", strerror(errno));
344            umount("/mnt/secure/staging");
345            setState(Volume::State_Idle);
346            return -1;
347        }
348
349        /*
350         * Now that the bindmount trickery is done, atomically move the
351         * whole subtree to expose it to non priviledged users.
352         */
353        if (doMoveMount("/mnt/secure/staging", getMountpoint(), false)) {
354            SLOGE("Failed to move mount (%s)", strerror(errno));
355            umount("/mnt/secure/staging");
356            setState(Volume::State_Idle);
357            return -1;
358        }
359        setState(Volume::State_Mounted);
360        mCurrentlyMountedKdev = deviceNodes[i];
361        return 0;
362    }
363
364    SLOGE("Volume %s found no suitable devices for mounting :(\n", getLabel());
365    setState(Volume::State_Idle);
366
367    return -1;
368}
369
370int Volume::createBindMounts() {
371    unsigned long flags;
372
373    /*
374     * Rename old /android_secure -> /.android_secure
375     */
376    if (!access("/mnt/secure/staging/android_secure", R_OK | X_OK) &&
377         access(SEC_STG_SECIMGDIR, R_OK | X_OK)) {
378        if (rename("/mnt/secure/staging/android_secure", SEC_STG_SECIMGDIR)) {
379            SLOGE("Failed to rename legacy asec dir (%s)", strerror(errno));
380        }
381    }
382
383    /*
384     * Ensure that /android_secure exists and is a directory
385     */
386    if (access(SEC_STG_SECIMGDIR, R_OK | X_OK)) {
387        if (errno == ENOENT) {
388            if (mkdir(SEC_STG_SECIMGDIR, 0777)) {
389                SLOGE("Failed to create %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
390                return -1;
391            }
392        } else {
393            SLOGE("Failed to access %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
394            return -1;
395        }
396    } else {
397        struct stat sbuf;
398
399        if (stat(SEC_STG_SECIMGDIR, &sbuf)) {
400            SLOGE("Failed to stat %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
401            return -1;
402        }
403        if (!S_ISDIR(sbuf.st_mode)) {
404            SLOGE("%s is not a directory", SEC_STG_SECIMGDIR);
405            errno = ENOTDIR;
406            return -1;
407        }
408    }
409
410    /*
411     * Bind mount /mnt/secure/staging/android_secure -> /mnt/secure/asec so we'll
412     * have a root only accessable mountpoint for it.
413     */
414    if (mount(SEC_STG_SECIMGDIR, SEC_ASECDIR, "", MS_BIND, NULL)) {
415        SLOGE("Failed to bind mount points %s -> %s (%s)",
416                SEC_STG_SECIMGDIR, SEC_ASECDIR, strerror(errno));
417        return -1;
418    }
419
420    /*
421     * Mount a read-only, zero-sized tmpfs  on <mountpoint>/android_secure to
422     * obscure the underlying directory from everybody - sneaky eh? ;)
423     */
424    if (mount("tmpfs", SEC_STG_SECIMGDIR, "tmpfs", MS_RDONLY, "size=0,mode=000,uid=0,gid=0")) {
425        SLOGE("Failed to obscure %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
426        umount("/mnt/asec_secure");
427        return -1;
428    }
429
430    return 0;
431}
432
433int Volume::doMoveMount(const char *src, const char *dst, bool force) {
434    unsigned int flags = MS_MOVE;
435    int retries = 5;
436
437    while(retries--) {
438        if (!mount(src, dst, "", flags, NULL)) {
439            if (mDebug) {
440                SLOGD("Moved mount %s -> %s sucessfully", src, dst);
441            }
442            return 0;
443        } else if (errno != EBUSY) {
444            SLOGE("Failed to move mount %s -> %s (%s)", src, dst, strerror(errno));
445            return -1;
446        }
447        int action = 0;
448
449        if (force) {
450            if (retries == 1) {
451                action = 2; // SIGKILL
452            } else if (retries == 2) {
453                action = 1; // SIGHUP
454            }
455        }
456        SLOGW("Failed to move %s -> %s (%s, retries %d, action %d)",
457                src, dst, strerror(errno), retries, action);
458        Process::killProcessesWithOpenFiles(src, action);
459        usleep(1000*250);
460    }
461
462    errno = EBUSY;
463    SLOGE("Giving up on move %s -> %s (%s)", src, dst, strerror(errno));
464    return -1;
465}
466
467int Volume::doUnmount(const char *path, bool force) {
468    int retries = 10;
469
470    if (mDebug) {
471        SLOGD("Unmounting {%s}, force = %d", path, force);
472    }
473
474    while (retries--) {
475        if (!umount(path) || errno == EINVAL || errno == ENOENT) {
476            SLOGI("%s sucessfully unmounted", path);
477            return 0;
478        }
479
480        int action = 0;
481
482        if (force) {
483            if (retries == 1) {
484                action = 2; // SIGKILL
485            } else if (retries == 2) {
486                action = 1; // SIGHUP
487            }
488        }
489
490        SLOGW("Failed to unmount %s (%s, retries %d, action %d)",
491                path, strerror(errno), retries, action);
492
493        Process::killProcessesWithOpenFiles(path, action);
494        usleep(1000*1000);
495    }
496    errno = EBUSY;
497    SLOGE("Giving up on unmount %s (%s)", path, strerror(errno));
498    return -1;
499}
500
501int Volume::unmountVol(bool force) {
502    int i, rc;
503
504    if (getState() != Volume::State_Mounted) {
505        SLOGE("Volume %s unmount request when not mounted", getLabel());
506        errno = EINVAL;
507        return -1;
508    }
509
510    setState(Volume::State_Unmounting);
511    usleep(1000 * 1000); // Give the framework some time to react
512
513    /*
514     * First move the mountpoint back to our internal staging point
515     * so nobody else can muck with it while we work.
516     */
517    if (doMoveMount(getMountpoint(), SEC_STGDIR, force)) {
518        SLOGE("Failed to move mount %s => %s (%s)", getMountpoint(), SEC_STGDIR, strerror(errno));
519        setState(Volume::State_Mounted);
520        return -1;
521    }
522
523    protectFromAutorunStupidity();
524
525    /*
526     * Unmount the tmpfs which was obscuring the asec image directory
527     * from non root users
528     */
529
530    if (doUnmount(Volume::SEC_STG_SECIMGDIR, force)) {
531        SLOGE("Failed to unmount tmpfs on %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
532        goto fail_republish;
533    }
534
535    /*
536     * Remove the bindmount we were using to keep a reference to
537     * the previously obscured directory.
538     */
539
540    if (doUnmount(Volume::SEC_ASECDIR, force)) {
541        SLOGE("Failed to remove bindmount on %s (%s)", SEC_ASECDIR, strerror(errno));
542        goto fail_remount_tmpfs;
543    }
544
545    /*
546     * Finally, unmount the actual block device from the staging dir
547     */
548    if (doUnmount(Volume::SEC_STGDIR, force)) {
549        SLOGE("Failed to unmount %s (%s)", SEC_STGDIR, strerror(errno));
550        goto fail_recreate_bindmount;
551    }
552
553    SLOGI("%s unmounted sucessfully", getMountpoint());
554
555    setState(Volume::State_Idle);
556    mCurrentlyMountedKdev = -1;
557    return 0;
558
559    /*
560     * Failure handling - try to restore everything back the way it was
561     */
562fail_recreate_bindmount:
563    if (mount(SEC_STG_SECIMGDIR, SEC_ASECDIR, "", MS_BIND, NULL)) {
564        SLOGE("Failed to restore bindmount after failure! - Storage will appear offline!");
565        goto out_nomedia;
566    }
567fail_remount_tmpfs:
568    if (mount("tmpfs", SEC_STG_SECIMGDIR, "tmpfs", MS_RDONLY, "size=0,mode=0,uid=0,gid=0")) {
569        SLOGE("Failed to restore tmpfs after failure! - Storage will appear offline!");
570        goto out_nomedia;
571    }
572fail_republish:
573    if (doMoveMount(SEC_STGDIR, getMountpoint(), force)) {
574        SLOGE("Failed to republish mount after failure! - Storage will appear offline!");
575        goto out_nomedia;
576    }
577
578    setState(Volume::State_Mounted);
579    return -1;
580
581out_nomedia:
582    setState(Volume::State_NoMedia);
583    return -1;
584}
585
586int Volume::initializeMbr(const char *deviceNode) {
587    struct disk_info dinfo;
588
589    memset(&dinfo, 0, sizeof(dinfo));
590
591    if (!(dinfo.part_lst = (struct part_info *) malloc(MAX_NUM_PARTS * sizeof(struct part_info)))) {
592        SLOGE("Failed to malloc prt_lst");
593        return -1;
594    }
595
596    memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
597    dinfo.device = strdup(deviceNode);
598    dinfo.scheme = PART_SCHEME_MBR;
599    dinfo.sect_size = 512;
600    dinfo.skip_lba = 2048;
601    dinfo.num_lba = 0;
602    dinfo.num_parts = 1;
603
604    struct part_info *pinfo = &dinfo.part_lst[0];
605
606    pinfo->name = strdup("android_sdcard");
607    pinfo->flags |= PART_ACTIVE_FLAG;
608    pinfo->type = PC_PART_TYPE_FAT32;
609    pinfo->len_kb = -1;
610
611    int rc = apply_disk_config(&dinfo, 0);
612
613    if (rc) {
614        SLOGE("Failed to apply disk configuration (%d)", rc);
615        goto out;
616    }
617
618 out:
619    free(pinfo->name);
620    free(dinfo.device);
621    free(dinfo.part_lst);
622
623    return rc;
624}
625