DirectVolume.cpp 15.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
18
#include <stdlib.h>
19
#include <string.h>
20
#include <errno.h>
21
#include <fnmatch.h>
22

23 24 25
#include <linux/kdev_t.h>

#define LOG_TAG "DirectVolume"
26 27

#include <cutils/log.h>
28
#include <sysutils/NetlinkEvent.h>
29

30
#include "DirectVolume.h"
31 32
#include "VolumeManager.h"
#include "ResponseCode.h"
33
#include "cryptfs.h"
34 35

// #define PARTITION_DEBUG
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
PathInfo::PathInfo(const char *p)
{
    warned = false;
    pattern = strdup(p);

    if (!strchr(pattern, '*')) {
        patternType = prefix;
    } else {
        patternType = wildcard;
    }
}

PathInfo::~PathInfo()
{
    free(pattern);
}

bool PathInfo::match(const char *path)
{
    switch (patternType) {
    case prefix:
    {
        bool ret = (strncmp(path, pattern, strlen(pattern)) == 0);
        if (!warned && ret && (strlen(pattern) != strlen(path))) {
            SLOGW("Deprecated implied prefix pattern detected, please use '%s*' instead", pattern);
            warned = true;
        }
        return ret;
    }
    case wildcard:
        return fnmatch(pattern, path, 0) == 0;
    }
    SLOGE("Bad matching type");
    return false;
}

73 74
DirectVolume::DirectVolume(VolumeManager *vm, const fstab_rec* rec, int flags) :
        Volume(vm, rec, flags) {
75
    mPaths = new PathCollection();
76 77
    for (int i = 0; i < MAX_PARTITIONS; i++)
        mPartMinors[i] = -1;
78
    mPendingPartCount = 0;
79 80 81
    mDiskMajor = -1;
    mDiskMinor = -1;
    mDiskNumParts = 0;
82
    mIsDecrypted = 0;
83

84 85 86 87 88 89 90 91 92 93 94 95
    if (strcmp(rec->mount_point, "auto") != 0) {
        ALOGE("Vold managed volumes must have auto mount point; ignoring %s",
              rec->mount_point);
    }

    char mount[PATH_MAX];

    snprintf(mount, PATH_MAX, "%s/%s", Volume::MEDIA_DIR, rec->label);
    mMountpoint = strdup(mount);
    snprintf(mount, PATH_MAX, "%s/%s", Volume::FUSE_DIR, rec->label);
    mFuseMountpoint = strdup(mount);

96
    setState(Volume::State_NoMedia);
97 98
}

99
DirectVolume::~DirectVolume() {
100 101 102
    PathCollection::iterator it;

    for (it = mPaths->begin(); it != mPaths->end(); ++it)
103
        delete *it;
104 105 106
    delete mPaths;
}

107
int DirectVolume::addPath(const char *path) {
108
    mPaths->push_back(new PathInfo(path));
109 110 111
    return 0;
}

112 113 114 115
dev_t DirectVolume::getDiskDevice() {
    return MKDEV(mDiskMajor, mDiskMinor);
}

116 117 118 119 120 121 122 123
dev_t DirectVolume::getShareDevice() {
    if (mPartIdx != -1) {
        return MKDEV(mDiskMajor, mPartIdx);
    } else {
        return MKDEV(mDiskMajor, mDiskMinor);
    }
}

124 125 126 127 128 129 130 131
void DirectVolume::handleVolumeShared() {
    setState(Volume::State_Shared);
}

void DirectVolume::handleVolumeUnshared() {
    setState(Volume::State_Idle);
}

