1 /*
2     Copyright (C) 2010-2018  <Roderick W. Smith>
3 
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8 
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13 
14     You should have received a copy of the GNU General Public License along
15     with this program; if not, write to the Free Software Foundation, Inc.,
16     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17 
18 */
19 
20 /* This class implements an interactive text-mode interface atop the
21    GPTData class */
22 
23 #include <string.h>
24 #include <errno.h>
25 #include <stdint.h>
26 #include <limits.h>
27 #include <iostream>
28 #include <fstream>
29 #include <sstream>
30 #include <cstdio>
31 #include "attributes.h"
32 #include "gpttext.h"
33 #include "support.h"
34 
35 using namespace std;
36 
37 /********************************************
38  *                                          *
39  * GPTDataText class and related structures *
40  *                                          *
41  ********************************************/
42 
GPTDataTextUI(void)43 GPTDataTextUI::GPTDataTextUI(void) : GPTData() {
44 } // default constructor
45 
GPTDataTextUI(string filename)46 GPTDataTextUI::GPTDataTextUI(string filename) : GPTData(filename) {
47 } // constructor passing filename
48 
~GPTDataTextUI(void)49 GPTDataTextUI::~GPTDataTextUI(void) {
50 } // default destructor
51 
52 /*********************************************************************
53  *                                                                   *
54  * The following functions are extended (interactive) versions of    *
55  * simpler functions in the base class....                           *
56  *                                                                   *
57  *********************************************************************/
58 
59 // Overridden function; calls base-class function and then makes
60 // additional queries of the user, if the base-class function can't
61 // decide what to do.
UseWhichPartitions(void)62 WhichToUse GPTDataTextUI::UseWhichPartitions(void) {
63    WhichToUse which;
64    MBRValidity mbrState;
65    int answer;
66 
67    which = GPTData::UseWhichPartitions();
68    if ((which != use_abort) || beQuiet)
69       return which;
70 
71    // If we get past here, it means that the non-interactive tests were
72    // inconclusive, so we must ask the user which table to use....
73    mbrState = protectiveMBR.GetValidity();
74 
75    if ((state == gpt_valid) && (mbrState == mbr)) {
76       cout << "Found valid MBR and GPT. Which do you want to use?\n";
77       answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
78       if (answer == 1) {
79          which = use_mbr;
80       } else if (answer == 2) {
81          which = use_gpt;
82          cout << "Using GPT and creating fresh protective MBR.\n";
83       } else which = use_new;
84    } // if
85 
86    // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
87    // problems)
88    if (state == gpt_corrupt) {
89       if ((mbrState == mbr) || (mbrState == hybrid)) {
90          cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
91               << "GPT MAY permit recovery of GPT data.)\n";
92          answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
93          if (answer == 1) {
94             which = use_mbr;
95          } else if (answer == 2) {
96             which = use_gpt;
97          } else which = use_new;
98       } else if (mbrState == invalid) {
99          cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
100               << "GPT MAY permit recovery of GPT data.)\n";
101          answer = GetNumber(1, 2, 1, " 1 - Use current GPT\n 2 - Create blank GPT\n\nYour answer: ");
102          if (answer == 1) {
103             which = use_gpt;
104          } else which = use_new;
105       } // if/else/else
106    } // if (corrupt GPT)
107 
108    return which;
109 } // UseWhichPartitions()
110 
111 // Ask the user for a partition number; and prompt for verification
112 // if the requested partition isn't of a known BSD type.
113 // Lets the base-class function do the work, and returns its value (the
114 // number of converted partitions).
XFormDisklabel(void)115 int GPTDataTextUI::XFormDisklabel(void) {
116    uint32_t partNum;
117    uint16_t hexCode;
118    int goOn = 1, numDone = 0;
119    BSDData disklabel;
120 
121    partNum = GetPartNum();
122 
123    // Now see if the specified partition has a BSD type code....
124    hexCode = partitions[partNum].GetHexType();
125    if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
126       cout << "Specified partition doesn't have a disklabel partition type "
127            << "code.\nContinue anyway? ";
128       goOn = (GetYN() == 'Y');
129    } // if
130 
131    if (goOn)
132       numDone = GPTData::XFormDisklabel(partNum);
133 
134    return numDone;
135 } // GPTDataTextUI::XFormDisklabel(void)
136 
137 
138 /*********************************************************************
139  *                                                                   *
140  * Begin functions that obtain information from the users, and often *
141  * do something with that information (call other functions)         *
142  *                                                                   *
143  *********************************************************************/
144 
145 // Prompts user for partition number and returns the result. Returns "0"
146 // (the first partition) if none are currently defined.
GetPartNum(void)147 uint32_t GPTDataTextUI::GetPartNum(void) {
148    uint32_t partNum;
149    uint32_t low, high;
150    ostringstream prompt;
151 
152    if (GetPartRange(&low, &high) > 0) {
153       prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
154       partNum = GetNumber(low + 1, high + 1, low, prompt.str());
155    } else partNum = 1;
156    return (partNum - 1);
157 } // GPTDataTextUI::GetPartNum()
158 
159 // What it says: Resize the partition table. (Default is 128 entries.)
ResizePartitionTable(void)160 void GPTDataTextUI::ResizePartitionTable(void) {
161    int newSize;
162    ostringstream prompt;
163    uint32_t curLow, curHigh;
164 
165    cout << "Current partition table size is " << numParts << ".\n";
166    GetPartRange(&curLow, &curHigh);
167    curHigh++; // since GetPartRange() returns numbers starting from 0...
168    // There's no point in having fewer than four partitions....
169    if (curHigh < (blockSize / GPT_SIZE))
170       curHigh = blockSize / GPT_SIZE;
171    prompt << "Enter new size (" << curHigh << " up, default " << NUM_GPT_ENTRIES << "): ";
172    newSize = GetNumber(4, 65535, 128, prompt.str());
173    if (newSize < 128) {
174       cout << "Caution: The partition table size should officially be 16KB or larger,\n"
175            << "which works out to 128 entries. In practice, smaller tables seem to\n"
176            << "work with most OSes, but this practice is risky. I'm proceeding with\n"
177            << "the resize, but you may want to reconsider this action and undo it.\n\n";
178    } // if
179    SetGPTSize(newSize);
180 } // GPTDataTextUI::ResizePartitionTable()
181 
182 // Move the main partition table (to enable some SoC boot loaders to place
183 // code at sector 2, for instance).
MoveMainTable(void)184 void GPTDataTextUI::MoveMainTable(void) {
185     uint64_t newStart, pteSize = GetTableSizeInSectors();
186     uint64_t maxValue = FindFirstUsedLBA() - pteSize;
187     ostringstream prompt;
188 
189     cout << "Currently, main partition table begins at sector " << mainHeader.partitionEntriesLBA
190          << " and ends at sector " << mainHeader.partitionEntriesLBA + pteSize - 1 << "\n";
191     prompt << "Enter new starting location (2 to " << maxValue << "; default is 2; 1 to abort): ";
192     newStart = GetNumber(1, maxValue, 2, prompt.str());
193     if (newStart != 1) {
194         GPTData::MoveMainTable(newStart);
195     } else {
196         cout << "Aborting change!\n";
197     } // if
198 } // GPTDataTextUI::MoveMainTable()
199 
200 // Interactively create a partition
CreatePartition(void)201 void GPTDataTextUI::CreatePartition(void) {
202    uint64_t firstBlock, firstInLargest, lastBlock, sector, origSector;
203    uint32_t firstFreePart = 0;
204    ostringstream prompt1, prompt2, prompt3;
205    int partNum;
206 
207    // Find first free partition...
208    while (partitions[firstFreePart].GetFirstLBA() != 0) {
209       firstFreePart++;
210    } // while
211 
212    if (((firstBlock = FindFirstAvailable()) != 0) &&
213        (firstFreePart < numParts)) {
214       lastBlock = FindLastAvailable();
215       firstInLargest = FindFirstInLargest();
216       Align(&firstInLargest);
217 
218       // Get partition number....
219       prompt1 << "Partition number (" << firstFreePart + 1 << "-" << numParts
220               << ", default " << firstFreePart + 1 << "): ";
221       do {
222          partNum = GetNumber(firstFreePart + 1, numParts,
223                              firstFreePart + 1, prompt1.str()) - 1;
224          if (partitions[partNum].GetFirstLBA() != 0)
225             cout << "partition " << partNum + 1 << " is in use.\n";
226       } while (partitions[partNum].GetFirstLBA() != 0);
227 
228       // Get first block for new partition...
229       prompt2 << "First sector (" << firstBlock << "-" << lastBlock << ", default = "
230               << firstInLargest << ") or {+-}size{KMGTP}: ";
231       do {
232          sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, blockSize, prompt2.str());
233       } while (IsFree(sector) == 0);
234       origSector = sector;
235       if (Align(&sector)) {
236          cout << "Information: Moved requested sector from " << origSector << " to "
237               << sector << " in\norder to align on " << sectorAlignment
238               << "-sector boundaries.\n";
239          if (!beQuiet)
240             cout << "Use 'l' on the experts' menu to adjust alignment\n";
241       } // if
242       //      Align(&sector); // Align sector to correct multiple
243       firstBlock = sector;
244 
245       // Get last block for new partitions...
246       lastBlock = FindLastInFree(firstBlock);
247       prompt3 << "Last sector (" << firstBlock << "-" << lastBlock << ", default = "
248             << lastBlock << ") or {+-}size{KMGTP}: ";
249       do {
250          sector = GetSectorNum(firstBlock, lastBlock, lastBlock, blockSize, prompt3.str());
251       } while (IsFree(sector) == 0);
252       lastBlock = sector;
253 
254       GPTData::CreatePartition(partNum, firstBlock, lastBlock);
255       partitions[partNum].ChangeType();
256       partitions[partNum].SetDefaultDescription();
257    } else {
258       if (firstFreePart >= numParts)
259          cout << "No table partition entries left\n";
260       else
261          cout << "No free sectors available\n";
262    } // if/else
263 } // GPTDataTextUI::CreatePartition()
264 
265 // Interactively delete a partition (duh!)
DeletePartition(void)266 void GPTDataTextUI::DeletePartition(void) {
267    int partNum;
268    uint32_t low, high;
269    ostringstream prompt;
270 
271    if (GetPartRange(&low, &high) > 0) {
272       prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
273       partNum = GetNumber(low + 1, high + 1, low, prompt.str());
274       GPTData::DeletePartition(partNum - 1);
275    } else {
276       cout << "No partitions\n";
277    } // if/else
278 } // GPTDataTextUI::DeletePartition()
279 
280 // Prompt user for a partition number, then change its type code
ChangePartType(void)281 void GPTDataTextUI::ChangePartType(void) {
282    int partNum;
283    uint32_t low, high;
284 
285    if (GetPartRange(&low, &high) > 0) {
286       partNum = GetPartNum();
287       partitions[partNum].ChangeType();
288    } else {
289       cout << "No partitions\n";
290    } // if/else
291 } // GPTDataTextUI::ChangePartType()
292 
293 // Prompt user for a partition number, then change its unique
294 // GUID.
ChangeUniqueGuid(void)295 void GPTDataTextUI::ChangeUniqueGuid(void) {
296    int partNum;
297    uint32_t low, high;
298    string guidStr;
299 
300    if (GetPartRange(&low, &high) > 0) {
301       partNum = GetPartNum();
302       cout << "Enter the partition's new unique GUID ('R' to randomize): ";
303       guidStr = ReadString();
304       if ((guidStr.length() >= 32) || (guidStr[0] == 'R') || (guidStr[0] == 'r')) {
305          SetPartitionGUID(partNum, (GUIDData) guidStr);
306          cout << "New GUID is " << partitions[partNum].GetUniqueGUID() << "\n";
307       } else {
308          cout << "GUID is too short!\n";
309       } // if/else
310    } else
311       cout << "No partitions\n";
312 } // GPTDataTextUI::ChangeUniqueGuid()
313 
314 // Partition attributes seem to be rarely used, but I want a way to
315 // adjust them for completeness....
SetAttributes(uint32_t partNum)316 void GPTDataTextUI::SetAttributes(uint32_t partNum) {
317    partitions[partNum].SetAttributes();
318 } // GPTDataTextUI::SetAttributes()
319 
320 // Prompts the user for a partition name and sets the partition's
321 // name. Returns 1 on success, 0 on failure (invalid partition
322 // number). (Note that the function skips prompting when an
323 // invalid partition number is detected.)
SetName(uint32_t partNum)324 int GPTDataTextUI::SetName(uint32_t partNum) {
325    UnicodeString theName = "";
326    int retval = 1;
327 
328    if (IsUsedPartNum(partNum)) {
329       cout << "Enter name: ";
330 #ifdef USE_UTF16
331       theName = ReadUString();
332 #else
333       theName = ReadString();
334 #endif
335       partitions[partNum].SetName(theName);
336    } else {
337       cerr << "Invalid partition number (" << partNum << ")\n";
338       retval = 0;
339    } // if/else
340 
341    return retval;
342 } // GPTDataTextUI::SetName()
343 
344 // Enable the user to byte-swap the name of the partition. Used to correct
345 // partition names damaged by incorrect byte order, as could be created by
346 // GPT fdisk 1.0.7 and earlier on big-endian systems, and perhaps other tools.
ReverseName(uint32_t partNum)347 void GPTDataTextUI::ReverseName(uint32_t partNum) {
348    int swapBytes;
349 
350    cout << "Current name is: " << partitions[partNum].GetDescription() << "\n";
351    partitions[partNum].ReverseNameBytes();
352    cout << "Byte-swapped name is: " << partitions[partNum].GetDescription() << "\n";
353    cout << "Do you want to byte-swap the name? ";
354    swapBytes = (GetYN() == 'Y');
355    // Already swapped for display, so undo if necessary....
356    if (!swapBytes)
357       partitions[partNum].ReverseNameBytes();
358 } // GPTDataTextUI::ReverseName()
359 
360 // Ask user for two partition numbers and swap them in the table. Note that
361 // this just reorders table entries; it doesn't adjust partition layout on
362 // the disk.
363 // Returns 1 if successful, 0 if not. (If user enters identical numbers, it
364 // counts as successful.)
SwapPartitions(void)365 int GPTDataTextUI::SwapPartitions(void) {
366    int partNum1, partNum2, didIt = 0;
367    uint32_t low, high;
368    ostringstream prompt;
369    GPTPart temp;
370 
371    if (GetPartRange(&low, &high) > 0) {
372       partNum1 = GetPartNum();
373       if (high >= numParts - 1)
374          high = 0;
375       prompt << "New partition number (1-" << numParts
376              << ", default " << high + 2 << "): ";
377       partNum2 = GetNumber(1, numParts, high + 2, prompt.str()) - 1;
378       didIt = GPTData::SwapPartitions(partNum1, partNum2);
379    } else {
380       cout << "No partitions\n";
381    } // if/else
382    return didIt;
383 } // GPTDataTextUI::SwapPartitionNumbers()
384 
385 // This function destroys the on-disk GPT structures. Returns 1 if the user
386 // confirms destruction, 0 if the user aborts or if there's a disk error.
DestroyGPTwPrompt(void)387 int GPTDataTextUI::DestroyGPTwPrompt(void) {
388    int allOK = 1;
389 
390    if ((apmFound) || (bsdFound)) {
391       cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
392            << "damage any APM or BSD partitions on this disk!\n";
393    } // if APM or BSD
394    cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
395    if (GetYN() == 'Y') {
396       if (DestroyGPT()) {
397          // Note on below: Touch the MBR only if the user wants it completely
398          // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
399          // the MBR, but this could wipe out a valid MBR that the program
400          // had subsequently discarded (say, if it conflicted with older GPT
401          // structures).
402          cout << "Blank out MBR? ";
403          if (GetYN() == 'Y') {
404             DestroyMBR();
405          } else {
406             cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
407                  << "with fdisk or another tool.\n";
408          } // if/else
409       } else allOK = 0; // if GPT structures destroyed
410    } else allOK = 0; // if user confirms destruction
411    return (allOK);
412 } // GPTDataTextUI::DestroyGPTwPrompt()
413 
414 // Get partition number from user and then call ShowPartDetails(partNum)
415 // to show its detailed information
ShowDetails(void)416 void GPTDataTextUI::ShowDetails(void) {
417    int partNum;
418    uint32_t low, high;
419 
420    if (GetPartRange(&low, &high) > 0) {
421       partNum = GetPartNum();
422       ShowPartDetails(partNum);
423    } else {
424       cout << "No partitions\n";
425    } // if/else
426 } // GPTDataTextUI::ShowDetails()
427 
428 // Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
429 // OSes that don't understand GPT.
MakeHybrid(void)430 void GPTDataTextUI::MakeHybrid(void) {
431    uint32_t partNums[3] = {0, 0, 0};
432    string line;
433    int numPartsToCvt = 0, numConverted = 0, i, j, mbrNum = 0;
434    unsigned int hexCode = 0;
435    MBRPart hybridPart;
436    MBRData hybridMBR;
437    char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
438 
439    cout << "\nWARNING! Hybrid MBRs are flaky and dangerous! If you decide not to use one,\n"
440         << "just hit the Enter key at the below prompt and your MBR partition table will\n"
441         << "be untouched.\n\n\a";
442 
443    // Use a local MBR structure, copying from protectiveMBR to keep its
444    // boot loader code intact....
445    hybridMBR = protectiveMBR;
446    hybridMBR.EmptyMBR(0);
447 
448    // Now get the numbers of up to three partitions to add to the
449    // hybrid MBR....
450    cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
451         << "added to the hybrid MBR, in sequence: ";
452    line = ReadString();
453    istringstream inLine(line);
454    do {
455       inLine >> partNums[numPartsToCvt];
456       if (partNums[numPartsToCvt] > 0)
457          numPartsToCvt++;
458    } while (!inLine.eof() && (numPartsToCvt < 3));
459 
460    if (numPartsToCvt > 0) {
461       cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
462       eeFirst = GetYN();
463    } // if
464 
465    for (i = 0; i < numPartsToCvt; i++) {
466       j = partNums[i] - 1;
467       if (partitions[j].IsUsed() && (partitions[j].IsSizedForMBR() != MBR_SIZED_BAD)) {
468          mbrNum = i + (eeFirst == 'Y');
469          cout << "\nCreating entry for GPT partition #" << j + 1
470               << " (MBR partition #" << mbrNum + 1 << ")\n";
471          hybridPart.SetType(GetMBRTypeCode(partitions[j].GetHexType() / 256));
472          hybridPart.SetLocation(partitions[j].GetFirstLBA(), partitions[j].GetLengthLBA());
473          hybridPart.SetInclusion(PRIMARY);
474          cout << "Set the bootable flag? ";
475          if (GetYN() == 'Y')
476             hybridPart.SetStatus(0x80);
477          else
478             hybridPart.SetStatus(0x00);
479          hybridPart.SetInclusion(PRIMARY);
480          if (partitions[j].IsSizedForMBR() == MBR_SIZED_IFFY)
481             WarnAboutIffyMBRPart(j + 1);
482          numConverted++;
483       } else {
484          cerr << "\nGPT partition #" << j + 1 << " does not exist or is too big; skipping.\n";
485       } // if/else
486       hybridMBR.AddPart(mbrNum, hybridPart);
487    } // for
488 
489    if (numConverted > 0) { // User opted to create a hybrid MBR....
490       // Create EFI protective partition that covers the start of the disk.
491       // If this location (covering the main GPT data structures) is omitted,
492       // Linux won't find any partitions on the disk.
493       hybridPart.SetLocation(1, hybridMBR.FindLastInFree(1));
494       hybridPart.SetStatus(0);
495       hybridPart.SetType(0xEE);
496       hybridPart.SetInclusion(PRIMARY);
497       // newNote firstLBA and lastLBA are computed later...
498       if (eeFirst == 'Y') {
499          hybridMBR.AddPart(0, hybridPart);
500       } else {
501          hybridMBR.AddPart(numConverted, hybridPart);
502       } // else
503       hybridMBR.SetHybrid();
504 
505       // ... and for good measure, if there are any partition spaces left,
506       // optionally create another protective EFI partition to cover as much
507       // space as possible....
508       if (hybridMBR.CountParts() < 4) { // unused entry....
509          cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
510          if (GetYN() == 'Y') {
511             cout << "Note: Default is 0xEE, but this may confuse Mac OS X.\n";
512             // Comment on above: Mac OS treats disks with more than one
513             // 0xEE MBR partition as MBR disks, not as GPT disks.
514             hexCode = GetMBRTypeCode(0xEE);
515             hybridMBR.MakeBiggestPart(3, hexCode);
516          } // if (GetYN() == 'Y')
517       } // if unused entry
518       protectiveMBR = hybridMBR;
519    } else {
520       cout << "\nNo partitions converted; original protective/hybrid MBR is unmodified!\n";
521    } // if/else (numConverted > 0)
522 } // GPTDataTextUI::MakeHybrid()
523 
524 // Convert the GPT to MBR form, storing partitions in the protectiveMBR
525 // variable. This function is necessarily limited; it may not be able to
526 // convert all partitions, depending on the disk size and available space
527 // before each partition (one free sector is required to create a logical
528 // partition, which are necessary to convert more than four partitions).
529 // Returns the number of converted partitions; if this value
530 // is over 0, the calling function should call DestroyGPT() to destroy
531 // the GPT data, call SaveMBR() to save the MBR, and then exit.
XFormToMBR(void)532 int GPTDataTextUI::XFormToMBR(void) {
533    uint32_t i;
534 
535    protectiveMBR.EmptyMBR(0);
536    for (i = 0; i < numParts; i++) {
537       if (partitions[i].IsUsed()) {
538          if (partitions[i].IsSizedForMBR() == MBR_SIZED_IFFY)
539             WarnAboutIffyMBRPart(i + 1);
540          // Note: MakePart() checks for oversized partitions, so don't
541          // bother checking other IsSizedForMBR() return values....
542          protectiveMBR.MakePart(i, partitions[i].GetFirstLBA(),
543                                 partitions[i].GetLengthLBA(),
544                                 partitions[i].GetHexType() / 0x0100, 0);
545       } // if
546    } // for
547    protectiveMBR.MakeItLegal();
548    return protectiveMBR.DoMenu();
549 } // GPTDataTextUI::XFormToMBR()
550 
551 /******************************************************
552  *                                                    *
553  * Display informational messages for the user....    *
554  *                                                    *
555  ******************************************************/
556 
557 // Although an MBR partition that begins below sector 2^32 and is less than 2^32 sectors in
558 // length is technically legal even if it ends above the 2^32-sector mark, such a partition
559 // tends to confuse a lot of OSes, so warn the user about such partitions. This function is
560 // called by XFormToMBR() and MakeHybrid(); it's a separate function just to consolidate the
561 // lengthy message in one place.
WarnAboutIffyMBRPart(int partNum)562 void GPTDataTextUI::WarnAboutIffyMBRPart(int partNum) {
563    cout << "\a\nWarning! GPT partition " << partNum << " ends after the 2^32 sector mark! The partition\n"
564         << "begins before this point, and is smaller than 2^32 sectors. This is technically\n"
565         << "legal, but will confuse some OSes. The partition IS being added to the MBR, but\n"
566         << "if your OS misbehaves or can't see the partition, the partition may simply be\n"
567         << "unusable in that OS and may need to be resized or omitted from the MBR.\n\n";
568 } // GPTDataTextUI::WarnAboutIffyMBRPart()
569 
570 /*********************************************************************
571  *                                                                   *
572  * The following functions provide the main menus for the gdisk      *
573  * program....                                                       *
574  *                                                                   *
575  *********************************************************************/
576 
577 // Accept a command and execute it. Returns only when the user
578 // wants to exit (such as after a 'w' or 'q' command).
MainMenu(string filename)579 void GPTDataTextUI::MainMenu(string filename) {
580    int goOn = 1;
581    PartType typeHelper;
582    uint32_t temp1, temp2;
583 
584    do {
585       cout << "\nCommand (? for help): ";
586       switch (ReadString()[0]) {
587          case '\0':
588             goOn = cin.good();
589             break;
590          case 'b': case 'B':
591             cout << "Enter backup filename to save: ";
592             SaveGPTBackup(ReadString());
593             break;
594          case 'c': case 'C':
595             if (GetPartRange(&temp1, &temp2) > 0)
596                SetName(GetPartNum());
597             else
598                cout << "No partitions\n";
599             break;
600          case 'd': case 'D':
601             DeletePartition();
602             break;
603          case 'i': case 'I':
604             ShowDetails();
605             break;
606          case 'l': case 'L':
607             typeHelper.ShowAllTypes();
608             break;
609          case 'n': case 'N':
610             CreatePartition();
611             break;
612          case 'o': case 'O':
613             cout << "This option deletes all partitions and creates a new protective MBR.\n"
614                  << "Proceed? ";
615             if (GetYN() == 'Y') {
616                ClearGPTData();
617                MakeProtectiveMBR();
618             } // if
619             break;
620          case 'p': case 'P':
621             DisplayGPTData();
622             break;
623          case 'q': case 'Q':
624             goOn = 0;
625             break;
626          case 'r': case 'R':
627             RecoveryMenu(filename);
628             goOn = 0;
629             break;
630          case 's': case 'S':
631             SortGPT();
632             cout << "You may need to edit /etc/fstab and/or your boot loader configuration!\n";
633             break;
634          case 't': case 'T':
635             ChangePartType();
636             break;
637          case 'v': case 'V':
638             Verify();
639             break;
640          case 'w': case 'W':
641             if (SaveGPTData() == 1)
642                goOn = 0;
643             break;
644          case 'x': case 'X':
645             ExpertsMenu(filename);
646             goOn = 0;
647             break;
648          default:
649             ShowCommands();
650             break;
651       } // switch
652    } while (goOn);
653 } // GPTDataTextUI::MainMenu()
654 
ShowCommands(void)655 void GPTDataTextUI::ShowCommands(void) {
656    cout << "b\tback up GPT data to a file\n";
657    cout << "c\tchange a partition's name\n";
658    cout << "d\tdelete a partition\n";
659    cout << "i\tshow detailed information on a partition\n";
660    cout << "l\tlist known partition types\n";
661    cout << "n\tadd a new partition\n";
662    cout << "o\tcreate a new empty GUID partition table (GPT)\n";
663    cout << "p\tprint the partition table\n";
664    cout << "q\tquit without saving changes\n";
665    cout << "r\trecovery and transformation options (experts only)\n";
666    cout << "s\tsort partitions\n";
667    cout << "t\tchange a partition's type code\n";
668    cout << "v\tverify disk\n";
669    cout << "w\twrite table to disk and exit\n";
670    cout << "x\textra functionality (experts only)\n";
671    cout << "?\tprint this menu\n";
672 } // GPTDataTextUI::ShowCommands()
673 
674 // Accept a recovery & transformation menu command. Returns only when the user
675 // issues an exit command, such as 'w' or 'q'.
RecoveryMenu(string filename)676 void GPTDataTextUI::RecoveryMenu(string filename) {
677    uint32_t numParts;
678    int goOn = 1, temp1;
679 
680    do {
681       cout << "\nRecovery/transformation command (? for help): ";
682       switch (ReadString()[0]) {
683          case '\0':
684             goOn = cin.good();
685             break;
686          case 'b': case 'B':
687             RebuildMainHeader();
688             break;
689          case 'c': case 'C':
690             cout << "Warning! This will probably do weird things if you've converted an MBR to\n"
691             << "GPT form and haven't yet saved the GPT! Proceed? ";
692             if (GetYN() == 'Y')
693                LoadSecondTableAsMain();
694             break;
695          case 'd': case 'D':
696             RebuildSecondHeader();
697             break;
698          case 'e': case 'E':
699             cout << "Warning! This will probably do weird things if you've converted an MBR to\n"
700             << "GPT form and haven't yet saved the GPT! Proceed? ";
701             if (GetYN() == 'Y')
702                LoadMainTable();
703             break;
704          case 'f': case 'F':
705             cout << "Warning! This will destroy the currently defined partitions! Proceed? ";
706             if (GetYN() == 'Y') {
707                if (LoadMBR(filename) == 1) { // successful load
708                   XFormPartitions();
709                } else {
710                   cout << "Problem loading MBR! GPT is untouched; regenerating protective MBR!\n";
711                   MakeProtectiveMBR();
712                } // if/else
713             } // if
714             break;
715          case 'g': case 'G':
716             numParts = GetNumParts();
717             temp1 = XFormToMBR();
718             if (temp1 > 0)
719                cout << "\nConverted " << temp1 << " partitions. Finalize and exit? ";
720             if ((temp1 > 0) && (GetYN() == 'Y')) {
721                if ((DestroyGPT() > 0) && (SaveMBR())) {
722                   goOn = 0;
723                } // if
724             } else {
725                MakeProtectiveMBR();
726                SetGPTSize(numParts, 0);
727                cout << "Note: New protective MBR created\n\n";
728             } // if/else
729             break;
730          case 'h': case 'H':
731             MakeHybrid();
732             break;
733          case 'i': case 'I':
734             ShowDetails();
735             break;
736          case 'l': case 'L':
737             cout << "Enter backup filename to load: ";
738             LoadGPTBackup(ReadString());
739             break;
740          case 'm': case 'M':
741             MainMenu(filename);
742             goOn = 0;
743             break;
744          case 'o': case 'O':
745             DisplayMBRData();
746             break;
747          case 'p': case 'P':
748             DisplayGPTData();
749             break;
750          case 'q': case 'Q':
751             goOn = 0;
752             break;
753          case 't': case 'T':
754             XFormDisklabel();
755             break;
756          case 'v': case 'V':
757             Verify();
758             break;
759          case 'w': case 'W':
760             if (SaveGPTData() == 1) {
761                goOn = 0;
762             } // if
763             break;
764          case 'x': case 'X':
765             ExpertsMenu(filename);
766             goOn = 0;
767             break;
768          default:
769             ShowRecoveryCommands();
770             break;
771       } // switch
772    } while (goOn);
773 } // GPTDataTextUI::RecoveryMenu()
774 
ShowRecoveryCommands(void)775 void GPTDataTextUI::ShowRecoveryCommands(void) {
776    cout << "b\tuse backup GPT header (rebuilding main)\n";
777    cout << "c\tload backup partition table from disk (rebuilding main)\n";
778    cout << "d\tuse main GPT header (rebuilding backup)\n";
779    cout << "e\tload main partition table from disk (rebuilding backup)\n";
780    cout << "f\tload MBR and build fresh GPT from it\n";
781    cout << "g\tconvert GPT into MBR and exit\n";
782    cout << "h\tmake hybrid MBR\n";
783    cout << "i\tshow detailed information on a partition\n";
784    cout << "l\tload partition data from a backup file\n";
785    cout << "m\treturn to main menu\n";
786    cout << "o\tprint protective MBR data\n";
787    cout << "p\tprint the partition table\n";
788    cout << "q\tquit without saving changes\n";
789    cout << "t\ttransform BSD disklabel partition\n";
790    cout << "v\tverify disk\n";
791    cout << "w\twrite table to disk and exit\n";
792    cout << "x\textra functionality (experts only)\n";
793    cout << "?\tprint this menu\n";
794 } // GPTDataTextUI::ShowRecoveryCommands()
795 
796 // Accept an experts' menu command. Returns only after the user
797 // selects an exit command, such as 'w' or 'q'.
ExpertsMenu(string filename)798 void GPTDataTextUI::ExpertsMenu(string filename) {
799    GPTData secondDevice;
800    uint32_t temp1, temp2;
801    int goOn = 1;
802    string guidStr, device;
803    GUIDData aGUID;
804    ostringstream prompt;
805 
806    do {
807       cout << "\nExpert command (? for help): ";
808       switch (ReadString()[0]) {
809          case '\0':
810             goOn = cin.good();
811             break;
812          case 'a': case 'A':
813             if (GetPartRange(&temp1, &temp2) > 0)
814                SetAttributes(GetPartNum());
815             else
816                cout << "No partitions\n";
817             break;
818          case 'b': case 'B':
819             ReverseName(GetPartNum());
820             break;
821          case 'c': case 'C':
822             ChangeUniqueGuid();
823             break;
824          case 'd': case 'D':
825             cout << "Partitions will begin on " << GetAlignment()
826             << "-sector boundaries.\n";
827             break;
828          case 'e': case 'E':
829             cout << "Relocating backup data structures to the end of the disk\n";
830             MoveSecondHeaderToEnd();
831             break;
832          case 'f': case 'F':
833             RandomizeGUIDs();
834             break;
835          case 'g': case 'G':
836             cout << "Enter the disk's unique GUID ('R' to randomize): ";
837             guidStr = ReadString();
838             if ((guidStr.length() >= 32) || (guidStr[0] == 'R') || (guidStr[0] == 'r')) {
839                SetDiskGUID((GUIDData) guidStr);
840                cout << "The new disk GUID is " << GetDiskGUID() << "\n";
841             } else {
842                cout << "GUID is too short!\n";
843             } // if/else
844             break;
845          case 'h': case 'H':
846             RecomputeCHS();
847             break;
848          case 'i': case 'I':
849             ShowDetails();
850             break;
851          case 'j': case 'J':
852              MoveMainTable();
853              break;
854          case 'l': case 'L':
855             prompt.seekp(0);
856             prompt << "Enter the sector alignment value (1-" << MAX_ALIGNMENT << ", default = "
857                    << DEFAULT_ALIGNMENT << "): ";
858             temp1 = GetNumber(1, MAX_ALIGNMENT, DEFAULT_ALIGNMENT, prompt.str());
859             SetAlignment(temp1);
860             break;
861          case 'm': case 'M':
862             MainMenu(filename);
863             goOn = 0;
864             break;
865          case 'n': case 'N':
866             MakeProtectiveMBR();
867             break;
868          case 'o': case 'O':
869             DisplayMBRData();
870             break;
871          case 'p': case 'P':
872             DisplayGPTData();
873             break;
874          case 'q': case 'Q':
875             goOn = 0;
876             break;
877          case 'r': case 'R':
878             RecoveryMenu(filename);
879             goOn = 0;
880             break;
881          case 's': case 'S':
882             ResizePartitionTable();
883             break;
884          case 't': case 'T':
885             SwapPartitions();
886             break;
887          case 'u': case 'U':
888             cout << "Type device filename, or press <Enter> to exit: ";
889             device = ReadString();
890             if (device.length() > 0) {
891                secondDevice = *this;
892                secondDevice.SetDisk(device);
893                secondDevice.SaveGPTData(0);
894             } // if
895             break;
896          case 'v': case 'V':
897             Verify();
898             break;
899          case 'w': case 'W':
900             if (SaveGPTData() == 1) {
901                goOn = 0;
902             } // if
903             break;
904          case 'z': case 'Z':
905             if (DestroyGPTwPrompt() == 1) {
906                goOn = 0;
907             }
908             break;
909          default:
910             ShowExpertCommands();
911             break;
912       } // switch
913    } while (goOn);
914 } // GPTDataTextUI::ExpertsMenu()
915 
ShowExpertCommands(void)916 void GPTDataTextUI::ShowExpertCommands(void) {
917    cout << "a\tset attributes\n";
918    cout << "b\tbyte-swap a partition's name\n";
919    cout << "c\tchange partition GUID\n";
920    cout << "d\tdisplay the sector alignment value\n";
921    cout << "e\trelocate backup data structures to the end of the disk\n";
922    cout << "f\trandomize disk and partition unique GUIDs\n";
923    cout << "g\tchange disk GUID\n";
924    cout << "h\trecompute CHS values in protective/hybrid MBR\n";
925    cout << "i\tshow detailed information on a partition\n";
926    cout << "j\tmove the main partition table\n";
927    cout << "l\tset the sector alignment value\n";
928    cout << "m\treturn to main menu\n";
929    cout << "n\tcreate a new protective MBR\n";
930    cout << "o\tprint protective MBR data\n";
931    cout << "p\tprint the partition table\n";
932    cout << "q\tquit without saving changes\n";
933    cout << "r\trecovery and transformation options (experts only)\n";
934    cout << "s\tresize partition table\n";
935    cout << "t\ttranspose two partition table entries\n";
936    cout << "u\treplicate partition table on new device\n";
937    cout << "v\tverify disk\n";
938    cout << "w\twrite table to disk and exit\n";
939    cout << "z\tzap (destroy) GPT data structures and exit\n";
940    cout << "?\tprint this menu\n";
941 } // GPTDataTextUI::ShowExpertCommands()
942 
943 
944 
945 /********************************
946  *                              *
947  * Non-class support functions. *
948  *                              *
949  ********************************/
950 
951 // GetMBRTypeCode() doesn't really belong in the class, since it's MBR-
952 // specific, but it's also user I/O-related, so I want to keep it in
953 // this file....
954 
955 // Get an MBR type code from the user and return it
GetMBRTypeCode(int defType)956 int GetMBRTypeCode(int defType) {
957    string line;
958    int typeCode;
959 
960    cout.setf(ios::uppercase);
961    cout.fill('0');
962    do {
963       cout << "Enter an MBR hex code (default " << hex;
964       cout.width(2);
965       cout << defType << "): " << dec;
966       line = ReadString();
967       if (line[0] == '\0')
968          typeCode = defType;
969       else
970          typeCode = StrToHex(line, 0);
971    } while ((typeCode <= 0) || (typeCode > 255));
972    cout.fill(' ');
973    return typeCode;
974 } // GetMBRTypeCode
975 
976 #ifdef USE_UTF16
977 // Note: ReadUString() is here rather than in support.cc so that the ICU
978 // libraries need not be linked to fixparts.
979 
980 // Reads a Unicode string from stdin, returning it as an ICU-style string.
981 // Note that the returned string will NOT include the carriage return
982 // entered by the user. Relies on the ICU constructor from a string
983 // encoded in the current codepage to work.
ReadUString(void)984 UnicodeString ReadUString(void) {
985    return ReadString().c_str();
986 } // ReadUString()
987 #endif
988 
989