1 /*
2 * Copyright (C) 2015 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 "Disk.h"
18 #include "FsCrypt.h"
19 #include "PrivateVolume.h"
20 #include "PublicVolume.h"
21 #include "Utils.h"
22 #include "VolumeBase.h"
23 #include "VolumeManager.h"
24
25 #include <android-base/file.h>
26 #include <android-base/logging.h>
27 #include <android-base/parseint.h>
28 #include <android-base/properties.h>
29 #include <android-base/stringprintf.h>
30 #include <android-base/strings.h>
31 #include <fscrypt/fscrypt.h>
32
33 #include "cryptfs.h"
34
35 #include <fcntl.h>
36 #include <inttypes.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <sys/mount.h>
40 #include <sys/stat.h>
41 #include <sys/sysmacros.h>
42 #include <sys/types.h>
43 #include <vector>
44
45 using android::base::ReadFileToString;
46 using android::base::StringPrintf;
47 using android::base::WriteStringToFile;
48
49 namespace android {
50 namespace vold {
51
52 static const char* kSgdiskPath = "/system/bin/sgdisk";
53 static const char* kSgdiskToken = " \t\n";
54
55 static const char* kSysfsLoopMaxMinors = "/sys/module/loop/parameters/max_part";
56 static const char* kSysfsMmcMaxMinorsDeprecated = "/sys/module/mmcblk/parameters/perdev_minors";
57 static const char* kSysfsMmcMaxMinors = "/sys/module/mmc_block/parameters/perdev_minors";
58
59 static const unsigned int kMajorBlockLoop = 7;
60 static const unsigned int kMajorBlockScsiA = 8;
61 static const unsigned int kMajorBlockScsiB = 65;
62 static const unsigned int kMajorBlockScsiC = 66;
63 static const unsigned int kMajorBlockScsiD = 67;
64 static const unsigned int kMajorBlockScsiE = 68;
65 static const unsigned int kMajorBlockScsiF = 69;
66 static const unsigned int kMajorBlockScsiG = 70;
67 static const unsigned int kMajorBlockScsiH = 71;
68 static const unsigned int kMajorBlockScsiI = 128;
69 static const unsigned int kMajorBlockScsiJ = 129;
70 static const unsigned int kMajorBlockScsiK = 130;
71 static const unsigned int kMajorBlockScsiL = 131;
72 static const unsigned int kMajorBlockScsiM = 132;
73 static const unsigned int kMajorBlockScsiN = 133;
74 static const unsigned int kMajorBlockScsiO = 134;
75 static const unsigned int kMajorBlockScsiP = 135;
76 static const unsigned int kMajorBlockMmc = 179;
77 static const unsigned int kMajorBlockExperimentalMin = 240;
78 static const unsigned int kMajorBlockExperimentalMax = 254;
79 static const unsigned int kMajorBlockDynamicMin = 234;
80 static const unsigned int kMajorBlockDynamicMax = 512;
81
82 static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7";
83 static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF";
84 static const char* kGptAndroidExpand = "193D1EA4-B3CA-11E4-B075-10604B889DCF";
85
86 enum class Table {
87 kUnknown,
88 kMbr,
89 kGpt,
90 };
91
isVirtioBlkDevice(unsigned int major)92 static bool isVirtioBlkDevice(unsigned int major) {
93 /*
94 * The new emulator's "ranchu" virtual board no longer includes a goldfish
95 * MMC-based SD card device; instead, it emulates SD cards with virtio-blk,
96 * which has been supported by upstream kernel and QEMU for quite a while.
97 * Unfortunately, the virtio-blk block device driver does not use a fixed
98 * major number, but relies on the kernel to assign one from a specific
99 * range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
100 * per Documentation/devices.txt. This is true even for the latest Linux
101 * kernel (4.4; see init() in drivers/block/virtio_blk.c).
102 *
103 * This makes it difficult for vold to detect a virtio-blk based SD card.
104 * The current solution checks two conditions (both must be met):
105 *
106 * a) If the running environment is the emulator;
107 * b) If the major number is an experimental block device major number (for
108 * x86/x86_64 3.10 ranchu kernels, virtio-blk always gets major number
109 * 253, but it is safer to match the range than just one value).
110 *
111 * Other conditions could be used, too, e.g. the hardware name should be
112 * "ranchu", the device's sysfs path should end with "/block/vd[d-z]", etc.
113 * But just having a) and b) is enough for now.
114 */
115 return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin &&
116 major <= kMajorBlockExperimentalMax;
117 }
118
isNvmeBlkDevice(unsigned int major,const std::string & sysPath)119 static bool isNvmeBlkDevice(unsigned int major, const std::string& sysPath) {
120 return sysPath.find("nvme") != std::string::npos && major >= kMajorBlockDynamicMin &&
121 major <= kMajorBlockDynamicMax;
122 }
123
Disk(const std::string & eventPath,dev_t device,const std::string & nickname,int flags)124 Disk::Disk(const std::string& eventPath, dev_t device, const std::string& nickname, int flags)
125 : mDevice(device),
126 mSize(-1),
127 mNickname(nickname),
128 mFlags(flags),
129 mCreated(false),
130 mJustPartitioned(false) {
131 mId = StringPrintf("disk:%u,%u", major(device), minor(device));
132 mEventPath = eventPath;
133 mSysPath = StringPrintf("/sys/%s", eventPath.c_str());
134 mDevPath = StringPrintf("/dev/block/vold/%s", mId.c_str());
135 CreateDeviceNode(mDevPath, mDevice);
136 }
137
~Disk()138 Disk::~Disk() {
139 CHECK(!mCreated);
140 DestroyDeviceNode(mDevPath);
141 }
142
findVolume(const std::string & id)143 std::shared_ptr<VolumeBase> Disk::findVolume(const std::string& id) {
144 for (auto vol : mVolumes) {
145 if (vol->getId() == id) {
146 return vol;
147 }
148 auto stackedVol = vol->findVolume(id);
149 if (stackedVol != nullptr) {
150 return stackedVol;
151 }
152 }
153 return nullptr;
154 }
155
listVolumes(VolumeBase::Type type,std::list<std::string> & list) const156 void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) const {
157 for (const auto& vol : mVolumes) {
158 if (vol->getType() == type) {
159 list.push_back(vol->getId());
160 }
161 // TODO: consider looking at stacked volumes
162 }
163 }
164
create()165 status_t Disk::create() {
166 CHECK(!mCreated);
167 mCreated = true;
168
169 auto listener = VolumeManager::Instance()->getListener();
170 if (listener) listener->onDiskCreated(getId(), mFlags);
171
172 readMetadata();
173 readPartitions();
174 return OK;
175 }
176
destroy()177 status_t Disk::destroy() {
178 CHECK(mCreated);
179 destroyAllVolumes();
180 mCreated = false;
181
182 auto listener = VolumeManager::Instance()->getListener();
183 if (listener) listener->onDiskDestroyed(getId());
184
185 return OK;
186 }
187
createPublicVolume(dev_t device)188 void Disk::createPublicVolume(dev_t device) {
189 auto vol = std::shared_ptr<VolumeBase>(new PublicVolume(device));
190 if (mJustPartitioned) {
191 LOG(DEBUG) << "Device just partitioned; silently formatting";
192 vol->setSilent(true);
193 vol->create();
194 vol->format("auto");
195 vol->destroy();
196 vol->setSilent(false);
197 }
198
199 mVolumes.push_back(vol);
200 vol->setDiskId(getId());
201 vol->create();
202 }
203
createPrivateVolume(dev_t device,const std::string & partGuid)204 void Disk::createPrivateVolume(dev_t device, const std::string& partGuid) {
205 std::string normalizedGuid;
206 if (NormalizeHex(partGuid, normalizedGuid)) {
207 LOG(WARNING) << "Invalid GUID " << partGuid;
208 return;
209 }
210
211 std::string keyRaw;
212 if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) {
213 PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid;
214 return;
215 }
216
217 LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
218
219 auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
220 if (mJustPartitioned) {
221 LOG(DEBUG) << "Device just partitioned; silently formatting";
222 vol->setSilent(true);
223 vol->create();
224 vol->format("auto");
225 vol->destroy();
226 vol->setSilent(false);
227 }
228
229 mVolumes.push_back(vol);
230 vol->setDiskId(getId());
231 vol->setPartGuid(partGuid);
232 vol->create();
233 }
234
destroyAllVolumes()235 void Disk::destroyAllVolumes() {
236 for (const auto& vol : mVolumes) {
237 vol->destroy();
238 }
239 mVolumes.clear();
240 }
241
readMetadata()242 status_t Disk::readMetadata() {
243 mSize = -1;
244 mLabel.clear();
245
246 if (GetBlockDevSize(mDevPath, &mSize) != OK) {
247 mSize = -1;
248 }
249
250 unsigned int majorId = major(mDevice);
251 switch (majorId) {
252 case kMajorBlockLoop: {
253 mLabel = "Virtual";
254 break;
255 }
256 // clang-format off
257 case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC:
258 case kMajorBlockScsiD: case kMajorBlockScsiE: case kMajorBlockScsiF:
259 case kMajorBlockScsiG: case kMajorBlockScsiH: case kMajorBlockScsiI:
260 case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
261 case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO:
262 case kMajorBlockScsiP: {
263 // clang-format on
264 std::string path(mSysPath + "/device/vendor");
265 std::string tmp;
266 if (!ReadFileToString(path, &tmp)) {
267 PLOG(WARNING) << "Failed to read vendor from " << path;
268 return -errno;
269 }
270 tmp = android::base::Trim(tmp);
271 mLabel = tmp;
272 break;
273 }
274 case kMajorBlockMmc: {
275 std::string path(mSysPath + "/device/manfid");
276 std::string tmp;
277 if (!ReadFileToString(path, &tmp)) {
278 PLOG(WARNING) << "Failed to read manufacturer from " << path;
279 return -errno;
280 }
281 tmp = android::base::Trim(tmp);
282 int64_t manfid;
283 if (!android::base::ParseInt(tmp, &manfid)) {
284 PLOG(WARNING) << "Failed to parse manufacturer " << tmp;
285 return -EINVAL;
286 }
287 // Our goal here is to give the user a meaningful label, ideally
288 // matching whatever is silk-screened on the card. To reduce
289 // user confusion, this list doesn't contain white-label manfid.
290 switch (manfid) {
291 // clang-format off
292 case 0x000003: mLabel = "SanDisk"; break;
293 case 0x00001b: mLabel = "Samsung"; break;
294 case 0x000028: mLabel = "Lexar"; break;
295 case 0x000074: mLabel = "Transcend"; break;
296 // clang-format on
297 }
298 break;
299 }
300 default: {
301 if (isVirtioBlkDevice(majorId)) {
302 LOG(DEBUG) << "Recognized experimental block major ID " << majorId
303 << " as virtio-blk (emulator's virtual SD card device)";
304 mLabel = "Virtual";
305 break;
306 }
307 if (isNvmeBlkDevice(majorId, mSysPath)) {
308 std::string path(mSysPath + "/device/model");
309 std::string tmp;
310 if (!ReadFileToString(path, &tmp)) {
311 PLOG(WARNING) << "Failed to read vendor from " << path;
312 return -errno;
313 }
314 mLabel = tmp;
315 break;
316 }
317 LOG(WARNING) << "Unsupported block major type " << majorId;
318 return -ENOTSUP;
319 }
320 }
321
322 auto listener = VolumeManager::Instance()->getListener();
323 if (listener) listener->onDiskMetadataChanged(getId(), mSize, mLabel, mSysPath);
324
325 return OK;
326 }
327
readPartitions()328 status_t Disk::readPartitions() {
329 int maxMinors = getMaxMinors();
330 if (maxMinors < 0) {
331 return -ENOTSUP;
332 }
333
334 destroyAllVolumes();
335
336 // Parse partition table
337
338 std::vector<std::string> cmd;
339 cmd.push_back(kSgdiskPath);
340 cmd.push_back("--android-dump");
341 cmd.push_back(mDevPath);
342
343 std::vector<std::string> output;
344 status_t res = ForkExecvp(cmd, &output);
345 if (res != OK) {
346 LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
347
348 auto listener = VolumeManager::Instance()->getListener();
349 if (listener) listener->onDiskScanned(getId());
350
351 mJustPartitioned = false;
352 return res;
353 }
354
355 Table table = Table::kUnknown;
356 bool foundParts = false;
357 for (const auto& line : output) {
358 auto split = android::base::Split(line, kSgdiskToken);
359 auto it = split.begin();
360 if (it == split.end()) continue;
361
362 if (*it == "DISK") {
363 if (++it == split.end()) continue;
364 if (*it == "mbr") {
365 table = Table::kMbr;
366 } else if (*it == "gpt") {
367 table = Table::kGpt;
368 } else {
369 LOG(WARNING) << "Invalid partition table " << *it;
370 continue;
371 }
372 } else if (*it == "PART") {
373 foundParts = true;
374
375 if (++it == split.end()) continue;
376 int i = 0;
377 if (!android::base::ParseInt(*it, &i, 1, maxMinors)) {
378 LOG(WARNING) << "Invalid partition number " << *it;
379 continue;
380 }
381 dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i);
382
383 if (table == Table::kMbr) {
384 if (++it == split.end()) continue;
385 int type = 0;
386 if (!android::base::ParseInt("0x" + *it, &type)) {
387 LOG(WARNING) << "Invalid partition type " << *it;
388 continue;
389 }
390
391 switch (type) {
392 case 0x06: // FAT16
393 case 0x07: // HPFS/NTFS/exFAT
394 case 0x0b: // W95 FAT32 (LBA)
395 case 0x0c: // W95 FAT32 (LBA)
396 case 0x0e: // W95 FAT16 (LBA)
397 createPublicVolume(partDevice);
398 break;
399 }
400 } else if (table == Table::kGpt) {
401 if (++it == split.end()) continue;
402 auto typeGuid = *it;
403 if (++it == split.end()) continue;
404 auto partGuid = *it;
405
406 if (android::base::EqualsIgnoreCase(typeGuid, kGptBasicData)) {
407 createPublicVolume(partDevice);
408 } else if (android::base::EqualsIgnoreCase(typeGuid, kGptAndroidExpand)) {
409 createPrivateVolume(partDevice, partGuid);
410 }
411 }
412 }
413 }
414
415 // Ugly last ditch effort, treat entire disk as partition
416 if (table == Table::kUnknown || !foundParts) {
417 LOG(WARNING) << mId << " has unknown partition table; trying entire device";
418
419 std::string fsType;
420 std::string unused;
421 if (ReadMetadataUntrusted(mDevPath, &fsType, &unused, &unused) == OK) {
422 createPublicVolume(mDevice);
423 } else {
424 LOG(WARNING) << mId << " failed to identify, giving up";
425 }
426 }
427
428 auto listener = VolumeManager::Instance()->getListener();
429 if (listener) listener->onDiskScanned(getId());
430
431 mJustPartitioned = false;
432 return OK;
433 }
434
unmountAll()435 status_t Disk::unmountAll() {
436 for (const auto& vol : mVolumes) {
437 vol->unmount();
438 }
439 return OK;
440 }
441
partitionPublic()442 status_t Disk::partitionPublic() {
443 int res;
444
445 destroyAllVolumes();
446 mJustPartitioned = true;
447
448 // First nuke any existing partition table
449 std::vector<std::string> cmd;
450 cmd.push_back(kSgdiskPath);
451 cmd.push_back("--zap-all");
452 cmd.push_back(mDevPath);
453
454 // Zap sometimes returns an error when it actually succeeded, so
455 // just log as warning and keep rolling forward.
456 if ((res = ForkExecvp(cmd)) != 0) {
457 LOG(WARNING) << "Failed to zap; status " << res;
458 }
459
460 // Now let's build the new MBR table. We heavily rely on sgdisk to
461 // force optimal alignment on the created partitions.
462 cmd.clear();
463 cmd.push_back(kSgdiskPath);
464 cmd.push_back("--new=0:0:-0");
465 cmd.push_back("--typecode=0:0c00");
466 cmd.push_back("--gpttombr=1");
467 cmd.push_back(mDevPath);
468
469 if ((res = ForkExecvp(cmd)) != 0) {
470 LOG(ERROR) << "Failed to partition; status " << res;
471 return res;
472 }
473
474 return OK;
475 }
476
partitionPrivate()477 status_t Disk::partitionPrivate() {
478 return partitionMixed(0);
479 }
480
partitionMixed(int8_t ratio)481 status_t Disk::partitionMixed(int8_t ratio) {
482 int res;
483
484 destroyAllVolumes();
485 mJustPartitioned = true;
486
487 // First nuke any existing partition table
488 std::vector<std::string> cmd;
489 cmd.push_back(kSgdiskPath);
490 cmd.push_back("--zap-all");
491 cmd.push_back(mDevPath);
492
493 // Zap sometimes returns an error when it actually succeeded, so
494 // just log as warning and keep rolling forward.
495 if ((res = ForkExecvp(cmd)) != 0) {
496 LOG(WARNING) << "Failed to zap; status " << res;
497 }
498
499 // We've had some success above, so generate both the private partition
500 // GUID and encryption key and persist them.
501 std::string partGuidRaw;
502 if (GenerateRandomUuid(partGuidRaw) != OK) {
503 LOG(ERROR) << "Failed to generate GUID";
504 return -EIO;
505 }
506
507 std::string keyRaw;
508 if (ReadRandomBytes(cryptfs_get_keysize(), keyRaw) != OK) {
509 LOG(ERROR) << "Failed to generate key";
510 return -EIO;
511 }
512
513 std::string partGuid;
514 StrToHex(partGuidRaw, partGuid);
515
516 if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) {
517 LOG(ERROR) << "Failed to persist key";
518 return -EIO;
519 } else {
520 LOG(DEBUG) << "Persisted key for GUID " << partGuid;
521 }
522
523 // Now let's build the new GPT table. We heavily rely on sgdisk to
524 // force optimal alignment on the created partitions.
525 cmd.clear();
526 cmd.push_back(kSgdiskPath);
527
528 // If requested, create a public partition first. Mixed-mode partitioning
529 // like this is an experimental feature.
530 if (ratio > 0) {
531 if (ratio < 10 || ratio > 90) {
532 LOG(ERROR) << "Mixed partition ratio must be between 10-90%";
533 return -EINVAL;
534 }
535
536 uint64_t splitMb = ((mSize / 100) * ratio) / 1024 / 1024;
537 cmd.push_back(StringPrintf("--new=0:0:+%" PRId64 "M", splitMb));
538 cmd.push_back(StringPrintf("--typecode=0:%s", kGptBasicData));
539 cmd.push_back("--change-name=0:shared");
540 }
541
542 // Define a metadata partition which is designed for future use; there
543 // should only be one of these per physical device, even if there are
544 // multiple private volumes.
545 cmd.push_back("--new=0:0:+16M");
546 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidMeta));
547 cmd.push_back("--change-name=0:android_meta");
548
549 // Define a single private partition filling the rest of disk.
550 cmd.push_back("--new=0:0:-0");
551 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidExpand));
552 cmd.push_back(StringPrintf("--partition-guid=0:%s", partGuid.c_str()));
553 cmd.push_back("--change-name=0:android_expand");
554
555 cmd.push_back(mDevPath);
556
557 if ((res = ForkExecvp(cmd)) != 0) {
558 LOG(ERROR) << "Failed to partition; status " << res;
559 return res;
560 }
561
562 return OK;
563 }
564
getMaxMinors()565 int Disk::getMaxMinors() {
566 // Figure out maximum partition devices supported
567 unsigned int majorId = major(mDevice);
568 switch (majorId) {
569 case kMajorBlockLoop: {
570 std::string tmp;
571 if (!ReadFileToString(kSysfsLoopMaxMinors, &tmp)) {
572 LOG(ERROR) << "Failed to read max minors";
573 return -errno;
574 }
575 return std::stoi(tmp);
576 }
577 // clang-format off
578 case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC:
579 case kMajorBlockScsiD: case kMajorBlockScsiE: case kMajorBlockScsiF:
580 case kMajorBlockScsiG: case kMajorBlockScsiH: case kMajorBlockScsiI:
581 case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
582 case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO:
583 case kMajorBlockScsiP: {
584 // clang-format on
585 // Per Documentation/devices.txt this is static
586 return 15;
587 }
588 case kMajorBlockMmc: {
589 // Per Documentation/devices.txt this is dynamic
590 std::string tmp;
591 if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp) &&
592 !ReadFileToString(kSysfsMmcMaxMinorsDeprecated, &tmp)) {
593 LOG(ERROR) << "Failed to read max minors";
594 return -errno;
595 }
596 return std::stoi(tmp);
597 }
598 default: {
599 if (isVirtioBlkDevice(majorId)) {
600 // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is
601 // 2^4 - 1 = 15
602 return 15;
603 }
604 if (isNvmeBlkDevice(majorId, mSysPath)) {
605 // despite kernel nvme driver supports up to 1M minors,
606 // #define NVME_MINORS (1U << MINORBITS)
607 // sgdisk can not support more than 127 partitions, due to
608 // #define MAX_MBR_PARTS 128
609 return 127;
610 }
611 }
612 }
613
614 LOG(ERROR) << "Unsupported block major type " << majorId;
615 return -ENOTSUP;
616 }
617
618 } // namespace vold
619 } // namespace android
620