blob: 3efbdf24078caa3d41b612518d48238372d58c92 [file] [log] [blame]
srs5694fad06422010-02-19 17:19:17 -05001/*
2 Copyright (C) <2010> <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 <iostream>
26#include <sstream>
srs56941c6f8b02010-02-21 11:09:20 -050027#include <cstdio>
srs5694fad06422010-02-19 17:19:17 -050028#include "attributes.h"
29#include "gpttext.h"
30
31using namespace std;
32
33/*******************************************
34* *
35* GPTDataText class and related structures *
36* *
37********************************************/
38
39GPTDataTextUI::GPTDataTextUI(void) : GPTData() {
40} // default constructor
41
42GPTDataTextUI::GPTDataTextUI(string filename) : GPTData(filename) {
43} // constructor passing filename
44
45GPTDataTextUI::~GPTDataTextUI(void) {
46} // default destructor
47
48/*********************************************************************
49 * *
50 * The following functions are extended (interactive) versions of *
51 * simpler functions in the base class.... *
52 * *
53 *********************************************************************/
54
55// Overridden function; calls base-class function and then makes
56// additional queries of the user, if the base-class function can't
57// decide what to do.
58WhichToUse GPTDataTextUI::UseWhichPartitions(void) {
59 WhichToUse which;
60 MBRValidity mbrState;
61 int answer;
62
63 which = GPTData::UseWhichPartitions();
64 if ((which != use_abort) || beQuiet)
65 return which;
66
67 // If we get past here, it means that the non-interactive tests were
68 // inconclusive, so we must ask the user which table to use....
69 mbrState = protectiveMBR.GetValidity();
70
71 if ((state == gpt_valid) && (mbrState == mbr)) {
72 cout << "Found valid MBR and GPT. Which do you want to use?\n";
73 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
74 if (answer == 1) {
75 which = use_mbr;
76 } else if (answer == 2) {
77 which = use_gpt;
78 cout << "Using GPT and creating fresh protective MBR.\n";
79 } else which = use_new;
80 } // if
81
82 // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
83 // problems)
84 if (state == gpt_corrupt) {
85 if ((mbrState == mbr) || (mbrState == hybrid)) {
86 cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
87 << "GPT MAY permit recovery of GPT data.)\n";
88 answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
89 if (answer == 1) {
90 which = use_mbr;
91 } else if (answer == 2) {
92 which = use_gpt;
93 } else which = use_new;
94 } else if (mbrState == invalid) {
95 cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
96 << "GPT MAY permit recovery of GPT data.)\n";
97 answer = GetNumber(1, 2, 1, " 1 - GPT\n 2 - Create blank GPT\n\nYour answer: ");
98 if (answer == 1) {
99 which = use_gpt;
100 } else which = use_new;
101 } // if/else/else
102 } // if (corrupt GPT)
103
104 return which;
105} // UseWhichPartitions()
106
107// Ask the user for a partition number; and prompt for verification
108// if the requested partition isn't of a known BSD type.
109// Lets the base-class function do the work, and returns its value (the
110// number of converted partitions).
111int GPTDataTextUI::XFormDisklabel(void) {
112 uint32_t partNum;
113 uint16_t hexCode;
114 int goOn = 1, numDone = 0;
115 BSDData disklabel;
116
117 partNum = GetPartNum();
118
119 // Now see if the specified partition has a BSD type code....
120 hexCode = partitions[partNum].GetHexType();
121 if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
122 cout << "Specified partition doesn't have a disklabel partition type "
123 << "code.\nContinue anyway? ";
124 goOn = (GetYN() == 'Y');
125 } // if
126
127 if (goOn)
128 numDone = GPTData::XFormDisklabel(partNum);
129
130 return numDone;
131} // GPTData::XFormDisklabel(int i)
132
133/*********************************************************************
134 * *
135 * Begin functions that obtain information from the users, and often *
136 * do something with that information (call other functions) *
137 * *
138 *********************************************************************/
139
140// Prompts user for partition number and returns the result.
141uint32_t GPTDataTextUI::GetPartNum(void) {
142 uint32_t partNum;
143 uint32_t low, high;
144 ostringstream prompt;
145
146 if (GetPartRange(&low, &high) > 0) {
147 prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
148 partNum = GetNumber(low + 1, high + 1, low, prompt.str());
149 } else partNum = 1;
150 return (partNum - 1);
151} // GPTDataTextUI::GetPartNum()
152
153// What it says: Resize the partition table. (Default is 128 entries.)
154void GPTDataTextUI::ResizePartitionTable(void) {
155 int newSize;
156 ostringstream prompt;
157 uint32_t curLow, curHigh;
158
159 cout << "Current partition table size is " << mainHeader.numParts << ".\n";
160 GetPartRange(&curLow, &curHigh);
161 curHigh++; // since GetPartRange() returns numbers starting from 0...
162 // There's no point in having fewer than four partitions....
163 if (curHigh < (blockSize / GPT_SIZE))
164 curHigh = blockSize / GPT_SIZE;
165 prompt << "Enter new size (" << curHigh << " up, default " << NUM_GPT_ENTRIES << "): ";
166 newSize = GetNumber(4, 65535, 128, prompt.str());
167 if (newSize < 128) {
168 cout << "Caution: The partition table size should officially be 16KB or larger,\n"
169 << "which works out to 128 entries. In practice, smaller tables seem to\n"
170 << "work with most OSes, but this practice is risky. I'm proceeding with\n"
171 << "the resize, but you may want to reconsider this action and undo it.\n\n";
172 } // if
173 SetGPTSize(newSize);
174} // GPTDataTextUI::ResizePartitionTable()
175
176// Interactively create a partition
177void GPTDataTextUI::CreatePartition(void) {
178 uint64_t firstBlock, firstInLargest, lastBlock, sector;
179 uint32_t firstFreePart = 0;
180 ostringstream prompt1, prompt2, prompt3;
181 int partNum;
182
183 // Find first free partition...
184 while (partitions[firstFreePart].GetFirstLBA() != 0) {
185 firstFreePart++;
186 } // while
187
188 if (((firstBlock = FindFirstAvailable()) != 0) &&
189 (firstFreePart < mainHeader.numParts)) {
190 lastBlock = FindLastAvailable();
191 firstInLargest = FindFirstInLargest();
192
193 // Get partition number....
194 do {
195 prompt1 << "Partition number (" << firstFreePart + 1 << "-" << mainHeader.numParts
196 << ", default " << firstFreePart + 1 << "): ";
197 partNum = GetNumber(firstFreePart + 1, mainHeader.numParts,
198 firstFreePart + 1, prompt1.str()) - 1;
199 if (partitions[partNum].GetFirstLBA() != 0)
200 cout << "partition " << partNum + 1 << " is in use.\n";
201 } while (partitions[partNum].GetFirstLBA() != 0);
202
203 // Get first block for new partition...
204 prompt2 << "First sector (" << firstBlock << "-" << lastBlock << ", default = "
205 << firstInLargest << ") or {+-}size{KMGT}: ";
206 do {
207 sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, prompt2.str());
208 } while (IsFree(sector) == 0);
209 Align(&sector); // Align sector to correct multiple
210 firstBlock = sector;
211
212 // Get last block for new partitions...
213 lastBlock = FindLastInFree(firstBlock);
214 prompt3 << "Last sector (" << firstBlock << "-" << lastBlock << ", default = "
215 << lastBlock << ") or {+-}size{KMGT}: ";
216 do {
217 sector = GetSectorNum(firstBlock, lastBlock, lastBlock, prompt3.str());
218 } while (IsFree(sector) == 0);
219 lastBlock = sector;
220
221 firstFreePart = GPTData::CreatePartition(partNum, firstBlock, lastBlock);
222 partitions[partNum].ChangeType();
223 partitions[partNum].SetDefaultDescription();
224 } else {
225 cout << "No free sectors available\n";
226 } // if/else
227} // GPTDataTextUI::CreatePartition()
228
229// Interactively delete a partition (duh!)
230void GPTDataTextUI::DeletePartition(void) {
231 int partNum;
232 uint32_t low, high;
233 ostringstream prompt;
234
235 if (GetPartRange(&low, &high) > 0) {
236 prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
237 partNum = GetNumber(low + 1, high + 1, low, prompt.str());
238 GPTData::DeletePartition(partNum - 1);
239 } else {
240 cout << "No partitions\n";
241 } // if/else
242} // GPTDataTextUI::DeletePartition()
243
244// Prompt user for a partition number, then change its type code
245// using ChangeGPTType(struct GPTPartition*) function.
246void GPTDataTextUI::ChangePartType(void) {
247 int partNum;
248 uint32_t low, high;
249
250 if (GetPartRange(&low, &high) > 0) {
251 partNum = GetPartNum();
252 partitions[partNum].ChangeType();
253 } else {
254 cout << "No partitions\n";
255 } // if/else
256} // GPTDataTextUI::ChangePartType()
257
258// Partition attributes seem to be rarely used, but I want a way to
259// adjust them for completeness....
260void GPTDataTextUI::SetAttributes(uint32_t partNum) {
261 Attributes theAttr;
262
263 theAttr.SetAttributes(partitions[partNum].GetAttributes());
264 theAttr.DisplayAttributes();
265 theAttr.ChangeAttributes();
266 partitions[partNum].SetAttributes(theAttr.GetAttributes());
267} // GPTDataTextUI::SetAttributes()
268
269// Ask user for two partition numbers and swap them in the table. Note that
270// this just reorders table entries; it doesn't adjust partition layout on
271// the disk.
272// Returns 1 if successful, 0 if not. (If user enters identical numbers, it
273// counts as successful.)
274int GPTDataTextUI::SwapPartitions(void) {
275 int partNum1, partNum2, didIt = 0;
276 uint32_t low, high;
277 ostringstream prompt;
278 GPTPart temp;
279
280 if (GetPartRange(&low, &high) > 0) {
281 partNum1 = GetPartNum();
282 if (high >= mainHeader.numParts - 1)
283 high = 0;
284 prompt << "New partition number (1-" << mainHeader.numParts
285 << ", default " << high + 2 << "): ";
286 partNum2 = GetNumber(1, mainHeader.numParts, high + 2, prompt.str()) - 1;
287 didIt = GPTData::SwapPartitions(partNum1, partNum2);
288 } else {
289 cout << "No partitions\n";
290 } // if/else
291 return didIt;
292} // GPTDataTextUI::SwapPartitionNumbers()
293
294// This function destroys the on-disk GPT structures. Returns 1 if the user
295// confirms destruction, 0 if the user aborts or if there's a disk error.
296int GPTDataTextUI::DestroyGPTwPrompt(void) {
297 int allOK = 1;
298
299 if ((apmFound) || (bsdFound)) {
300 cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
301 << "damage any APM or BSD partitions on this disk!\n";
302 } // if APM or BSD
303 cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
304 if (GetYN() == 'Y') {
305 if (DestroyGPT()) {
306 // Note on below: Touch the MBR only if the user wants it completely
307 // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
308 // the MBR, but this could wipe out a valid MBR that the program
309 // had subsequently discarded (say, if it conflicted with older GPT
310 // structures).
311 cout << "Blank out MBR? ";
312 if (GetYN() == 'Y') {
313 DestroyMBR();
314 } else {
315 cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
316 << "with fdisk or another tool.\n";
317 } // if/else
318 } else allOK = 0; // if GPT structures destroyed
319 } else allOK = 0; // if user confirms destruction
320 return (allOK);
321} // GPTDataTextUI::DestroyGPTwPrompt()
322
323// Get partition number from user and then call ShowPartDetails(partNum)
324// to show its detailed information
325void GPTDataTextUI::ShowDetails(void) {
326 int partNum;
327 uint32_t low, high;
328
329 if (GetPartRange(&low, &high) > 0) {
330 partNum = GetPartNum();
331 ShowPartDetails(partNum);
332 } else {
333 cout << "No partitions\n";
334 } // if/else
335} // GPTDataTextUI::ShowDetails()
336
337// Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
338// OSes that don't understand GPT.
339void GPTDataTextUI::MakeHybrid(void) {
340 uint32_t partNums[3];
341 char line[255];
342 char* junk;
343 int numParts, i, j, mbrNum, bootable = -1;
344 int gptParts[4], mbrTypes[4];
345 char fillItUp = 'M'; // fill extra partition entries? (Yes/No/Maybe)
346 char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
347
348 cout << "\nWARNING! Hybrid MBRs are flaky and potentially dangerous! If you decide not\n"
349 << "to use one, just hit the Enter key at the below prompt and your MBR\n"
350 << "partition table will be untouched.\n\n\a";
351
352 // Now get the numbers of up to three partitions to add to the
353 // hybrid MBR....
354 cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
355 << "added to the hybrid MBR, in sequence: ";
356 junk = fgets(line, 255, stdin);
357 numParts = sscanf(line, "%d %d %d", &partNums[0], &partNums[1], &partNums[2]);
358
359 if (numParts > 0) {
360 cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
361 eeFirst = GetYN();
362 } // if
363
364 for (i = 0; i < 4; i++)
365 gptParts[i] = MBR_EMPTY;
366
367 for (i = 0; i < numParts; i++) {
368 j = partNums[i] - 1;
369 mbrNum = i + (eeFirst == 'Y');
370 cout << "\nCreating entry for GPT partition #" << j + 1
371 << " (MBR partition #" << mbrNum + 1 << ")\n";
372 gptParts[mbrNum] = j;
373 mbrTypes[mbrNum] = GetMBRTypeCode(partitions[j].GetHexType() / 256);
374 cout << "Set the bootable flag? ";
375 if (GetYN() == 'Y')
376 bootable = mbrNum;
377 } // for
378
379 if (numParts > 0) { // User opted to create a hybrid MBR....
380 // Create EFI protective partition that covers the start of the disk.
381 // If this location (covering the main GPT data structures) is omitted,
382 // Linux won't find any partitions on the disk.
383 if (eeFirst == 'Y')
384 mbrNum = 0;
385 else
386 mbrNum = numParts;
387 gptParts[mbrNum] = MBR_EFI_GPT;
388 mbrTypes[mbrNum] = 0xEE;
389 protectiveMBR.SetHybrid();
390
391 // ... and for good measure, if there are any partition spaces left,
392 // optionally create another protective EFI partition to cover as much
393 // space as possible....
394 for (i = 0; i < 4; i++) {
395 if (gptParts[i] == MBR_EMPTY) { // unused entry....
396 if (fillItUp == 'M') {
397 cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
398 fillItUp = GetYN();
399 mbrTypes[i] = 0x00; // use this to flag a need to get type code
400 } // if
401 if (fillItUp == 'Y') {
402 while ((mbrTypes[i] <= 0) || (mbrTypes[i] > 255)) {
403 cout << "Enter an MBR hex code (EE is EFI GPT, but may confuse MacOS): ";
404 // Comment on above: Mac OS treats disks with more than one
405 // 0xEE MBR partition as MBR disks, not as GPT disks.
406 junk = fgets(line, 255, stdin);
407 sscanf(line, "%x", &mbrTypes[i]);
408 if (line[0] == '\n')
409 mbrTypes[i] = 0;
410 } // while
411 gptParts[i] = MBR_EFI_GPT;
412 } // if (fillItUp == 'Y')
413 } // if unused entry
414 } // for (i = 0; i < 4; i++)
415 PartsToMBR(gptParts, mbrTypes);
416 if (bootable > 0)
417 protectiveMBR.SetPartBootable(bootable);
418 } // if (numParts > 0)
419} // GPTDataTextUI::MakeHybrid()
420
421// Convert the GPT to MBR form. This function is necessarily limited; it
422// handles at most four partitions and creates layouts that ignore CHS
423// geometries. Returns the number of converted partitions; if this value
424// is over 0, the calling function should call DestroyGPT() to destroy
425// the GPT data, and then exit.
426int GPTDataTextUI::XFormToMBR(void) {
427 char line[255];
428 char* junk;
429 int j, numParts, bootable = -1, numConverted = 0, numReallyConverted;
430 int gptParts[4], mbrTypes[4];
431 uint32_t i, partNums[4];
432
433 // Get the numbers of up to four partitions to add to the
434 // hybrid MBR....
435 numParts = CountParts();
436 cout << "Counted " << numParts << " partitions.\n";
437
438 if (numParts > 4) { // Over four partitions; engage in triage
439 cout << "Type from one to four GPT partition numbers, separated by spaces, to be\n"
440 << "used in the MBR, in sequence: ";
441 junk = fgets(line, 255, stdin);
442 numParts = sscanf(line, "%d %d %d %d", &partNums[0], &partNums[1],
443 &partNums[2], &partNums[3]);
444 } else { // Four or fewer partitions; convert them all
445 i = j = 0;
446 while ((j < numParts) && (i < mainHeader.numParts)) {
447 if (partitions[i].GetFirstLBA() > 0) { // if GPT part. is defined
448 partNums[j++] = ++i; // flag it for conversion
449 } else i++;
450 } // while
451 } // if/else
452
453 for (i = 0; i < 4; i++)
454 gptParts[i] = MBR_EMPTY;
455
456 for (i = 0; i < (uint32_t) numParts; i++) {
457 j = partNums[i] - 1;
458 cout << "\nCreating entry for GPT partition #" << j + 1
459 << " (MBR partition #" << i + 1 << ")\n";
460 gptParts[i] = j;
461 mbrTypes[i] = GetMBRTypeCode(partitions[j].GetHexType() / 256);
462 cout << "Set the bootable flag? ";
463 if (GetYN() == 'Y')
464 bootable = i;
465 numConverted++;
466 } // for
467 numReallyConverted = PartsToMBR(gptParts, mbrTypes);
468 if (bootable > 0)
469 protectiveMBR.SetPartBootable(bootable);
470 if (numReallyConverted == numConverted) {
471 protectiveMBR.WriteMBRData(&myDisk);
472 } else {
473 cerr << "Error converting partitions to MBR; aborting operation!\n";
474 numConverted = 0;
475 protectiveMBR.MakeProtectiveMBR();
476 } // if/else
477 return numConverted;
478} // GPTDataTextUI::XFormToMBR()
479
480/*********************************************************************
481 * *
482 * The following doesn't really belong in the class, since it's MBR- *
483 * specific, but it's also user I/O-related, so I want to keep it in *
484 * this file.... *
485 * *
486 *********************************************************************/
487
488// Get an MBR type code from the user and return it
489int GetMBRTypeCode(int defType) {
490 char line[255];
491 char* junk;
492 int typeCode;
493
494 cout.setf(ios::uppercase);
495 cout.fill('0');
496 do {
497 cout << "Enter an MBR hex code (default " << hex;
498 cout.width(2);
499 cout << defType << "): " << dec;
500 junk = fgets(line, 255, stdin);
501 if (line[0] == '\n')
502 typeCode = defType;
503 else
504 sscanf(line, "%x", &typeCode);
505 } while ((typeCode <= 0) || (typeCode > 255));
506 cout.fill(' ');
507 return typeCode;
srs56941c6f8b02010-02-21 11:09:20 -0500508} // GetMBRTypeCode