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