Volume.cpp revision a3e06084564c86ff618c40f185f3676b8b629b94
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
147void Volume::handleVolumeShared() {
148}
149
150void Volume::handleVolumeUnshared() {
151}
152
153int Volume::handleBlockEvent(NetlinkEvent *evt) {
154    errno = ENOSYS;
155    return -1;
156}
157
158void Volume::setState(int state) {
159    char msg[255];
160    int oldState = mState;
161
162    if (oldState == state) {
163        SLOGW("Duplicate state (%d)\n", state);
164        return;
165    }
166
167    mState = state;
168
169    SLOGD("Volume %s state changing %d (%s) -> %d (%s)", mLabel,
170         oldState, stateToStr(oldState), mState, stateToStr(mState));
171    snprintf(msg, sizeof(msg),
172             "Volume %s %s state changed from %d (%s) to %d (%s)", getLabel(),
173             getMountpoint(), oldState, stateToStr(oldState), mState,
174             stateToStr(mState));
175
176    mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeStateChange,
177                                         msg, false);
178}
179
180int Volume::createDeviceNode(const char *path, int major, int minor) {
181    mode_t mode = 0660 | S_IFBLK;
182    dev_t dev = (major << 8) | minor;
183    if (mknod(path, mode, dev) < 0) {
184        if (errno != EEXIST) {
185            return -1;
186        }
187    }
188    return 0;
189}
190
191int Volume::formatVol() {
192
193    if (getState() == Volume::State_NoMedia) {
194        errno = ENODEV;
195        return -1;
196    } else if (getState() != Volume::State_Idle) {
197        errno = EBUSY;
198        return -1;
199    }
200
201    if (isMountpointMounted(getMountpoint())) {
202        SLOGW("Volume is idle but appears to be mounted - fixing");
203        setState(Volume::State_Mounted);
204        // mCurrentlyMountedKdev = XXX
205        errno = EBUSY;
206        return -1;
207    }
208
209    char devicePath[255];
210    dev_t diskNode = getDiskDevice();
211    dev_t partNode = MKDEV(MAJOR(diskNode), 1); // XXX: Hmmm
212
213    sprintf(devicePath, "/dev/block/vold/%d:%d",
214            MAJOR(diskNode), MINOR(diskNode));
215
216    if (mDebug) {
217        SLOGI("Formatting volume %s (%s)", getLabel(), devicePath);
218    }
219    setState(Volume::State_Formatting);
220
221    if (initializeMbr(devicePath)) {
222        SLOGE("Failed to initialize MBR (%s)", strerror(errno));
223        goto err;
224    }
225
226    sprintf(devicePath, "/dev/block/vold/%d:%d",
227            MAJOR(partNode), MINOR(partNode));
228
229    if (Fat::format(devicePath, 0)) {
230        SLOGE("Failed to format (%s)", strerror(errno));
231        goto err;
232    }
233
234    setState(Volume::State_Idle);
235    return 0;
236err:
237    return -1;
238}
239
240bool Volume::isMountpointMounted(const char *path) {
241    char device[256];
242    char mount_path[256];
243    char rest[256];
244    FILE *fp;
245    char line[1024];
246
247    if (!(fp = fopen("/proc/mounts", "r"))) {
248        SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
249        return false;
250    }
251
252    while(fgets(line, sizeof(line), fp)) {
253        line[strlen(line)-1] = '\0';
254        sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
255        if (!strcmp(mount_path, path)) {
256            fclose(fp);
257            return true;
258        }
259
260    }
261
262    fclose(fp);
263    return false;
264}
265
266int Volume::mountVol() {
267    dev_t deviceNodes[4];
268    int n, i, rc = 0;
269    char errmsg[255];
270
271    if (getState() == Volume::State_NoMedia) {
272        snprintf(errmsg, sizeof(errmsg),
273                 "Volume %s %s mount failed - no media",
274                 getLabel(), getMountpoint());
275        mVm->getBroadcaster()->sendBroadcast(
276                                         ResponseCode::VolumeMountFailedNoMedia,
277                                         errmsg, false);
278        errno = ENODEV;
279        return -1;
280    } else if (getState() != Volume::State_Idle) {
281        errno = EBUSY;
282        return -1;
283    }
284
285    if (isMountpointMounted(getMountpoint())) {
286        SLOGW("Volume is idle but appears to be mounted - fixing");
287        setState(Volume::State_Mounted);
288        // mCurrentlyMountedKdev = XXX
289        return 0;
290    }
291
292    n = getDeviceNodes((dev_t *) &deviceNodes, 4);
293    if (!n) {
294        SLOGE("Failed to get device nodes (%s)\n", strerror(errno));
295        return -1;
296    }
297
298    for (i = 0; i < n; i++) {
299        char devicePath[255];
300
301        sprintf(devicePath, "/dev/block/vold/%d:%d", MAJOR(deviceNodes[i]),
302                MINOR(deviceNodes[i]));
303
304        SLOGI("%s being considered for volume %s\n", devicePath, getLabel());
305
306        errno = 0;
307        setState(Volume::State_Checking);
308
309        if (Fat::check(devicePath)) {
310            if (errno == ENODATA) {
311                SLOGW("%s does not contain a FAT filesystem\n", devicePath);
312                continue;
313            }
314            errno = EIO;
315            /* Badness - abort the mount */
316            SLOGE("%s failed FS checks (%s)", devicePath, strerror(errno));
317            setState(Volume::State_Idle);
318            return -1;
319        }
320
321        /*
322         * Mount the device on our internal staging mountpoint so we can
323         * muck with it before exposing it to non priviledged users.
324         */
325        errno = 0;
326        if (Fat::doMount(devicePath, "/mnt/secure/staging", false, false, false,
327                1000, 1015, 0702, true)) {
328            SLOGE("%s failed to mount via VFAT (%s)\n", devicePath, strerror(errno));
329            continue;
330        }
331
332        SLOGI("Device %s, target %s mounted @ /mnt/secure/staging", devicePath, getMountpoint());
333
334        protectFromAutorunStupidity();
335
336        if (createBindMounts()) {
337            SLOGE("Failed to create bindmounts (%s)", strerror(errno));
338            umount("/mnt/secure/staging");
339            setState(Volume::State_Idle);
340            return -1;
341        }
342
343        /*
344         * Now that the bindmount trickery is done, atomically move the
345         * whole subtree to expose it to non priviledged users.
346         */
347        if (doMoveMount("/mnt/secure/staging", getMountpoint(), false)) {
348            SLOGE("Failed to move mount (%s)", strerror(errno));
349            umount("/mnt/secure/staging");
350            setState(Volume::State_Idle);
351            return -1;
352        }
353        setState(Volume::State_Mounted);
354        mCurrentlyMountedKdev = deviceNodes[i];
355        return 0;
356    }
357
358    SLOGE("Volume %s found no suitable devices for mounting :(\n", getLabel());
359    setState(Volume::State_Idle);
360
361    return -1;
362}
363
364int Volume::createBindMounts() {
365    unsigned long flags;
366
367    /*
368     * Rename old /android_secure -> /.android_secure
369     */
370    if (!access("/mnt/secure/staging/android_secure", R_OK | X_OK) &&
371         access(SEC_STG_SECIMGDIR, R_OK | X_OK)) {
372        if (rename("/mnt/secure/staging/android_secure", SEC_STG_SECIMGDIR)) {
373            SLOGE("Failed to rename legacy asec dir (%s)", strerror(errno));
374        }
375    }
376
377    /*
378     * Ensure that /android_secure exists and is a directory
379     */
380    if (access(SEC_STG_SECIMGDIR, R_OK | X_OK)) {
381        if (errno == ENOENT) {
382            if (mkdir(SEC_STG_SECIMGDIR, 0777)) {
383                SLOGE("Failed to create %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
384                return -1;
385            }
386        } else {
387            SLOGE("Failed to access %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
388            return -1;
389        }
390    } else {
391        struct stat sbuf;
392
393        if (stat(SEC_STG_SECIMGDIR, &sbuf)) {
394            SLOGE("Failed to stat %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
395            return -1;
396        }
397        if (!S_ISDIR(sbuf.st_mode)) {
398            SLOGE("%s is not a directory", SEC_STG_SECIMGDIR);
399            errno = ENOTDIR;
400            return -1;
401        }
402    }
403
404    /*
405     * Bind mount /mnt/secure/staging/android_secure -> /mnt/secure/asec so we'll
406     * have a root only accessable mountpoint for it.
407     */
408    if (mount(SEC_STG_SECIMGDIR, SEC_ASECDIR, "", MS_BIND, NULL)) {
409        SLOGE("Failed to bind mount points %s -> %s (%s)",
410                SEC_STG_SECIMGDIR, SEC_ASECDIR, strerror(errno));
411        return -1;
412    }
413
414    /*
415     * Mount a read-only, zero-sized tmpfs  on <mountpoint>/android_secure to
416     * obscure the underlying directory from everybody - sneaky eh? ;)
417     */
418    if (mount("tmpfs", SEC_STG_SECIMGDIR, "tmpfs", MS_RDONLY, "size=0,mode=000,uid=0,gid=0")) {
419        SLOGE("Failed to obscure %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
420        umount("/mnt/asec_secure");
421        return -1;
422    }
423
424    return 0;
425}
426
427int Volume::doMoveMount(const char *src, const char *dst, bool force) {
428    unsigned int flags = MS_MOVE;
429    int retries = 5;
430
431    while(retries--) {
432        if (!mount(src, dst, "", flags, NULL)) {
433            if (mDebug) {
434                SLOGD("Moved mount %s -> %s sucessfully", src, dst);
435            }
436            return 0;
437        } else if (errno != EBUSY) {
438            SLOGE("Failed to move mount %s -> %s (%s)", src, dst, strerror(errno));
439            return -1;
440        }
441        int action = 0;
442
443        if (force) {
444            if (retries == 1) {
445                action = 2; // SIGKILL
446            } else if (retries == 2) {
447                action = 1; // SIGHUP
448            }
449        }
450        SLOGW("Failed to move %s -> %s (%s, retries %d, action %d)",
451                src, dst, strerror(errno), retries, action);
452        Process::killProcessesWithOpenFiles(src, action);
453        usleep(1000*250);
454    }
455
456    errno = EBUSY;
457    SLOGE("Giving up on move %s -> %s (%s)", src, dst, strerror(errno));
458    return -1;
459}
460
461int Volume::doUnmount(const char *path, bool force) {
462    int retries = 10;
463
464    if (mDebug) {
465        SLOGD("Unmounting {%s}, force = %d", path, force);
466    }
467
468    while (retries--) {
469        if (!umount(path) || errno == EINVAL || errno == ENOENT) {
470            SLOGI("%s sucessfully unmounted", path);
471            return 0;
472        }
473
474        int action = 0;
475
476        if (force) {
477            if (retries == 1) {
478                action = 2; // SIGKILL
479            } else if (retries == 2) {
480                action = 1; // SIGHUP
481            }
482        }
483
484        SLOGW("Failed to unmount %s (%s, retries %d, action %d)",
485                path, strerror(errno), retries, action);
486
487        Process::killProcessesWithOpenFiles(path, action);
488        usleep(1000*1000);
489    }
490    errno = EBUSY;
491    SLOGE("Giving up on unmount %s (%s)", path, strerror(errno));
492    return -1;
493}
494
495int Volume::unmountVol(bool force) {
496    int i, rc;
497
498    if (getState() != Volume::State_Mounted) {
499        SLOGE("Volume %s unmount request when not mounted", getLabel());
500        errno = EINVAL;
501        return -1;
502    }
503
504    setState(Volume::State_Unmounting);
505    usleep(1000 * 1000); // Give the framework some time to react
506
507    /*
508     * First move the mountpoint back to our internal staging point
509     * so nobody else can muck with it while we work.
510     */
511    if (doMoveMount(getMountpoint(), SEC_STGDIR, force)) {
512        SLOGE("Failed to move mount %s => %s (%s)", getMountpoint(), SEC_STGDIR, strerror(errno));
513        setState(Volume::State_Mounted);
514        return -1;
515    }
516
517    protectFromAutorunStupidity();
518
519    /*
520     * Unmount the tmpfs which was obscuring the asec image directory
521     * from non root users
522     */
523
524    if (doUnmount(Volume::SEC_STG_SECIMGDIR, force)) {
525        SLOGE("Failed to unmount tmpfs on %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
526        goto fail_republish;
527    }
528
529    /*
530     * Remove the bindmount we were using to keep a reference to
531     * the previously obscured directory.
532     */
533
534    if (doUnmount(Volume::SEC_ASECDIR, force)) {
535        SLOGE("Failed to remove bindmount on %s (%s)", SEC_ASECDIR, strerror(errno));
536        goto fail_remount_tmpfs;
537    }
538
539    /*
540     * Finally, unmount the actual block device from the staging dir
541     */
542    if (doUnmount(Volume::SEC_STGDIR, force)) {
543        SLOGE("Failed to unmount %s (%s)", SEC_STGDIR, strerror(errno));
544        goto fail_recreate_bindmount;
545    }
546
547    SLOGI("%s unmounted sucessfully", getMountpoint());
548
549    setState(Volume::State_Idle);
550    mCurrentlyMountedKdev = -1;
551    return 0;
552
553    /*
554     * Failure handling - try to restore everything back the way it was
555     */
556fail_recreate_bindmount:
557    if (mount(SEC_STG_SECIMGDIR, SEC_ASECDIR, "", MS_BIND, NULL)) {
558        SLOGE("Failed to restore bindmount after failure! - Storage will appear offline!");
559        goto out_nomedia;
560    }
561fail_remount_tmpfs:
562    if (mount("tmpfs", SEC_STG_SECIMGDIR, "tmpfs", MS_RDONLY, "size=0,mode=0,uid=0,gid=0")) {
563        SLOGE("Failed to restore tmpfs after failure! - Storage will appear offline!");
564        goto out_nomedia;
565    }
566fail_republish:
567    if (doMoveMount(SEC_STGDIR, getMountpoint(), force)) {
568        SLOGE("Failed to republish mount after failure! - Storage will appear offline!");
569        goto out_nomedia;
570    }
571
572    setState(Volume::State_Mounted);
573    return -1;
574
575out_nomedia:
576    setState(Volume::State_NoMedia);
577    return -1;
578}
579
580int Volume::initializeMbr(const char *deviceNode) {
581    struct disk_info dinfo;
582
583    memset(&dinfo, 0, sizeof(dinfo));
584
585    if (!(dinfo.part_lst = (struct part_info *) malloc(MAX_NUM_PARTS * sizeof(struct part_info)))) {
586        SLOGE("Failed to malloc prt_lst");
587        return -1;
588    }
589
590    memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
591    dinfo.device = strdup(deviceNode);
592    dinfo.scheme = PART_SCHEME_MBR;
593    dinfo.sect_size = 512;
594    dinfo.skip_lba = 2048;
595    dinfo.num_lba = 0;
596    dinfo.num_parts = 1;
597
598    struct part_info *pinfo = &dinfo.part_lst[0];
599
600    pinfo->name = strdup("android_sdcard");
601    pinfo->flags |= PART_ACTIVE_FLAG;
602    pinfo->type = PC_PART_TYPE_FAT32;
603    pinfo->len_kb = -1;
604
605    int rc = apply_disk_config(&dinfo, 0);
606
607    if (rc) {
608        SLOGE("Failed to apply disk configuration (%d)", rc);
609        goto out;
610    }
611
612 out:
613    free(pinfo->name);
614    free(dinfo.device);
615    free(dinfo.part_lst);
616
617    return rc;
618}
619