-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathomapi-devicefinder-win.cpp
More file actions
1744 lines (1443 loc) · 63.2 KB
/
Copy pathomapi-devicefinder-win.cpp
File metadata and controls
1744 lines (1443 loc) · 63.2 KB
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
/*
* Copyright (c) 2009-, Newcastle University, UK.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// Open Movement API - Device Discovery (Windows)
// Dan Jackson, 2011-
#ifdef _WIN32 // || defined(__CYGWIN__)
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#define _WIN32_DCOM
#include <comdef.h>
#include <wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
#include <setupapi.h>
#include <winioctl.h>
#include <cfgmgr32.h>
#pragma comment(lib, "setupapi.lib")
#pragma comment(lib, "advapi32.lib") // For RegQueryValueEx()
//#pragma comment(lib, "gdi32.lib") // For CreateSolidBrush()
#include <dbt.h>
#include <tchar.h>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <set>
#include <list>
#include <string>
#include <map>
using namespace std;
#define DEBUG_PRINT
class Device
{
public:
std::string usb; // Unique PNP prefix, e.g. "USB\VID_04D8&PID_0057\7&91737B1&0"
std::string port; // Serial port device name, e.g. "\\.\COM98"
std::string usbStor; // USBSTOR identifier, e.g. "USBSTOR\DISK&VEN_CWA&PROD_CWA_MASS_STORAGE&REV_0017\8&1A780901&0&CWA17_65535&0"
std::string usbComposite; // USB composite device ID
unsigned int deviceNumber; // Device number, e.g. 1
std::string physicalVolume; // e.g. "\Device\HarddiskVolume105"
std::string volumeName; // e.g. "\\?\Volume{377c1972-0fbb-11e1-98fc-0024bed79d50}\"
std::string volumePath; // e.g. "E:\"
std::string serialString; // Parent composite device serial number, e.g. "CWA17_00123"
unsigned int serialNumber; // Serial number, e.g. 123
std::string ToString();
bool operator==(const Device &other) const;
bool operator!=(const Device &other) const { return !(*this == other); }
};
typedef void(*DeviceFinderCallback)(void *, const Device &);
class DeviceFinder
{
public:
// Constructs a DeviceFinder with the specified vendor id and product id
DeviceFinder(unsigned int vidPid);
// Destructs the DeviceFinder
~DeviceFinder();
// Some VID/PID identifiers
static const unsigned int VID_PID_CWA = 0x04D80057; // VID/PID for CWA Composite Device
static const unsigned int VID_PID_WAX = 0x04D8000A; // VID/PID for WAX CDC Device
// Macros to construct/destruct a single vid/pid identifier
#define VID_PID(vid, pid) ((((unsigned int)(vid)) << 16) | (unsigned short)(pid))
#define VID(id) ((unsigned short)((id) >> 16))
#define PID(id) ((unsigned short)(id))
// Discovery loop
bool Start(bool continuous, DeviceFinderCallback addedCallback, DeviceFinderCallback removedCallback, void *callbackReference);
void Stop(void);
// (Usually internal)
bool Initialize(void);
bool Uninitialize(void);
bool FindDevices(std::list<Device>& devices);
bool InitialScanDevices(void);
bool RescanDevices(void);
std::map<int, Device> deviceMap;
// (private)
unsigned int DiscoveryLoop(void);
long long WinProc(void *windowHandle, unsigned int message, unsigned long long wParam, long long lParam);
private:
// (Usually internal) method to perform searches
static bool MappingUsbToPort(unsigned int vidPid, std::map<std::string, std::string>& usbToPortMap);
static bool MappingUsbToUsbstorAndUsbComposite(unsigned int vidPid, std::map<std::string, std::string>& usbToUsbstorMap, std::map<std::string, std::string>& usbToUsbComposite);
bool MappingUsbstorToDeviceNumber(std::map<std::string, int>& usbStorToDeviceMap);
static bool MappingDeviceNumberToPhysicalVolume(std::map<int, std::string>& deviceNumberToPhysicalVolumeMap);
static bool MappingPhysicalVolumeToVolumeName(std::map<std::string, std::string>& physicalVolumeToVolumeNameMap);
static std::string GetVolumePathForVolumeName(std::string volumeName);
static std::string GetUniquePart(std::string id);
static unsigned int GetDeviceNumber(wchar_t *devicePath);
// General
bool initialized;
unsigned int vidPid; // USB vendor id & product id
// Device discovery
volatile bool quitFlag; // Thread termination flag
void *thread; // HANDLE
void *pLoc; // IWbemLocator
void *pSvc; // IWbemServices
void *hWndDeviceFinder; // HWND
void *hDeviceNotify; // HDEVNOTIFY
int timerUpdateCountdown;
// Callback
DeviceFinderCallback addedCallback;
DeviceFinderCallback removedCallback;
void *callbackReference;
};
// NOTE: Finding the pairs of CDC and MSD instances, together with their composite parent device serial number,
// is quite a mess on Windows. This file is still a complete mess from getting it working!
// TODO: The big messy mixture of char strings, wchar_t strings, std::string, etc. needs a lot of tidying up!
#if 1
extern "C" int OmLog(int level, const char *format, ...);
#define Log(level, ...) OmLog(level, __VA_ARGS__)
#else
#define Log(level, ...) ((level), fprintf(stderr, __VA_ARGS__))
#endif
// Utility function
static const char *GetLastErrorString()
{
static char lastError[1024];
lastError[0] = '\0';
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lastError, 1024, NULL);
return lastError;
}
std::string Device::ToString()
{
std::string returnValue;
returnValue += "[";
returnValue += serialNumber;
returnValue += ": ";
returnValue += port;
returnValue += " / ";
returnValue += volumePath;
returnValue += "]";
return returnValue;
}
bool Device::operator==(const Device &other) const
{
return this->usb == other.usb
&& this->port == other.port
&& this->usbStor == other.usbStor
&& this->usbComposite == other.usbComposite
&& this->deviceNumber == other.deviceNumber
&& this->physicalVolume == other.physicalVolume
&& this->volumeName == other.volumeName
&& this->volumePath == other.volumePath
&& this->serialString == other.serialString
&& this->serialNumber == other.serialNumber;
}
bool DeviceFinder::Initialize(void)
{
if (initialized) { return true; }
initialized = false;
pLoc = NULL;
pSvc = NULL;
hWndDeviceFinder = NULL;
hDeviceNotify = NULL;
// Initialize COM
HRESULT hr;
hr = CoInitializeEx(0, COINIT_MULTITHREADED);
if (hr != S_OK && hr != S_FALSE && hr != RPC_E_CHANGED_MODE) { Log(0, "ERROR: Failed to initialize COM library: 0x%08x\n", hr); return false; }
// Set COM security levels
hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
if (FAILED(hr)) { Log(0, "NOTE: Initialize security result: 0x%08x\n", hr); }
// Obtain the WMI initial locator
hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc);
if (FAILED(hr)) { Log(0, "ERROR: Failed to create IWbemLocator object: 0x%08x\n", hr); CoUninitialize(); return false; }
// Connect to the root\cimv2 WMI namespace through the IWbemLocator::ConnectServer method with the current user and obtain pointer pSvc to make IWbemServices calls.
hr = ((IWbemLocator *)pLoc)->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, (IWbemServices **)&pSvc);
if (FAILED(hr)) { Log(0, "ERROR: Could not connect to WMI ROOT\\CIMV2: 0x%08x\n", hr); ((IWbemLocator *)pLoc)->Release(); pLoc = NULL; CoUninitialize(); return false; }
// Set security levels on the proxy
hr = CoSetProxyBlanket((IWbemServices *)pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
if (FAILED(hr)) { Log(0, "WARNING: Could not set proxy blanket: 0x%08x\n", hr); }
initialized = true;
return true;
}
bool DeviceFinder::Uninitialize(void)
{
// Cleanup IWbemServices, IWbemLocator
if (pSvc != NULL) { ((IWbemServices *)pSvc)->Release(); pSvc = NULL; }
if (pLoc != NULL) { ((IWbemLocator *)pLoc)->Release(); pLoc = NULL; }
// Un-initialize COM
// TODO: Track whether we initialized com or if it was already initialized
// if (initialized) { CoUninitialize(); }
initialized = false;
return true;
}
// Constructs a DeviceFinder with the specified vendor id and product id
DeviceFinder::DeviceFinder(unsigned int vidPid)
{
this->initialized = false;
this->vidPid = vidPid;
this->pLoc = NULL;
this->pSvc = NULL;
this->hWndDeviceFinder = NULL;
this->hDeviceNotify = NULL;
return;
}
// Destructs the DeviceFinder
DeviceFinder::~DeviceFinder()
{
Stop();
Uninitialize();
}
// From a USB string, find the unique part (will be the same for composite child instances)
std::string DeviceFinder::GetUniquePart(std::string id)
{
// Input:
// USB\VID_04D8&PID_0057&MI_01\6&23C68C4E&0&0001
// USB\VID_04D8&PID_0057&MI_00\6&23C68C4E&0&0000
// Output:
// USB\VID_04D8&PID_0057\6&23C68C4E&0
int miIndex = (int)id.find("&MI_");
if (miIndex >= 0)
{
id = id.erase(miIndex, 6);
}
int lastAnd = (int)id.find_last_of('&');
int lastSlash = (int)id.find_last_of('\\');
if (lastSlash >= miIndex && lastAnd > lastSlash)
{
id = id.substr(0, lastAnd);
}
return id;
}
// Get device type and number from device path
unsigned int DeviceFinder::GetDeviceNumber(wchar_t *devicePath)
{
HANDLE handle = CreateFileW(devicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL);
if (handle == INVALID_HANDLE_VALUE) { return -1; }
DWORD len = 0;
STORAGE_DEVICE_NUMBER sdn = {0};
DeviceIoControl(handle, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &len, NULL);
CloseHandle(handle);
return sdn.DeviceNumber;
}
/*
// (Usually internal) method to perform USB serial port search against vid/pid
bool DeviceFinder::FindPorts(unsigned int vidPid, std::map<std::string, std::string>& ports)
{
// Clear list of port names
ports.clear();
// PNPDeviceID to search for
char prefix[32];
sprintf_s(prefix, 32, "USB\\VID_%04X&PID_%04X", VID(vidPid), PID(vidPid));
HRESULT hr;
// Use the IWbemServices pointer to make a WMI request for Win32_SerialPort
IEnumWbemClassObject* pEnumerator = NULL;
hr = ((IWbemServices *)pSvc)->ExecQuery(bstr_t("WQL"), bstr_t("SELECT PNPDeviceID, DeviceID FROM Win32_SerialPort"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hr)) { cerr << "ERROR: Query for Win32_SerialPort has failed: " << hr << endl; return false; }
// Get the data from the query
if (pEnumerator)
{
for (;;)
{
// Get next item in enumeration
IWbemClassObject *pclsObj;
ULONG uReturn = 0;
hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
// If no more items, exit loop
if (uReturn == 0) { break; }
// Get value of the "PNPDeviceID" property
VARIANT vtPropPnpDeviceId;
hr = pclsObj->Get(L"PNPDeviceID", 0, &vtPropPnpDeviceId, 0, 0);
char pnpDeviceId[256] = { 0 };
wcstombs_s(NULL, pnpDeviceId, vtPropPnpDeviceId.bstrVal, 255); // Convert to ASCII
VariantClear(&vtPropPnpDeviceId);
//cerr << "DeviceFinder: Checking PNPDeviceId: " << pnpDeviceId << " --> " << endl;
// See if matches requested VID/PID
if (_strnicmp(pnpDeviceId, prefix, strlen(prefix)) == 0)
{
string uniqueId = GetUniquePart(pnpDeviceId);
// Get value of the "DeviceID" property
VARIANT vtPropDeviceId;
hr = pclsObj->Get(L"DeviceID", 0, &vtPropDeviceId, 0, 0);
char deviceId[256] = { 0 };
wcstombs_s(NULL, deviceId, vtPropDeviceId.bstrVal, 255); // Convert to ASCII
VariantClear(&vtPropDeviceId);
// Prefix with UNC device specifier (to work with port numbers higher than the few reserved names)
string portName = string("\\\\.\\") + deviceId;
cerr << "PORT: " << uniqueId << " --> " << portName << endl;
// Add to list of matched port names
ports[uniqueId] = portName;
}
pclsObj->Release();
}
pEnumerator->Release();
}
return true;
}
*/
/*
bool DeviceFinder::DiskDriveToLogicalDrive(char *deviceId)
{
// deviceId = "\\.\PHYSICALDRIVE1"
HRESULT hr;
_bstr_t query;
query += L"ASSOCIATORS OF {Win32_DiskDrive.DeviceID=\"";
for (char *p = deviceId; *p != '\0'; p++)
{
wchar_t c[2];
c[0] = *p; c[1] = '\0';
if (*p == '\\') { query += c; }
query += c;
}
query += L"\"} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
IEnumWbemClassObject* pEnumerator2 = NULL;
hr = ((IWbemServices *)pSvc)->ExecQuery(bstr_t("WQL"), query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator2);
if (FAILED(hr) || !pEnumerator2) { cerr << "ERROR: Query for Win32_DiskDriveToDiskPartition has failed: " << hr << endl; return false; }
for (;;)
{
VARIANT vtProp;
// Get next item in enumeration
IWbemClassObject *pclsObj2;
ULONG uReturn2 = 0;
hr = pEnumerator2->Next(WBEM_INFINITE, 1, &pclsObj2, &uReturn2);
// If no more items, exit loop
if (uReturn2 == 0) { break; }
// Get value of the "DeviceID" property
hr = pclsObj2->Get(L"DeviceID", 0, &vtProp, 0, 0);
char deviceId2[256] = { 0 };
wcstombs_s(NULL, deviceId2, vtProp.bstrVal, 255); // Convert to ASCII
VariantClear(&vtProp);
cerr << "[DRIVE:PARTITION] " << deviceId2 << endl;
// Get the logical disks for the partition
_bstr_t query2;
query2 += L"ASSOCIATORS OF {Win32_DiskPartition.DeviceID=\"";
for (char *p = deviceId2; *p != '\0'; p++)
{
wchar_t c[2];
c[0] = *p; c[1] = '\0';
if (*p == '\\') { query2 += c; }
query2 += c;
}
query2 += L"\"} WHERE AssocClass = Win32_LogicalDiskToPartition";
IEnumWbemClassObject* pEnumerator3 = NULL;
hr = ((IWbemServices *)pSvc)->ExecQuery(bstr_t("WQL"), query2, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator3);
if (FAILED(hr) || !pEnumerator3) { cerr << "ERROR: Query for Win32_LogicalDiskToPartition has failed: " << hr << endl; break; }
for (;;)
{
// Get next item in enumeration
IWbemClassObject *pclsObj3;
ULONG uReturn3 = 0;
hr = pEnumerator3->Next(WBEM_INFINITE, 1, &pclsObj3, &uReturn3);
// If no more items, exit loop
if (uReturn3 == 0) { break; }
// Get value of the "DeviceID" property
hr = pclsObj3->Get(L"DeviceID", 0, &vtProp, 0, 0);
char deviceId3[256] = { 0 };
wcstombs_s(NULL, deviceId3, vtProp.bstrVal, 255); // Convert to ASCII
VariantClear(&vtProp);
cerr << "[DRIVE:LOGICAL] " << deviceId3 << endl;
}
}
return true;
}
*/
// Find a mapping of unique USB prefix to port names
bool DeviceFinder::MappingUsbToPort(unsigned int vidPid, std::map<std::string, std::string>& usbToPortMap)
{
usbToPortMap.clear();
// PNPDeviceID to search for
char prefix[32];
sprintf_s(prefix, 32, "USB\\VID_%04X&PID_%04X", VID(vidPid), PID(vidPid));
// Convert the name "Ports" to a GUID
DWORD dwGuids = 0;
SetupDiClassGuidsFromNameW(L"Ports", NULL, 0, &dwGuids) ;
if (dwGuids == 0) { Log(0, "ERROR: SetupDiClassGuidsFromName() failed.\n"); return false; }
GUID *pGuids = new GUID[dwGuids]; // &GUID_DEVINTERFACE_COMPORT
if (!SetupDiClassGuidsFromNameW(L"Ports", pGuids, dwGuids, &dwGuids)) { Log(0, "ERROR: SetupDiClassGuidsFromName() failed.\n"); return false; }
// For each GUID returned
for (unsigned int guidIndex = 0; guidIndex < dwGuids; guidIndex++)
{
// From the root of the device tree, look for all devices that match the interface GUID
HDEVINFO hDevInfo = SetupDiGetClassDevs(&pGuids[guidIndex], NULL, NULL, DIGCF_PRESENT); // | DIGCF_DEVICEINTERFACE
if (hDevInfo == INVALID_HANDLE_VALUE) { delete [] pGuids; return false; }
for (int index = 0; ; index++)
{
wchar_t scratch[256];
// Enumerate the current device
SP_DEVINFO_DATA devInfo;
devInfo.cbSize = sizeof(SP_DEVINFO_DATA);
if (!SetupDiEnumDeviceInfo(hDevInfo, index, &devInfo)) { break; }
// Get USB id for device
scratch[0] = 0;
CM_Get_Device_IDW(devInfo.DevInst, scratch, 256, 0);
char usbId[256];
wcstombs_s(NULL, usbId, scratch, 256);
//Log(3, "[PORT:USB] %s\n", usbId);
// If this is the device we're after
if (strncmp(usbId, prefix, strlen(prefix)) == 0)
{
/*
// Move up one level to get to the composite device
DWORD parent = 0;
CM_Get_Parent(&parent, devInfo.DevInst, 0);
scratch[0] = 0;
CM_Get_Device_ID(parent, scratch, 256, 0);
char usbComposite[256];
wcstombs_s(NULL, usbComposite, scratch, 256);
if (strncmp(usbComposite, prefix, strlen(prefix)) != 0)
{
usbComposite[0] = '\0';
}
*/
// Registry key for the ports settings
char portName[256] = "";
HKEY hDeviceKey = SetupDiOpenDevRegKey(hDevInfo, &devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
if (hDeviceKey)
{
// Name of the port
scratch[0] = 0;
DWORD dwSize = sizeof(scratch);
DWORD dwType = 0;
if ((RegQueryValueExW(hDeviceKey, L"PortName", NULL, &dwType, (LPBYTE)scratch, &dwSize) == ERROR_SUCCESS) && (dwType == REG_SZ))
{
portName[0] = '\\'; portName[1] = '\\'; portName[2] = '.'; portName[3] = '\\';
wcstombs(portName + 4, scratch, 255 - 4);
}
}
char usbUnique[256] = "";
strcpy(usbUnique, GetUniquePart(usbId).c_str());
// Store mapping
//Log(3, "[PORT:KEY] %s\n", key);
//Log(3, "[PORT:NAME] %s\n", portName);
#ifdef DEBUG_PRINT
Log(3, "[USB->PORT] %s -> %s\n", usbUnique, portName);
#endif
usbToPortMap[usbUnique] = portName;
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
}
delete [] pGuids;
return true;
}
// Find drive mapping from USBSTOR id to their parent USB device id
bool DeviceFinder::MappingUsbToUsbstorAndUsbComposite(unsigned int vidPid, std::map<std::string, std::string>& usbToUsbstorMap, std::map<std::string, std::string>& usbToUsbCompositeMap)
{
usbToUsbstorMap.clear();
usbToUsbCompositeMap.clear();
// PNPDeviceID to search for
char prefix[32];
sprintf_s(prefix, 32, "USB\\VID_%04X&PID_%04X", VID(vidPid), PID(vidPid));
const GUID *pGuid = &GUID_DEVINTERFACE_DISK;
// From the root of the device tree, look for all devices that match the interface GUID
HANDLE hDevInfo = SetupDiGetClassDevs(pGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (hDevInfo == INVALID_HANDLE_VALUE) { return false; }
for (int index = 0; ; index++)
{
wchar_t scratch[256];
// Enumerate the current device
SP_DEVINFO_DATA devInfo;
devInfo.cbSize = sizeof(SP_DEVINFO_DATA);
if (!SetupDiEnumDeviceInfo(hDevInfo, index, &devInfo)) { break; }
#if 0
char path[256] = "";
// Device Interface Data structure
SP_DEVICE_INTERFACE_DATA devInterface;
devInterface.cbSize = sizeof(devInterface);
if (SetupDiEnumDeviceInterfaces(hDevInfo, NULL, pGuid, (unsigned int)index, &devInterface))
{
// Get more detailed information
DWORD nRequiredSize = 0;
SetupDiGetDeviceInterfaceDetail(hDevInfo, &devInterface, NULL, 0, &nRequiredSize, NULL);
SP_DEVICE_INTERFACE_DETAIL_DATA *devInterfaceDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA *)malloc(nRequiredSize + sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
if (devInterfaceDetail != NULL)
{
devInterfaceDetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &devInterface, devInterfaceDetail, nRequiredSize, NULL, NULL))
{
wcstombs_s(NULL, path, devInterfaceDetail->DevicePath, 256);
}
free(devInterfaceDetail);
}
}
Log(3, "[DRIVEMAP:PATH] %s\n", path);
#endif
// Move up one level to get to the "USB" level
DWORD parent = 0;
CM_Get_Parent(&parent, devInfo.DevInst, 0);
scratch[0] = 0;
CM_Get_Device_IDW(parent, scratch, 256, 0);
char usbId[256];
wcstombs_s(NULL, usbId, scratch, 256);
//Log(3, "[DRIVEMAP:USB] %s\n", usbId);
// If this is the device we're after
if (strncmp(usbId, prefix, strlen(prefix)) == 0)
{
// Get USBSTOR name at current level
scratch[0] = 0;
CM_Get_Device_IDW(devInfo.DevInst, scratch, 256, 0);
char usbstorId[256];
wcstombs_s(NULL, usbstorId, scratch, 256);
// Move up another level to get to the composite device
DWORD grandparent = 0;
CM_Get_Parent(&grandparent, parent, 0);
scratch[0] = 0;
CM_Get_Device_IDW(grandparent, scratch, 256, 0);
char usbComposite[256];
wcstombs_s(NULL, usbComposite, scratch, 256);
if (strncmp(usbComposite, prefix, strlen(prefix)) != 0)
{
usbComposite[0] = '\0';
}
// If the grandparent doesn't seem to be a composite, use the unique part of the USB id instead
char usbUnique[256];
strcpy(usbUnique, GetUniquePart(usbId).c_str());
// Store mapping
//Log(3, "[DRIVEMAP:KEY] %s\n", key);
//Log(3, "[DRIVEMAP:USBSTOR] %s\n", usbstorId);
#ifdef DEBUG_PRINT
Log(3, "[USB->USBSTOR] %s -> %s\n", usbUnique, usbstorId);
#endif
usbToUsbstorMap[usbUnique] = usbstorId;
usbToUsbCompositeMap[usbUnique] = usbComposite;
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
return true;
}
// (Usually internal) method to perform usb drive search
bool DeviceFinder::MappingUsbstorToDeviceNumber(std::map<std::string, int>& usbStorToDeviceMap)
{
HRESULT hr;
// Clear list of drive names
usbStorToDeviceMap.clear();
// Ensure pSvc is initialized
if (!Initialize()) { Log(0, "ERROR: Unable to initialize for usbstor-deviceNumber mapping.\n"); return false; }
// Use the IWbemServices pointer to make a WMI request for Win32_SerialPort
IEnumWbemClassObject* pEnumerator = NULL;
IWbemServices *pServices = (IWbemServices *)pSvc; // Cast required as the public API doesn't include the type information
if (pServices == NULL) { Log(0, "ERROR: Unable to get usbstor-deviceNumber mapping.\n"); return false; }
hr = pServices->ExecQuery(bstr_t("WQL"), bstr_t("SELECT PNPDeviceID, DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hr)) { Log(0, "ERROR: Query for Win32_DiskDrive has failed: 0x%08x\n", hr); return false; }
// Get the data from the query
if (pEnumerator)
{
for (;;)
{
// Get next item in enumeration
IWbemClassObject *pclsObj;
ULONG uReturn = 0;
hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
// If no more items, exit loop
if (uReturn == 0) { break; }
// Get value of the "PNPDeviceID" property
VARIANT vtProp;
hr = pclsObj->Get(L"PNPDeviceID", 0, &vtProp, 0, 0);
char usbstorId[256] = { 0 };
wcstombs_s(NULL, usbstorId, vtProp.bstrVal, 255); // Convert to ASCII
VariantClear(&vtProp);
//cerr << "[DRIVE:USBSTOR] " << usbstorId << endl;
// Get value of the "DeviceID" property
hr = pclsObj->Get(L"DeviceID", 0, &vtProp, 0, 0);
char deviceId[256] = { 0 };
wcstombs_s(NULL, deviceId, vtProp.bstrVal, 255); // Convert to ASCII
unsigned int deviceNumber = GetDeviceNumber(vtProp.bstrVal);
VariantClear(&vtProp);
//cerr << "[DRIVE:DEVICEID] " << deviceId << endl;
//cerr << "[DRIVE:DEVICENUMBER] " << deviceNumber << endl;
//DiskDriveToLogicalDrive(deviceId);
#ifdef DEBUG_PRINT
Log(3, "[USBSTOR->DEVICEID->DEVICENUMBER] %s -> %s -> %u\n", usbstorId, deviceId, deviceNumber);
#endif
usbStorToDeviceMap[usbstorId] = deviceNumber;
pclsObj->Release();
}
pEnumerator->Release();
}
return true;
}
// Find the mapping of drive device numbers to the first volume returned for that drive
bool DeviceFinder::MappingDeviceNumberToPhysicalVolume(std::map<int, std::string>& deviceNumberToPhysicalVolumeMap)
{
deviceNumberToPhysicalVolumeMap.clear();
HDEVINFO devInfoSet = SetupDiGetClassDevsW(&GUID_DEVINTERFACE_VOLUME, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
SP_DEVICE_INTERFACE_DATA devInterface = { 0 };
devInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
for (int i = 0; SetupDiEnumDeviceInterfaces(devInfoSet, NULL, &GUID_DEVINTERFACE_VOLUME, i, &devInterface); ++i)
{
SP_DEVINFO_DATA devInfoData = { 0 };
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
DWORD len;
SetupDiGetDeviceInterfaceDetailW(devInfoSet, &devInterface, NULL, 0, &len, &devInfoData);
std::vector<char> buf(len);
SP_DEVICE_INTERFACE_DETAIL_DATA_W *devInterfaceDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA_W *)&buf[0];
devInterfaceDetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
if (SetupDiGetDeviceInterfaceDetailW(devInfoSet, &devInterface, devInterfaceDetail, len, NULL, &devInfoData))
{
unsigned int volumeDeviceNumber = GetDeviceNumber(devInterfaceDetail->DevicePath);
// If we don't already have a volume for this device...
#define DGJ_FIX
#ifndef DGJ_FIX
if (deviceNumberToPhysicalVolumeMap.find(volumeDeviceNumber) == deviceNumberToPhysicalVolumeMap.end())
#endif
{
wchar_t buf[MAX_PATH + 1];
DWORD type, len;
if (SetupDiGetDeviceRegistryPropertyW(devInfoSet, &devInfoData, SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, &type, (unsigned char *)buf, MAX_PATH, &len))
{
char dp[MAX_PATH + 1];
wcstombs(dp, devInterfaceDetail->DevicePath, MAX_PATH);
char physicalVolume[MAX_PATH + 1];
wcstombs(physicalVolume, buf, MAX_PATH);
#ifdef DEBUG_PRINT
Log(3, "[DEVICE->PHYSICALVOLUME] %u [%s] -> %s\n", volumeDeviceNumber, dp, physicalVolume);
#endif
#ifdef DGJ_FIX
// TODO: Match on USBSTOR prefix+"USBSTOR\DISK&VEN_AX3&PROD_AX3_MASS_STORAGE&REV_0017\8&10A9691A&0&CWA17_01808&0"
// TODO: WinXP matches on "\\?\storage#removablemedia#8&75ad516&0&rm#{53f5630d-b6bf-11d0-94f2-00a0c91efb8b}"
// ...the devicePath has a prefix "\\?\storage#volume#_??_" and is the same as the USBSTOR but in lower-case and '\' substituted for '#', then ends with "#{GUID}#{GUID}"
// TEMPORARY HACK: If we don't have a mapping, or this one seems better
if (deviceNumberToPhysicalVolumeMap.find(volumeDeviceNumber) == deviceNumberToPhysicalVolumeMap.end() || strstr(dp, "&ven_ax3&") != NULL || strstr(dp, "#removablemedia#") != NULL)
#endif
deviceNumberToPhysicalVolumeMap[volumeDeviceNumber] = physicalVolume;
}
}
}
}
return true;
}
// Find the mapping of physical volume name to the volume name
bool DeviceFinder::MappingPhysicalVolumeToVolumeName(std::map<std::string, std::string>& physicalVolumeToVolumeNameMap)
{
physicalVolumeToVolumeNameMap.clear();
// Enumerate through all system volumes
wchar_t volumeNameW[MAX_PATH] = L"";
HANDLE hFind = FindFirstVolumeW(volumeNameW, sizeof(volumeNameW)/sizeof(volumeNameW[0]));
if (hFind == INVALID_HANDLE_VALUE) { return false; }
for (;;)
{
size_t index = wcslen(volumeNameW) - 1;
if (volumeNameW[0] != L'\\' || volumeNameW[1] != L'\\' || volumeNameW[2] != L'?' || volumeNameW[3] != L'\\' || volumeNameW[index] != L'\\')
{
// error, expected prefix missing
#ifdef DEBUG_PRINT
char volumeName[MAX_PATH];
wcstombs(volumeName, volumeNameW, MAX_PATH);
Log(3, "[PHYSICALVOLUME->VOLUMENAME volume-name non-matched, skipped] %s\n", volumeName);
#endif
}
else
{
char volumeName[MAX_PATH];
wcstombs(volumeName, volumeNameW, MAX_PATH);
// Get physical volume name
wchar_t physicalVolumeW[MAX_PATH] = L"";
physicalVolumeW[0] = L'\0'; physicalVolumeW[1] = L'\0'; // Empty return list
volumeNameW[index] = L'\0'; // Remove trailing backslash for QueryDosDevice
DWORD count = QueryDosDeviceW(&volumeNameW[4], physicalVolumeW, sizeof(physicalVolumeW)/sizeof(physicalVolumeW[0]));
volumeNameW[index] = L'\\'; // Replace trailing backslash
char physicalVolume[MAX_PATH];
physicalVolume[0] = '\0';
int pvcount = 0;
wchar_t *pv;
for (pv = physicalVolumeW; *pv != L'\0'; pv += wcslen(pv))
{
if (physicalVolume[0] == '\0')
{
wcstombs(physicalVolume, pv, MAX_PATH);
Log(3, "[PHYSICALVOLUME->VOLUMENAME] Using #%d %s -> %s\n", pvcount, physicalVolume, volumeName);
}
else
{
#ifdef DEBUG_PRINT
char pva[MAX_PATH];
wcstombs(pva, pv, MAX_PATH);
Log(3, "[PHYSICALVOLUME->VOLUMENAME] Other #%d %s -> %s\n", pvcount, pva, volumeName);
#endif
;
}
pvcount++;
}
// Check for no mapping
if (physicalVolume[0] == '\0')
{
#ifdef DEBUG_PRINT
Log(3, "[PHYSICALVOLUME->VOLUMENAME] <none> -> %s\n", volumeName);
#endif
;
}
physicalVolumeToVolumeNameMap[physicalVolume] = volumeName;
}
// Move to the next volume
if (!FindNextVolumeW(hFind, volumeNameW, sizeof(volumeNameW)/sizeof(volumeNameW[0]))) { break; }
}
FindVolumeClose(hFind);
return true;
}
// Find the (first) mapping path for the given volume name
std::string DeviceFinder::GetVolumePathForVolumeName(std::string volumeName)
{
if (volumeName.length() <= 0) { return ""; }
std::string ret = "";
wchar_t *volumeNameW = new wchar_t[volumeName.length() + 2];
mbstowcs(volumeNameW, volumeName.c_str(), volumeName.length() + 1);
DWORD charCount = MAX_PATH + 1;
for (;;)
{
// Allocate a buffer to hold the paths
wchar_t *names = new wchar_t[charCount + 2];
// Obtain all of the paths for this volume
if (GetVolumePathNamesForVolumeNameW(volumeNameW, names, charCount + 1, &charCount))
{
// Enumerate over the paths
//for (wchar_t *nameIndex = names; *nameIndex != L'\0'; nameIndex += wcslen(nameIndex) + 1) { wprintf(L"- %s\n", nameIndex); }
// Return the first path
char *buf = new char[wcslen(names) + 1];
wcstombs(buf, names, wcslen(names) + 1);
ret = buf;
delete[] buf;
delete[] names;
break;
}
delete[] names;
if (GetLastError() != ERROR_MORE_DATA) { break; }
}
delete[] volumeNameW;
return ret;
}
bool DeviceFinder::FindDevices(std::list<Device>& devices)
{
devices.clear();
std::map<std::string, std::string> mapUsbToPort;
if (!MappingUsbToPort(vidPid, mapUsbToPort)) { Log(0, "ERROR: Problem finding ports.\n"); return false; }
std::map<std::string, std::string> mapUsbToUsbstor;
std::map<std::string, std::string> mapUsbToUsbComposite;
if (!MappingUsbToUsbstorAndUsbComposite(vidPid, mapUsbToUsbstor, mapUsbToUsbComposite)) { Log(0, "ERROR: Problem finding drive mapping.\n"); return false; }
std::map<std::string, int> mapUsbstorToDeviceNumber;
if (!MappingUsbstorToDeviceNumber(mapUsbstorToDeviceNumber)) { Log(0, "ERROR: Problem finding drives.\n"); return false; }
std::map<int, std::string> mapDeviceNumberToPhysicalVolume;
if (!MappingDeviceNumberToPhysicalVolume(mapDeviceNumberToPhysicalVolume)) { Log(0, "ERROR: Problem finding physical volumes.\n"); return false; }
std::map<std::string, std::string> mapPhysicalVolumeToVolumeName;
if (!MappingPhysicalVolumeToVolumeName(mapPhysicalVolumeToVolumeName)) { Log(0, "ERROR: Problem finding volume names.\n"); return false; }
for (map<string, string>::const_iterator i = mapUsbToPort.begin(); i != mapUsbToPort.end(); ++i)
{
string usb = (*i).first;
string port = (*i).second;
string usbStor = mapUsbToUsbstor[usb];
string usbComposite = mapUsbToUsbComposite[usb];
unsigned int deviceNumber = mapUsbstorToDeviceNumber[usbStor];
string physicalVolume = mapDeviceNumberToPhysicalVolume[deviceNumber];
string volumeName = mapPhysicalVolumeToVolumeName[physicalVolume];
string volumePath = GetVolumePathForVolumeName(volumeName);
// Find serial string from composite device name
string serialString;
char prefix[32];
sprintf_s(prefix, 32, "USB\\VID_%04X&PID_%04X", VID(vidPid), PID(vidPid));
if (usbComposite.length() > 0)
{
// If this is the composite device we're after, find the serial string
if (strncmp(usbComposite.c_str(), prefix, strlen(prefix)) == 0)
{
int index = (int)strlen(prefix);
if (usbComposite[index] == '\\') { index++; }
serialString = usbComposite.substr(index);
}
}
// If serial string not set, use the unique id
if (serialString.length() == 0)
{
// If this is the device we're after
if (strncmp(usb.c_str(), prefix, strlen(prefix)) == 0)
{
int index = (int)strlen(prefix);
if (usb[index] == '\\') { index++; }
serialString = usb.substr(index);
}
}
// Find the serial number from the serial string
unsigned int serialNumber = 0;
//printf("SERIAL: [%s]\n", serialString.c_str());
OmLog(2, "SERIAL: [%s]\n", serialString.c_str());
if (serialString.length() > 0)
{
int firstDigit = (int)serialString.find_first_of('&') + 1;
int lastDigit = -1;
if ((serialString[firstDigit] >= '0' && serialString[firstDigit] <= '9') || (serialString[firstDigit] >= 'A' && serialString[firstDigit] <= 'F'))
{
lastDigit = (int)serialString.find_first_not_of("0123456789ABCDEF", firstDigit) - 1;
}
// Check whether this is a Windows-generated number for a device without a serial number
if (firstDigit >= 1 && lastDigit >= firstDigit)
{
// Extract the part after the first ampersand as a hexadecimal serial number
serialNumber = strtol(serialString.substr(firstDigit, lastDigit - firstDigit + 1).c_str(), NULL, 16);
serialNumber |= 0xffff0000; // ensure it's not a valid serial number from the device (the high word is fully set)
}
else
{
// Extract the last decimal numeric part of the serial string as a serial number
int lastNumber = (int)serialString.find_last_of("0123456789");
if (lastNumber >= 0)
{
int firstNumber = (int)serialString.find_last_not_of("0123456789", lastNumber) + 1;
if (firstNumber >= 0)
{
OmLog(2, "SERIAL: numeric [%s]\n", serialString.substr(firstNumber, lastNumber - firstNumber + 1).c_str());
serialNumber = (unsigned int)strtoul(serialString.substr(firstNumber, lastNumber - firstNumber + 1).c_str(), NULL, 10);
OmLog(2, "SERIAL: =%u %u 0x%08x\n", serialNumber, strtol(serialString.substr(firstNumber, lastNumber - firstNumber + 1).c_str(), NULL, 10), serialNumber);
}
}
}
}