132
int DirectVolume::handleBlockEvent(NetlinkEvent *evt) {
133
    const char *dp = evt->findParam("DEVPATH");
134

135
    PathCollection::iterator  it;
136
    for (it = mPaths->begin(); it != mPaths->end(); ++it) {
137
        if ((*it)->match(dp)) {
138 139 140 141
            /* We can handle this disk */
            int action = evt->getAction();
            const char *devtype = evt->findParam("DEVTYPE");

142 143 144 145 146 147 148 149 150
            if (action == NetlinkEvent::NlActionAdd) {
                int major = atoi(evt->findParam("MAJOR"));
                int minor = atoi(evt->findParam("MINOR"));
                char nodepath[255];

                snprintf(nodepath,
                         sizeof(nodepath), "/dev/block/vold/%d:%d",
                         major, minor);
                if (createDeviceNode(nodepath, major, minor)) {
San Mehat's avatar
San Mehat committed
151
                    SLOGE("Error making device node '%s' (%s)", nodepath,
152 153 154
                                                               strerror(errno));
                }
                if (!strcmp(devtype, "disk")) {
155
                    handleDiskAdded(dp, evt);
156
                } else {
157
                    handlePartitionAdded(dp, evt);
158
                }
159 160 161 162 163 164
                /* Send notification iff disk is ready (ie all partitions found) */
                if (getState() == Volume::State_Idle) {
                    char msg[255];

                    snprintf(msg, sizeof(msg),
                             "Volume %s %s disk inserted (%d:%d)", getLabel(),
165
                             getFuseMountpoint(), mDiskMajor, mDiskMinor);
166 167 168
                    mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeDiskInserted,
                                                         msg, false);
                }
169 170 171 172
            } else if (action == NetlinkEvent::NlActionRemove) {
                if (!strcmp(devtype, "disk")) {
                    handleDiskRemoved(dp, evt);
                } else {
173
                    handlePartitionRemoved(dp, evt);
174 175 176 177 178 179 180 181
                }
            } else if (action == NetlinkEvent::NlActionChange) {
                if (!strcmp(devtype, "disk")) {
                    handleDiskChanged(dp, evt);
                } else {
                    handlePartitionChanged(dp, evt);
                }
            } else {
San Mehat's avatar
San Mehat committed
182
                    SLOGW("Ignoring non add/remove/change event");
183
            }
184

185 186 187 188 189 190
            return 0;
        }
    }
    errno = ENODEV;
    return -1;
}
191

192 193
void DirectVolume::handleDiskAdded(const char * /*devpath*/,
                                   NetlinkEvent *evt) {
194 195
    mDiskMajor = atoi(evt->findParam("MAJOR"));
    mDiskMinor = atoi(evt->findParam("MINOR"));
196 197 198 199 200

    const char *tmp = evt->findParam("NPARTS");
    if (tmp) {
        mDiskNumParts = atoi(tmp);
    } else {
San Mehat's avatar
San Mehat committed
201
        SLOGW("Kernel block uevent missing 'NPARTS'");
202 203 204
        mDiskNumParts = 1;
    }

205 206 207
    mPendingPartCount = mDiskNumParts;
    for (int i = 0; i < MAX_PARTITIONS; i++)
        mPartMinors[i] = -1;
208 209

    if (mDiskNumParts == 0) {
210
#ifdef PARTITION_DEBUG
San Mehat's avatar
San Mehat committed
211
        SLOGD("Dv::diskIns - No partitions - good to go son!");
212
#endif
213 214
        setState(Volume::State_Idle);
    } else {
215
#ifdef PARTITION_DEBUG
216
        SLOGD("Dv::diskIns - waiting for %d pending partitions", mPendingPartCount);
217
#endif
218 219 220 221
        setState(Volume::State_Pending);
    }
}

222
void DirectVolume::handlePartitionAdded(const char *devpath, NetlinkEvent *evt) {
223 224
    int major = atoi(evt->findParam("MAJOR"));
    int minor = atoi(evt->findParam("MINOR"));
225 226 227 228 229 230 231 232

    int part_num;

    const char *tmp = evt->findParam("PARTN");

    if (tmp) {
        part_num = atoi(tmp);
    } else {
San Mehat's avatar
San Mehat committed
233
        SLOGW("Kernel block uevent missing 'PARTN'");
234 235
        part_num = 1;
    }
236

237
    if (part_num > MAX_PARTITIONS || part_num < 1) {
238 239
        SLOGE("Invalid 'PARTN' value");
        return;
240 241
    }

242 243 244 245
    if (part_num > mDiskNumParts) {
        mDiskNumParts = part_num;
    }

246
    if (major != mDiskMajor) {
San Mehat's avatar
San Mehat committed
247
        SLOGE("Partition '%s' has a different major than its disk!", devpath);
248 249
        return;
    }
250
#ifdef PARTITION_DEBUG
San Mehat's avatar
San Mehat committed
251
    SLOGD("Dv:partAdd: part_num = %d, minor = %d\n", part_num, minor);
252
#endif
253 254
    if (part_num >= MAX_PARTITIONS) {
        SLOGE("Dv:partAdd: ignoring part_num = %d (max: %d)\n", part_num, MAX_PARTITIONS-1);
255
    } else {
256 257
        if ((mPartMinors[part_num - 1] == -1) && mPendingPartCount)
            mPendingPartCount--;
258 259 260
        mPartMinors[part_num -1] = minor;
    }

261
    if (!mPendingPartCount) {
262
#ifdef PARTITION_DEBUG
San Mehat's avatar
San Mehat committed
263
        SLOGD("Dv:partAdd: Got all partitions - ready to rock!");
264
#endif
265 266
        if (getState() != Volume::State_Formatting) {
            setState(Volume::State_Idle);
Joseph Lehrer's avatar
Joseph Lehrer committed
267 268 269 270
            if (mRetryMount == true) {
                mRetryMount = false;
                mountVol();
            }
271
        }
272
    } else {
273
#ifdef PARTITION_DEBUG
274
        SLOGD("Dv:partAdd: pending %d disk", mPendingPartCount);
275 276 277 278
#endif
    }
}

