1 /*
2 Implementation of GPTData class derivative with popt-based command
3 line processing
4 Copyright (C) 2010-2022 Roderick W. Smith
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include <string.h>
22 #include <string>
23 #include <iostream>
24 #include <sstream>
25 #include <errno.h>
26 #include <popt.h>
27 #include "gptcl.h"
28
29 using namespace std;
30
GPTDataCL(void)31 GPTDataCL::GPTDataCL(void) {
32 attributeOperation = backupFile = partName = hybrids = newPartInfo = NULL;
33 mbrParts = twoParts = outDevice = typeCode = partGUID = diskGUID = NULL;
34 alignment = DEFAULT_ALIGNMENT;
35 alignEnd = false;
36 deletePartNum = infoPartNum = largestPartNum = bsdPartNum = 0;
37 tableSize = GPT_SIZE;
38 } // GPTDataCL constructor
39
GPTDataCL(string filename)40 GPTDataCL::GPTDataCL(string filename) {
41 } // GPTDataCL constructor with filename
42
~GPTDataCL(void)43 GPTDataCL::~GPTDataCL(void) {
44 } // GPTDataCL destructor
45
LoadBackupFile(string backupFile,int & saveData,int & neverSaveData)46 void GPTDataCL::LoadBackupFile(string backupFile, int &saveData, int &neverSaveData) {
47 if (LoadGPTBackup(backupFile) == 1) {
48 JustLooking(0);
49 saveData = 1;
50 } else {
51 saveData = 0;
52 neverSaveData = 1;
53 cerr << "Error loading backup file!\n";
54 } // else
55 } // GPTDataCL::LoadBackupFile()
56
57 // Perform the actions specified on the command line. This is necessarily one
58 // monster of a function!
59 // Returns values:
60 // 0 = success
61 // 1 = too few arguments
62 // 2 = error when reading partition table
63 // 3 = non-GPT disk and no -g option
64 // 4 = unable to save changes
65 // 8 = disk replication operation (-R) failed
DoOptions(int argc,char * argv[])66 int GPTDataCL::DoOptions(int argc, char* argv[]) {
67 GPTData secondDevice;
68 int opt, numOptions = 0, saveData = 0, neverSaveData = 0;
69 int partNum = 0, newPartNum = -1, saveNonGPT = 1, retval = 0, pretend = 0;
70 int byteSwapPartNum = 0;
71 uint64_t low, high, startSector, endSector, sSize, mainTableLBA;
72 uint64_t temp; // temporary variable; free to use in any case
73 char *device;
74 string cmd, typeGUID, name;
75 PartType typeHelper;
76
77 struct poptOption theOptions[] =
78 {
79 {"attributes", 'A', POPT_ARG_STRING, &attributeOperation, 'A', "operate on partition attributes",
80 "list|[partnum:show|or|nand|xor|=|set|clear|toggle|get[:bitnum|hexbitmask]]"},
81 {"set-alignment", 'a', POPT_ARG_INT, &alignment, 'a', "set sector alignment", "value"},
82 {"backup", 'b', POPT_ARG_STRING, &backupFile, 'b', "backup GPT to file", "file"},
83 {"byte-swap-name", 'B', POPT_ARG_INT, &byteSwapPartNum, 'B', "byte-swap partition's name", "partnum"},
84 {"change-name", 'c', POPT_ARG_STRING, &partName, 'c', "change partition's name", "partnum:name"},
85 {"recompute-chs", 'C', POPT_ARG_NONE, NULL, 'C', "recompute CHS values in protective/hybrid MBR", ""},
86 {"delete", 'd', POPT_ARG_INT, &deletePartNum, 'd', "delete a partition", "partnum"},
87 {"display-alignment", 'D', POPT_ARG_NONE, NULL, 'D', "show number of sectors per allocation block", ""},
88 {"move-second-header", 'e', POPT_ARG_NONE, NULL, 'e', "move second header to end of disk", ""},
89 {"end-of-largest", 'E', POPT_ARG_NONE, NULL, 'E', "show end of largest free block", ""},
90 {"first-in-largest", 'f', POPT_ARG_NONE, NULL, 'f', "show start of the largest free block", ""},
91 {"first-aligned-in-largest", 'F', POPT_ARG_NONE, NULL, 'F', "show start of the largest free block, aligned", ""},
92 {"mbrtogpt", 'g', POPT_ARG_NONE, NULL, 'g', "convert MBR to GPT", ""},
93 {"randomize-guids", 'G', POPT_ARG_NONE, NULL, 'G', "randomize disk and partition GUIDs", ""},
94 {"hybrid", 'h', POPT_ARG_STRING, &hybrids, 'h', "create hybrid MBR", "partnum[:partnum...][:EE]"},
95 {"info", 'i', POPT_ARG_INT, &infoPartNum, 'i', "show detailed information on partition", "partnum"},
96 {"align-end", 'I', POPT_ARG_NONE, NULL, 'I', "align partition end points", ""},
97 {"move-main-table", 'j', POPT_ARG_INT, &mainTableLBA, 'j', "adjust the location of the main partition table", "sector"},
98 {"load-backup", 'l', POPT_ARG_STRING, &backupFile, 'l', "load GPT backup from file", "file"},
99 {"list-types", 'L', POPT_ARG_NONE, NULL, 'L', "list known partition types", ""},
100 {"gpttombr", 'm', POPT_ARG_STRING, &mbrParts, 'm', "convert GPT to MBR", "partnum[:partnum...]"},
101 {"new", 'n', POPT_ARG_STRING, &newPartInfo, 'n', "create new partition", "partnum:start:end"},
102 {"largest-new", 'N', POPT_ARG_INT, &largestPartNum, 'N', "create largest possible new partition", "partnum"},
103 {"clear", 'o', POPT_ARG_NONE, NULL, 'o', "clear partition table", ""},
104 {"print-mbr", 'O', POPT_ARG_NONE, NULL, 'O', "print MBR partition table", ""},
105 {"print", 'p', POPT_ARG_NONE, NULL, 'p', "print partition table", ""},
106 {"pretend", 'P', POPT_ARG_NONE, NULL, 'P', "make changes in memory, but don't write them", ""},
107 {"transpose", 'r', POPT_ARG_STRING, &twoParts, 'r', "transpose two partitions", "partnum:partnum"},
108 {"replicate", 'R', POPT_ARG_STRING, &outDevice, 'R', "replicate partition table", "device_filename"},
109 {"sort", 's', POPT_ARG_NONE, NULL, 's', "sort partition table entries", ""},
110 {"resize-table", 'S', POPT_ARG_INT, &tableSize, 'S', "resize partition table", "numparts"},
111 {"typecode", 't', POPT_ARG_STRING, &typeCode, 't', "change partition type code", "partnum:{hexcode|GUID}"},
112 {"transform-bsd", 'T', POPT_ARG_INT, &bsdPartNum, 'T', "transform BSD disklabel partition to GPT", "partnum"},
113 {"partition-guid", 'u', POPT_ARG_STRING, &partGUID, 'u', "set partition GUID", "partnum:guid"},
114 {"disk-guid", 'U', POPT_ARG_STRING, &diskGUID, 'U', "set disk GUID", "guid"},
115 {"verify", 'v', POPT_ARG_NONE, NULL, 'v', "check partition table integrity", ""},
116 {"version", 'V', POPT_ARG_NONE, NULL, 'V', "display version information", ""},
117 {"zap", 'z', POPT_ARG_NONE, NULL, 'z', "zap (destroy) GPT (but not MBR) data structures", ""},
118 {"zap-all", 'Z', POPT_ARG_NONE, NULL, 'Z', "zap (destroy) GPT and MBR data structures", ""},
119 POPT_AUTOHELP { NULL, 0, 0, NULL, 0 }
120 };
121
122 // Create popt context...
123 poptCon = poptGetContext(NULL, argc, (const char**) argv, theOptions, 0);
124
125 poptSetOtherOptionHelp(poptCon, " [OPTION...] <device>");
126
127 if (argc < 2) {
128 poptPrintUsage(poptCon, stderr, 0);
129 return 1;
130 }
131
132 // Do one loop through the options to find the device filename and deal
133 // with options that don't require a device filename, to flag destructive
134 // (o, z, or Z) options, and to flag presence of a --pretend/-P option
135 while ((opt = poptGetNextOpt(poptCon)) > 0) {
136 switch (opt) {
137 case 'A':
138 cmd = GetString(attributeOperation, 1);
139 if (cmd == "list")
140 Attributes::ListAttributes();
141 break;
142 case 'L':
143 typeHelper.ShowAllTypes(0);
144 break;
145 case 'P':
146 pretend = 1;
147 break;
148 case 'V':
149 cout << "GPT fdisk (sgdisk) version " << GPTFDISK_VERSION << "\n\n";
150 break;
151 default:
152 break;
153 } // switch
154 numOptions++;
155 } // while
156
157 // Assume first non-option argument is the device filename....
158 device = (char*) poptGetArg(poptCon);
159 poptResetContext(poptCon);
160
161 if (device != NULL) {
162 JustLooking(); // reset as necessary
163 BeQuiet(); // Tell called functions to be less verbose & interactive
164 if (LoadPartitions((string) device)) {
165 if ((WhichWasUsed() == use_mbr) || (WhichWasUsed() == use_bsd))
166 saveNonGPT = 0; // flag so we don't overwrite unless directed to do so
167 sSize = GetBlockSize();
168 while ((opt = poptGetNextOpt(poptCon)) > 0) {
169 switch (opt) {
170 case 'A': {
171 if (cmd != "list") {
172 partNum = (int) GetInt(attributeOperation, 1) - 1;
173 if (partNum < 0)
174 partNum = newPartNum;
175 if ((partNum >= 0) && (partNum < (int) GetNumParts())) {
176 switch (ManageAttributes(partNum, GetString(attributeOperation, 2),
177 GetString(attributeOperation, 3))) {
178 case -1:
179 saveData = 0;
180 neverSaveData = 1;
181 break;
182 case 1:
183 JustLooking(0);
184 saveData = 1;
185 break;
186 default:
187 break;
188 } // switch
189 } else {
190 cerr << "Error: Invalid partition number " << partNum + 1 << "\n";
191 saveData = 0;
192 neverSaveData = 1;
193 } // if/else reasonable partition #
194 } // if (cmd != "list")
195 break;
196 } // case 'A':
197 case 'a':
198 SetAlignment(alignment);
199 break;
200 case 'B':
201 if (IsUsedPartNum(byteSwapPartNum - 1)) {
202 partitions[byteSwapPartNum - 1].ReverseNameBytes();
203 cout << "Changed partition " << byteSwapPartNum << "'s name to "
204 << partitions[byteSwapPartNum - 1].GetDescription() << "\n";
205 JustLooking(0);
206 saveData = 1;
207 }
208 break;
209 case 'b':
210 SaveGPTBackup(backupFile);
211 free(backupFile);
212 break;
213 case 'c':
214 JustLooking(0);
215 partNum = (int) GetInt(partName, 1) - 1;
216 if (partNum < 0)
217 partNum = newPartNum;
218 if ((partNum >= 0) && (partNum < (int) GetNumParts())) {
219 name = GetString(partName, 2);
220 if (SetName(partNum, (UnicodeString) name.c_str())) {
221 saveData = 1;
222 } else {
223 cerr << "Unable to set partition " << partNum + 1
224 << "'s name to '" << GetString(partName, 2) << "'!\n";
225 neverSaveData = 1;
226 } // if/else
227 free(partName);
228 }
229 break;
230 case 'C':
231 JustLooking(0);
232 RecomputeCHS();
233 saveData = 1;
234 break;
235 case 'd':
236 JustLooking(0);
237 if (DeletePartition(deletePartNum - 1) == 0) {
238 cerr << "Error " << errno << " deleting partition!\n";
239 neverSaveData = 1;
240 } else saveData = 1;
241 break;
242 case 'D':
243 cout << GetAlignment() << "\n";
244 break;
245 case 'e':
246 JustLooking(0);
247 MoveSecondHeaderToEnd();
248 saveData = 1;
249 break;
250 case 'E':
251 cout << FindLastInFree(FindFirstInLargest()) << "\n";
252 break;
253 case 'f':
254 cout << FindFirstInLargest() << "\n";
255 break;
256 case 'F':
257 temp = FindFirstInLargest();
258 Align(&temp);
259 cout << temp << "\n";
260 break;
261 case 'g':
262 JustLooking(0);
263 saveData = 1;
264 saveNonGPT = 1;
265 break;
266 case 'G':
267 JustLooking(0);
268 saveData = 1;
269 RandomizeGUIDs();
270 break;
271 case 'h':
272 JustLooking(0);
273 if (BuildMBR(hybrids, 1) == 1)
274 saveData = 1;
275 break;
276 case 'i':
277 ShowPartDetails(infoPartNum - 1);
278 break;
279 case 'I':
280 alignEnd = true;
281 break;
282 case 'j':
283 if (MoveMainTable(mainTableLBA)) {
284 JustLooking(0);
285 saveData = 1;
286 } else {
287 neverSaveData = 1;
288 } // if/else
289 break;
290 case 'l':
291 LoadBackupFile(backupFile, saveData, neverSaveData);
292 free(backupFile);
293 break;
294 case 'L':
295 break;
296 case 'm':
297 JustLooking(0);
298 if (BuildMBR(mbrParts, 0) == 1) {
299 if (!pretend) {
300 if (SaveMBR()) {
301 DestroyGPT();
302 } else
303 cerr << "Problem saving MBR!\n";
304 } // if
305 saveNonGPT = 0;
306 pretend = 1; // Not really, but works around problem if -g is used with this...
307 saveData = 0;
308 } // if
309 break;
310 case 'n':
311 JustLooking(0);
312 newPartNum = (int) GetInt(newPartInfo, 1) - 1;
313 if (newPartNum < 0)
314 newPartNum = FindFirstFreePart();
315 low = FindFirstInLargest();
316 Align(&low);
317 high = FindLastInFree(low, alignEnd);
318 startSector = IeeeToInt(GetString(newPartInfo, 2), sSize, low, high, sectorAlignment, low);
319 endSector = IeeeToInt(GetString(newPartInfo, 3), sSize, startSector, high, sectorAlignment, high);
320 if (CreatePartition(newPartNum, startSector, endSector)) {
321 saveData = 1;
322 } else {
323 cerr << "Could not create partition " << newPartNum + 1 << " from "
324 << startSector << " to " << endSector << "\n";
325 neverSaveData = 1;
326 } // if/else
327 free(newPartInfo);
328 break;
329 case 'N':
330 JustLooking(0);
331 startSector = FindFirstInLargest();
332 Align(&startSector);
333 endSector = FindLastInFree(startSector, alignEnd);
334 if (largestPartNum <= 0)
335 largestPartNum = FindFirstFreePart() + 1;
336 if (CreatePartition(largestPartNum - 1, startSector, endSector)) {
337 saveData = 1;
338 } else {
339 cerr << "Could not create partition " << largestPartNum << " from "
340 << startSector << " to " << endSector << "\n";
341 neverSaveData = 1;
342 } // if/else
343 break;
344 case 'o':
345 JustLooking(0);
346 ClearGPTData();
347 saveData = 1;
348 break;
349 case 'O':
350 DisplayMBRData();
351 break;
352 case 'p':
353 DisplayGPTData();
354 break;
355 case 'P':
356 pretend = 1;
357 break;
358 case 'r':
359 JustLooking(0);
360 uint64_t p1, p2;
361 p1 = GetInt(twoParts, 1) - 1;
362 p2 = GetInt(twoParts, 2) - 1;
363 if (SwapPartitions((uint32_t) p1, (uint32_t) p2) == 0) {
364 neverSaveData = 1;
365 cerr << "Cannot swap partitions " << p1 + 1 << " and " << p2 + 1 << "\n";
366 } else saveData = 1;
367 break;
368 case 'R':
369 secondDevice = *this;
370 secondDevice.SetDisk(outDevice);
371 secondDevice.JustLooking(0);
372 if (!secondDevice.SaveGPTData(1))
373 retval = 8;
374 break;
375 case 's':
376 JustLooking(0);
377 SortGPT();
378 saveData = 1;
379 break;
380 case 'S':
381 JustLooking(0);
382 if (SetGPTSize(tableSize) == 0)
383 neverSaveData = 1;
384 else
385 saveData = 1;
386 break;
387 case 't':
388 JustLooking(0);
389 partNum = (int) GetInt(typeCode, 1) - 1;
390 if (partNum < 0)
391 partNum = newPartNum;
392 if ((partNum >= 0) && (partNum < (int) GetNumParts())) {
393 typeHelper = GetString(typeCode, 2);
394 if ((typeHelper != PartType::unusedPartType) &&
395 (ChangePartType(partNum, typeHelper))) {
396 saveData = 1;
397 } else {
398 cerr << "Could not change partition " << partNum + 1
399 << "'s type code to " << GetString(typeCode, 2) << "!\n";
400 neverSaveData = 1;
401 } // if/else
402 free(typeCode);
403 }
404 break;
405 case 'T':
406 JustLooking(0);
407 XFormDisklabel(bsdPartNum - 1);
408 saveData = 1;
409 break;
410 case 'u':
411 JustLooking(0);
412 saveData = 1;
413 partNum = (int) GetInt(partGUID, 1) - 1;
414 if (partNum < 0)
415 partNum = newPartNum;
416 if ((partNum >= 0) && (partNum < (int) GetNumParts())) {
417 SetPartitionGUID(partNum, GetString(partGUID, 2).c_str());
418 }
419 break;
420 case 'U':
421 JustLooking(0);
422 saveData = 1;
423 SetDiskGUID(diskGUID);
424 break;
425 case 'v':
426 Verify();
427 break;
428 case 'z':
429 if (!pretend) {
430 DestroyGPT();
431 } // if
432 saveNonGPT = 1;
433 saveData = 0;
434 break;
435 case 'Z':
436 if (!pretend) {
437 DestroyGPT();
438 DestroyMBR();
439 } // if
440 saveNonGPT = 1;
441 saveData = 0;
442 break;
443 default:
444 cerr << "Unknown option (-" << opt << ")!\n";
445 break;
446 } // switch
447 } // while
448 } else { // if loaded OK
449 poptResetContext(poptCon);
450 // Do a few types of operations even if there are problems....
451 while ((opt = poptGetNextOpt(poptCon)) > 0) {
452 switch (opt) {
453 case 'l':
454 LoadBackupFile(backupFile, saveData, neverSaveData);
455 cout << "Information: Loading backup partition table; will override earlier problems!\n";
456 free(backupFile);
457 retval = 0;
458 break;
459 case 'o':
460 JustLooking(0);
461 ClearGPTData();
462 saveData = 1;
463 cout << "Information: Creating fresh partition table; will override earlier problems!\n";
464 retval = 0;
465 break;
466 case 'v':
467 cout << "Verification may miss some problems or report too many!\n";
468 Verify();
469 break;
470 case 'z':
471 if (!pretend) {
472 DestroyGPT();
473 } // if
474 saveNonGPT = 1;
475 saveData = 0;
476 break;
477 case 'Z':
478 if (!pretend) {
479 DestroyGPT();
480 DestroyMBR();
481 } // if
482 saveNonGPT = 1;
483 saveData = 0;
484 break;
485 } // switch
486 } // while
487 retval = 2;
488 } // if/else loaded OK
489 if ((saveData) && (!neverSaveData) && (saveNonGPT) && (!pretend)) {
490 if (!SaveGPTData(1))
491 retval = 4;
492 }
493 if (saveData && (!saveNonGPT)) {
494 cout << "Non-GPT disk; not saving changes. Use -g to override.\n";
495 retval = 3;
496 } // if
497 if (neverSaveData) {
498 cerr << "Error encountered; not saving changes.\n";
499 retval = 4;
500 } // if
501 } // if (device != NULL)
502 poptFreeContext(poptCon);
503 return retval;
504 } // GPTDataCL::DoOptions()
505
506 // Create a hybrid or regular MBR from GPT data structures
BuildMBR(char * argument,int isHybrid)507 int GPTDataCL::BuildMBR(char* argument, int isHybrid) {
508 int numParts, allOK = 1, i, origPartNum;
509 int eeLast = 0, mbrNum = 0;
510 MBRPart newPart;
511 BasicMBRData newMBR;
512
513 if (argument != NULL) {
514 numParts = CountColons(argument) + 1;
515 if (isHybrid) {
516 eeLast = GetString(argument, numParts) == "EE";
517 if (eeLast) {
518 numParts--;
519 }
520 }
521
522 if (numParts <= (4 - isHybrid)) {
523 newMBR.SetDisk(GetDisk());
524 for (i = 0; i < numParts; i++) {
525 origPartNum = GetInt(argument, i + 1) - 1;
526 if (IsUsedPartNum(origPartNum) && (partitions[origPartNum].IsSizedForMBR() == MBR_SIZED_GOOD)) {
527 mbrNum = i + (isHybrid && ! eeLast);
528 newPart.SetInclusion(PRIMARY);
529 newPart.SetLocation(operator[](origPartNum).GetFirstLBA(),
530 operator[](origPartNum).GetLengthLBA());
531 newPart.SetStatus(0);
532 newPart.SetType((uint8_t)(operator[](origPartNum).GetHexType() / 0x0100));
533 newMBR.AddPart(mbrNum, newPart);
534 } else {
535 cerr << "Original partition " << origPartNum + 1 << " does not exist or is too big! Aborting operation!\n";
536 allOK = 0;
537 } // if/else
538 } // for
539 if (isHybrid) {
540 if (eeLast) {
541 mbrNum = i;
542 } else {
543 mbrNum = 0;
544 }
545 newPart.SetInclusion(PRIMARY);
546 newPart.SetLocation(1, newMBR.FindLastInFree(1));
547 newPart.SetStatus(0);
548 newPart.SetType(0xEE);
549 newMBR.AddPart(mbrNum, newPart);
550 } // if
551 if (allOK)
552 SetProtectiveMBR(newMBR);
553 } else allOK = 0;
554 } else allOK = 0;
555 if (!allOK)
556 cerr << "Problem creating MBR!\n";
557 return allOK;
558 } // GPTDataCL::BuildMBR()
559
560 // Returns the number of colons in argument string, ignoring the
561 // first character (thus, a leading colon is ignored, as GetString()
562 // does).
CountColons(char * argument)563 int CountColons(char* argument) {
564 int num = 0;
565
566 while ((argument[0] != '\0') && (argument = strchr(&argument[1], ':')))
567 num++;
568
569 return num;
570 } // GPTDataCL::CountColons()
571
572 // Extract integer data from argument string, which should be colon-delimited
GetInt(const string & argument,int itemNum)573 uint64_t GetInt(const string & argument, int itemNum) {
574 uint64_t retval;
575
576 istringstream inString(GetString(argument, itemNum));
577 inString >> retval;
578 return retval;
579 } // GPTDataCL::GetInt()
580
581 // Extract string data from argument string, which should be colon-delimited
582 // If string begins with a colon, that colon is skipped in the counting. If an
583 // invalid itemNum is specified, returns an empty string.
GetString(string argument,int itemNum)584 string GetString(string argument, int itemNum) {
585 size_t startPos = 0, endPos = 0;
586 string retVal = "";
587 int foundLast = 0;
588 int numFound = 0;
589
590 if (argument[0] == ':')
591 argument.erase(0, 1);
592 while ((numFound < itemNum) && (!foundLast)) {
593 endPos = argument.find(':', startPos);
594 numFound++;
595 if (endPos == string::npos) {
596 foundLast = 1;
597 endPos = argument.length();
598 } else if (numFound < itemNum) {
599 startPos = endPos + 1;
600 } // if/elseif
601 } // while
602 if ((numFound == itemNum) && (numFound > 0))
603 retVal = argument.substr(startPos, endPos - startPos);
604
605 return retVal;
606 } // GetString()
607