1// support.cc
2// Non-class support functions for gdisk program.
3// Primarily by Rod Smith, February 2009, but with a few functions
4// copied from other sources (see attributions below).
5
6/* This program is copyright (c) 2009-2013 by Roderick W. Smith. It is distributed
7  under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
9#define __STDC_LIMIT_MACROS
10#define __STDC_CONSTANT_MACROS
11
12#include <stdio.h>
13#include <stdint.h>
14#include <errno.h>
15#include <fcntl.h>
16#include <string.h>
17#include <sys/stat.h>
18#include <string>
19#include <iostream>
20#include <sstream>
21#include "support.h"
22
23#include <sys/types.h>
24
25// As of 1/2010, BLKPBSZGET is very new, so I'm explicitly defining it if
26// it's not already defined. This should become unnecessary in the future.
27// Note that this is a Linux-only ioctl....
28#ifndef BLKPBSZGET
29#define BLKPBSZGET _IO(0x12,123)
30#endif
31
32using namespace std;
33
34// Reads a string from stdin, returning it as a C++-style string.
35// Note that the returned string will NOT include the carriage return
36// entered by the user.
37string ReadString(void) {
38   string inString;
39
40   getline(cin, inString);
41   if (!cin.good())
42      exit(5);
43   return inString;
44} // ReadString()
45
46// Get a numeric value from the user, between low and high (inclusive).
47// Keeps looping until the user enters a value within that range.
48// If user provides no input, def (default value) is returned.
49// (If def is outside of the low-high range, an explicit response
50// is required.)
51int GetNumber(int low, int high, int def, const string & prompt) {
52   int response, num;
53   char line[255];
54
55   if (low != high) { // bother only if low and high differ...
56      do {
57         cout << prompt;
58         cin.getline(line, 255);
59         if (!cin.good())
60            exit(5);
61         num = sscanf(line, "%d", &response);
62         if (num == 1) { // user provided a response
63            if ((response < low) || (response > high))
64               cout << "Value out of range\n";
65         } else { // user hit enter; return default
66            response = def;
67         } // if/else
68      } while ((response < low) || (response > high));
69   } else { // low == high, so return this value
70      cout << "Using " << low << "\n";
71      response = low;
72   } // else
73   return (response);
74} // GetNumber()
75
76// Gets a Y/N response (and converts lowercase to uppercase)
77char GetYN(void) {
78   char response;
79   string line;
80   bool again = 0 ;
81
82   do {
83      if ( again ) { cout << "Your option? " ; }
84      again = 1 ;
85      cout << "(Y/N): ";
86      line = ReadString();
87      response = toupper(line[0]);
88   } while ((response != 'Y') && (response != 'N'));
89   return response;
90} // GetYN(void)
91
92// Obtains a sector number, between low and high, from the
93// user, accepting values prefixed by "+" to add sectors to low,
94// or the same with "K", "M", "G", "T", or "P" as suffixes to add
95// kilobytes, megabytes, gigabytes, terabytes, or petabytes,
96// respectively. If a "-" prefix is used, use the high value minus
97// the user-specified number of sectors (or KiB, MiB, etc.). Use the
98// def value as the default if the user just hits Enter. The sSize is
99// the sector size of the device.
100uint64_t GetSectorNum(uint64_t low, uint64_t high, uint64_t def, uint64_t sSize,
101                      const string & prompt) {
102   uint64_t response;
103   char line[255];
104
105   do {
106      cout << prompt;
107      cin.getline(line, 255);
108      if (!cin.good())
109         exit(5);
110      response = IeeeToInt(line, sSize, low, high, def);
111   } while ((response < low) || (response > high));
112   return response;
113} // GetSectorNum()
114
115// Convert an IEEE-1541-2002 value (K, M, G, T, P, or E) to its equivalent in
116// number of sectors. If no units are appended, interprets as the number
117// of sectors; otherwise, interprets as number of specified units and
118// converts to sectors. For instance, with 512-byte sectors, "1K" converts
119// to 2. If value includes a "+", adds low and subtracts 1; if SIValue
120// inclues a "-", subtracts from high. If IeeeValue is empty, returns def.
121// Returns final sector value. In case inValue is invalid, returns 0 (a
122// sector value that's always in use on GPT and therefore invalid); and if
123// inValue works out to something outside the range low-high, returns the
124// computed value; the calling function is responsible for checking the
125// validity of this value.
126// NOTE: There's a difference in how GCC and VC++ treat oversized values
127// (say, "999999999999999999999") read via the ">>" operator; GCC turns
128// them into the maximum value for the type, whereas VC++ turns them into
129// 0 values. The result is that IeeeToInt() returns UINT64_MAX when
130// compiled with GCC (and so the value is rejected), whereas when VC++
131// is used, the default value is returned.
132uint64_t IeeeToInt(string inValue, uint64_t sSize, uint64_t low, uint64_t high, uint64_t def) {
133   uint64_t response = def, bytesPerUnit = 1, mult = 1, divide = 1;
134   size_t foundAt = 0;
135   char suffix, plusFlag = ' ';
136   string suffixes = "KMGTPE";
137   int badInput = 0; // flag bad input; once this goes to 1, other values are irrelevant
138
139   if (sSize == 0) {
140      sSize = SECTOR_SIZE;
141      cerr << "Bug: Sector size invalid in IeeeToInt()!\n";
142   } // if
143
144   // Remove leading spaces, if present
145   while (inValue[0] == ' ')
146      inValue.erase(0, 1);
147
148   // If present, flag and remove leading plus or minus sign
149   if ((inValue[0] == '+') || (inValue[0] == '-')) {
150      plusFlag = inValue[0];
151      inValue.erase(0, 1);
152   } // if
153
154   // Extract numeric response and, if present, suffix
155   istringstream inString(inValue);
156   if (((inString.peek() < '0') || (inString.peek() > '9')) && (inString.peek() != -1))
157      badInput = 1;
158   inString >> response >> suffix;
159   suffix = toupper(suffix);
160
161   // If no response, or if response == 0, use default (def)
162   if ((inValue.length() == 0) || (response == 0)) {
163      response = def;
164      suffix = ' ';
165      plusFlag = ' ';
166   } // if
167
168   // Find multiplication and division factors for the suffix
169   foundAt = suffixes.find(suffix);
170   if (foundAt != string::npos) {
171      bytesPerUnit = UINT64_C(1) << (10 * (foundAt + 1));
172      mult = bytesPerUnit / sSize;
173      divide = sSize / bytesPerUnit;
174   } // if
175
176   // Adjust response based on multiplier and plus flag, if present
177   if (mult > 1) {
178      if (response > (UINT64_MAX / mult))
179         badInput = 1;
180      else
181         response *= mult;
182   } else if (divide > 1) {
183         response /= divide;
184   } // if/elseif
185
186   if (plusFlag == '+') {
187      // Recompute response based on low part of range (if default == high
188      // value, which should be the case when prompting for the end of a
189      // range) or the defaut value (if default != high, which should be
190      // the case for the first sector of a partition).
191      if (def == high) {
192         if (response > 0)
193            response--;
194         if (response > (UINT64_MAX - low))
195            badInput = 1;
196         else
197            response = response + low;
198      } else {
199         if (response > (UINT64_MAX - def))
200            badInput = 1;
201         else
202            response = response + def;
203      } // if/else
204   } else if (plusFlag == '-') {
205      if (response > high)
206         badInput = 1;
207      else
208         response = high - response;
209   } // if
210
211   if (badInput)
212      response = UINT64_C(0);
213
214   return response;
215} // IeeeToInt()
216
217// Takes a size and converts this to a size in IEEE-1541-2002 units (KiB, MiB,
218// GiB, TiB, PiB, or EiB), returned in C++ string form. The size is either in
219// units of the sector size or, if that parameter is omitted, in bytes.
220// (sectorSize defaults to 1). Note that this function uses peculiar
221// manual computation of decimal value rather than simply setting
222// theValue.precision() because this isn't possible using the available
223// EFI library.
224string BytesToIeee(uint64_t size, uint32_t sectorSize) {
225   uint64_t sizeInIeee;
226   uint64_t previousIeee;
227   float decimalIeee;
228   uint index = 0;
229   string units, prefixes = " KMGTPEZ";
230   ostringstream theValue;
231
232   sizeInIeee = previousIeee = size * (uint64_t) sectorSize;
233   while ((sizeInIeee > 1024) && (index < (prefixes.length() - 1))) {
234      index++;
235      previousIeee = sizeInIeee;
236      sizeInIeee /= 1024;
237   } // while
238   if (prefixes[index] == ' ') {
239      theValue << sizeInIeee << " bytes";
240   } else {
241      units = "  iB";
242      units[1] = prefixes[index];
243      decimalIeee = ((float) previousIeee -
244                     ((float) sizeInIeee * 1024.0) + 51.2) / 102.4;
245      if (decimalIeee >= 10.0) {
246         decimalIeee = 0.0;
247         sizeInIeee++;
248      }
249      theValue << sizeInIeee << "." << (uint32_t) decimalIeee << units;
250   } // if/else
251   return theValue.str();
252} // BytesToIeee()
253
254// Converts two consecutive characters in the input string into a
255// number, interpreting the string as a hexadecimal number, starting
256// at the specified position.
257unsigned char StrToHex(const string & input, unsigned int position) {
258   unsigned char retval = 0x00;
259   unsigned int temp;
260
261   if (input.length() > position) {
262      sscanf(input.substr(position, 2).c_str(), "%x", &temp);
263      retval = (unsigned char) temp;
264   } // if
265   return retval;
266} // StrToHex()
267
268// Returns 1 if input can be interpreted as a hexadecimal number --
269// all characters must be spaces, digits, or letters A-F (upper- or
270// lower-case), with at least one valid hexadecimal digit; with the
271// exception of the first two characters, which may be "0x"; otherwise
272// returns 0.
273int IsHex(string input) {
274   int isHex = 1, foundHex = 0, i;
275
276   if (input.substr(0, 2) == "0x")
277      input.erase(0, 2);
278   for (i = 0; i < (int) input.length(); i++) {
279      if ((input[i] < '0') || (input[i] > '9')) {
280         if ((input[i] < 'A') || (input[i] > 'F')) {
281            if ((input[i] < 'a') || (input[i] > 'f')) {
282               if ((input[i] != ' ') && (input[i] != '\n')) {
283                  isHex = 0;
284               }
285            } else foundHex = 1;
286         } else foundHex = 1;
287      } else foundHex = 1;
288   } // for
289   if (!foundHex)
290      isHex = 0;
291   return isHex;
292} // IsHex()
293
294// Return 1 if the CPU architecture is little endian, 0 if it's big endian....
295int IsLittleEndian(void) {
296   int littleE = 1; // assume little-endian (Intel-style)
297   union {
298      uint32_t num;
299      unsigned char uc[sizeof(uint32_t)];
300   } endian;
301
302   endian.num = 1;
303   if (endian.uc[0] != (unsigned char) 1) {
304      littleE = 0;
305   } // if
306   return (littleE);
307} // IsLittleEndian()
308
309// Reverse the byte order of theValue; numBytes is number of bytes
310void ReverseBytes(void* theValue, int numBytes) {
311   char* tempValue = NULL;
312   int i;
313
314   tempValue = new char [numBytes];
315   if (tempValue != NULL) {
316      memcpy(tempValue, theValue, numBytes);
317      for (i = 0; i < numBytes; i++)
318         ((char*) theValue)[i] = tempValue[numBytes - i - 1];
319      delete[] tempValue;
320   } else {
321      cerr << "Could not allocate memory in ReverseBytes()! Terminating\n";
322      exit(1);
323   } // if/else
324} // ReverseBytes()
325
326// On Windows, display a warning and ask whether to continue. If the user elects
327// not to continue, exit immediately.
328void WinWarning(void) {
329   #ifdef _WIN32
330   cout << "\a************************************************************************\n"
331        << "Most versions of Windows cannot boot from a GPT disk except on a UEFI-based\n"
332        << "computer, and most varieties prior to Vista cannot read GPT disks. Therefore,\n"
333        << "you should exit now unless you understand the implications of converting MBR\n"
334        << "to GPT or creating a new GPT disk layout!\n"
335        << "************************************************************************\n\n";
336   cout << "Are you SURE you want to continue? ";
337   if (GetYN() != 'Y')
338      exit(0);
339   #endif
340} // WinWarning()
341