279 280
void DirectVolume::handleDiskChanged(const char * /*devpath*/,
                                     NetlinkEvent *evt) {
281 282
    int major = atoi(evt->findParam("MAJOR"));
    int minor = atoi(evt->findParam("MINOR"));
283 284 285 286 287

    if ((major != mDiskMajor) || (minor != mDiskMinor)) {
        return;
    }

San Mehat's avatar
San Mehat committed
288
    SLOGI("Volume %s disk has changed", getLabel());
289 290 291 292
    const char *tmp = evt->findParam("NPARTS");
    if (tmp) {
        mDiskNumParts = atoi(tmp);
    } else {
San Mehat's avatar
San Mehat committed
293
        SLOGW("Kernel block uevent missing 'NPARTS'");
294 295 296
        mDiskNumParts = 1;
    }

297 298 299
    mPendingPartCount = mDiskNumParts;
    for (int i = 0; i < MAX_PARTITIONS; i++)
        mPartMinors[i] = -1;
300

301 302 303 304 305 306
    if (getState() != Volume::State_Formatting) {
        if (mDiskNumParts == 0) {
            setState(Volume::State_Idle);
        } else {
            setState(Volume::State_Pending);
        }
307
    }
308 309
}

310 311
void DirectVolume::handlePartitionChanged(const char * /*devpath*/,
                                          NetlinkEvent *evt) {
312 313
    int major = atoi(evt->findParam("MAJOR"));
    int minor = atoi(evt->findParam("MINOR"));
San Mehat's avatar
San Mehat committed
314
    SLOGD("Volume %s %s partition %d:%d changed\n", getLabel(), getMountpoint(), major, minor);
315 316
}

317 318
void DirectVolume::handleDiskRemoved(const char * /*devpath*/,
                                     NetlinkEvent *evt) {
319 320
    int major = atoi(evt->findParam("MAJOR"));
    int minor = atoi(evt->findParam("MINOR"));
321
    char msg[255];
322 323
    bool enabled;

324 325 326 327 328 329 330 331
    SLOGD("Volume %s %s disk %d:%d removed\n", getLabel(), getMountpoint(), major, minor);
    if ((dev_t) MKDEV(major, minor) == mCurrentlyMountedKdev) {
        /*
         * Yikes, our mounted disk is going away!
         */

        doUnmount(major, minor);
    } else if (mVm->shareEnabled(getLabel(), "ums", &enabled) == 0 && enabled) {
332 333
        mVm->unshareVolume(getLabel(), "ums");
    }
334 335

    snprintf(msg, sizeof(msg), "Volume %s %s disk removed (%d:%d)",
336
             getLabel(), getFuseMountpoint(), major, minor);
337 338 339
    mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeDiskRemoved,
                                             msg, false);
    setState(Volume::State_NoMedia);
340 341
}

342 343
void DirectVolume::handlePartitionRemoved(const char * /*devpath*/,
                                          NetlinkEvent *evt) {
344 345
    int major = atoi(evt->findParam("MAJOR"));
    int minor = atoi(evt->findParam("MINOR"));
346
    char msg[255];
347
    int state;
348

San Mehat's avatar
San Mehat committed
349
    SLOGD("Volume %s %s partition %d:%d removed\n", getLabel(), getMountpoint(), major, minor);
350 351 352 353 354 355 356

    /*
     * The framework doesn't need to get notified of
     * partition removal unless it's mounted. Otherwise
     * the removal notification will be sent on the Disk
     * itself
     */
357 358
    state = getState();
    if (state != Volume::State_Mounted && state != Volume::State_Shared) {
359 360
        return;
    }
361

362 363 364 365
    if ((dev_t) MKDEV(major, minor) == mCurrentlyMountedKdev) {
        /*
         * Yikes, our mounted partition is going away!
         */
366
        doUnmount(major, minor);
367 368 369 370 371 372 373 374 375 376 377 378 379
    } else if (state == Volume::State_Shared) {
        /* removed during mass storage */
        snprintf(msg, sizeof(msg), "Volume %s bad removal (%d:%d)",
                 getLabel(), major, minor);
        mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeBadRemoval,
                                             msg, false);

        if (mVm->unshareVolume(getLabel(), "ums")) {
            SLOGE("Failed to unshare volume on bad removal (%s)",
                strerror(errno));
        } else {
            SLOGD("Crisis averted");
        }
380
    }
