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