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