-
Notifications
You must be signed in to change notification settings - Fork 0
/
disk.cpp
483 lines (453 loc) · 20.4 KB
/
disk.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#ifndef WINVER
#define WINVER 0x0601
#endif
#include <QtWidgets>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <windows.h>
#include <winioctl.h>
#include "disk.h"
#include "mainwindow.h"
HANDLE getHandleOnFile(LPCWSTR filelocation, DWORD access)
{
HANDLE hFile;
hFile = CreateFileW(filelocation, access, (access == GENERIC_READ) ? FILE_SHARE_READ : 0, NULL, (access == GENERIC_READ) ? OPEN_EXISTING:CREATE_ALWAYS, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
wchar_t *errormessage=NULL;
::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0,
(LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("File Error"), QObject::tr("An error occurred when attempting to get a handle on the file.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
return hFile;
}
DWORD getDeviceID(HANDLE hVolume)
{
VOLUME_DISK_EXTENTS sd;
DWORD bytesreturned;
if (!DeviceIoControl(hVolume, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &sd, sizeof(sd), &bytesreturned, NULL))
{
wchar_t *errormessage=NULL;
::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0,
(LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Volume Error"),
QObject::tr("An error occurred when attempting to get information on volume.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
return sd.Extents[0].DiskNumber;
}
HANDLE getHandleOnDevice(int device, DWORD access)
{
HANDLE hDevice;
QString devicename = QString("\\\\.\\PhysicalDrive%1").arg(device);
hDevice = CreateFile(LPCWSTR(devicename.toStdWString().c_str()), access, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Device Error"),
QObject::tr("An error occurred when attempting to get a handle on the device.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
return hDevice;
}
HANDLE getHandleOnVolume(int volume, DWORD access)
{
HANDLE hVolume;
char volumename[] = "\\\\.\\A:";
volumename[4] += volume;
hVolume = CreateFile(LPCWSTR(QString(volumename).toStdWString().c_str()), access, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hVolume == INVALID_HANDLE_VALUE)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Volume Error"),
QObject::tr("An error occurred when attempting to get a handle on the volume.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
return hVolume;
}
bool getLockOnVolume(HANDLE handle)
{
DWORD bytesreturned;
BOOL bResult;
bResult = DeviceIoControl(handle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &bytesreturned, NULL);
if (!bResult)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Lock Error"),
QObject::tr("An error occurred when attempting to lock the volume.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
return (bResult);
}
bool removeLockOnVolume(HANDLE handle)
{
DWORD junk;
BOOL bResult;
bResult = DeviceIoControl(handle, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &junk, NULL);
if (!bResult)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Unlock Error"),
QObject::tr("An error occurred when attempting to unlock the volume.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
return (bResult);
}
bool unmountVolume(HANDLE handle)
{
DWORD junk;
BOOL bResult;
bResult = DeviceIoControl(handle, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &junk, NULL);
if (!bResult)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Dismount Error"),
QObject::tr("An error occurred when attempting to dismount the volume.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
return (bResult);
}
bool isVolumeUnmounted(HANDLE handle)
{
DWORD junk;
BOOL bResult;
bResult = DeviceIoControl(handle, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &junk, NULL);
return (!bResult);
}
char *readSectorDataFromHandle(HANDLE handle, unsigned long long startsector, unsigned long long numsectors, unsigned long long sectorsize)
{
unsigned long bytesread;
char *data = new char[sectorsize * numsectors];
LARGE_INTEGER li;
li.QuadPart = startsector * sectorsize;
SetFilePointer(handle, li.LowPart, &li.HighPart, FILE_BEGIN);
if (!ReadFile(handle, data, sectorsize * numsectors, &bytesread, NULL))
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Read Error"),
QObject::tr("An error occurred when attempting to read data from handle.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
delete[] data;
data = NULL;
}
if (data && bytesread < (sectorsize * numsectors))
{
memset(data + bytesread,0,(sectorsize * numsectors) - bytesread);
}
return data;
}
bool writeSectorDataToHandle(HANDLE handle, char *data, unsigned long long startsector, unsigned long long numsectors, unsigned long long sectorsize)
{
unsigned long byteswritten;
BOOL bResult;
LARGE_INTEGER li;
li.QuadPart = startsector * sectorsize;
SetFilePointer(handle, li.LowPart, &li.HighPart, FILE_BEGIN);
bResult = WriteFile(handle, data, sectorsize * numsectors, &byteswritten, NULL);
if (!bResult)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Write Error"),
QObject::tr("An error occurred when attempting to write data to handle.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
return (bResult);
}
unsigned long long getNumberOfSectors(HANDLE handle, unsigned long long *sectorsize)
{
DWORD junk;
DISK_GEOMETRY_EX diskgeometry;
BOOL bResult;
bResult = DeviceIoControl(handle, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, &diskgeometry, sizeof(diskgeometry), &junk, NULL);
if (!bResult)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Device Error"),
QObject::tr("An error occurred when attempting to get the device's geometry.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
return 0;
}
if (sectorsize != NULL)
{
*sectorsize = (unsigned long long)diskgeometry.Geometry.BytesPerSector;
}
return (unsigned long long)diskgeometry.DiskSize.QuadPart / (unsigned long long)diskgeometry.Geometry.BytesPerSector;
}
unsigned long long getFileSizeInSectors(HANDLE handle, unsigned long long sectorsize)
{
unsigned long long retVal = 0;
if (sectorsize) // avoid divide by 0
{
LARGE_INTEGER filesize;
if(GetFileSizeEx(handle, &filesize) == 0)
{
// error
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("File Error"),
QObject::tr("An error occurred while getting the file size.\n"
"Error %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
retVal = 0;
}
else
{
retVal = ((unsigned long long)filesize.QuadPart / sectorsize ) + (((unsigned long long)filesize.QuadPart % sectorsize )?1:0);
}
}
return(retVal);
}
bool spaceAvailable(char *location, unsigned long long spaceneeded)
{
ULARGE_INTEGER freespace;
BOOL bResult;
bResult = GetDiskFreeSpaceEx(LPCWSTR(QString(location).toStdWString().c_str()), NULL, NULL, &freespace);
if (!bResult)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Free Space Error"),
QObject::tr("Failed to get the free space on drive %1.\n"
"Error %2: %3\n"
"Checking of free space will be skipped.").arg(location).arg(GetLastError()).arg(errText));
return true;
}
return (spaceneeded <= freespace.QuadPart);
}
// given a drive letter (ending in a slash), return the label for that drive
// TODO make this more robust by adding input verification
QString getDriveLabel(const char *drv)
{
QString retVal;
int szNameBuf = MAX_PATH + 1;
char *nameBuf = NULL;
if( (nameBuf = (char *)calloc(szNameBuf, sizeof(char))) != 0 )
{
::GetVolumeInformationA(drv, nameBuf, szNameBuf, NULL,
NULL, NULL, NULL, 0);
}
// if malloc fails, nameBuf will be NULL.
// if GetVolumeInfo fails, nameBuf will contain empty string
// if all succeeds, nameBuf will contain label
if(nameBuf == NULL)
{
retVal = QString("");
}
else
{
retVal = QString(nameBuf);
free(nameBuf);
}
return(retVal);
}
BOOL GetDisksProperty(HANDLE hDevice, PSTORAGE_DEVICE_DESCRIPTOR pDevDesc,
DEVICE_NUMBER *devInfo)
{
STORAGE_PROPERTY_QUERY Query; // input param for query
DWORD dwOutBytes; // IOCTL output length
BOOL bResult; // IOCTL return val
BOOL retVal = true;
DWORD cbBytesReturned;
// specify the query type
Query.PropertyId = StorageDeviceProperty;
Query.QueryType = PropertyStandardQuery;
// Query using IOCTL_STORAGE_QUERY_PROPERTY
bResult = ::DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
&Query, sizeof(STORAGE_PROPERTY_QUERY), pDevDesc,
pDevDesc->Size, &dwOutBytes, (LPOVERLAPPED)NULL);
if (bResult)
{
bResult = ::DeviceIoControl(hDevice, IOCTL_STORAGE_GET_DEVICE_NUMBER,
NULL, 0, devInfo, sizeof(DEVICE_NUMBER), &dwOutBytes,
(LPOVERLAPPED)NULL);
if (!bResult)
{
retVal = false;
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("File Error"),
QObject::tr("An error occurred while getting the device number.\n"
"This usually means something is currently accessing the device;"
"please close all applications and try again.\n\nError %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
}
else
{
bResult = DeviceIoControl(hDevice, IOCTL_STORAGE_CHECK_VERIFY2, NULL, 0, NULL, 0, &cbBytesReturned,
(LPOVERLAPPED) NULL);
if (bResult && GetLastError() == ERROR_INVALID_FUNCTION)
{
retVal = false;
}
else
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("File Error"),
QObject::tr("An error occurred while querying the properties.\n"
"This usually means something is currently accessing the device;"
" please close all applications and try again.\n\nError %1: %2").arg(GetLastError()).arg(errText));
LocalFree(errormessage);
}
retVal = false;
}
return(retVal);
}
// some routines fail if there's no trailing slash in a name,
// others fail if there is. So this routine takes a name (trailing
// slash or no), and creates 2 versions - one with the slash, and one w/o
//
// CALLER MUST FREE THE 2 RETURNED STRINGS
bool slashify(char *str, char **slash, char **noSlash)
{
bool retVal = false;
int strLen = static_cast<int>(strlen(str));
if ( strLen > 0 )
{
if ( *(str + strLen - 1) == '\\' )
{
// trailing slash exists
if (( (*slash = (char *)calloc( (strLen + 1), sizeof(char))) != NULL) &&
( (*noSlash = (char *)calloc(strLen, sizeof(char))) != NULL))
{
strncpy(*slash, str, strLen);
strncpy(*noSlash, *slash, (strLen - 1));
retVal = true;
}
}
else
{
// no trailing slash exists
if ( ((*slash = (char *)calloc( (strLen + 2), sizeof(char))) != NULL) &&
((*noSlash = (char *)calloc( (strLen + 1), sizeof(char))) != NULL) )
{
strncpy(*noSlash, str, strLen);
sprintf(*slash, "%s\\", *noSlash);
retVal = true;
}
}
}
return(retVal);
}
bool GetMediaType(HANDLE hDevice)
{
DISK_GEOMETRY diskGeo;
DWORD cbBytesReturned;
if (DeviceIoControl(hDevice, IOCTL_DISK_GET_DRIVE_GEOMETRY,NULL, 0, &diskGeo, sizeof(diskGeo), &cbBytesReturned, NULL))
{
if ((diskGeo.MediaType == FixedMedia) || (diskGeo.MediaType == RemovableMedia))
{
return true; // Not a floppy
}
}
return false;
}
bool checkDriveType(char *name, ULONG *pid)
{
HANDLE hDevice;
PSTORAGE_DEVICE_DESCRIPTOR pDevDesc;
DEVICE_NUMBER deviceInfo;
bool retVal = false;
char *nameWithSlash;
char *nameNoSlash;
int driveType;
DWORD cbBytesReturned;
// some calls require no tailing slash, some require a trailing slash...
if ( !(slashify(name, &nameWithSlash, &nameNoSlash)) )
{
return(retVal);
}
driveType = GetDriveType(LPCWSTR(QString(nameWithSlash).toStdWString().c_str()));
switch( driveType )
{
case DRIVE_REMOVABLE: // The media can be removed from the drive.
case DRIVE_FIXED: // The media cannot be removed from the drive. Some USB drives report as this.
hDevice = CreateFile(LPCWSTR(QString(nameNoSlash).toStdWString().c_str()), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
wchar_t *errormessage=NULL;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPWSTR)&errormessage, 0, NULL);
QString errText = QString::fromUtf16((const ushort *)errormessage);
QMessageBox::critical(MainWindow::getInstance(), QObject::tr("Volume Error"),
QObject::tr("An error occurred when attempting to get a handle on %3.\n"
"Error %1: %2").arg(GetLastError()).arg(errText).arg(nameWithSlash));
LocalFree(errormessage);
}
else
{
int arrSz = sizeof(STORAGE_DEVICE_DESCRIPTOR) + 512 - 1;
pDevDesc = (PSTORAGE_DEVICE_DESCRIPTOR)new BYTE[arrSz];
pDevDesc->Size = arrSz;
// get the device number if the drive is
// removable or (fixed AND on the usb bus, SD, or MMC (undefined in XP/mingw))
if(GetMediaType(hDevice) && GetDisksProperty(hDevice, pDevDesc, &deviceInfo) &&
( ((driveType == DRIVE_REMOVABLE) && (pDevDesc->BusType != BusTypeSata))
|| ( (driveType == DRIVE_FIXED) && ((pDevDesc->BusType == BusTypeUsb)
|| (pDevDesc->BusType == BusTypeSd ) || (pDevDesc->BusType == BusTypeMmc )) ) ) )
{
// ensure that the drive is actually accessible
// multi-card hubs were reporting "removable" even when empty
if(DeviceIoControl(hDevice, IOCTL_STORAGE_CHECK_VERIFY2, NULL, 0, NULL, 0, &cbBytesReturned, (LPOVERLAPPED) NULL))
{
*pid = deviceInfo.DeviceNumber;
retVal = true;
}
else
// IOCTL_STORAGE_CHECK_VERIFY2 fails on some devices under XP/Vista, try the other (slower) method, just in case.
{
CloseHandle(hDevice);
hDevice = CreateFile(LPCWSTR(QString(nameNoSlash).toStdWString().c_str()), FILE_READ_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if(DeviceIoControl(hDevice, IOCTL_STORAGE_CHECK_VERIFY, NULL, 0, NULL, 0, &cbBytesReturned, (LPOVERLAPPED) NULL))
{
*pid = deviceInfo.DeviceNumber;
retVal = true;
}
}
}
delete[] pDevDesc;
CloseHandle(hDevice);
}
break;
default:
retVal = false;
}
// free the strings allocated by slashify
free(nameWithSlash);
free(nameNoSlash);
return(retVal);
}