381
}
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
void DirectVolume::doUnmount(int major, int minor) {
    char msg[255];
    bool providesAsec = (getFlags() & VOL_PROVIDES_ASEC) != 0;
    if (providesAsec && mVm->cleanupAsec(this, true)) {
        SLOGE("Failed to cleanup ASEC - unmount will probably fail!");
    }

    snprintf(msg, sizeof(msg), "Volume %s %s bad removal (%d:%d)",
                getLabel(), getFuseMountpoint(), major, minor);
    mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeBadRemoval,
                                            msg, false);

    if (Volume::unmountVol(true, false)) {
        SLOGE("Failed to unmount volume on bad removal (%s)",
                strerror(errno));
        // XXX: At this point we're screwed for now
    } else {
        SLOGD("Crisis averted");
    }
}

404
/*
405
 * Called from base to get a list of devicenodes for mounting
406
 */
407
int DirectVolume::getDeviceNodes(dev_t *devs, int max) {
408 409

    if (mPartIdx == -1) {
410
        // If the disk has no partitions, try the disk itself
411
        if (!mDiskNumParts) {
412 413
            devs[0] = MKDEV(mDiskMajor, mDiskMinor);
            return 1;
414 415
        }

416 417 418 419 420 421 422
        int i;
        for (i = 0; i < mDiskNumParts; i++) {
            if (i == max)
                break;
            devs[i] = MKDEV(mDiskMajor, mPartMinors[i]);
        }
        return mDiskNumParts;
423
    }
424 425
    devs[0] = MKDEV(mDiskMajor, mPartMinors[mPartIdx -1]);
    return 1;
426
}
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

/*
 * Called from base to update device info,
 * e.g. When setting up an dm-crypt mapping for the sd card.
 */
int DirectVolume::updateDeviceInfo(char *new_path, int new_major, int new_minor)
{
    PathCollection::iterator it;

    if (mPartIdx == -1) {
        SLOGE("Can only change device info on a partition\n");
        return -1;
    }

    /*
     * This is to change the sysfs path associated with a partition, in particular,
     * for an internal SD card partition that is encrypted.  Thus, the list is
     * expected to be only 1 entry long.  Check that and bail if not.
     */
    if (mPaths->size() != 1) {
        SLOGE("Cannot change path if there are more than one for a volume\n");
        return -1;
    }

    it = mPaths->begin();
452
    delete *it; /* Free the string storage */
453 454 455
    mPaths->erase(it); /* Remove it from the list */
    addPath(new_path); /* Put the new path on the list */

456 457 458 459 460 461 462 463 464 465
    /* Save away original info so we can restore it when doing factory reset.
     * Then, when doing the format, it will format the original device in the
     * clear, otherwise it just formats the encrypted device which is not
     * readable when the device boots unencrypted after the reset.
     */
    mOrigDiskMajor = mDiskMajor;
    mOrigDiskMinor = mDiskMinor;
    mOrigPartIdx = mPartIdx;
    memcpy(mOrigPartMinors, mPartMinors, sizeof(mPartMinors));

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    mDiskMajor = new_major;
    mDiskMinor = new_minor;
    /* Ugh, virual block devices don't use minor 0 for whole disk and minor > 0 for
     * partition number.  They don't have partitions, they are just virtual block
     * devices, and minor number 0 is the first dm-crypt device.  Luckily the first
     * dm-crypt device is for the userdata partition, which gets minor number 0, and
     * it is not managed by vold.  So the next device is minor number one, which we
     * will call partition one.
     */
    mPartIdx = new_minor;
    mPartMinors[new_minor-1] = new_minor;

    mIsDecrypted = 1;

    return 0;
}

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
/*
 * Called from base to revert device info to the way it was before a
 * crypto mapping was created for it.
 */
void DirectVolume::revertDeviceInfo(void)
{
    if (mIsDecrypted) {
        mDiskMajor = mOrigDiskMajor;
        mDiskMinor = mOrigDiskMinor;
        mPartIdx = mOrigPartIdx;
        memcpy(mPartMinors, mOrigPartMinors, sizeof(mPartMinors));

        mIsDecrypted = 0;
    }

    return;
}

501 502 503 504 505 506 507
/*
 * Called from base to give cryptfs all the info it needs to encrypt eligible volumes
 */
int DirectVolume::getVolInfo(struct volume_info *v)
{
    strcpy(v->label, mLabel);
    strcpy(v->mnt_point, mMountpoint);
508
    v->flags = getFlags();
509 510 511 512
    /* Other fields of struct volume_info are filled in by the caller or cryptfs.c */

    return 0;
}