OSDN Git Service

Merge "Extract UUID and label from inserted volumes." into klp-dev
[android-x86/system-vold.git] / Volume.cpp
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 #include <sys/param.h>
29
30 #include <linux/kdev_t.h>
31
32 #include <cutils/properties.h>
33
34 #include <diskconfig/diskconfig.h>
35
36 #include <private/android_filesystem_config.h>
37
38 #define LOG_TAG "Vold"
39
40 #include <cutils/fs.h>
41 #include <cutils/log.h>
42
43 #include <string>
44
45 #include "Volume.h"
46 #include "VolumeManager.h"
47 #include "ResponseCode.h"
48 #include "Fat.h"
49 #include "Process.h"
50 #include "cryptfs.h"
51
52 extern "C" void dos_partition_dec(void const *pp, struct dos_partition *d);
53 extern "C" void dos_partition_enc(void *pp, struct dos_partition *d);
54
55
56 /*
57  * Media directory - stuff that only media_rw user can see
58  */
59 const char *Volume::MEDIA_DIR           = "/mnt/media_rw";
60
61 /*
62  * Fuse directory - location where fuse wrapped filesystems go
63  */
64 const char *Volume::FUSE_DIR           = "/storage";
65
66 /*
67  * Path to external storage where *only* root can access ASEC image files
68  */
69 const char *Volume::SEC_ASECDIR_EXT   = "/mnt/secure/asec";
70
71 /*
72  * Path to internal storage where *only* root can access ASEC image files
73  */
74 const char *Volume::SEC_ASECDIR_INT   = "/data/app-asec";
75 /*
76  * Path to where secure containers are mounted
77  */
78 const char *Volume::ASECDIR           = "/mnt/asec";
79
80 /*
81  * Path to where OBBs are mounted
82  */
83 const char *Volume::LOOPDIR           = "/mnt/obb";
84
85 const char *Volume::BLKID_PATH = "/system/bin/blkid";
86
87 static const char *stateToStr(int state) {
88     if (state == Volume::State_Init)
89         return "Initializing";
90     else if (state == Volume::State_NoMedia)
91         return "No-Media";
92     else if (state == Volume::State_Idle)
93         return "Idle-Unmounted";
94     else if (state == Volume::State_Pending)
95         return "Pending";
96     else if (state == Volume::State_Mounted)
97         return "Mounted";
98     else if (state == Volume::State_Unmounting)
99         return "Unmounting";
100     else if (state == Volume::State_Checking)
101         return "Checking";
102     else if (state == Volume::State_Formatting)
103         return "Formatting";
104     else if (state == Volume::State_Shared)
105         return "Shared-Unmounted";
106     else if (state == Volume::State_SharedMnt)
107         return "Shared-Mounted";
108     else
109         return "Unknown-Error";
110 }
111
112 Volume::Volume(VolumeManager *vm, const fstab_rec* rec, int flags) {
113     mVm = vm;
114     mDebug = false;
115     mLabel = strdup(rec->label);
116     mUuid = NULL;
117     mUserLabel = NULL;
118     mState = Volume::State_Init;
119     mFlags = flags;
120     mCurrentlyMountedKdev = -1;
121     mPartIdx = rec->partnum;
122     mRetryMount = false;
123 }
124
125 Volume::~Volume() {
126     free(mLabel);
127     free(mUuid);
128     free(mUserLabel);
129 }
130
131 void Volume::setDebug(bool enable) {
132     mDebug = enable;
133 }
134
135 dev_t Volume::getDiskDevice() {
136     return MKDEV(0, 0);
137 };
138
139 dev_t Volume::getShareDevice() {
140     return getDiskDevice();
141 }
142
143 void Volume::handleVolumeShared() {
144 }
145
146 void Volume::handleVolumeUnshared() {
147 }
148
149 int Volume::handleBlockEvent(NetlinkEvent *evt) {
150     errno = ENOSYS;
151     return -1;
152 }
153
154 void Volume::setUuid(const char* uuid) {
155     char msg[256];
156
157     if (mUuid) {
158         free(mUuid);
159     }
160
161     if (uuid) {
162         mUuid = strdup(uuid);
163         snprintf(msg, sizeof(msg), "%s %s \"%s\"", getLabel(),
164                 getFuseMountpoint(), mUuid);
165     } else {
166         mUuid = NULL;
167         snprintf(msg, sizeof(msg), "%s %s", getLabel(), getFuseMountpoint());
168     }
169
170     mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeUuidChange, msg,
171             false);
172 }
173
174 void Volume::setUserLabel(const char* userLabel) {
175     char msg[256];
176
177     if (mUserLabel) {
178         free(mUserLabel);
179     }
180
181     if (userLabel) {
182         mUserLabel = strdup(userLabel);
183         snprintf(msg, sizeof(msg), "%s %s \"%s\"", getLabel(),
184                 getFuseMountpoint(), mUserLabel);
185     } else {
186         mUserLabel = NULL;
187         snprintf(msg, sizeof(msg), "%s %s", getLabel(), getFuseMountpoint());
188     }
189
190     mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeUserLabelChange,
191             msg, false);
192 }
193
194 void Volume::setState(int state) {
195     char msg[255];
196     int oldState = mState;
197
198     if (oldState == state) {
199         SLOGW("Duplicate state (%d)\n", state);
200         return;
201     }
202
203     if ((oldState == Volume::State_Pending) && (state != Volume::State_Idle)) {
204         mRetryMount = false;
205     }
206
207     mState = state;
208
209     SLOGD("Volume %s state changing %d (%s) -> %d (%s)", mLabel,
210          oldState, stateToStr(oldState), mState, stateToStr(mState));
211     snprintf(msg, sizeof(msg),
212              "Volume %s %s state changed from %d (%s) to %d (%s)", getLabel(),
213              getFuseMountpoint(), oldState, stateToStr(oldState), mState,
214              stateToStr(mState));
215
216     mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeStateChange,
217                                          msg, false);
218 }
219
220 int Volume::createDeviceNode(const char *path, int major, int minor) {
221     mode_t mode = 0660 | S_IFBLK;
222     dev_t dev = (major << 8) | minor;
223     if (mknod(path, mode, dev) < 0) {
224         if (errno != EEXIST) {
225             return -1;
226         }
227     }
228     return 0;
229 }
230
231 int Volume::formatVol(bool wipe) {
232
233     if (getState() == Volume::State_NoMedia) {
234         errno = ENODEV;
235         return -1;
236     } else if (getState() != Volume::State_Idle) {
237         errno = EBUSY;
238         return -1;
239     }
240
241     if (isMountpointMounted(getMountpoint())) {
242         SLOGW("Volume is idle but appears to be mounted - fixing");
243         setState(Volume::State_Mounted);
244         // mCurrentlyMountedKdev = XXX
245         errno = EBUSY;
246         return -1;
247     }
248
249     bool formatEntireDevice = (mPartIdx == -1);
250     char devicePath[255];
251     dev_t diskNode = getDiskDevice();
252     dev_t partNode = MKDEV(MAJOR(diskNode), (formatEntireDevice ? 1 : mPartIdx));
253
254     setState(Volume::State_Formatting);
255
256     int ret = -1;
257     // Only initialize the MBR if we are formatting the entire device
258     if (formatEntireDevice) {
259         sprintf(devicePath, "/dev/block/vold/%d:%d",
260                 MAJOR(diskNode), MINOR(diskNode));
261
262         if (initializeMbr(devicePath)) {
263             SLOGE("Failed to initialize MBR (%s)", strerror(errno));
264             goto err;
265         }
266     }
267
268     sprintf(devicePath, "/dev/block/vold/%d:%d",
269             MAJOR(partNode), MINOR(partNode));
270
271     if (mDebug) {
272         SLOGI("Formatting volume %s (%s)", getLabel(), devicePath);
273     }
274
275     if (Fat::format(devicePath, 0, wipe)) {
276         SLOGE("Failed to format (%s)", strerror(errno));
277         goto err;
278     }
279
280     ret = 0;
281
282 err:
283     setState(Volume::State_Idle);
284     return ret;
285 }
286
287 bool Volume::isMountpointMounted(const char *path) {
288     char device[256];
289     char mount_path[256];
290     char rest[256];
291     FILE *fp;
292     char line[1024];
293
294     if (!(fp = fopen("/proc/mounts", "r"))) {
295         SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
296         return false;
297     }
298
299     while(fgets(line, sizeof(line), fp)) {
300         line[strlen(line)-1] = '\0';
301         sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
302         if (!strcmp(mount_path, path)) {
303             fclose(fp);
304             return true;
305         }
306     }
307
308     fclose(fp);
309     return false;
310 }
311
312 int Volume::mountVol() {
313     dev_t deviceNodes[4];
314     int n, i, rc = 0;
315     char errmsg[255];
316
317     int flags = getFlags();
318     bool providesAsec = (flags & VOL_PROVIDES_ASEC) != 0;
319
320     // TODO: handle "bind" style mounts, for emulated storage
321
322     char decrypt_state[PROPERTY_VALUE_MAX];
323     char crypto_state[PROPERTY_VALUE_MAX];
324     char encrypt_progress[PROPERTY_VALUE_MAX];
325
326     property_get("vold.decrypt", decrypt_state, "");
327     property_get("vold.encrypt_progress", encrypt_progress, "");
328
329     /* Don't try to mount the volumes if we have not yet entered the disk password
330      * or are in the process of encrypting.
331      */
332     if ((getState() == Volume::State_NoMedia) ||
333         ((!strcmp(decrypt_state, "1") || encrypt_progress[0]) && providesAsec)) {
334         snprintf(errmsg, sizeof(errmsg),
335                  "Volume %s %s mount failed - no media",
336                  getLabel(), getFuseMountpoint());
337         mVm->getBroadcaster()->sendBroadcast(
338                                          ResponseCode::VolumeMountFailedNoMedia,
339                                          errmsg, false);
340         errno = ENODEV;
341         return -1;
342     } else if (getState() != Volume::State_Idle) {
343         errno = EBUSY;
344         if (getState() == Volume::State_Pending) {
345             mRetryMount = true;
346         }
347         return -1;
348     }
349
350     if (isMountpointMounted(getMountpoint())) {
351         SLOGW("Volume is idle but appears to be mounted - fixing");
352         setState(Volume::State_Mounted);
353         // mCurrentlyMountedKdev = XXX
354         return 0;
355     }
356
357     n = getDeviceNodes((dev_t *) &deviceNodes, 4);
358     if (!n) {
359         SLOGE("Failed to get device nodes (%s)\n", strerror(errno));
360         return -1;
361     }
362
363     /* If we're running encrypted, and the volume is marked as encryptable and nonremovable,
364      * and also marked as providing Asec storage, then we need to decrypt
365      * that partition, and update the volume object to point to it's new decrypted
366      * block device
367      */
368     property_get("ro.crypto.state", crypto_state, "");
369     if (providesAsec &&
370         ((flags & (VOL_NONREMOVABLE | VOL_ENCRYPTABLE))==(VOL_NONREMOVABLE | VOL_ENCRYPTABLE)) &&
371         !strcmp(crypto_state, "encrypted") && !isDecrypted()) {
372        char new_sys_path[MAXPATHLEN];
373        char nodepath[256];
374        int new_major, new_minor;
375
376        if (n != 1) {
377            /* We only expect one device node returned when mounting encryptable volumes */
378            SLOGE("Too many device nodes returned when mounting %d\n", getMountpoint());
379            return -1;
380        }
381
382        if (cryptfs_setup_volume(getLabel(), MAJOR(deviceNodes[0]), MINOR(deviceNodes[0]),
383                                 new_sys_path, sizeof(new_sys_path),
384                                 &new_major, &new_minor)) {
385            SLOGE("Cannot setup encryption mapping for %d\n", getMountpoint());
386            return -1;
387        }
388        /* We now have the new sysfs path for the decrypted block device, and the
389         * majore and minor numbers for it.  So, create the device, update the
390         * path to the new sysfs path, and continue.
391         */
392         snprintf(nodepath,
393                  sizeof(nodepath), "/dev/block/vold/%d:%d",
394                  new_major, new_minor);
395         if (createDeviceNode(nodepath, new_major, new_minor)) {
396             SLOGE("Error making device node '%s' (%s)", nodepath,
397                                                        strerror(errno));
398         }
399
400         // Todo: Either create sys filename from nodepath, or pass in bogus path so
401         //       vold ignores state changes on this internal device.
402         updateDeviceInfo(nodepath, new_major, new_minor);
403
404         /* Get the device nodes again, because they just changed */
405         n = getDeviceNodes((dev_t *) &deviceNodes, 4);
406         if (!n) {
407             SLOGE("Failed to get device nodes (%s)\n", strerror(errno));
408             return -1;
409         }
410     }
411
412     for (i = 0; i < n; i++) {
413         char devicePath[255];
414
415         sprintf(devicePath, "/dev/block/vold/%d:%d", MAJOR(deviceNodes[i]),
416                 MINOR(deviceNodes[i]));
417
418         SLOGI("%s being considered for volume %s\n", devicePath, getLabel());
419
420         errno = 0;
421         setState(Volume::State_Checking);
422
423         if (Fat::check(devicePath)) {
424             if (errno == ENODATA) {
425                 SLOGW("%s does not contain a FAT filesystem\n", devicePath);
426                 continue;
427             }
428             errno = EIO;
429             /* Badness - abort the mount */
430             SLOGE("%s failed FS checks (%s)", devicePath, strerror(errno));
431             setState(Volume::State_Idle);
432             return -1;
433         }
434
435         errno = 0;
436         int gid;
437
438         if (Fat::doMount(devicePath, getMountpoint(), false, false, false,
439                 AID_MEDIA_RW, AID_MEDIA_RW, 0007, true)) {
440             SLOGE("%s failed to mount via VFAT (%s)\n", devicePath, strerror(errno));
441             continue;
442         }
443
444         extractMetadata(devicePath);
445
446         if (providesAsec && mountAsecExternal() != 0) {
447             SLOGE("Failed to mount secure area (%s)", strerror(errno));
448             umount(getMountpoint());
449             setState(Volume::State_Idle);
450             return -1;
451         }
452
453         char service[64];
454         snprintf(service, 64, "fuse_%s", getLabel());
455         property_set("ctl.start", service);
456
457         setState(Volume::State_Mounted);
458         mCurrentlyMountedKdev = deviceNodes[i];
459         return 0;
460     }
461
462     SLOGE("Volume %s found no suitable devices for mounting :(\n", getLabel());
463     setState(Volume::State_Idle);
464
465     return -1;
466 }
467
468 int Volume::mountAsecExternal() {
469     char legacy_path[PATH_MAX];
470     char secure_path[PATH_MAX];
471
472     snprintf(legacy_path, PATH_MAX, "%s/android_secure", getMountpoint());
473     snprintf(secure_path, PATH_MAX, "%s/.android_secure", getMountpoint());
474
475     // Recover legacy secure path
476     if (!access(legacy_path, R_OK | X_OK) && access(secure_path, R_OK | X_OK)) {
477         if (rename(legacy_path, secure_path)) {
478             SLOGE("Failed to rename legacy asec dir (%s)", strerror(errno));
479         }
480     }
481
482     if (fs_prepare_dir(secure_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
483         return -1;
484     }
485
486     if (mount(secure_path, SEC_ASECDIR_EXT, "", MS_BIND, NULL)) {
487         SLOGE("Failed to bind mount points %s -> %s (%s)", secure_path,
488                 SEC_ASECDIR_EXT, strerror(errno));
489         return -1;
490     }
491
492     return 0;
493 }
494
495 int Volume::doUnmount(const char *path, bool force) {
496     int retries = 10;
497
498     if (mDebug) {
499         SLOGD("Unmounting {%s}, force = %d", path, force);
500     }
501
502     while (retries--) {
503         if (!umount(path) || errno == EINVAL || errno == ENOENT) {
504             SLOGI("%s sucessfully unmounted", path);
505             return 0;
506         }
507
508         int action = 0;
509
510         if (force) {
511             if (retries == 1) {
512                 action = 2; // SIGKILL
513             } else if (retries == 2) {
514                 action = 1; // SIGHUP
515             }
516         }
517
518         SLOGW("Failed to unmount %s (%s, retries %d, action %d)",
519                 path, strerror(errno), retries, action);
520
521         Process::killProcessesWithOpenFiles(path, action);
522         usleep(1000*1000);
523     }
524     errno = EBUSY;
525     SLOGE("Giving up on unmount %s (%s)", path, strerror(errno));
526     return -1;
527 }
528
529 int Volume::unmountVol(bool force, bool revert) {
530     int i, rc;
531
532     int flags = getFlags();
533     bool providesAsec = (flags & VOL_PROVIDES_ASEC) != 0;
534
535     if (getState() != Volume::State_Mounted) {
536         SLOGE("Volume %s unmount request when not mounted", getLabel());
537         errno = EINVAL;
538         return UNMOUNT_NOT_MOUNTED_ERR;
539     }
540
541     setState(Volume::State_Unmounting);
542     usleep(1000 * 1000); // Give the framework some time to react
543
544     char service[64];
545     snprintf(service, 64, "fuse_%s", getLabel());
546     property_set("ctl.stop", service);
547     /* Give it a chance to stop.  I wish we had a synchronous way to determine this... */
548     sleep(1);
549
550     // TODO: determine failure mode if FUSE times out
551
552     if (providesAsec && doUnmount(Volume::SEC_ASECDIR_EXT, force) != 0) {
553         SLOGE("Failed to unmount secure area on %s (%s)", getMountpoint(), strerror(errno));
554         goto out_mounted;
555     }
556
557     /* Now that the fuse daemon is dead, unmount it */
558     if (doUnmount(getFuseMountpoint(), force) != 0) {
559         SLOGE("Failed to unmount %s (%s)", getFuseMountpoint(), strerror(errno));
560         goto fail_remount_secure;
561     }
562
563     /* Unmount the real sd card */
564     if (doUnmount(getMountpoint(), force) != 0) {
565         SLOGE("Failed to unmount %s (%s)", getMountpoint(), strerror(errno));
566         goto fail_remount_secure;
567     }
568
569     SLOGI("%s unmounted successfully", getMountpoint());
570
571     /* If this is an encrypted volume, and we've been asked to undo
572      * the crypto mapping, then revert the dm-crypt mapping, and revert
573      * the device info to the original values.
574      */
575     if (revert && isDecrypted()) {
576         cryptfs_revert_volume(getLabel());
577         revertDeviceInfo();
578         SLOGI("Encrypted volume %s reverted successfully", getMountpoint());
579     }
580
581     setUuid(NULL);
582     setUserLabel(NULL);
583     setState(Volume::State_Idle);
584     mCurrentlyMountedKdev = -1;
585     return 0;
586
587 fail_remount_secure:
588     if (providesAsec && mountAsecExternal() != 0) {
589         SLOGE("Failed to remount secure area (%s)", strerror(errno));
590         goto out_nomedia;
591     }
592
593 out_mounted:
594     setState(Volume::State_Mounted);
595     return -1;
596
597 out_nomedia:
598     setState(Volume::State_NoMedia);
599     return -1;
600 }
601
602 int Volume::initializeMbr(const char *deviceNode) {
603     struct disk_info dinfo;
604
605     memset(&dinfo, 0, sizeof(dinfo));
606
607     if (!(dinfo.part_lst = (struct part_info *) malloc(MAX_NUM_PARTS * sizeof(struct part_info)))) {
608         SLOGE("Failed to malloc prt_lst");
609         return -1;
610     }
611
612     memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
613     dinfo.device = strdup(deviceNode);
614     dinfo.scheme = PART_SCHEME_MBR;
615     dinfo.sect_size = 512;
616     dinfo.skip_lba = 2048;
617     dinfo.num_lba = 0;
618     dinfo.num_parts = 1;
619
620     struct part_info *pinfo = &dinfo.part_lst[0];
621
622     pinfo->name = strdup("android_sdcard");
623     pinfo->flags |= PART_ACTIVE_FLAG;
624     pinfo->type = PC_PART_TYPE_FAT32;
625     pinfo->len_kb = -1;
626
627     int rc = apply_disk_config(&dinfo, 0);
628
629     if (rc) {
630         SLOGE("Failed to apply disk configuration (%d)", rc);
631         goto out;
632     }
633
634  out:
635     free(pinfo->name);
636     free(dinfo.device);
637     free(dinfo.part_lst);
638
639     return rc;
640 }
641
642 /*
643  * Use blkid to extract UUID and label from device, since it handles many
644  * obscure edge cases around partition types and formats. Always broadcasts
645  * updated metadata values.
646  */
647 int Volume::extractMetadata(const char* devicePath) {
648     int res = 0;
649
650     std::string cmd;
651     cmd = BLKID_PATH;
652     cmd += " -c /dev/null ";
653     cmd += devicePath;
654
655     FILE* fp = popen(cmd.c_str(), "r");
656     if (!fp) {
657         ALOGE("Failed to run %s: %s", cmd.c_str(), strerror(errno));
658         res = -1;
659         goto done;
660     }
661
662     char line[1024];
663     char value[128];
664     if (fgets(line, sizeof(line), fp) != NULL) {
665         ALOGD("blkid reported: %s", line);
666
667         char* start = strstr(line, "UUID=") + 5;
668         if (sscanf(start, "\"%127[^\"]\"", value) == 1) {
669             setUuid(value);
670         } else {
671             setUuid(NULL);
672         }
673
674         start = strstr(line, "LABEL=") + 6;
675         if (sscanf(start, "\"%127[^\"]\"", value) == 1) {
676             setUserLabel(value);
677         } else {
678             setUserLabel(NULL);
679         }
680     } else {
681         res = -1;
682     }
683
684     pclose(fp);
685
686 done:
687     if (res == -1) {
688         setUuid(NULL);
689         setUserLabel(NULL);
690     }
691     return res;
692 }