-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathdrive.c
2691 lines (2423 loc) · 99.4 KB
/
drive.c
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Rufus: The Reliable USB Formatting Utility
* Drive access function calls
* Copyright © 2011-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#if !defined(__MINGW32__)
#include <initguid.h>
#include <vds.h>
#endif
#include "rufus.h"
#include "missing.h"
#include "resource.h"
#include "settings.h"
#include "msapi_utf8.h"
#include "localization.h"
#include "file.h"
#include "drive.h"
#include "mbr_types.h"
#include "gpt_types.h"
#include "br.h"
#include "fat16.h"
#include "fat32.h"
#include "ntfs.h"
#define GLOBALROOT_NAME "\\\\?\\GLOBALROOT"
const char* sfd_name = "Super Floppy Disk";
const char* groot_name = GLOBALROOT_NAME;
const size_t groot_len = sizeof(GLOBALROOT_NAME) - 1;
#if defined(__MINGW32__)
const IID CLSID_VdsLoader = { 0x9c38ed61, 0xd565, 0x4728, { 0xae, 0xee, 0xc8, 0x09, 0x52, 0xf0, 0xec, 0xde } };
const IID IID_IVdsServiceLoader = { 0xe0393303, 0x90d4, 0x4a97, { 0xab, 0x71, 0xe9, 0xb6, 0x71, 0xee, 0x27, 0x29 } };
const IID IID_IVdsProvider = { 0x10c5e575, 0x7984, 0x4e81, { 0xa5, 0x6b, 0x43, 0x1f, 0x5f, 0x92, 0xae, 0x42 } };
const IID IID_IVdsSwProvider = { 0x9aa58360, 0xce33, 0x4f92, { 0xb6, 0x58, 0xed, 0x24, 0xb1, 0x44, 0x25, 0xb8 } };
const IID IID_IVdsPack = { 0x3b69d7f5, 0x9d94, 0x4648, { 0x91, 0xca, 0x79, 0x93, 0x9b, 0xa2, 0x63, 0xbf } };
const IID IID_IVdsDisk = { 0x07e5c822, 0xf00c, 0x47a1, { 0x8f, 0xce, 0xb2, 0x44, 0xda, 0x56, 0xfd, 0x06 } };
const IID IID_IVdsAdvancedDisk = { 0x6e6f6b40, 0x977c, 0x4069, { 0xbd, 0xdd, 0xac, 0x71, 0x00, 0x59, 0xf8, 0xc0 } };
const IID IID_IVdsVolume = { 0x88306BB2, 0xE71F, 0x478C, { 0x86, 0xA2, 0x79, 0xDA, 0x20, 0x0A, 0x0F, 0x11} };
const IID IID_IVdsVolumeMF3 = { 0x6788FAF9, 0x214E, 0x4B85, { 0xBA, 0x59, 0x26, 0x69, 0x53, 0x61, 0x6E, 0x09 } };
#endif
PF_TYPE_DECL(NTAPI, NTSTATUS, NtQueryVolumeInformationFile, (HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FS_INFORMATION_CLASS));
/*
* Globals
*/
RUFUS_DRIVE_INFO SelectedDrive;
extern BOOL write_as_esp;
extern windows_version_t WindowsVersion;
int partition_index[PI_MAX];
uint64_t persistence_size = 0;
/*
* The following methods get or set the AutoMount setting (which is different from AutoRun)
* Rufus needs AutoMount to be set as the format process may fail for fixed drives otherwise.
* See https://github.com/pbatard/rufus/issues/386.
*
* Reverse engineering diskpart and mountvol indicates that the former uses the IVdsService
* ClearFlags()/SetFlags() to set VDS_SVF_AUTO_MOUNT_OFF whereas mountvol on uses
* IOCTL_MOUNTMGR_SET_AUTO_MOUNT on "\\\\.\\MountPointManager".
* As the latter is MUCH simpler this is what we'll use too
*/
BOOL SetAutoMount(BOOL enable)
{
HANDLE hMountMgr;
BOOL ret = FALSE;
hMountMgr = CreateFileA(MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hMountMgr == INVALID_HANDLE_VALUE)
return FALSE;
ret = DeviceIoControl(hMountMgr, IOCTL_MOUNTMGR_SET_AUTO_MOUNT, &enable, sizeof(enable), NULL, 0, NULL, NULL);
CloseHandle(hMountMgr);
return ret;
}
BOOL GetAutoMount(BOOL* enabled)
{
HANDLE hMountMgr;
DWORD size;
BOOL ret = FALSE;
if (enabled == NULL)
return FALSE;
hMountMgr = CreateFileA(MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hMountMgr == INVALID_HANDLE_VALUE)
return FALSE;
ret = DeviceIoControl(hMountMgr, IOCTL_MOUNTMGR_QUERY_AUTO_MOUNT, NULL, 0, enabled, sizeof(*enabled), &size, NULL);
CloseHandle(hMountMgr);
return ret;
}
/*
* Working with drive indexes quite risky (left unchecked,inadvertently passing 0 as
* index would return a handle to C:, which we might then proceed to unknowingly
* clear the MBR of!), so we mitigate the risk by forcing our indexes to belong to
* the specific range [DRIVE_INDEX_MIN; DRIVE_INDEX_MAX].
*/
#define CheckDriveIndex(DriveIndex) do { \
if ((int)DriveIndex < 0) goto out; \
assert((DriveIndex >= DRIVE_INDEX_MIN) && (DriveIndex <= DRIVE_INDEX_MAX)); \
if ((DriveIndex < DRIVE_INDEX_MIN) || (DriveIndex > DRIVE_INDEX_MAX)) goto out; \
DriveIndex -= DRIVE_INDEX_MIN; } while (0)
/*
* Open a drive or volume with optional write and lock access
* Return INVALID_HANDLE_VALUE (/!\ which is DIFFERENT from NULL /!\) on failure.
*/
static HANDLE GetHandle(char* Path, BOOL bLockDrive, BOOL bWriteAccess, BOOL bWriteShare)
{
int i;
BYTE access_mask = 0;
uint64_t EndTime;
HANDLE hDrive = INVALID_HANDLE_VALUE;
char DevPath[MAX_PATH];
if ((safe_strlen(Path) < 5) || (Path[0] != '\\') || (Path[1] != '\\') || (Path[3] != '\\'))
goto out;
// Resolve a device path, so that we can look for that handle in case of access issues.
if (safe_strncmp(Path, groot_name, groot_len) == 0)
static_strcpy(DevPath, &Path[groot_len]);
else if (QueryDosDeviceA(&Path[4], DevPath, sizeof(DevPath)) == 0)
strcpy(DevPath, "???");
for (i = 0; i < DRIVE_ACCESS_RETRIES; i++) {
// Try without FILE_SHARE_WRITE (unless specifically requested) so that
// we won't be bothered by the OS or other apps when we set up our data.
// However this means we might have to wait for an access gap...
// We keep FILE_SHARE_READ though, as this shouldn't hurt us any, and is
// required for enumeration.
hDrive = CreateFileA(Path, GENERIC_READ|(bWriteAccess?GENERIC_WRITE:0),
FILE_SHARE_READ|(bWriteShare?FILE_SHARE_WRITE:0),
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDrive != INVALID_HANDLE_VALUE)
break;
if ((GetLastError() != ERROR_SHARING_VIOLATION) && (GetLastError() != ERROR_ACCESS_DENIED))
break;
if (i == 0) {
uprintf("Notice: Volume Device Path is %s", DevPath);
uprintf("Waiting for access on %s...", Path);
} else if (!bWriteShare && (i > DRIVE_ACCESS_RETRIES/3)) {
// If we can't seem to get a hold of the drive for some time, try to enable FILE_SHARE_WRITE...
uprintf("Warning: Could not obtain exclusive rights. Retrying with write sharing enabled...");
bWriteShare = TRUE;
// Try to report the process that is locking the drive
access_mask = GetProcessSearch(SEARCH_PROCESS_TIMEOUT, 0x07, FALSE);
}
Sleep(DRIVE_ACCESS_TIMEOUT / DRIVE_ACCESS_RETRIES);
}
if (hDrive == INVALID_HANDLE_VALUE) {
uprintf("Could not open %s: %s", Path, WindowsErrorString());
goto out;
}
if (bWriteAccess) {
uprintf("Opened %s for %s write access", Path, bWriteShare?"shared":"exclusive");
}
if (bLockDrive) {
if (DeviceIoControl(hDrive, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0, NULL, NULL)) {
uprintf("I/O boundary checks disabled");
}
EndTime = GetTickCount64() + DRIVE_ACCESS_TIMEOUT;
do {
if (DeviceIoControl(hDrive, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, NULL, NULL))
goto out;
if (IS_ERROR(ErrorStatus)) // User cancel
break;
Sleep(DRIVE_ACCESS_TIMEOUT / DRIVE_ACCESS_RETRIES);
} while (GetTickCount64() < EndTime);
// If we reached this section, either we didn't manage to get a lock or the user cancelled
uprintf("Could not lock access to %s: %s", Path, WindowsErrorString());
// See if we can report the processes are accessing the drive
if (!IS_ERROR(ErrorStatus) && (access_mask == 0))
access_mask = GetProcessSearch(SEARCH_PROCESS_TIMEOUT, 0x07, FALSE);
// Try to continue if the only access rights we saw were for read-only
if ((access_mask & 0x07) != 0x01)
safe_closehandle(hDrive);
}
out:
return hDrive;
}
/*
* Return the path to access the physical drive, or NULL on error.
* The string is allocated and must be freed (to ensure concurrent access)
*/
char* GetPhysicalName(DWORD DriveIndex)
{
BOOL success = FALSE;
char physical_name[24];
CheckDriveIndex(DriveIndex);
static_sprintf(physical_name, "\\\\.\\PhysicalDrive%lu", DriveIndex);
success = TRUE;
out:
return (success)?safe_strdup(physical_name):NULL;
}
/*
* Return a handle to the physical drive identified by DriveIndex
*/
HANDLE GetPhysicalHandle(DWORD DriveIndex, BOOL bLockDrive, BOOL bWriteAccess, BOOL bWriteShare)
{
HANDLE hPhysical = INVALID_HANDLE_VALUE;
char* PhysicalPath = GetPhysicalName(DriveIndex);
hPhysical = GetHandle(PhysicalPath, bLockDrive, bWriteAccess, bWriteShare);
safe_free(PhysicalPath);
return hPhysical;
}
/*
* Return the GUID volume name for the disk and partition specified, or NULL if not found.
* See http://msdn.microsoft.com/en-us/library/cc542456.aspx
* If PartitionOffset is 0, the offset is ignored and the first partition found is returned.
* The returned string is allocated and must be freed.
*/
char* GetLogicalName(DWORD DriveIndex, uint64_t PartitionOffset, BOOL bKeepTrailingBackslash, BOOL bSilent)
{
static const char* ignore_device[] = { "\\Device\\CdRom", "\\Device\\Floppy" };
static const char* volume_start = "\\\\?\\";
char *ret = NULL, volume_name[MAX_PATH], path[MAX_PATH];
BOOL r, bPrintHeader = TRUE;
HANDLE hDrive = INVALID_HANDLE_VALUE, hVolume = INVALID_HANDLE_VALUE;
VOLUME_DISK_EXTENTS_REDEF DiskExtents;
DWORD size = 0;
UINT drive_type;
StrArray found_name;
uint64_t found_offset[MAX_PARTITIONS] = { 0 };
uint32_t i, j;
size_t len;
StrArrayCreate(&found_name, MAX_PARTITIONS);
CheckDriveIndex(DriveIndex);
for (i = 0; hDrive == INVALID_HANDLE_VALUE; i++) {
if (i == 0) {
hVolume = FindFirstVolumeA(volume_name, sizeof(volume_name));
if (hVolume == INVALID_HANDLE_VALUE) {
suprintf("Could not access first GUID volume: %s", WindowsErrorString());
goto out;
}
} else {
if (!FindNextVolumeA(hVolume, volume_name, sizeof(volume_name))) {
if (GetLastError() != ERROR_NO_MORE_FILES) {
suprintf("Could not access next GUID volume: %s", WindowsErrorString());
}
break;
}
}
// Sanity checks
len = safe_strlen(volume_name);
if_not_assert(len > 4)
continue;
if_not_assert(safe_strnicmp(volume_name, volume_start, 4) == 0)
continue;
if_not_assert(volume_name[len - 1] == '\\')
continue;
drive_type = GetDriveTypeA(volume_name);
if ((drive_type != DRIVE_REMOVABLE) && (drive_type != DRIVE_FIXED))
continue;
volume_name[len-1] = 0;
if (QueryDosDeviceA(&volume_name[4], path, sizeof(path)) == 0) {
suprintf("Failed to get device path for GUID volume '%s': %s", volume_name, WindowsErrorString());
continue;
}
for (j=0; (j<ARRAYSIZE(ignore_device)) &&
(_strnicmp(path, ignore_device[j], safe_strlen(ignore_device[j])) != 0); j++);
if (j < ARRAYSIZE(ignore_device)) {
suprintf("Skipping GUID volume for '%s'", path);
continue;
}
hDrive = CreateFileWithTimeout(volume_name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL, 3000);
if (hDrive == INVALID_HANDLE_VALUE) {
suprintf("Could not open GUID volume '%s': %s", volume_name, WindowsErrorString());
continue;
}
r = DeviceIoControl(hDrive, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &DiskExtents, sizeof(DiskExtents), &size, NULL);
if ((!r) || (size == 0)) {
suprintf("Could not get Disk Extents: %s", r ? "(empty data)" : WindowsErrorString());
safe_closehandle(hDrive);
continue;
}
safe_closehandle(hDrive);
if (DiskExtents.NumberOfDiskExtents == 0) {
suprintf("Ignoring volume '%s' because it has no extents...", volume_name);
continue;
}
if (DiskExtents.NumberOfDiskExtents != 1) {
// If we have more than one extent for a volume, it means that someone
// is using RAID-1 or something => Stay well away from such a volume!
suprintf("Ignoring volume '%s' because it has more than one extent (RAID?)...", volume_name);
continue;
}
if (DiskExtents.Extents[0].DiskNumber != DriveIndex)
// Not on our disk
continue;
if (found_name.Index == MAX_PARTITIONS) {
uprintf("Error: Trying to process a disk with more than %d partitions!", MAX_PARTITIONS);
goto out;
}
if (bKeepTrailingBackslash)
volume_name[len - 1] = '\\';
found_offset[found_name.Index] = DiskExtents.Extents[0].StartingOffset.QuadPart;
StrArrayAdd(&found_name, volume_name, TRUE);
if (!bSilent) {
if (bPrintHeader) {
bPrintHeader = FALSE;
uuprintf("Windows volumes from this device:");
}
uuprintf("● %s @%lld", volume_name, DiskExtents.Extents[0].StartingOffset.QuadPart);
}
}
if (found_name.Index == 0)
goto out;
// Now process all the volumes we found, and try to match one with our partition offset
for (i = 0; (i < found_name.Index) && (PartitionOffset != 0) && (PartitionOffset != found_offset[i]); i++);
if (i < found_name.Index) {
ret = safe_strdup(found_name.String[i]);
} else {
// NB: We need to re-add DRIVE_INDEX_MIN for this call since CheckDriveIndex() subtracted it
ret = AltGetLogicalName(DriveIndex + DRIVE_INDEX_MIN, PartitionOffset, bKeepTrailingBackslash, bSilent);
if ((ret != NULL) && (strchr(ret, ' ') != NULL))
uprintf("Warning: Using physical device to access partition data");
}
out:
if (hVolume != INVALID_HANDLE_VALUE)
FindVolumeClose(hVolume);
StrArrayDestroy(&found_name);
return ret;
}
/*
* Alternative version of the above, needed because some volumes, such as ESPs, are not listed
* by Windows, be it with VDS or other APIs.
* For these, we return the "\\?\GLOBALROOT\Device\HarddiskVolume#" identifier that matches
* our "Harddisk#Partition#", as reported by QueryDosDevice().
* The returned string is allocated and must be freed.
*/
char* AltGetLogicalName(DWORD DriveIndex, uint64_t PartitionOffset, BOOL bKeepTrailingBackslash, BOOL bSilent)
{
BOOL matching_drive = (DriveIndex == SelectedDrive.DeviceNumber);
DWORD i;
char *ret = NULL, volume_name[MAX_PATH], path[64];
CheckDriveIndex(DriveIndex);
// Match the offset to a partition index
if (PartitionOffset == 0) {
i = 0;
} else if (matching_drive) {
for (i = 0; (i < MAX_PARTITIONS) && (PartitionOffset != SelectedDrive.Partition[i].Offset); i++);
if (i >= MAX_PARTITIONS) {
suprintf("Error: Could not find a partition at offset %lld on this disk", PartitionOffset);
goto out;
}
} else {
suprintf("Error: Searching for a partition on a non matching disk");
goto out;
}
static_sprintf(path, "Harddisk%luPartition%lu", DriveIndex, i + 1);
static_strcpy(volume_name, groot_name);
if (!QueryDosDeviceA(path, &volume_name[groot_len], (DWORD)(MAX_PATH - groot_len)) || (strlen(volume_name) < 20)) {
suprintf("Could not find a DOS volume name for '%s': %s", path, WindowsErrorString());
goto out;
} else if (bKeepTrailingBackslash) {
static_strcat(volume_name, "\\");
}
ret = safe_strdup(volume_name);
out:
return ret;
}
/*
* Custom volume name for extfs formatting (that includes partition offset and partition size)
* so that these can be created and accessed on pre 1703 versions of Windows.
*/
char* GetExtPartitionName(DWORD DriveIndex, uint64_t PartitionOffset)
{
DWORD i;
char* ret = NULL, volume_name[MAX_PATH];
// Can't operate if we're not on the selected drive
if (DriveIndex != SelectedDrive.DeviceNumber)
goto out;
CheckDriveIndex(DriveIndex);
for (i = 0; (i < MAX_PARTITIONS) && (PartitionOffset != SelectedDrive.Partition[i].Offset); i++);
if (i >= MAX_PARTITIONS)
goto out;
static_sprintf(volume_name, "\\\\.\\PhysicalDrive%lu %I64u %I64u", DriveIndex,
SelectedDrive.Partition[i].Offset, SelectedDrive.Partition[i].Size);
ret = safe_strdup(volume_name);
out:
return ret;
}
static const char* VdsErrorString(HRESULT hr) {
SetLastError(hr);
return WindowsErrorString();
}
/*
* Per https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance
* and even though we aren't a UWP app, Windows Store prevents the ability to use of VDS when the
* Store version of Rufus is running (the call to IVdsServiceLoader_LoadService() will return
* E_ACCESSDENIED).
*/
BOOL IsVdsAvailable(BOOL bSilent)
{
HRESULT hr = S_FALSE;
IVdsService* pService = NULL;
IVdsServiceLoader* pLoader = NULL;
// Initialize COM
IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
IGNORE_RETVAL(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL));
// Create a VDS Loader Instance
hr = CoCreateInstance(&CLSID_VdsLoader, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER,
&IID_IVdsServiceLoader, (void**)&pLoader);
if (hr != S_OK) {
suprintf("Notice: Disabling VDS (Could not create VDS Loader Instance: %s)", VdsErrorString(hr));
goto out;
}
hr = IVdsServiceLoader_LoadService(pLoader, L"", &pService);
if (hr != S_OK) {
suprintf("Notice: Disabling VDS (Could not load VDS Service: %s)", VdsErrorString(hr));
goto out;
}
out:
if (pService != NULL)
IVdsService_Release(pService);
if (pLoader != NULL)
IVdsServiceLoader_Release(pLoader);
VDS_SET_ERROR(hr);
return (hr == S_OK);
}
/*
* Call on VDS to refresh the drive layout
*/
BOOL RefreshLayout(DWORD DriveIndex)
{
HRESULT hr = S_FALSE;
wchar_t wPhysicalName[24];
IVdsServiceLoader* pLoader = NULL;
IVdsService* pService = NULL;
IEnumVdsObject *pEnum;
CheckDriveIndex(DriveIndex);
wnsprintf(wPhysicalName, ARRAYSIZE(wPhysicalName), L"\\\\?\\PhysicalDrive%lu", DriveIndex);
// Initialize COM
IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
IGNORE_RETVAL(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL));
// Create a VDS Loader Instance
hr = CoCreateInstance(&CLSID_VdsLoader, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER,
&IID_IVdsServiceLoader, (void **)&pLoader);
if (hr != S_OK) {
uprintf("Could not create VDS Loader Instance: %s", VdsErrorString(hr));
goto out;
}
// Load the VDS Service
hr = IVdsServiceLoader_LoadService(pLoader, L"", &pService);
if (hr != S_OK) {
uprintf("Could not load VDS Service: %s", VdsErrorString(hr));
goto out;
}
// Wait for the Service to become ready if needed
hr = IVdsService_WaitForServiceReady(pService);
if (hr != S_OK) {
uprintf("VDS Service is not ready: %s", VdsErrorString(hr));
goto out;
}
// Query the VDS Service Providers
hr = IVdsService_QueryProviders(pService, VDS_QUERY_SOFTWARE_PROVIDERS, &pEnum);
if (hr != S_OK) {
uprintf("Could not query VDS Service Providers: %s", VdsErrorString(hr));
goto out;
}
// Remove mountpoints
hr = IVdsService_CleanupObsoleteMountPoints(pService);
if (hr != S_OK) {
uprintf("Could not clean up VDS mountpoints: %s", VdsErrorString(hr));
goto out;
}
// Invoke layout refresh
hr = IVdsService_Refresh(pService);
if (hr != S_OK) {
uprintf("Could not refresh VDS layout: %s", VdsErrorString(hr));
goto out;
}
// Force re-enum
hr = IVdsService_Reenumerate(pService);
if (hr != S_OK) {
uprintf("Could not refresh VDS layout: %s", VdsErrorString(hr));
goto out;
}
out:
if (pService != NULL)
IVdsService_Release(pService);
if (pLoader != NULL)
IVdsServiceLoader_Release(pLoader);
VDS_SET_ERROR(hr);
return (hr == S_OK);
}
/*
* Generic call to instantiate a VDS Disk Interface. Mostly copied from:
* https://social.msdn.microsoft.com/Forums/vstudio/en-US/b90482ae-4e44-4b08-8731-81915030b32a/createpartition-using-vds-interface-throw-error-enointerface-dcom?forum=vcgeneral
* See also: https://docs.microsoft.com/en-us/windows/win32/vds/working-with-enumeration-objects
*/
static BOOL GetVdsDiskInterface(DWORD DriveIndex, const IID* InterfaceIID, void** pInterfaceInstance, BOOL bSilent)
{
HRESULT hr = S_FALSE;
ULONG ulFetched;
wchar_t wPhysicalName[24];
IVdsServiceLoader* pLoader;
IVdsService* pService;
IEnumVdsObject* pEnum;
IUnknown* pUnk;
*pInterfaceInstance = NULL;
CheckDriveIndex(DriveIndex);
wnsprintf(wPhysicalName, ARRAYSIZE(wPhysicalName), L"\\\\?\\PhysicalDrive%lu", DriveIndex);
// Initialize COM
IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
IGNORE_RETVAL(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL));
// Create a VDS Loader Instance
hr = CoCreateInstance(&CLSID_VdsLoader, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER,
&IID_IVdsServiceLoader, (void**)&pLoader);
if (hr != S_OK) {
suprintf("Could not create VDS Loader Instance: %s", VdsErrorString(hr));
goto out;
}
// Load the VDS Service
hr = IVdsServiceLoader_LoadService(pLoader, L"", &pService);
IVdsServiceLoader_Release(pLoader);
if (hr != S_OK) {
suprintf("Could not load VDS Service: %s", VdsErrorString(hr));
goto out;
}
// Wait for the Service to become ready if needed
hr = IVdsService_WaitForServiceReady(pService);
if (hr != S_OK) {
suprintf("VDS Service is not ready: %s", VdsErrorString(hr));
goto out;
}
// Query the VDS Service Providers
hr = IVdsService_QueryProviders(pService, VDS_QUERY_SOFTWARE_PROVIDERS, &pEnum);
IVdsService_Release(pService);
if (hr != S_OK) {
suprintf("Could not query VDS Service Providers: %s", VdsErrorString(hr));
goto out;
}
while (IEnumVdsObject_Next(pEnum, 1, &pUnk, &ulFetched) == S_OK) {
IVdsProvider* pProvider;
IVdsSwProvider* pSwProvider;
IEnumVdsObject* pEnumPack;
IUnknown* pPackUnk;
// Get VDS Provider
hr = IUnknown_QueryInterface(pUnk, &IID_IVdsProvider, (void**)&pProvider);
IUnknown_Release(pUnk);
if (hr != S_OK) {
suprintf("Could not get VDS Provider: %s", VdsErrorString(hr));
break;
}
// Get VDS Software Provider
hr = IVdsSwProvider_QueryInterface(pProvider, &IID_IVdsSwProvider, (void**)&pSwProvider);
IVdsProvider_Release(pProvider);
if (hr != S_OK) {
suprintf("Could not get VDS Software Provider: %s", VdsErrorString(hr));
break;
}
// Get VDS Software Provider Packs
hr = IVdsSwProvider_QueryPacks(pSwProvider, &pEnumPack);
IVdsSwProvider_Release(pSwProvider);
if (hr != S_OK) {
suprintf("Could not get VDS Software Provider Packs: %s", VdsErrorString(hr));
break;
}
// Enumerate Provider Packs
while (IEnumVdsObject_Next(pEnumPack, 1, &pPackUnk, &ulFetched) == S_OK) {
IVdsPack* pPack;
IEnumVdsObject* pEnumDisk;
IUnknown* pDiskUnk;
hr = IUnknown_QueryInterface(pPackUnk, &IID_IVdsPack, (void**)&pPack);
IUnknown_Release(pPackUnk);
if (hr != S_OK) {
suprintf("Could not query VDS Software Provider Pack: %s", VdsErrorString(hr));
break;
}
// Use the pack interface to access the disks
hr = IVdsPack_QueryDisks(pPack, &pEnumDisk);
IVdsPack_Release(pPack);
if (hr != S_OK) {
suprintf("Could not query VDS disks: %s", VdsErrorString(hr));
break;
}
// List disks
while (IEnumVdsObject_Next(pEnumDisk, 1, &pDiskUnk, &ulFetched) == S_OK) {
VDS_DISK_PROP prop;
IVdsDisk* pDisk;
// Get the disk interface.
hr = IUnknown_QueryInterface(pDiskUnk, &IID_IVdsDisk, (void**)&pDisk);
IUnknown_Release(pDiskUnk);
if (hr != S_OK) {
suprintf("Could not query VDS Disk Interface: %s", VdsErrorString(hr));
break;
}
// Get the disk properties
hr = IVdsDisk_GetProperties(pDisk, &prop);
if ((hr != S_OK) && (hr != VDS_S_PROPERTIES_INCOMPLETE)) {
IVdsDisk_Release(pDisk);
suprintf("Could not query VDS Disk Properties: %s", VdsErrorString(hr));
break;
}
// Check if we are on the target disk
// uprintf("GetVdsDiskInterface: Seeking %S found %S", wPhysicalName, prop.pwszName);
hr = (HRESULT)_wcsicmp(wPhysicalName, prop.pwszName);
CoTaskMemFree(prop.pwszName);
if (hr != S_OK) {
hr = S_OK;
continue;
}
// Instantiate the requested VDS disk interface
hr = IVdsDisk_QueryInterface(pDisk, InterfaceIID, pInterfaceInstance);
IVdsDisk_Release(pDisk);
if (hr != S_OK)
suprintf("Could not access the requested Disk interface: %s", VdsErrorString(hr));
// With the interface found, we should be able to return
break;
}
IEnumVdsObject_Release(pEnumDisk);
}
IEnumVdsObject_Release(pEnumPack);
}
IEnumVdsObject_Release(pEnum);
out:
VDS_SET_ERROR(hr);
return (hr == S_OK);
}
/*
* Invoke IVdsService::Refresh() and/or IVdsService::Reenumerate() to force a
* rescan of the VDS disks. This can become necessary after writing an image
* such as Ubuntu 20.10, as Windows may "lose" the active disk otherwise...
*/
BOOL VdsRescan(DWORD dwRescanType, DWORD dwSleepTime, BOOL bSilent)
{
BOOL ret = TRUE;
HRESULT hr = S_FALSE;
IVdsServiceLoader* pLoader;
IVdsService* pService;
IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
IGNORE_RETVAL(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL));
hr = CoCreateInstance(&CLSID_VdsLoader, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER,
&IID_IVdsServiceLoader, (void**)&pLoader);
if (hr != S_OK) {
suprintf("Could not create VDS Loader Instance: %s", VdsErrorString(hr));
return FALSE;
}
hr = IVdsServiceLoader_LoadService(pLoader, L"", &pService);
IVdsServiceLoader_Release(pLoader);
if (hr != S_OK) {
suprintf("Could not load VDS Service: %s", VdsErrorString(hr));
return FALSE;
}
hr = IVdsService_WaitForServiceReady(pService);
if (hr != S_OK) {
suprintf("VDS Service is not ready: %s", VdsErrorString(hr));
return FALSE;
}
// https://docs.microsoft.com/en-us/windows/win32/api/vds/nf-vds-ivdsservice-refresh
// This method synchronizes the disk layout to the layout known to the disk driver.
// It does not force the driver to read the layout from the disk.
// Additionally, this method refreshes the view of all objects in the VDS cache.
if (dwRescanType & VDS_RESCAN_REFRESH) {
hr = IVdsService_Refresh(pService);
if (hr != S_OK) {
suprintf("VDS Refresh failed: %s", VdsErrorString(hr));
ret = FALSE;
}
}
// https://docs.microsoft.com/en-us/windows/win32/api/vds/nf-vds-ivdsservice-reenumerate
// This method returns immediately after a bus rescan request is issued.
// The operation might be incomplete when the method returns.
if (dwRescanType & VDS_RESCAN_REENUMERATE) {
hr = IVdsService_Reenumerate(pService);
if (hr != S_OK) {
suprintf("VDS Re-enumeration failed: %s", VdsErrorString(hr));
ret = FALSE;
}
}
if (dwSleepTime != 0)
Sleep(dwSleepTime);
return ret;
}
/*
* Delete one partition at offset PartitionOffset, or all partitions if the offset is 0.
*/
BOOL DeletePartition(DWORD DriveIndex, ULONGLONG PartitionOffset, BOOL bSilent)
{
HRESULT hr = S_FALSE;
VDS_PARTITION_PROP* prop_array = NULL;
LONG i, prop_array_size;
IVdsAdvancedDisk *pAdvancedDisk = NULL;
if (!GetVdsDiskInterface(DriveIndex, &IID_IVdsAdvancedDisk, (void**)&pAdvancedDisk, bSilent))
return FALSE;
if (pAdvancedDisk == NULL) {
suprintf("Looks like Windows has \"lost\" our disk - Forcing a VDS rescan...");
VdsRescan(VDS_RESCAN_REFRESH | VDS_RESCAN_REENUMERATE, 1000, bSilent);
if (!GetVdsDiskInterface(DriveIndex, &IID_IVdsAdvancedDisk, (void**)&pAdvancedDisk, bSilent) ||
(pAdvancedDisk == NULL)) {
suprintf("Could not locate disk - Aborting.");
return FALSE;
}
}
// Query the partition data, so we can get the start offset, which we need for deletion
hr = IVdsAdvancedDisk_QueryPartitions(pAdvancedDisk, &prop_array, &prop_array_size);
if (hr == S_OK) {
suprintf("Deleting partition%s:", (PartitionOffset == 0) ? "s" : "");
// Now go through each partition
for (i = 0; i < prop_array_size; i++) {
if ((PartitionOffset != 0) && (prop_array[i].ullOffset != PartitionOffset))
continue;
suprintf("● Partition %d (offset: %lld, size: %s)", prop_array[i].ulPartitionNumber,
prop_array[i].ullOffset, SizeToHumanReadable(prop_array[i].ullSize, FALSE, FALSE));
hr = IVdsAdvancedDisk_DeletePartition(pAdvancedDisk, prop_array[i].ullOffset, TRUE, TRUE);
if (hr != S_OK)
suprintf("Could not delete partition: %s", VdsErrorString(hr));
}
} else {
suprintf("No partition to delete on disk");
hr = S_OK;
}
CoTaskMemFree(prop_array);
IVdsAdvancedDisk_Release(pAdvancedDisk);
VDS_SET_ERROR(hr);
return (hr == S_OK);
}
/*
* Count on Microsoft for *COMPLETELY CRIPPLING* an API when allegedly upgrading it...
* As illustrated when you do so with diskpart (which uses VDS behind the scenes), VDS
* simply *DOES NOT* list all the volumes that the system can see, especially compared
* to what mountvol (which uses FindFirstVolume()/FindNextVolume()) and other APIs do.
* Also for reference, if you want to list volumes through WMI in PowerShell:
* Get-WmiObject win32_volume | Format-Table -Property DeviceID,Name,Label,Capacity
*/
BOOL ListVdsVolumes(BOOL bSilent)
{
HRESULT hr = S_FALSE;
ULONG ulFetched;
IVdsServiceLoader* pLoader;
IVdsService* pService;
IEnumVdsObject* pEnum;
IUnknown* pUnk;
// Initialize COM
IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
IGNORE_RETVAL(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL));
// Create a VDS Loader Instance
hr = CoCreateInstance(&CLSID_VdsLoader, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER,
&IID_IVdsServiceLoader, (void**)&pLoader);
if (hr != S_OK) {
suprintf("Could not create VDS Loader Instance: %s", VdsErrorString(hr));
goto out;
}
// Load the VDS Service
hr = IVdsServiceLoader_LoadService(pLoader, L"", &pService);
IVdsServiceLoader_Release(pLoader);
if (hr != S_OK) {
suprintf("Could not load VDS Service: %s", VdsErrorString(hr));
goto out;
}
// Wait for the Service to become ready if needed
hr = IVdsService_WaitForServiceReady(pService);
if (hr != S_OK) {
suprintf("VDS Service is not ready: %s", VdsErrorString(hr));
goto out;
}
// Query the VDS Service Providers
hr = IVdsService_QueryProviders(pService, VDS_QUERY_SOFTWARE_PROVIDERS, &pEnum);
IVdsService_Release(pService);
if (hr != S_OK) {
suprintf("Could not query VDS Service Providers: %s", VdsErrorString(hr));
goto out;
}
while (IEnumVdsObject_Next(pEnum, 1, &pUnk, &ulFetched) == S_OK) {
IVdsProvider* pProvider;
IVdsSwProvider* pSwProvider;
IEnumVdsObject* pEnumPack;
IUnknown* pPackUnk;
// Get VDS Provider
hr = IUnknown_QueryInterface(pUnk, &IID_IVdsProvider, (void**)&pProvider);
IUnknown_Release(pUnk);
if (hr != S_OK) {
suprintf("Could not get VDS Provider: %s", VdsErrorString(hr));
break;
}
// Get VDS Software Provider
hr = IVdsSwProvider_QueryInterface(pProvider, &IID_IVdsSwProvider, (void**)&pSwProvider);
IVdsProvider_Release(pProvider);
if (hr != S_OK) {
suprintf("Could not get VDS Software Provider: %s", VdsErrorString(hr));
break;
}
// Get VDS Software Provider Packs
hr = IVdsSwProvider_QueryPacks(pSwProvider, &pEnumPack);
IVdsSwProvider_Release(pSwProvider);
if (hr != S_OK) {
suprintf("Could not get VDS Software Provider Packs: %s", VdsErrorString(hr));
break;
}
// Enumerate Provider Packs
while (IEnumVdsObject_Next(pEnumPack, 1, &pPackUnk, &ulFetched) == S_OK) {
IVdsPack* pPack;
IEnumVdsObject* pEnumVolume;
IUnknown* pVolumeUnk;
hr = IUnknown_QueryInterface(pPackUnk, &IID_IVdsPack, (void**)&pPack);
IUnknown_Release(pPackUnk);
if (hr != S_OK) {
suprintf("Could not query VDS Software Provider Pack: %s", VdsErrorString(hr));
break;
}
// Use the pack interface to access the disks
hr = IVdsPack_QueryVolumes(pPack, &pEnumVolume);
if (hr != S_OK) {
suprintf("Could not query VDS volumes: %s", VdsErrorString(hr));
break;
}
// List volumes
while (IEnumVdsObject_Next(pEnumVolume, 1, &pVolumeUnk, &ulFetched) == S_OK) {
IVdsVolume* pVolume;
IVdsVolumeMF3* pVolumeMF3;
VDS_VOLUME_PROP prop;
LPWSTR* wszPathArray;
ULONG i, ulNumberOfPaths;
// Get the volume interface.
hr = IUnknown_QueryInterface(pVolumeUnk, &IID_IVdsVolume, (void**)&pVolume);
if (hr != S_OK) {
suprintf("Could not query VDS Volume Interface: %s", VdsErrorString(hr));
break;
}
// Get the volume properties
hr = IVdsVolume_GetProperties(pVolume, &prop);
if ((hr != S_OK) && (hr != VDS_S_PROPERTIES_INCOMPLETE)) {
suprintf("Could not query VDS Volume Properties: %s", VdsErrorString(hr));
break;
}
uprintf("FOUND VOLUME: '%S'", prop.pwszName);
CoTaskMemFree(prop.pwszName);
IVdsVolume_Release(pVolume);
// Get the volume MF3 interface.
hr = IUnknown_QueryInterface(pVolumeUnk, &IID_IVdsVolumeMF3, (void**)&pVolumeMF3);
if (hr != S_OK) {
suprintf("Could not query VDS VolumeMF3 Interface: %s", VdsErrorString(hr));
break;
}
// Get the volume properties
hr = IVdsVolumeMF3_QueryVolumeGuidPathnames(pVolumeMF3, &wszPathArray, &ulNumberOfPaths);
if ((hr != S_OK) && (hr != VDS_S_PROPERTIES_INCOMPLETE)) {
suprintf("Could not query VDS VolumeMF3 GUID PathNames: %s", VdsErrorString(hr));
break;
}
hr = S_OK;
for (i = 0; i < ulNumberOfPaths; i++)
uprintf(" VOL GUID: '%S'", wszPathArray[i]);
CoTaskMemFree(wszPathArray);
IVdsVolume_Release(pVolumeMF3);
IUnknown_Release(pVolumeUnk);
}
IEnumVdsObject_Release(pEnumVolume);
}
IEnumVdsObject_Release(pEnumPack);
}
IEnumVdsObject_Release(pEnum);
out:
VDS_SET_ERROR(hr);
return (hr == S_OK);
}
/* Wait for a logical drive to reappear - Used when a drive has just been repartitioned */
BOOL WaitForLogical(DWORD DriveIndex, uint64_t PartitionOffset)
{
uint64_t EndTime;
char* LogicalPath = NULL;
// GetLogicalName() calls may be slow, so use the system time to
// make sure we don't spend more than DRIVE_ACCESS_TIMEOUT in wait.
EndTime = GetTickCount64() + DRIVE_ACCESS_TIMEOUT;