forked from LudovicRousseau/libusbx
/
windows_usb.c
4378 lines (3887 loc) · 150 KB
/
windows_usb.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
/*
* windows backend for libusbx 1.0
* Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
* With contributions from Michael Plante, Orin Eman et al.
* Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
* HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
* Hash table functions adapted from glibc, by Ulrich Drepper et al.
* Major code testing contribution by Xiaofan Chen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <config.h>
#include <windows.h>
#include <setupapi.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <process.h>
#include <stdio.h>
#include <inttypes.h>
#include <objbase.h>
#include <winioctl.h>
#include <libusbi.h>
#include "poll_windows.h"
#include "windows_usb.h"
// The 2 macros below are used in conjunction with safe loops.
#define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
#define LOOP_BREAK(err) { r=err; continue; }
extern void usbi_fd_notification(struct libusb_context *ctx);
// Helper prototypes
static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
static int windows_clock_gettime(int clk_id, struct timespec *tp);
unsigned __stdcall windows_clock_gettime_threaded(void* param);
// Common calls
static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
// WinUSB-like API prototypes
static int winusbx_init(int sub_api, struct libusb_context *ctx);
static int winusbx_exit(int sub_api);
static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer);
static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
// HID API prototypes
static int hid_init(int sub_api, struct libusb_context *ctx);
static int hid_exit(int sub_api);
static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
// Composite API prototypes
static int composite_init(int sub_api, struct libusb_context *ctx);
static int composite_exit(int sub_api);
static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer);
static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
// Global variables
uint64_t hires_frequency, hires_ticks_to_ps;
const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
enum windows_version windows_version = WINDOWS_UNSUPPORTED;
// Concurrency
static int concurrent_usage = -1;
usbi_mutex_t autoclaim_lock;
// Timer thread
// NB: index 0 is for monotonic and 1 is for the thread exit event
HANDLE timer_thread = NULL;
HANDLE timer_mutex = NULL;
struct timespec timer_tp;
volatile LONG request_count[2] = {0, 1}; // last one must be > 0
HANDLE timer_request[2] = { NULL, NULL };
HANDLE timer_response = NULL;
// API globals
#define CHECK_WINUSBX_AVAILABLE(sub_api) do { if (sub_api == SUB_API_NOTSET) sub_api = priv->sub_api; \
if (!WinUSBX[sub_api].initialized) return LIBUSB_ERROR_ACCESS; } while(0)
static struct winusb_interface WinUSBX[SUB_API_MAX];
const char* sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES;
bool api_hid_available = false;
#define CHECK_HID_AVAILABLE do { if (!api_hid_available) return LIBUSB_ERROR_ACCESS; } while (0)
static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
if ((guid1 != NULL) && (guid2 != NULL)) {
return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
}
return false;
}
#if defined(ENABLE_LOGGING)
static char* guid_to_string(const GUID* guid)
{
static char guid_string[MAX_GUID_STRING_LENGTH];
if (guid == NULL) return NULL;
sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
(unsigned int)guid->Data1, guid->Data2, guid->Data3,
guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
return guid_string;
}
#endif
/*
* Converts a windows error to human readable string
* uses retval as errorcode, or, if 0, use GetLastError()
*/
#if defined(ENABLE_LOGGING)
static char *windows_error_str(uint32_t retval)
{
static char err_string[ERR_BUFFER_SIZE];
DWORD size;
size_t i;
uint32_t error_code, format_error;
error_code = retval?retval:GetLastError();
safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%u] ", error_code);
size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
if (size == 0) {
format_error = GetLastError();
if (format_error)
safe_sprintf(err_string, ERR_BUFFER_SIZE,
"Windows error code %u (FormatMessage error code %u)", error_code, format_error);
else
safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
} else {
// Remove CR/LF terminators
for (i=safe_strlen(err_string)-1; ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
err_string[i] = 0;
}
}
return err_string;
}
#endif
/*
* Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
* Return an allocated sanitized string or NULL on error.
*/
static char* sanitize_path(const char* path)
{
const char root_prefix[] = "\\\\.\\";
size_t j, size, root_size;
char* ret_path = NULL;
size_t add_root = 0;
if (path == NULL)
return NULL;
size = safe_strlen(path)+1;
root_size = sizeof(root_prefix)-1;
// Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
add_root = root_size;
size += add_root;
}
if ((ret_path = (char*) calloc(size, 1)) == NULL)
return NULL;
safe_strcpy(&ret_path[add_root], size-add_root, path);
// Ensure consistancy with root prefix
for (j=0; j<root_size; j++)
ret_path[j] = root_prefix[j];
// Same goes for '\' and '#' after the root prefix. Ensure '#' is used
for(j=root_size; j<size; j++) {
ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
if (ret_path[j] == '\\')
ret_path[j] = '#';
}
return ret_path;
}
/*
* Cfgmgr32, OLE32 and SetupAPI DLL functions
*/
static int init_dlls(void)
{
DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
// Prefixed to avoid conflict with header files
DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDeviceInterfaceRegKey, TRUE);
DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
return LIBUSB_SUCCESS;
}
/*
* enumerate interfaces for the whole USB class
*
* Parameters:
* dev_info: a pointer to a dev_info list
* dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
* usb_class: the generic USB class for which to retrieve interface details
* index: zero based index of the interface in the device info list
*
* Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
* structure returned and call this function repeatedly using the same guid (with an
* incremented index starting at zero) until all interfaces have been returned.
*/
static bool get_devinfo_data(struct libusb_context *ctx,
HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, char* usb_class, unsigned _index)
{
if (_index <= 0) {
*dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
if (*dev_info == INVALID_HANDLE_VALUE) {
return false;
}
}
dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
if (GetLastError() != ERROR_NO_MORE_ITEMS) {
usbi_err(ctx, "Could not obtain device info data for index %u: %s",
_index, windows_error_str(0));
}
pSetupDiDestroyDeviceInfoList(*dev_info);
*dev_info = INVALID_HANDLE_VALUE;
return false;
}
return true;
}
/*
* enumerate interfaces for a specific GUID
*
* Parameters:
* dev_info: a pointer to a dev_info list
* dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
* guid: the GUID for which to retrieve interface details
* index: zero based index of the interface in the device info list
*
* Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
* structure returned and call this function repeatedly using the same guid (with an
* incremented index starting at zero) until all interfaces have been returned.
*/
static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
{
SP_DEVICE_INTERFACE_DATA dev_interface_data;
SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
DWORD size;
if (_index <= 0) {
*dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
}
if (dev_info_data != NULL) {
dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
if (GetLastError() != ERROR_NO_MORE_ITEMS) {
usbi_err(ctx, "Could not obtain device info data for index %u: %s",
_index, windows_error_str(0));
}
pSetupDiDestroyDeviceInfoList(*dev_info);
*dev_info = INVALID_HANDLE_VALUE;
return NULL;
}
}
dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
if (GetLastError() != ERROR_NO_MORE_ITEMS) {
usbi_err(ctx, "Could not obtain interface data for index %u: %s",
_index, windows_error_str(0));
}
pSetupDiDestroyDeviceInfoList(*dev_info);
*dev_info = INVALID_HANDLE_VALUE;
return NULL;
}
// Read interface data (dummy + actual) to access the device path
if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
// The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
_index, windows_error_str(0));
goto err_exit;
}
} else {
usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
goto err_exit;
}
if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
usbi_err(ctx, "could not allocate interface data for index %u.", _index);
goto err_exit;
}
dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
dev_interface_details, size, &size, NULL)) {
usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
_index, windows_error_str(0));
}
return dev_interface_details;
err_exit:
pSetupDiDestroyDeviceInfoList(*dev_info);
*dev_info = INVALID_HANDLE_VALUE;
return NULL;
}
/* For libusb0 filter */
SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx,
HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index, char* filter_path){
SP_DEVICE_INTERFACE_DATA dev_interface_data;
SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
DWORD size;
if (_index <= 0) {
*dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
}
if (dev_info_data != NULL) {
dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
if (GetLastError() != ERROR_NO_MORE_ITEMS) {
usbi_err(ctx, "Could not obtain device info data for index %u: %s",
_index, windows_error_str(0));
}
pSetupDiDestroyDeviceInfoList(*dev_info);
*dev_info = INVALID_HANDLE_VALUE;
return NULL;
}
}
dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
if (GetLastError() != ERROR_NO_MORE_ITEMS) {
usbi_err(ctx, "Could not obtain interface data for index %u: %s",
_index, windows_error_str(0));
}
pSetupDiDestroyDeviceInfoList(*dev_info);
*dev_info = INVALID_HANDLE_VALUE;
return NULL;
}
// Read interface data (dummy + actual) to access the device path
if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
// The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
_index, windows_error_str(0));
goto err_exit;
}
} else {
usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
goto err_exit;
}
if ((dev_interface_details = malloc(size)) == NULL) {
usbi_err(ctx, "could not allocate interface data for index %u.", _index);
goto err_exit;
}
dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
dev_interface_details, size, &size, NULL)) {
usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
_index, windows_error_str(0));
}
// [trobinso] lookup the libusb0 symbolic index.
if (dev_interface_details) {
HKEY hkey_device_interface=pSetupDiOpenDeviceInterfaceRegKey(*dev_info,&dev_interface_data,0,KEY_READ);
if (hkey_device_interface != INVALID_HANDLE_VALUE) {
DWORD libusb0_symboliclink_index=0;
DWORD value_length=sizeof(DWORD);
DWORD value_type=0;
LONG status;
status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type,
(LPBYTE) &libusb0_symboliclink_index, &value_length);
if (status == ERROR_SUCCESS) {
if (libusb0_symboliclink_index < 256) {
// libusb0.sys is connected to this device instance.
// If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
safe_sprintf(filter_path, sizeof("\\\\.\\libusb0-0000"), "\\\\.\\libusb0-%04d", libusb0_symboliclink_index);
usbi_dbg("assigned libusb0 symbolic link %s", filter_path);
} else {
// libusb0.sys was connected to this device instance at one time; but not anymore.
}
}
pRegCloseKey(hkey_device_interface);
}
}
return dev_interface_details;
err_exit:
pSetupDiDestroyDeviceInfoList(*dev_info);
*dev_info = INVALID_HANDLE_VALUE;
return NULL;}
/* Hash table functions - modified From glibc 2.3.2:
[Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
[Knuth] The Art of Computer Programming, part 3 (6.4) */
typedef struct htab_entry {
unsigned long used;
char* str;
} htab_entry;
htab_entry* htab_table = NULL;
usbi_mutex_t htab_write_mutex = NULL;
unsigned long htab_size, htab_filled;
/* For the used double hash method the table size has to be a prime. To
correct the user given table size we need a prime test. This trivial
algorithm is adequate because the code is called only during init and
the number is likely to be small */
static int isprime(unsigned long number)
{
// no even number will be passed
unsigned int divider = 3;
while((divider * divider < number) && (number % divider != 0))
divider += 2;
return (number % divider != 0);
}
/* Before using the hash table we must allocate memory for it.
We allocate one element more as the found prime number says.
This is done for more effective indexing as explained in the
comment for the hash function. */
static int htab_create(struct libusb_context *ctx, unsigned long nel)
{
if (htab_table != NULL) {
usbi_err(ctx, "hash table already allocated");
}
// Create a mutex
usbi_mutex_init(&htab_write_mutex, NULL);
// Change nel to the first prime number not smaller as nel.
nel |= 1;
while(!isprime(nel))
nel += 2;
htab_size = nel;
usbi_dbg("using %d entries hash table", nel);
htab_filled = 0;
// allocate memory and zero out.
htab_table = (htab_entry*) calloc(htab_size + 1, sizeof(htab_entry));
if (htab_table == NULL) {
usbi_err(ctx, "could not allocate space for hash table");
return 0;
}
return 1;
}
/* After using the hash table it has to be destroyed. */
static void htab_destroy(void)
{
size_t i;
if (htab_table == NULL) {
return;
}
for (i=0; i<htab_size; i++) {
if (htab_table[i].used) {
safe_free(htab_table[i].str);
}
}
usbi_mutex_destroy(&htab_write_mutex);
safe_free(htab_table);
}
/* This is the search function. It uses double hashing with open addressing.
We use an trick to speed up the lookup. The table is created with one
more element available. This enables us to use the index zero special.
This index will never be used because we store the first hash index in
the field used where zero means not used. Every other value means used.
The used field can be used as a first fast comparison for equality of
the stored and the parameter value. This helps to prevent unnecessary
expensive calls of strcmp. */
static unsigned long htab_hash(char* str)
{
unsigned long hval, hval2;
unsigned long idx;
unsigned long r = 5381;
int c;
char* sz = str;
// Compute main hash value (algorithm suggested by Nokia)
while ((c = *sz++) != 0)
r = ((r << 5) + r) + c;
if (r == 0)
++r;
// compute table hash: simply take the modulus
hval = r % htab_size;
if (hval == 0)
++hval;
// Try the first index
idx = hval;
if (htab_table[idx].used) {
if ( (htab_table[idx].used == hval)
&& (safe_strcmp(str, htab_table[idx].str) == 0) ) {
// existing hash
return idx;
}
usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
// Second hash function, as suggested in [Knuth]
hval2 = 1 + hval % (htab_size - 2);
do {
// Because size is prime this guarantees to step through all available indexes
if (idx <= hval2) {
idx = htab_size + idx - hval2;
} else {
idx -= hval2;
}
// If we visited all entries leave the loop unsuccessfully
if (idx == hval) {
break;
}
// If entry is found use it.
if ( (htab_table[idx].used == hval)
&& (safe_strcmp(str, htab_table[idx].str) == 0) ) {
return idx;
}
}
while (htab_table[idx].used);
}
// Not found => New entry
// If the table is full return an error
if (htab_filled >= htab_size) {
usbi_err(NULL, "hash table is full (%d entries)", htab_size);
return 0;
}
// Concurrent threads might be storing the same entry at the same time
// (eg. "simultaneous" enums from different threads) => use a mutex
usbi_mutex_lock(&htab_write_mutex);
// Just free any previously allocated string (which should be the same as
// new one). The possibility of concurrent threads storing a collision
// string (same hash, different string) at the same time is extremely low
safe_free(htab_table[idx].str);
htab_table[idx].used = hval;
htab_table[idx].str = (char*) malloc(safe_strlen(str)+1);
if (htab_table[idx].str == NULL) {
usbi_err(NULL, "could not duplicate string for hash table");
usbi_mutex_unlock(&htab_write_mutex);
return 0;
}
memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
++htab_filled;
usbi_mutex_unlock(&htab_write_mutex);
return idx;
}
/*
* Returns the session ID of a device's nth level ancestor
* If there's no device at the nth level, return 0
*/
static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
{
DWORD parent_devinst;
unsigned long session_id = 0;
char* sanitized_path = NULL;
char path[MAX_PATH_LENGTH];
unsigned i;
if (level < 1) return 0;
for (i = 0; i<level; i++) {
if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
return 0;
}
devinst = parent_devinst;
}
if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
return 0;
}
// TODO (post hotplug): try without sanitizing
sanitized_path = sanitize_path(path);
if (sanitized_path == NULL) {
return 0;
}
session_id = htab_hash(sanitized_path);
safe_free(sanitized_path);
return session_id;
}
/*
* Populate the endpoints addresses of the device_priv interface helper structs
*/
static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
{
int i, r;
struct windows_device_priv *priv = _device_priv(dev_handle->dev);
struct libusb_config_descriptor *conf_desc;
const struct libusb_interface_descriptor *if_desc;
struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
if (r != LIBUSB_SUCCESS) {
usbi_warn(ctx, "could not read config descriptor: error %d", r);
return r;
}
if_desc = &conf_desc->interface[iface].altsetting[altsetting];
safe_free(priv->usb_interface[iface].endpoint);
if (if_desc->bNumEndpoints == 0) {
usbi_dbg("no endpoints found for interface %d", iface);
return LIBUSB_SUCCESS;
}
priv->usb_interface[iface].endpoint = (uint8_t*) malloc(if_desc->bNumEndpoints);
if (priv->usb_interface[iface].endpoint == NULL) {
return LIBUSB_ERROR_NO_MEM;
}
priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
for (i=0; i<if_desc->bNumEndpoints; i++) {
priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
}
libusb_free_config_descriptor(conf_desc);
// Extra init may be required to configure endpoints
return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
}
// Lookup for a match in the list of API driver names
// return -1 if not found, driver match number otherwise
int get_sub_api(char* driver, int api){
int i;
const char sep_str[2] = {LIST_SEPARATOR, 0};
char *tok, *tmp_str;
size_t len = safe_strlen(driver);
if (len == 0) return SUB_API_NOTSET;
tmp_str = (char*) calloc(len+1, 1);
if (tmp_str == NULL) return SUB_API_NOTSET;
memcpy(tmp_str, driver, len+1);
tok = strtok(tmp_str, sep_str);
while (tok != NULL) {
for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
if (safe_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
free(tmp_str);
return i;
}
}
tok = strtok(NULL, sep_str);
}
free (tmp_str);
return SUB_API_NOTSET;
}
/*
* auto-claiming and auto-release helper functions
*/
static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
{
struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
struct windows_device_handle_priv *handle_priv = _device_handle_priv(
transfer->dev_handle);
struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
int current_interface = *interface_number;
int r = LIBUSB_SUCCESS;
switch(api_type) {
case USB_API_WINUSBX:
case USB_API_HID:
break;
default:
return LIBUSB_ERROR_INVALID_PARAM;
}
usbi_mutex_lock(&autoclaim_lock);
if (current_interface < 0) // No serviceable interface was found
{
for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
// Must claim an interface of the same API type
if ( (priv->usb_interface[current_interface].apib->id == api_type)
&& (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
usbi_dbg("auto-claimed interface %d for control request", current_interface);
if (handle_priv->autoclaim_count[current_interface] != 0) {
usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
}
handle_priv->autoclaim_count[current_interface]++;
break;
}
}
if (current_interface == USB_MAXINTERFACES) {
usbi_err(ctx, "could not auto-claim any interface");
r = LIBUSB_ERROR_NOT_FOUND;
}
} else {
// If we have a valid interface that was autoclaimed, we must increment
// its autoclaim count so that we can prevent an early release.
if (handle_priv->autoclaim_count[current_interface] != 0) {
handle_priv->autoclaim_count[current_interface]++;
}
}
usbi_mutex_unlock(&autoclaim_lock);
*interface_number = current_interface;
return r;
}
static void auto_release(struct usbi_transfer *itransfer)
{
struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
libusb_device_handle *dev_handle = transfer->dev_handle;
struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
int r;
usbi_mutex_lock(&autoclaim_lock);
if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
handle_priv->autoclaim_count[transfer_priv->interface_number]--;
if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
if (r == LIBUSB_SUCCESS) {
usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
} else {
usbi_dbg("failed to auto-release interface %d (%s)",
transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
}
}
}
usbi_mutex_unlock(&autoclaim_lock);
}
/*
* init: libusbx backend init function
*
* This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
* In our implementation, we equate Windows' "HCD" to libusbx's "bus". Note that bus is zero indexed.
* HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
*/
static int windows_init(struct libusb_context *ctx)
{
int i, r = LIBUSB_ERROR_OTHER;
OSVERSIONINFO os_version;
HANDLE semaphore;
char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
if (semaphore == NULL) {
usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
return LIBUSB_ERROR_NO_MEM;
}
// A successful wait brings our semaphore count to 0 (unsignaled)
// => any concurent wait stalls until the semaphore's release
if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
CloseHandle(semaphore);
return LIBUSB_ERROR_NO_MEM;
}
// NB: concurrent usage supposes that init calls are equally balanced with
// exit calls. If init is called more than exit, we will not exit properly
if ( ++concurrent_usage == 0 ) { // First init?
// Detect OS version
memset(&os_version, 0, sizeof(OSVERSIONINFO));
os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
windows_version = WINDOWS_UNSUPPORTED;
if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
windows_version = WINDOWS_XP;
} else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
windows_version = WINDOWS_2003; // also includes XP 64
} else if (os_version.dwMajorVersion >= 6) {
windows_version = WINDOWS_VISTA_AND_LATER;
}
}
if (windows_version == WINDOWS_UNSUPPORTED) {
usbi_err(ctx, "This version of Windows is NOT supported");
r = LIBUSB_ERROR_NOT_SUPPORTED;
goto init_exit;
}
// We need a lock for proper auto-release
usbi_mutex_init(&autoclaim_lock, NULL);
// Initialize pollable file descriptors
init_polling();
// Load DLL imports
if (init_dlls() != LIBUSB_SUCCESS) {
usbi_err(ctx, "could not resolve DLL functions");
return LIBUSB_ERROR_NOT_FOUND;
}
// Initialize the low level APIs (we don't care about errors at this stage)
for (i=0; i<USB_API_MAX; i++) {
usb_api_backend[i].init(SUB_API_NOTSET, ctx);
}
// Because QueryPerformanceCounter might report different values when
// running on different cores, we create a separate thread for the timer
// calls, which we glue to the first core always to prevent timing discrepancies.
r = LIBUSB_ERROR_NO_MEM;
for (i = 0; i < 2; i++) {
timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
if (timer_request[i] == NULL) {
usbi_err(ctx, "could not create timer request event %d - aborting", i);
goto init_exit;
}
}
timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
if (timer_response == NULL) {
usbi_err(ctx, "could not create timer response semaphore - aborting");
goto init_exit;
}
timer_mutex = CreateMutex(NULL, FALSE, NULL);
if (timer_mutex == NULL) {
usbi_err(ctx, "could not create timer mutex - aborting");
goto init_exit;
}
timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
if (timer_thread == NULL) {
usbi_err(ctx, "Unable to create timer thread - aborting");
goto init_exit;
}
SetThreadAffinityMask(timer_thread, 0);
// Create a hash table to store session ids. Second parameter is better if prime
htab_create(ctx, HTAB_SIZE);
}
// At this stage, either we went through full init successfully, or didn't need to
r = LIBUSB_SUCCESS;
init_exit: // Holds semaphore here.
if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
if (timer_thread) {
SetEvent(timer_request[1]); // actually the signal to quit the thread.
if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
usbi_warn(ctx, "could not wait for timer thread to quit");
TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
// all objects it might have held anyway.
}
CloseHandle(timer_thread);
timer_thread = NULL;
}
for (i = 0; i < 2; i++) {
if (timer_request[i]) {
CloseHandle(timer_request[i]);
timer_request[i] = NULL;
}
}
if (timer_response) {
CloseHandle(timer_response);
timer_response = NULL;
}
if (timer_mutex) {
CloseHandle(timer_mutex);
timer_mutex = NULL;
}
htab_destroy();
}
if (r != LIBUSB_SUCCESS)
--concurrent_usage; // Not expected to call libusb_exit if we failed.
ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
CloseHandle(semaphore);
return r;
}
/*
* HCD (root) hubs need to have their device descriptor manually populated
*
* Note that, like Microsoft does in the device manager, we populate the
* Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
*/
static int force_hcd_device_descriptor(struct libusb_device *dev)
{
struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
struct libusb_context *ctx = DEVICE_CTX(dev);
int vid, pid;
dev->num_configurations = 1;
priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
priv->dev_descriptor.bNumConfigurations = 1;
priv->active_config = 1;
if (priv->parent_dev == NULL) {
usbi_err(ctx, "program assertion failed - HCD hub has no parent");
return LIBUSB_ERROR_NO_DEVICE;
}
parent_priv = _device_priv(priv->parent_dev);
if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
priv->dev_descriptor.idVendor = (uint16_t)vid;
priv->dev_descriptor.idProduct = (uint16_t)pid;
} else {
usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
priv->dev_descriptor.idProduct = 1;
}
return LIBUSB_SUCCESS;
}
/*
* fetch and cache all the config descriptors through I/O
*/
static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
{
DWORD size, ret_size;
struct libusb_context *ctx = DEVICE_CTX(dev);
struct windows_device_priv *priv = _device_priv(dev);
int r;
uint8_t i;
USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
if (dev->num_configurations == 0)
return LIBUSB_ERROR_INVALID_PARAM;
priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(unsigned char*));
if (priv->config_descriptor == NULL)
return LIBUSB_ERROR_NO_MEM;
for (i=0; i<dev->num_configurations; i++)
priv->config_descriptor[i] = NULL;
for (i=0, r=LIBUSB_SUCCESS; ; i++)
{
// safe loop: release all dynamic resources
safe_free(cd_buf_actual);
// safe loop: end of loop condition
if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
break;
size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
memset(&cd_buf_short, 0, size);