-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWin32HDSN.h
1458 lines (1200 loc) · 44 KB
/
Win32HDSN.h
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
#ifndef _PikaCRM_Win32HDSN_h_
#define _PikaCRM_Win32HDSN_h_
//#define PRINTING_TO_CONSOLE_ALLOWED
#include <cstdio>
#include <windows.h>
#include <winioctl.h>
#include <cctype>
char HardDriveSerialNumber [1024];
char HardDriveModelNumber [1024];
int PRINT_DEBUG = false;
static void dump_buffer (const char* title,
const unsigned char* buffer,
int len)
{
int i = 0;
int j;
printf ("\n-- %s --\n", title);
if (len > 0)
{
printf ("%8.8s ", " ");
for (j = 0; j < 16; ++j)
{
printf (" %2X", j);
}
printf (" ");
for (j = 0; j < 16; ++j)
{
printf ("%1X", j);
}
printf ("\n");
}
while (i < len)
{
printf("%08x ", i);
for (j = 0; j < 16; ++j)
{
if ((i + j) < len)
printf (" %02x", (int) buffer[i +j]);
else
printf (" ");
}
printf (" ");
for (j = 0; j < 16; ++j)
{
if ((i + j) < len)
printf ("%c", isprint (buffer[i + j]) ? buffer [i + j] : '.');
else
printf (" ");
}
printf ("\n");
i += 16;
}
printf ("-- DONE --\n");
}
void WriteConstantString (const char *entry, const char *string)
{
}
// Required to ensure correct PhysicalDrive IOCTL structure setup
#pragma pack(1)
#define IDENTIFY_BUFFER_SIZE 512
// IOCTL commands
#define DFP_GET_VERSION 0x00074080
#define DFP_SEND_DRIVE_COMMAND 0x0007c084
#define DFP_RECEIVE_DRIVE_DATA 0x0007c088
#define FILE_DEVICE_SCSI 0x0000001b
#define IOCTL_SCSI_MINIPORT_IDENTIFY ((FILE_DEVICE_SCSI << 16) + 0x0501)
#define IOCTL_SCSI_MINIPORT 0x0004D008 // see NTDDSCSI.H for definition
#define SMART_GET_VERSION CTL_CODE(IOCTL_DISK_BASE, 0x0020, METHOD_BUFFERED, FILE_READ_ACCESS)
#define SMART_SEND_DRIVE_COMMAND CTL_CODE(IOCTL_DISK_BASE, 0x0021, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define SMART_RCV_DRIVE_DATA CTL_CODE(IOCTL_DISK_BASE, 0x0022, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
typedef struct _GETVERSIONINPARAMS {
UCHAR bVersion; // Binary driver version.
UCHAR bRevision; // Binary driver revision.
UCHAR bReserved; // Not used.
UCHAR bIDEDeviceMap; // Bit map of IDE devices.
ULONG fCapabilities; // Bit mask of driver capabilities.
ULONG dwReserved[4]; // For future use.
} GETVERSIONINPARAMS, *PGETVERSIONINPARAMS, *LPGETVERSIONINPARAMS;
// GETVERSIONOUTPARAMS contains the data returned from the
// Get Driver Version function.
typedef struct _GETVERSIONOUTPARAMS
{
BYTE bVersion; // Binary driver version.
BYTE bRevision; // Binary driver revision.
BYTE bReserved; // Not used.
BYTE bIDEDeviceMap; // Bit map of IDE devices.
DWORD fCapabilities; // Bit mask of driver capabilities.
DWORD dwReserved[4]; // For future use.
} GETVERSIONOUTPARAMS, *PGETVERSIONOUTPARAMS, *LPGETVERSIONOUTPARAMS;
// Bits returned in the fCapabilities member of GETVERSIONOUTPARAMS
#define CAP_IDE_ID_FUNCTION 1 // ATA ID command supported
#define CAP_IDE_ATAPI_ID 2 // ATAPI ID command supported
#define CAP_IDE_EXECUTE_SMART_FUNCTION 4 // SMART commannds supported
// IDE registers
typedef struct _IDEREGS
{
BYTE bFeaturesReg; // Used for specifying SMART "commands".
BYTE bSectorCountReg; // IDE sector count register
BYTE bSectorNumberReg; // IDE sector number register
BYTE bCylLowReg; // IDE low order cylinder value
BYTE bCylHighReg; // IDE high order cylinder value
BYTE bDriveHeadReg; // IDE drive/head register
BYTE bCommandReg; // Actual IDE command.
BYTE bReserved; // reserved for future use. Must be zero.
} IDEREGS, *PIDEREGS, *LPIDEREGS;
// SENDCMDINPARAMS contains the input parameters for the
// Send Command to Drive function.
typedef struct _SENDCMDINPARAMS
{
DWORD cBufferSize; // Buffer size in bytes
IDEREGS irDriveRegs; // Structure with drive register values.
BYTE bDriveNumber; // Physical drive number to send
// command to (0,1,2,3).
BYTE bReserved[3]; // Reserved for future expansion.
DWORD dwReserved[4]; // For future use.
BYTE bBuffer[1]; // Input buffer.
} SENDCMDINPARAMS, *PSENDCMDINPARAMS, *LPSENDCMDINPARAMS;
// Valid values for the bCommandReg member of IDEREGS.
#define IDE_ATAPI_IDENTIFY 0xA1 // Returns ID sector for ATAPI.
#define IDE_ATA_IDENTIFY 0xEC // Returns ID sector for ATA.
// Status returned from driver
typedef struct _DRIVERSTATUS
{
BYTE bDriverError; // Error code from driver, or 0 if no error.
BYTE bIDEStatus; // Contents of IDE Error register.
// Only valid when bDriverError is SMART_IDE_ERROR.
BYTE bReserved[2]; // Reserved for future expansion.
DWORD dwReserved[2]; // Reserved for future expansion.
} DRIVERSTATUS, *PDRIVERSTATUS, *LPDRIVERSTATUS;
// Structure returned by PhysicalDrive IOCTL for several commands
typedef struct _SENDCMDOUTPARAMS
{
DWORD cBufferSize; // Size of bBuffer in bytes
DRIVERSTATUS DriverStatus; // Driver status structure.
BYTE bBuffer[1]; // Buffer of arbitrary length in which to store the data read from the // drive.
} SENDCMDOUTPARAMS, *PSENDCMDOUTPARAMS, *LPSENDCMDOUTPARAMS;
// The following struct defines the interesting part of the IDENTIFY
// buffer:
typedef struct _IDSECTOR
{
USHORT wGenConfig;
USHORT wNumCyls;
USHORT wReserved;
USHORT wNumHeads;
USHORT wBytesPerTrack;
USHORT wBytesPerSector;
USHORT wSectorsPerTrack;
USHORT wVendorUnique[3];
CHAR sSerialNumber[20];
USHORT wBufferType;
USHORT wBufferSize;
USHORT wECCSize;
CHAR sFirmwareRev[8];
CHAR sModelNumber[40];
USHORT wMoreVendorUnique;
USHORT wDoubleWordIO;
USHORT wCapabilities;
USHORT wReserved1;
USHORT wPIOTiming;
USHORT wDMATiming;
USHORT wBS;
USHORT wNumCurrentCyls;
USHORT wNumCurrentHeads;
USHORT wNumCurrentSectorsPerTrack;
ULONG ulCurrentSectorCapacity;
USHORT wMultSectorStuff;
ULONG ulTotalAddressableSectors;
USHORT wSingleWordDMA;
USHORT wMultiWordDMA;
BYTE bReserved[128];
} IDSECTOR, *PIDSECTOR;
typedef struct _SRB_IO_CONTROL
{
ULONG HeaderLength;
UCHAR Signature[8];
ULONG Timeout;
ULONG ControlCode;
ULONG ReturnCode;
ULONG Length;
} SRB_IO_CONTROL, *PSRB_IO_CONTROL;
// Define global buffers.
BYTE IdOutCmd [sizeof (SENDCMDOUTPARAMS) + IDENTIFY_BUFFER_SIZE - 1];
char *ConvertToString (DWORD diskdata [256],
int firstIndex,
int lastIndex,
char* buf);
void PrintIdeInfo (int drive, DWORD diskdata [256]);
BOOL DoIDENTIFY (HANDLE, PSENDCMDINPARAMS, PSENDCMDOUTPARAMS, BYTE, BYTE,
PDWORD);
// Max number of drives assuming primary/secondary, master/slave topology
#define MAX_IDE_DRIVES 16
int ReadPhysicalDriveInNTWithAdminRights (int drive)
{
int done = FALSE;
//int drive = 0;
//for (drive = 0; drive < MAX_IDE_DRIVES; drive++)
{
HANDLE hPhysicalDriveIOCTL = 0;
// Try to get a handle to PhysicalDrive IOCTL, report failure
// and exit if can't.
char driveName [256];
sprintf (driveName, "\\\\.\\PhysicalDrive%d", drive);
// Windows NT, Windows 2000, must have admin rights
hPhysicalDriveIOCTL = CreateFile (driveName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE , NULL,
OPEN_EXISTING, 0, NULL);
// if (hPhysicalDriveIOCTL == INVALID_HANDLE_VALUE)
// printf ("Unable to open physical drive %d, error code: 0x%lX\n",
// drive, GetLastError ());
if (hPhysicalDriveIOCTL == INVALID_HANDLE_VALUE)
{
#ifdef PRINTING_TO_CONSOLE_ALLOWED
if (PRINT_DEBUG)
printf ("\n%d ReadPhysicalDriveInNTWithAdminRights ERROR"
"\nCreateFile(%s) returned INVALID_HANDLE_VALUE\n",
__LINE__, driveName);
#endif
}
else
{
GETVERSIONOUTPARAMS VersionParams;
DWORD cbBytesReturned = 0;
// Get the version, etc of PhysicalDrive IOCTL
memset ((void*) &VersionParams, 0, sizeof(VersionParams));
if ( ! DeviceIoControl (hPhysicalDriveIOCTL, DFP_GET_VERSION,
NULL,
0,
&VersionParams,
sizeof(VersionParams),
&cbBytesReturned, NULL) )
{
#ifdef PRINTING_TO_CONSOLE_ALLOWED
if (PRINT_DEBUG)
{
DWORD err = GetLastError ();
printf ("\n%d ReadPhysicalDriveInNTWithAdminRights ERROR"
"\nDeviceIoControl(%d, DFP_GET_VERSION) returned 0, error is %d\n",
__LINE__, (int) hPhysicalDriveIOCTL, (int) err);
}
#endif
}
// If there is a IDE device at number "i" issue commands
// to the device
if (VersionParams.bIDEDeviceMap <= 0)
{
#ifdef PRINTING_TO_CONSOLE_ALLOWED
if (PRINT_DEBUG)
printf ("\n%d ReadPhysicalDriveInNTWithAdminRights ERROR"
"\nNo device found at position %d (%d)\n",
__LINE__, (int) drive, (int) VersionParams.bIDEDeviceMap);
#endif
}
else
{
BYTE bIDCmd = 0; // IDE or ATAPI IDENTIFY cmd
SENDCMDINPARAMS scip;
//SENDCMDOUTPARAMS OutCmd;
// Now, get the ID sector for all IDE devices in the system.
// If the device is ATAPI use the IDE_ATAPI_IDENTIFY command,
// otherwise use the IDE_ATA_IDENTIFY command
bIDCmd = (VersionParams.bIDEDeviceMap >> drive & 0x10) ? \
IDE_ATAPI_IDENTIFY : IDE_ATA_IDENTIFY;
memset (&scip, 0, sizeof(scip));
memset (IdOutCmd, 0, sizeof(IdOutCmd));
if ( DoIDENTIFY (hPhysicalDriveIOCTL,
&scip,
(PSENDCMDOUTPARAMS)&IdOutCmd,
(BYTE) bIDCmd,
(BYTE) drive,
&cbBytesReturned))
{
DWORD diskdata [256];
int ijk = 0;
USHORT *pIdSector = (USHORT *)
((PSENDCMDOUTPARAMS) IdOutCmd) -> bBuffer;
for (ijk = 0; ijk < 256; ijk++)
diskdata [ijk] = pIdSector [ijk];
PrintIdeInfo (drive, diskdata);
done = TRUE;
}
}
CloseHandle (hPhysicalDriveIOCTL);
}
}
return done;
}
//
// IDENTIFY data (from ATAPI driver source)
//
#pragma pack(1)
typedef struct _IDENTIFY_DATA {
USHORT GeneralConfiguration; // 00 00
USHORT NumberOfCylinders; // 02 1
USHORT Reserved1; // 04 2
USHORT NumberOfHeads; // 06 3
USHORT UnformattedBytesPerTrack; // 08 4
USHORT UnformattedBytesPerSector; // 0A 5
USHORT SectorsPerTrack; // 0C 6
USHORT VendorUnique1[3]; // 0E 7-9
USHORT SerialNumber[10]; // 14 10-19
USHORT BufferType; // 28 20
USHORT BufferSectorSize; // 2A 21
USHORT NumberOfEccBytes; // 2C 22
USHORT FirmwareRevision[4]; // 2E 23-26
USHORT ModelNumber[20]; // 36 27-46
UCHAR MaximumBlockTransfer; // 5E 47
UCHAR VendorUnique2; // 5F
USHORT DoubleWordIo; // 60 48
USHORT Capabilities; // 62 49
USHORT Reserved2; // 64 50
UCHAR VendorUnique3; // 66 51
UCHAR PioCycleTimingMode; // 67
UCHAR VendorUnique4; // 68 52
UCHAR DmaCycleTimingMode; // 69
USHORT TranslationFieldsValid:1; // 6A 53
USHORT Reserved3:15;
USHORT NumberOfCurrentCylinders; // 6C 54
USHORT NumberOfCurrentHeads; // 6E 55
USHORT CurrentSectorsPerTrack; // 70 56
ULONG CurrentSectorCapacity; // 72 57-58
USHORT CurrentMultiSectorSetting; // 59
ULONG UserAddressableSectors; // 60-61
USHORT SingleWordDMASupport : 8; // 62
USHORT SingleWordDMAActive : 8;
USHORT MultiWordDMASupport : 8; // 63
USHORT MultiWordDMAActive : 8;
USHORT AdvancedPIOModes : 8; // 64
USHORT Reserved4 : 8;
USHORT MinimumMWXferCycleTime; // 65
USHORT RecommendedMWXferCycleTime; // 66
USHORT MinimumPIOCycleTime; // 67
USHORT MinimumPIOCycleTimeIORDY; // 68
USHORT Reserved5[2]; // 69-70
USHORT ReleaseTimeOverlapped; // 71
USHORT ReleaseTimeServiceCommand; // 72
USHORT MajorRevision; // 73
USHORT MinorRevision; // 74
USHORT Reserved6[50]; // 75-126
USHORT SpecialFunctionsEnabled; // 127
USHORT Reserved7[128]; // 128-255
} IDENTIFY_DATA, *PIDENTIFY_DATA;
#pragma pack()
int ReadPhysicalDriveInNTUsingSmart (int drive)
{
int done = FALSE;
//int drive = 0;
//for (drive = 0; drive < MAX_IDE_DRIVES; drive++)
{
HANDLE hPhysicalDriveIOCTL = 0;
// Try to get a handle to PhysicalDrive IOCTL, report failure
// and exit if can't.
char driveName [256];
sprintf (driveName, "\\\\.\\PhysicalDrive%d", drive);
// Windows NT, Windows 2000, Windows Server 2003, Vista
hPhysicalDriveIOCTL = CreateFile (driveName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
// if (hPhysicalDriveIOCTL == INVALID_HANDLE_VALUE)
// printf ("Unable to open physical drive %d, error code: 0x%lX\n",
// drive, GetLastError ());
if (hPhysicalDriveIOCTL == INVALID_HANDLE_VALUE)
{
#ifdef PRINTING_TO_CONSOLE_ALLOWED
if (PRINT_DEBUG)
printf ("\n%d ReadPhysicalDriveInNTUsingSmart ERROR"
"\nCreateFile(%s) returned INVALID_HANDLE_VALUE\n"
"Error Code %d\n",
__LINE__, driveName, GetLastError ());
#endif
}
else
{
GETVERSIONINPARAMS GetVersionParams;
DWORD cbBytesReturned = 0;
// Get the version, etc of PhysicalDrive IOCTL
memset ((void*) & GetVersionParams, 0, sizeof(GetVersionParams));
if ( ! DeviceIoControl (hPhysicalDriveIOCTL, SMART_GET_VERSION,
NULL,
0,
&GetVersionParams, sizeof (GETVERSIONINPARAMS),
&cbBytesReturned, NULL) )
{
#ifdef PRINTING_TO_CONSOLE_ALLOWED
if (PRINT_DEBUG)
{
DWORD err = GetLastError ();
printf ("\n%d ReadPhysicalDriveInNTUsingSmart ERROR"
"\nDeviceIoControl(%d, SMART_GET_VERSION) returned 0, error is %d\n",
__LINE__, (int) hPhysicalDriveIOCTL, (int) err);
}
#endif
}
else
{
// Print the SMART version
// PrintVersion (& GetVersionParams);
// Allocate the command buffer
ULONG CommandSize = sizeof(SENDCMDINPARAMS) + IDENTIFY_BUFFER_SIZE;
PSENDCMDINPARAMS Command = (PSENDCMDINPARAMS) malloc (CommandSize);
// Retrieve the IDENTIFY data
// Prepare the command
#define ID_CMD 0xEC // Returns ID sector for ATA
Command -> irDriveRegs.bCommandReg = ID_CMD;
DWORD BytesReturned = 0;
if ( ! DeviceIoControl (hPhysicalDriveIOCTL,
SMART_RCV_DRIVE_DATA, Command, sizeof(SENDCMDINPARAMS),
Command, CommandSize,
&BytesReturned, NULL) )
{
// Print the error
//PrintError ("SMART_RCV_DRIVE_DATA IOCTL", GetLastError());
}
else
{
// Print the IDENTIFY data
DWORD diskdata [256];
USHORT *pIdSector = (USHORT *)
(PIDENTIFY_DATA) ((PSENDCMDOUTPARAMS) Command) -> bBuffer;
for (int ijk = 0; ijk < 256; ijk++)
diskdata [ijk] = pIdSector [ijk];
PrintIdeInfo (drive, diskdata);
done = TRUE;
}
// Done
CloseHandle (hPhysicalDriveIOCTL);
free (Command);
}
}
}
return done;
}
// Required to ensure correct PhysicalDrive IOCTL structure setup
#pragma pack(4)
//
// IOCTL_STORAGE_QUERY_PROPERTY
//
// Input Buffer:
// a STORAGE_PROPERTY_QUERY structure which describes what type of query
// is being done, what property is being queried for, and any additional
// parameters which a particular property query requires.
//
// Output Buffer:
// Contains a buffer to place the results of the query into. Since all
// property descriptors can be cast into a STORAGE_DESCRIPTOR_HEADER,
// the IOCTL can be called once with a small buffer then again using
// a buffer as large as the header reports is necessary.
//
//
// Types of queries
//
typedef enum _STORAGE_QUERY_TYPE {
PropertyStandardQuery = 0, // Retrieves the descriptor
PropertyExistsQuery, // Used to test whether the descriptor is supported
PropertyMaskQuery, // Used to retrieve a mask of writeable fields in the descriptor
PropertyQueryMaxDefined // use to validate the value
} STORAGE_QUERY_TYPE, *PSTORAGE_QUERY_TYPE;
//
// define some initial property id's
//
typedef enum _STORAGE_PROPERTY_ID {
StorageDeviceProperty = 0,
StorageAdapterProperty
} STORAGE_PROPERTY_ID, *PSTORAGE_PROPERTY_ID;
//
// Query structure - additional parameters for specific queries can follow
// the header
//
typedef struct _STORAGE_PROPERTY_QUERY {
//
// ID of the property being retrieved
//
STORAGE_PROPERTY_ID PropertyId;
//
// Flags indicating the type of query being performed
//
STORAGE_QUERY_TYPE QueryType;
//
// Space for additional parameters if necessary
//
UCHAR AdditionalParameters[1];
} STORAGE_PROPERTY_QUERY, *PSTORAGE_PROPERTY_QUERY;
#define IOCTL_STORAGE_QUERY_PROPERTY CTL_CODE(IOCTL_STORAGE_BASE, 0x0500, METHOD_BUFFERED, FILE_ANY_ACCESS)
//
// Device property descriptor - this is really just a rehash of the inquiry
// data retrieved from a scsi device
//
// This may only be retrieved from a target device. Sending this to the bus
// will result in an error
//
#pragma pack(4)
typedef struct _STORAGE_DEVICE_DESCRIPTOR {
//
// Sizeof(STORAGE_DEVICE_DESCRIPTOR)
//
ULONG Version;
//
// Total size of the descriptor, including the space for additional
// data and id strings
//
ULONG Size;
//
// The SCSI-2 device type
//
UCHAR DeviceType;
//
// The SCSI-2 device type modifier (if any) - this may be zero
//
UCHAR DeviceTypeModifier;
//
// Flag indicating whether the device's media (if any) is removable. This
// field should be ignored for media-less devices
//
BOOLEAN RemovableMedia;
//
// Flag indicating whether the device can support mulitple outstanding
// commands. The actual synchronization in this case is the responsibility
// of the port driver.
//
BOOLEAN CommandQueueing;
//
// Byte offset to the zero-terminated ascii string containing the device's
// vendor id string. For devices with no such ID this will be zero
//
ULONG VendorIdOffset;
//
// Byte offset to the zero-terminated ascii string containing the device's
// product id string. For devices with no such ID this will be zero
//
ULONG ProductIdOffset;
//
// Byte offset to the zero-terminated ascii string containing the device's
// product revision string. For devices with no such string this will be
// zero
//
ULONG ProductRevisionOffset;
//
// Byte offset to the zero-terminated ascii string containing the device's
// serial number. For devices with no serial number this will be zero
//
ULONG SerialNumberOffset;
//
// Contains the bus type (as defined above) of the device. It should be
// used to interpret the raw device properties at the end of this structure
// (if any)
//
typedef enum _STORAGE_BUS_TYPE {
BusTypeUnknown = 0x00,
BusTypeScsi = 0x01,
BusTypeAtapi = 0x02,
BusTypeAta = 0x03,
BusType1394 = 0x04,
BusTypeSsa = 0x05,
BusTypeFibre = 0x06,
BusTypeUsb = 0x07,
BusTypeRAID = 0x08,
BusTypeiSCSI = 0x09,
BusTypeSas = 0x0A,
BusTypeSata = 0x0B,
BusTypeMaxReserved = 0x7F
} STORAGE_BUS_TYPE, *PSTORAGE_BUS_TYPE;
STORAGE_BUS_TYPE BusType;
//
// The number of bytes of bus-specific data which have been appended to
// this descriptor
//
ULONG RawPropertiesLength;
//
// Place holder for the first byte of the bus specific property data
//
UCHAR RawDeviceProperties[1];
} STORAGE_DEVICE_DESCRIPTOR, *PSTORAGE_DEVICE_DESCRIPTOR;
#pragma pack()
// function to decode the serial numbers of IDE hard drives
// using the IOCTL_STORAGE_QUERY_PROPERTY command
char * flipAndCodeBytes (const char * str,
int pos,
int flip,
char * buf)
{
int i;
int j = 0;
int k = 0;
buf [0] = '\0';
if (pos <= 0)
return buf;
if ( ! j)
{
char p = 0;
// First try to gather all characters representing hex digits only.
j = 1;
k = 0;
buf[k] = 0;
for (i = pos; j && str[i] != '\0'; ++i)
{
char c = tolower(str[i]);
if (isspace(c))
c = '0';
++p;
buf[k] <<= 4;
if (c >= '0' && c <= '9')
buf[k] |= (unsigned char) (c - '0');
else if (c >= 'a' && c <= 'f')
buf[k] |= (unsigned char) (c - 'a' + 10);
else
{
j = 0;
break;
}
if (p == 2)
{
if (buf[k] != '\0' && ! isprint(buf[k]))
{
j = 0;
break;
}
++k;
p = 0;
buf[k] = 0;
}
}
}
if ( ! j)
{
// There are non-digit characters, gather them as is.
j = 1;
k = 0;
for (i = pos; j && str[i] != '\0'; ++i)
{
char c = str[i];
if ( ! isprint(c))
{
j = 0;
break;
}
buf[k++] = c;
}
}
if ( ! j)
{
// The characters are not there or are not printable.
k = 0;
}
buf[k] = '\0';
if (flip)
// Flip adjacent characters
for (j = 0; j < k; j += 2)
{
char t = buf[j];
buf[j] = buf[j + 1];
buf[j + 1] = t;
}
// Trim any beginning and end space
i = j = -1;
for (k = 0; buf[k] != '\0'; ++k)
{
if (! isspace(buf[k]))
{
if (i < 0)
i = k;
j = k;
}
}
if ((i >= 0) && (j >= 0))
{
for (k = i; (k <= j) && (buf[k] != '\0'); ++k)
buf[k - i] = buf[k];
buf[k - i] = '\0';
}
return buf;
}
int ReadPhysicalDriveInNTWithZeroRights (int drive)
{
int done = FALSE;
//int drive = 0;
//for (drive = 0; drive < MAX_IDE_DRIVES; drive++)
{
HANDLE hPhysicalDriveIOCTL = 0;
// Try to get a handle to PhysicalDrive IOCTL, report failure
// and exit if can't.
char driveName [256];
sprintf (driveName, "\\\\.\\PhysicalDrive%d", drive);
// Windows NT, Windows 2000, Windows XP - admin rights not required
hPhysicalDriveIOCTL = CreateFile (driveName, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, 0, NULL);
if (hPhysicalDriveIOCTL == INVALID_HANDLE_VALUE)
{
#ifdef PRINTING_TO_CONSOLE_ALLOWED
if (PRINT_DEBUG)
printf ("\n%d ReadPhysicalDriveInNTWithZeroRights ERROR"
"\nCreateFile(%s) returned INVALID_HANDLE_VALUE\n",
__LINE__, driveName);
#endif
}
else
{
STORAGE_PROPERTY_QUERY query;
DWORD cbBytesReturned = 0;
char buffer [10000];
memset ((void *) & query, 0, sizeof (query));
query.PropertyId = StorageDeviceProperty;
query.QueryType = PropertyStandardQuery;
memset (buffer, 0, sizeof (buffer));
if ( DeviceIoControl (hPhysicalDriveIOCTL, IOCTL_STORAGE_QUERY_PROPERTY,
& query,
sizeof (query),
& buffer,
sizeof (buffer),
& cbBytesReturned, NULL) )
{
STORAGE_DEVICE_DESCRIPTOR * descrip = (STORAGE_DEVICE_DESCRIPTOR *) & buffer;
char serialNumber [1000];
char modelNumber [1000];
char vendorId [1000];
char productRevision [1000];
#ifdef PRINTING_TO_CONSOLE_ALLOWED
if (PRINT_DEBUG)
{
printf ("\n%d STORAGE_DEVICE_DESCRIPTOR contents for drive %d\n"
" Version: %ld\n"
" Size: %ld\n"
" DeviceType: %02x\n"
" DeviceTypeModifier: %02x\n"
" RemovableMedia: %d\n"
" CommandQueueing: %d\n"
" VendorIdOffset: %4ld (0x%02lx)\n"
" ProductIdOffset: %4ld (0x%02lx)\n"
" ProductRevisionOffset: %4ld (0x%02lx)\n"
" SerialNumberOffset: %4ld (0x%02lx)\n"
" BusType: %d\n"
" RawPropertiesLength: %ld\n",
__LINE__, drive,
(unsigned long) descrip->Version,
(unsigned long) descrip->Size,
(int) descrip->DeviceType,
(int) descrip->DeviceTypeModifier,
(int) descrip->RemovableMedia,
(int) descrip->CommandQueueing,
(unsigned long) descrip->VendorIdOffset,
(unsigned long) descrip->VendorIdOffset,
(unsigned long) descrip->ProductIdOffset,
(unsigned long) descrip->ProductIdOffset,
(unsigned long) descrip->ProductRevisionOffset,
(unsigned long) descrip->ProductRevisionOffset,
(unsigned long) descrip->SerialNumberOffset,
(unsigned long) descrip->SerialNumberOffset,
(int) descrip->BusType,
(unsigned long) descrip->RawPropertiesLength);
dump_buffer ("Contents of RawDeviceProperties",
(unsigned char*) descrip->RawDeviceProperties,
descrip->RawPropertiesLength);
dump_buffer ("Contents of first 256 bytes in buffer",
(unsigned char*) buffer, 256);
}
#endif
flipAndCodeBytes (buffer,
descrip -> VendorIdOffset,
0, vendorId );
flipAndCodeBytes (buffer,
descrip -> ProductIdOffset,
0, modelNumber );
flipAndCodeBytes (buffer,
descrip -> ProductRevisionOffset,
0, productRevision );
flipAndCodeBytes (buffer,
descrip -> SerialNumberOffset,
1, serialNumber );
if (0 == HardDriveSerialNumber [0] &&
// serial number must be alphanumeric
// (but there can be leading spaces on IBM drives)
(isalnum (serialNumber [0]) || isalnum (serialNumber [19])))
{
strcpy (HardDriveSerialNumber, serialNumber);
strcpy (HardDriveModelNumber, modelNumber);
done = TRUE;
}
#ifdef PRINTING_TO_CONSOLE_ALLOWED
printf ("\n**** STORAGE_DEVICE_DESCRIPTOR for drive %d ****\n"
"Vendor Id = [%s]\n"
"Product Id = [%s]\n"
"Product Revision = [%s]\n"
"Serial Number = [%s]\n",
drive,
vendorId,
modelNumber,
productRevision,
serialNumber);
#endif
// Get the disk drive geometry.
memset (buffer, 0, sizeof(buffer));
if ( ! DeviceIoControl (hPhysicalDriveIOCTL,
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
NULL,
0,
&buffer,
sizeof(buffer),
&cbBytesReturned,
NULL))
{
#ifdef PRINTING_TO_CONSOLE_ALLOWED
if (PRINT_DEBUG)
printf ("\n%d ReadPhysicalDriveInNTWithZeroRights ERROR"
"|nDeviceIoControl(%s, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX) returned 0",
driveName);
#endif
}
else
{
DISK_GEOMETRY_EX* geom = (DISK_GEOMETRY_EX*) &buffer;
int fixed = (geom->Geometry.MediaType == FixedMedia);
__int64 size = geom->DiskSize.QuadPart;
#ifdef PRINTING_TO_CONSOLE_ALLOWED
printf ("\n**** DISK_GEOMETRY_EX for drive %d ****\n"
"Disk is%s fixed\n"
"DiskSize = %I64d\n",
drive,
fixed ? "" : " NOT",
size);
#endif
}
}
else
{
DWORD err = GetLastError ();
#ifdef PRINTING_TO_CONSOLE_ALLOWED
printf ("\nDeviceIOControl IOCTL_STORAGE_QUERY_PROPERTY error = %d\n", err);
#endif
}