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 "PublicVolume.h"
19 #include "PrivateVolume.h"
20 #include "Utils.h"
21 #include "VolumeBase.h"
22 #include "VolumeManager.h"
23 #include "ResponseCode.h"
24 
25 #include <base/file.h>
26 #include <base/stringprintf.h>
27 #include <base/logging.h>
28 #include <diskconfig/diskconfig.h>
29 
30 #include <vector>
31 #include <fcntl.h>
32 #include <inttypes.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/mount.h>
38 
39 using android::base::ReadFileToString;
40 using android::base::WriteStringToFile;
41 using android::base::StringPrintf;
42 
43 namespace android {
44 namespace vold {
45 
46 static const char* kSgdiskPath = "/system/bin/sgdisk";
47 static const char* kSgdiskToken = " \t\n";
48 
49 static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors";
50 
51 static const unsigned int kMajorBlockScsiA = 8;
52 static const unsigned int kMajorBlockScsiB = 65;
53 static const unsigned int kMajorBlockScsiC = 66;
54 static const unsigned int kMajorBlockScsiD = 67;
55 static const unsigned int kMajorBlockScsiE = 68;
56 static const unsigned int kMajorBlockScsiF = 69;
57 static const unsigned int kMajorBlockScsiG = 70;
58 static const unsigned int kMajorBlockScsiH = 71;
59 static const unsigned int kMajorBlockScsiI = 128;
60 static const unsigned int kMajorBlockScsiJ = 129;
61 static const unsigned int kMajorBlockScsiK = 130;
62 static const unsigned int kMajorBlockScsiL = 131;
63 static const unsigned int kMajorBlockScsiM = 132;
64 static const unsigned int kMajorBlockScsiN = 133;
65 static const unsigned int kMajorBlockScsiO = 134;
66 static const unsigned int kMajorBlockScsiP = 135;
67 static const unsigned int kMajorBlockMmc = 179;
68 
69 static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7";
70 static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF";
71 static const char* kGptAndroidExpand = "193D1EA4-B3CA-11E4-B075-10604B889DCF";
72 
73 enum class Table {
74     kUnknown,
75     kMbr,
76     kGpt,
77 };
78 
Disk(const std::string & eventPath,dev_t device,const std::string & nickname,int flags)79 Disk::Disk(const std::string& eventPath, dev_t device,
80         const std::string& nickname, int flags) :
81         mDevice(device), mSize(-1), mNickname(nickname), mFlags(flags), mCreated(
82                 false), mJustPartitioned(false) {
83     mId = StringPrintf("disk:%u,%u", major(device), minor(device));
84     mEventPath = eventPath;
85     mSysPath = StringPrintf("/sys/%s", eventPath.c_str());
86     mDevPath = StringPrintf("/dev/block/vold/%s", mId.c_str());
87     CreateDeviceNode(mDevPath, mDevice);
88 }
89 
~Disk()90 Disk::~Disk() {
91     CHECK(!mCreated);
92     DestroyDeviceNode(mDevPath);
93 }
94 
findVolume(const std::string & id)95 std::shared_ptr<VolumeBase> Disk::findVolume(const std::string& id) {
96     for (auto vol : mVolumes) {
97         if (vol->getId() == id) {
98             return vol;
99         }
100         auto stackedVol = vol->findVolume(id);
101         if (stackedVol != nullptr) {
102             return stackedVol;
103         }
104     }
105     return nullptr;
106 }
107 
listVolumes(VolumeBase::Type type,std::list<std::string> & list)108 void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) {
109     for (auto vol : mVolumes) {
110         if (vol->getType() == type) {
111             list.push_back(vol->getId());
112         }
113         // TODO: consider looking at stacked volumes
114     }
115 }
116 
create()117 status_t Disk::create() {
118     CHECK(!mCreated);
119     mCreated = true;
120     notifyEvent(ResponseCode::DiskCreated, StringPrintf("%d", mFlags));
121     readMetadata();
122     readPartitions();
123     return OK;
124 }
125 
destroy()126 status_t Disk::destroy() {
127     CHECK(mCreated);
128     destroyAllVolumes();
129     mCreated = false;
130     notifyEvent(ResponseCode::DiskDestroyed);
131     return OK;
132 }
133 
createPublicVolume(dev_t device)134 void Disk::createPublicVolume(dev_t device) {
135     auto vol = std::shared_ptr<VolumeBase>(new PublicVolume(device));
136     if (mJustPartitioned) {
137         LOG(DEBUG) << "Device just partitioned; silently formatting";
138         vol->setSilent(true);
139         vol->create();
140         vol->format("auto");
141         vol->destroy();
142         vol->setSilent(false);
143     }
144 
145     mVolumes.push_back(vol);
146     vol->setDiskId(getId());
147     vol->create();
148 }
149 
createPrivateVolume(dev_t device,const std::string & partGuid)150 void Disk::createPrivateVolume(dev_t device, const std::string& partGuid) {
151     std::string normalizedGuid;
152     if (NormalizeHex(partGuid, normalizedGuid)) {
153         LOG(WARNING) << "Invalid GUID " << partGuid;
154         return;
155     }
156 
157     std::string keyRaw;
158     if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) {
159         PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid;
160         return;
161     }
162 
163     LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
164 
165     auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
166     if (mJustPartitioned) {
167         LOG(DEBUG) << "Device just partitioned; silently formatting";
168         vol->setSilent(true);
169         vol->create();
170         vol->format("auto");
171         vol->destroy();
172         vol->setSilent(false);
173     }
174 
175     mVolumes.push_back(vol);
176     vol->setDiskId(getId());
177     vol->setPartGuid(partGuid);
178     vol->create();
179 }
180 
destroyAllVolumes()181 void Disk::destroyAllVolumes() {
182     for (auto vol : mVolumes) {
183         vol->destroy();
184     }
185     mVolumes.clear();
186 }
187 
readMetadata()188 status_t Disk::readMetadata() {
189     mSize = -1;
190     mLabel.clear();
191 
192     int fd = open(mDevPath.c_str(), O_RDONLY | O_CLOEXEC);
193     if (fd != -1) {
194         if (ioctl(fd, BLKGETSIZE64, &mSize)) {
195             mSize = -1;
196         }
197         close(fd);
198     }
199 
200     switch (major(mDevice)) {
201     case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
202     case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
203     case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
204     case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
205         std::string path(mSysPath + "/device/vendor");
206         std::string tmp;
207         if (!ReadFileToString(path, &tmp)) {
208             PLOG(WARNING) << "Failed to read vendor from " << path;
209             return -errno;
210         }
211         mLabel = tmp;
212         break;
213     }
214     case kMajorBlockMmc: {
215         std::string path(mSysPath + "/device/manfid");
216         std::string tmp;
217         if (!ReadFileToString(path, &tmp)) {
218             PLOG(WARNING) << "Failed to read manufacturer from " << path;
219             return -errno;
220         }
221         uint64_t manfid = strtoll(tmp.c_str(), nullptr, 16);
222         // Our goal here is to give the user a meaningful label, ideally
223         // matching whatever is silk-screened on the card.  To reduce
224         // user confusion, this list doesn't contain white-label manfid.
225         switch (manfid) {
226         case 0x000003: mLabel = "SanDisk"; break;
227         case 0x00001b: mLabel = "Samsung"; break;
228         case 0x000028: mLabel = "Lexar"; break;
229         case 0x000074: mLabel = "Transcend"; break;
230         }
231         break;
232     }
233     default: {
234         LOG(WARNING) << "Unsupported block major type" << major(mDevice);
235         return -ENOTSUP;
236     }
237     }
238 
239     notifyEvent(ResponseCode::DiskSizeChanged, StringPrintf("%" PRId64, mSize));
240     notifyEvent(ResponseCode::DiskLabelChanged, mLabel);
241     notifyEvent(ResponseCode::DiskSysPathChanged, mSysPath);
242     return OK;
243 }
244 
readPartitions()245 status_t Disk::readPartitions() {
246     int8_t maxMinors = getMaxMinors();
247     if (maxMinors < 0) {
248         return -ENOTSUP;
249     }
250 
251     destroyAllVolumes();
252 
253     // Parse partition table
254 
255     std::vector<std::string> cmd;
256     cmd.push_back(kSgdiskPath);
257     cmd.push_back("--android-dump");
258     cmd.push_back(mDevPath);
259 
260     std::vector<std::string> output;
261     status_t res = ForkExecvp(cmd, output);
262     if (res != OK) {
263         LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
264         notifyEvent(ResponseCode::DiskScanned);
265         mJustPartitioned = false;
266         return res;
267     }
268 
269     Table table = Table::kUnknown;
270     bool foundParts = false;
271     for (auto line : output) {
272         char* cline = (char*) line.c_str();
273         char* token = strtok(cline, kSgdiskToken);
274         if (token == nullptr) continue;
275 
276         if (!strcmp(token, "DISK")) {
277             const char* type = strtok(nullptr, kSgdiskToken);
278             if (!strcmp(type, "mbr")) {
279                 table = Table::kMbr;
280             } else if (!strcmp(type, "gpt")) {
281                 table = Table::kGpt;
282             }
283         } else if (!strcmp(token, "PART")) {
284             foundParts = true;
285             int i = strtol(strtok(nullptr, kSgdiskToken), nullptr, 10);
286             if (i <= 0 || i > maxMinors) {
287                 LOG(WARNING) << mId << " is ignoring partition " << i
288                         << " beyond max supported devices";
289                 continue;
290             }
291             dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i);
292 
293             if (table == Table::kMbr) {
294                 const char* type = strtok(nullptr, kSgdiskToken);
295 
296                 switch (strtol(type, nullptr, 16)) {
297                 case 0x06: // FAT16
298                 case 0x0b: // W95 FAT32 (LBA)
299                 case 0x0c: // W95 FAT32 (LBA)
300                 case 0x0e: // W95 FAT16 (LBA)
301                     createPublicVolume(partDevice);
302                     break;
303                 }
304             } else if (table == Table::kGpt) {
305                 const char* typeGuid = strtok(nullptr, kSgdiskToken);
306                 const char* partGuid = strtok(nullptr, kSgdiskToken);
307 
308                 if (!strcasecmp(typeGuid, kGptBasicData)) {
309                     createPublicVolume(partDevice);
310                 } else if (!strcasecmp(typeGuid, kGptAndroidExpand)) {
311                     createPrivateVolume(partDevice, partGuid);
312                 }
313             }
314         }
315     }
316 
317     // Ugly last ditch effort, treat entire disk as partition
318     if (table == Table::kUnknown || !foundParts) {
319         LOG(WARNING) << mId << " has unknown partition table; trying entire device";
320 
321         std::string fsType;
322         std::string unused;
323         if (ReadMetadataUntrusted(mDevPath, fsType, unused, unused) == OK) {
324             createPublicVolume(mDevice);
325         } else {
326             LOG(WARNING) << mId << " failed to identify, giving up";
327         }
328     }
329 
330     notifyEvent(ResponseCode::DiskScanned);
331     mJustPartitioned = false;
332     return OK;
333 }
334 
unmountAll()335 status_t Disk::unmountAll() {
336     for (auto vol : mVolumes) {
337         vol->unmount();
338     }
339     return OK;
340 }
341 
partitionPublic()342 status_t Disk::partitionPublic() {
343     // TODO: improve this code
344     destroyAllVolumes();
345     mJustPartitioned = true;
346 
347     struct disk_info dinfo;
348     memset(&dinfo, 0, sizeof(dinfo));
349 
350     if (!(dinfo.part_lst = (struct part_info *) malloc(
351             MAX_NUM_PARTS * sizeof(struct part_info)))) {
352         return -1;
353     }
354 
355     memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
356     dinfo.device = strdup(mDevPath.c_str());
357     dinfo.scheme = PART_SCHEME_MBR;
358     dinfo.sect_size = 512;
359     dinfo.skip_lba = 2048;
360     dinfo.num_lba = 0;
361     dinfo.num_parts = 1;
362 
363     struct part_info *pinfo = &dinfo.part_lst[0];
364 
365     pinfo->name = strdup("android_sdcard");
366     pinfo->flags |= PART_ACTIVE_FLAG;
367     pinfo->type = PC_PART_TYPE_FAT32;
368     pinfo->len_kb = -1;
369 
370     int rc = apply_disk_config(&dinfo, 0);
371     if (rc) {
372         LOG(ERROR) << "Failed to apply disk configuration: " << rc;
373         goto out;
374     }
375 
376 out:
377     free(pinfo->name);
378     free(dinfo.device);
379     free(dinfo.part_lst);
380 
381     return rc;
382 }
383 
partitionPrivate()384 status_t Disk::partitionPrivate() {
385     return partitionMixed(0);
386 }
387 
partitionMixed(int8_t ratio)388 status_t Disk::partitionMixed(int8_t ratio) {
389     int res;
390 
391     destroyAllVolumes();
392     mJustPartitioned = true;
393 
394     // First nuke any existing partition table
395     std::vector<std::string> cmd;
396     cmd.push_back(kSgdiskPath);
397     cmd.push_back("--zap-all");
398     cmd.push_back(mDevPath);
399 
400     // Zap sometimes returns an error when it actually succeeded, so
401     // just log as warning and keep rolling forward.
402     if ((res = ForkExecvp(cmd)) != 0) {
403         LOG(WARNING) << "Failed to zap; status " << res;
404     }
405 
406     // We've had some success above, so generate both the private partition
407     // GUID and encryption key and persist them.
408     std::string partGuidRaw;
409     std::string keyRaw;
410     if (ReadRandomBytes(16, partGuidRaw) || ReadRandomBytes(16, keyRaw)) {
411         LOG(ERROR) << "Failed to generate GUID or key";
412         return -EIO;
413     }
414 
415     std::string partGuid;
416     StrToHex(partGuidRaw, partGuid);
417 
418     if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) {
419         LOG(ERROR) << "Failed to persist key";
420         return -EIO;
421     } else {
422         LOG(DEBUG) << "Persisted key for GUID " << partGuid;
423     }
424 
425     // Now let's build the new GPT table. We heavily rely on sgdisk to
426     // force optimal alignment on the created partitions.
427     cmd.clear();
428     cmd.push_back(kSgdiskPath);
429 
430     // If requested, create a public partition first. Mixed-mode partitioning
431     // like this is an experimental feature.
432     if (ratio > 0) {
433         if (ratio < 10 || ratio > 90) {
434             LOG(ERROR) << "Mixed partition ratio must be between 10-90%";
435             return -EINVAL;
436         }
437 
438         uint64_t splitMb = ((mSize / 100) * ratio) / 1024 / 1024;
439         cmd.push_back(StringPrintf("--new=0:0:+%" PRId64 "M", splitMb));
440         cmd.push_back(StringPrintf("--typecode=0:%s", kGptBasicData));
441         cmd.push_back("--change-name=0:shared");
442     }
443 
444     // Define a metadata partition which is designed for future use; there
445     // should only be one of these per physical device, even if there are
446     // multiple private volumes.
447     cmd.push_back("--new=0:0:+16M");
448     cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidMeta));
449     cmd.push_back("--change-name=0:android_meta");
450 
451     // Define a single private partition filling the rest of disk.
452     cmd.push_back("--new=0:0:-0");
453     cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidExpand));
454     cmd.push_back(StringPrintf("--partition-guid=0:%s", partGuid.c_str()));
455     cmd.push_back("--change-name=0:android_expand");
456 
457     cmd.push_back(mDevPath);
458 
459     if ((res = ForkExecvp(cmd)) != 0) {
460         LOG(ERROR) << "Failed to partition; status " << res;
461         return res;
462     }
463 
464     return OK;
465 }
466 
notifyEvent(int event)467 void Disk::notifyEvent(int event) {
468     VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
469             getId().c_str(), false);
470 }
471 
notifyEvent(int event,const std::string & value)472 void Disk::notifyEvent(int event, const std::string& value) {
473     VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
474             StringPrintf("%s %s", getId().c_str(), value.c_str()).c_str(), false);
475 }
476 
getMaxMinors()477 int Disk::getMaxMinors() {
478     // Figure out maximum partition devices supported
479     switch (major(mDevice)) {
480     case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
481     case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
482     case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
483     case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
484         // Per Documentation/devices.txt this is static
485         return 15;
486     }
487     case kMajorBlockMmc: {
488         // Per Documentation/devices.txt this is dynamic
489         std::string tmp;
490         if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) {
491             LOG(ERROR) << "Failed to read max minors";
492             return -errno;
493         }
494         return atoi(tmp.c_str());
495     }
496     }
497 
498     LOG(ERROR) << "Unsupported block major type " << major(mDevice);
499     return -ENOTSUP;
500 }
501 
502 }  // namespace vold
503 }  // namespace android
504