windows: fix USB 3.0 speed detection on Windows 8 or later
[platform/upstream/libusb.git] / libusb / os / windows_usb.c
1 /*
2  * windows backend for libusb 1.0
3  * Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
4  * With contributions from Michael Plante, Orin Eman et al.
5  * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6  * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
7  * Hash table functions adapted from glibc, by Ulrich Drepper et al.
8  * Major code testing contribution by Xiaofan Chen
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 #include <config.h>
26 #include <windows.h>
27 #include <setupapi.h>
28 #include <ctype.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <process.h>
32 #include <stdio.h>
33 #include <inttypes.h>
34 #include <objbase.h>
35 #include <winioctl.h>
36
37 #include "libusbi.h"
38 #include "poll_windows.h"
39 #include "windows_usb.h"
40
41 // The 2 macros below are used in conjunction with safe loops.
42 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
43 #define LOOP_BREAK(err) { r=err; continue; }
44
45 // Helper prototypes
46 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
47 static int windows_clock_gettime(int clk_id, struct timespec *tp);
48 unsigned __stdcall windows_clock_gettime_threaded(void* param);
49 // Common calls
50 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
51
52 // WinUSB-like API prototypes
53 static int winusbx_init(int sub_api, struct libusb_context *ctx);
54 static int winusbx_exit(int sub_api);
55 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
56 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
57 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
58 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
59 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
60 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
61 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
62 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
63 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
64 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
65 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer);
66 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
67 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
68 // HID API prototypes
69 static int hid_init(int sub_api, struct libusb_context *ctx);
70 static int hid_exit(int sub_api);
71 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
72 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
73 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
74 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
75 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
76 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
77 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
78 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
79 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
80 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
81 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
82 // Composite API prototypes
83 static int composite_init(int sub_api, struct libusb_context *ctx);
84 static int composite_exit(int sub_api);
85 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
86 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
87 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
88 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
89 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
90 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
91 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
92 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
93 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
94 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
95 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer);
96 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
97 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
98
99
100 // Global variables
101 uint64_t hires_frequency, hires_ticks_to_ps;
102 const uint64_t epoch_time = UINT64_C(116444736000000000);       // 1970.01.01 00:00:000 in MS Filetime
103 int windows_version = WINDOWS_UNDEFINED;
104 static char windows_version_str[128] = "Windows Undefined";
105 // Concurrency
106 static int concurrent_usage = -1;
107 usbi_mutex_t autoclaim_lock;
108 // Timer thread
109 // NB: index 0 is for monotonic and 1 is for the thread exit event
110 HANDLE timer_thread = NULL;
111 HANDLE timer_mutex = NULL;
112 struct timespec timer_tp;
113 volatile LONG request_count[2] = {0, 1};        // last one must be > 0
114 HANDLE timer_request[2] = { NULL, NULL };
115 HANDLE timer_response = NULL;
116 // API globals
117 #define CHECK_WINUSBX_AVAILABLE(sub_api) do { if (sub_api == SUB_API_NOTSET) sub_api = priv->sub_api; \
118         if (!WinUSBX[sub_api].initialized) return LIBUSB_ERROR_ACCESS; } while(0)
119 static struct winusb_interface WinUSBX[SUB_API_MAX];
120 const char* sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES;
121 bool api_hid_available = false;
122 #define CHECK_HID_AVAILABLE do { if (!api_hid_available) return LIBUSB_ERROR_ACCESS; } while (0)
123
124 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
125         if ((guid1 != NULL) && (guid2 != NULL)) {
126                 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
127         }
128         return false;
129 }
130
131 #if defined(ENABLE_LOGGING)
132 static char* guid_to_string(const GUID* guid)
133 {
134         static char guid_string[MAX_GUID_STRING_LENGTH];
135
136         if (guid == NULL) return NULL;
137         sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
138                 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
139                 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
140                 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
141         return guid_string;
142 }
143 #endif
144
145 /*
146  * Converts a windows error to human readable string
147  * uses retval as errorcode, or, if 0, use GetLastError()
148  */
149 #if defined(ENABLE_LOGGING)
150 static char *windows_error_str(uint32_t retval)
151 {
152 static char err_string[ERR_BUFFER_SIZE];
153
154         DWORD size;
155         ssize_t i;
156         uint32_t error_code, format_error;
157
158         error_code = retval?retval:GetLastError();
159
160         safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%u] ", error_code);
161
162         // Translate codes returned by SetupAPI. The ones we are dealing with are either
163         // in 0x0000xxxx or 0xE000xxxx and can be distinguished from standard error codes.
164         // See http://msdn.microsoft.com/en-us/library/windows/hardware/ff545011.aspx
165         switch (error_code & 0xE0000000) {
166         case 0:
167                 error_code = HRESULT_FROM_WIN32(error_code);    // Still leaves ERROR_SUCCESS unmodified
168                 break;
169         case 0xE0000000:
170                 error_code =  0x80000000 | (FACILITY_SETUPAPI << 16) | (error_code & 0x0000FFFF);
171                 break;
172         default:
173                 break;
174         }
175
176         size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
177                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
178                 ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
179         if (size == 0) {
180                 format_error = GetLastError();
181                 if (format_error)
182                         safe_sprintf(err_string, ERR_BUFFER_SIZE,
183                                 "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
184                 else
185                         safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
186         } else {
187                 // Remove CR/LF terminators
188                 for (i=safe_strlen(err_string)-1; (i>=0) && ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
189                         err_string[i] = 0;
190                 }
191         }
192         return err_string;
193 }
194 #endif
195
196 /*
197  * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
198  * Return an allocated sanitized string or NULL on error.
199  */
200 static char* sanitize_path(const char* path)
201 {
202         const char root_prefix[] = "\\\\.\\";
203         size_t j, size, root_size;
204         char* ret_path = NULL;
205         size_t add_root = 0;
206
207         if (path == NULL)
208                 return NULL;
209
210         size = safe_strlen(path)+1;
211         root_size = sizeof(root_prefix)-1;
212
213         // Microsoft indiscriminately uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
214         if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
215                 ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
216                 add_root = root_size;
217                 size += add_root;
218         }
219
220         if ((ret_path = (char*) calloc(size, 1)) == NULL)
221                 return NULL;
222
223         safe_strcpy(&ret_path[add_root], size-add_root, path);
224
225         // Ensure consistency with root prefix
226         for (j=0; j<root_size; j++)
227                 ret_path[j] = root_prefix[j];
228
229         // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
230         for(j=root_size; j<size; j++) {
231                 ret_path[j] = (char)toupper((int)ret_path[j]);  // Fix case too
232                 if (ret_path[j] == '\\')
233                         ret_path[j] = '#';
234         }
235
236         return ret_path;
237 }
238
239 /*
240  * Cfgmgr32, OLE32 and SetupAPI DLL functions
241  */
242 static int init_dlls(void)
243 {
244         DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
245         DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
246         DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
247         DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
248         // Prefixed to avoid conflict with header files
249         DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
250         DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
251         DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
252         DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
253         DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
254         DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
255         DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
256         DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
257         DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDeviceInterfaceRegKey, TRUE);
258         DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
259         DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
260         return LIBUSB_SUCCESS;
261 }
262
263 /*
264  * enumerate interfaces for the whole USB class
265  *
266  * Parameters:
267  * dev_info: a pointer to a dev_info list
268  * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
269  * usb_class: the generic USB class for which to retrieve interface details
270  * index: zero based index of the interface in the device info list
271  *
272  * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
273  * structure returned and call this function repeatedly using the same guid (with an
274  * incremented index starting at zero) until all interfaces have been returned.
275  */
276 static bool get_devinfo_data(struct libusb_context *ctx,
277         HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char* usb_class, unsigned _index)
278 {
279         if (_index <= 0) {
280                 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
281                 if (*dev_info == INVALID_HANDLE_VALUE) {
282                         return false;
283                 }
284         }
285
286         dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
287         if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
288                 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
289                         usbi_err(ctx, "Could not obtain device info data for index %u: %s",
290                                 _index, windows_error_str(0));
291                 }
292                 pSetupDiDestroyDeviceInfoList(*dev_info);
293                 *dev_info = INVALID_HANDLE_VALUE;
294                 return false;
295         }
296         return true;
297 }
298
299 /*
300  * enumerate interfaces for a specific GUID
301  *
302  * Parameters:
303  * dev_info: a pointer to a dev_info list
304  * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
305  * guid: the GUID for which to retrieve interface details
306  * index: zero based index of the interface in the device info list
307  *
308  * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
309  * structure returned and call this function repeatedly using the same guid (with an
310  * incremented index starting at zero) until all interfaces have been returned.
311  */
312 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
313         HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
314 {
315         SP_DEVICE_INTERFACE_DATA dev_interface_data;
316         SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
317         DWORD size;
318
319         if (_index <= 0) {
320                 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
321         }
322
323         if (dev_info_data != NULL) {
324                 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
325                 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
326                         if (GetLastError() != ERROR_NO_MORE_ITEMS) {
327                                 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
328                                         _index, windows_error_str(0));
329                         }
330                         pSetupDiDestroyDeviceInfoList(*dev_info);
331                         *dev_info = INVALID_HANDLE_VALUE;
332                         return NULL;
333                 }
334         }
335
336         dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
337         if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
338                 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
339                         usbi_err(ctx, "Could not obtain interface data for index %u: %s",
340                                 _index, windows_error_str(0));
341                 }
342                 pSetupDiDestroyDeviceInfoList(*dev_info);
343                 *dev_info = INVALID_HANDLE_VALUE;
344                 return NULL;
345         }
346
347         // Read interface data (dummy + actual) to access the device path
348         if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
349                 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
350                 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
351                         usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
352                                 _index, windows_error_str(0));
353                         goto err_exit;
354                 }
355         } else {
356                 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
357                 goto err_exit;
358         }
359
360         if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
361                 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
362                 goto err_exit;
363         }
364
365         dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
366         if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
367                 dev_interface_details, size, &size, NULL)) {
368                 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
369                         _index, windows_error_str(0));
370         }
371
372         return dev_interface_details;
373
374 err_exit:
375         pSetupDiDestroyDeviceInfoList(*dev_info);
376         *dev_info = INVALID_HANDLE_VALUE;
377         return NULL;
378 }
379
380 /* For libusb0 filter */
381 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx,
382         HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index, char* filter_path){
383         SP_DEVICE_INTERFACE_DATA dev_interface_data;
384         SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
385         DWORD size;
386         if (_index <= 0) {
387                 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
388         }
389         if (dev_info_data != NULL) {
390                 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
391                 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
392                         if (GetLastError() != ERROR_NO_MORE_ITEMS) {
393                                 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
394                                         _index, windows_error_str(0));
395                         }
396                         pSetupDiDestroyDeviceInfoList(*dev_info);
397                         *dev_info = INVALID_HANDLE_VALUE;
398                         return NULL;
399                 }
400         }
401         dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
402         if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
403                 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
404                         usbi_err(ctx, "Could not obtain interface data for index %u: %s",
405                                 _index, windows_error_str(0));
406                 }
407                 pSetupDiDestroyDeviceInfoList(*dev_info);
408                 *dev_info = INVALID_HANDLE_VALUE;
409                 return NULL;
410         }
411         // Read interface data (dummy + actual) to access the device path
412         if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
413                 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
414                 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
415                         usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
416                                 _index, windows_error_str(0));
417                         goto err_exit;
418                 }
419         } else {
420                 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
421                 goto err_exit;
422         }
423         if ((dev_interface_details = malloc(size)) == NULL) {
424                 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
425                 goto err_exit;
426         }
427         dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
428         if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
429                 dev_interface_details, size, &size, NULL)) {
430                 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
431                         _index, windows_error_str(0));
432         }
433         // [trobinso] lookup the libusb0 symbolic index.
434         if (dev_interface_details) {
435                 HKEY hkey_device_interface=pSetupDiOpenDeviceInterfaceRegKey(*dev_info,&dev_interface_data,0,KEY_READ);
436                 if (hkey_device_interface != INVALID_HANDLE_VALUE) {
437                         DWORD libusb0_symboliclink_index=0;
438                         DWORD value_length=sizeof(DWORD);
439                         DWORD value_type=0;
440                         LONG status;
441                         status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type,
442                                 (LPBYTE) &libusb0_symboliclink_index, &value_length);
443                         if (status == ERROR_SUCCESS) {
444                                 if (libusb0_symboliclink_index < 256) {
445                                         // libusb0.sys is connected to this device instance.
446                                         // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
447                                         safe_sprintf(filter_path, sizeof("\\\\.\\libusb0-0000"), "\\\\.\\libusb0-%04d", libusb0_symboliclink_index);
448                                         usbi_dbg("assigned libusb0 symbolic link %s", filter_path);
449                                 } else {
450                                         // libusb0.sys was connected to this device instance at one time; but not anymore.
451                                 }
452                         }
453                         pRegCloseKey(hkey_device_interface);
454                 }
455         }
456         return dev_interface_details;
457 err_exit:
458         pSetupDiDestroyDeviceInfoList(*dev_info);
459         *dev_info = INVALID_HANDLE_VALUE;
460         return NULL;}
461
462 /* Hash table functions - modified From glibc 2.3.2:
463    [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
464    [Knuth]            The Art of Computer Programming, part 3 (6.4)  */
465 typedef struct htab_entry {
466         unsigned long used;
467         char* str;
468 } htab_entry;
469 htab_entry* htab_table = NULL;
470 usbi_mutex_t htab_write_mutex = NULL;
471 unsigned long htab_size, htab_filled;
472
473 /* For the used double hash method the table size has to be a prime. To
474    correct the user given table size we need a prime test.  This trivial
475    algorithm is adequate because the code is called only during init and
476    the number is likely to be small  */
477 static int isprime(unsigned long number)
478 {
479         // no even number will be passed
480         unsigned int divider = 3;
481
482         while((divider * divider < number) && (number % divider != 0))
483                 divider += 2;
484
485         return (number % divider != 0);
486 }
487
488 /* Before using the hash table we must allocate memory for it.
489    We allocate one element more as the found prime number says.
490    This is done for more effective indexing as explained in the
491    comment for the hash function.  */
492 static int htab_create(struct libusb_context *ctx, unsigned long nel)
493 {
494         if (htab_table != NULL) {
495                 usbi_err(ctx, "hash table already allocated");
496         }
497
498         // Create a mutex
499         usbi_mutex_init(&htab_write_mutex, NULL);
500
501         // Change nel to the first prime number not smaller as nel.
502         nel |= 1;
503         while(!isprime(nel))
504                 nel += 2;
505
506         htab_size = nel;
507         usbi_dbg("using %d entries hash table", nel);
508         htab_filled = 0;
509
510         // allocate memory and zero out.
511         htab_table = (htab_entry*) calloc(htab_size + 1, sizeof(htab_entry));
512         if (htab_table == NULL) {
513                 usbi_err(ctx, "could not allocate space for hash table");
514                 return 0;
515         }
516
517         return 1;
518 }
519
520 /* After using the hash table it has to be destroyed.  */
521 static void htab_destroy(void)
522 {
523         size_t i;
524         if (htab_table == NULL) {
525                 return;
526         }
527
528         for (i=0; i<htab_size; i++) {
529                 if (htab_table[i].used) {
530                         safe_free(htab_table[i].str);
531                 }
532         }
533         usbi_mutex_destroy(&htab_write_mutex);
534         safe_free(htab_table);
535 }
536
537 /* This is the search function. It uses double hashing with open addressing.
538    We use an trick to speed up the lookup. The table is created with one
539    more element available. This enables us to use the index zero special.
540    This index will never be used because we store the first hash index in
541    the field used where zero means not used. Every other value means used.
542    The used field can be used as a first fast comparison for equality of
543    the stored and the parameter value. This helps to prevent unnecessary
544    expensive calls of strcmp.  */
545 static unsigned long htab_hash(char* str)
546 {
547         unsigned long hval, hval2;
548         unsigned long idx;
549         unsigned long r = 5381;
550         int c;
551         char* sz = str;
552
553         if (str == NULL)
554                 return 0;
555
556         // Compute main hash value (algorithm suggested by Nokia)
557         while ((c = *sz++) != 0)
558                 r = ((r << 5) + r) + c;
559         if (r == 0)
560                 ++r;
561
562         // compute table hash: simply take the modulus
563         hval = r % htab_size;
564         if (hval == 0)
565                 ++hval;
566
567         // Try the first index
568         idx = hval;
569
570         if (htab_table[idx].used) {
571                 if ( (htab_table[idx].used == hval)
572                   && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
573                         // existing hash
574                         return idx;
575                 }
576                 usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
577
578                 // Second hash function, as suggested in [Knuth]
579                 hval2 = 1 + hval % (htab_size - 2);
580
581                 do {
582                         // Because size is prime this guarantees to step through all available indexes
583                         if (idx <= hval2) {
584                                 idx = htab_size + idx - hval2;
585                         } else {
586                                 idx -= hval2;
587                         }
588
589                         // If we visited all entries leave the loop unsuccessfully
590                         if (idx == hval) {
591                                 break;
592                         }
593
594                         // If entry is found use it.
595                         if ( (htab_table[idx].used == hval)
596                           && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
597                                 return idx;
598                         }
599                 }
600                 while (htab_table[idx].used);
601         }
602
603         // Not found => New entry
604
605         // If the table is full return an error
606         if (htab_filled >= htab_size) {
607                 usbi_err(NULL, "hash table is full (%d entries)", htab_size);
608                 return 0;
609         }
610
611         // Concurrent threads might be storing the same entry at the same time
612         // (eg. "simultaneous" enums from different threads) => use a mutex
613         usbi_mutex_lock(&htab_write_mutex);
614         // Just free any previously allocated string (which should be the same as
615         // new one). The possibility of concurrent threads storing a collision
616         // string (same hash, different string) at the same time is extremely low
617         safe_free(htab_table[idx].str);
618         htab_table[idx].used = hval;
619         htab_table[idx].str = (char*) malloc(safe_strlen(str)+1);
620         if (htab_table[idx].str == NULL) {
621                 usbi_err(NULL, "could not duplicate string for hash table");
622                 usbi_mutex_unlock(&htab_write_mutex);
623                 return 0;
624         }
625         memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
626         ++htab_filled;
627         usbi_mutex_unlock(&htab_write_mutex);
628
629         return idx;
630 }
631
632 /*
633  * Returns the session ID of a device's nth level ancestor
634  * If there's no device at the nth level, return 0
635  */
636 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
637 {
638         DWORD parent_devinst;
639         unsigned long session_id = 0;
640         char* sanitized_path = NULL;
641         char path[MAX_PATH_LENGTH];
642         unsigned i;
643
644         if (level < 1) return 0;
645         for (i = 0; i<level; i++) {
646                 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
647                         return 0;
648                 }
649                 devinst = parent_devinst;
650         }
651         if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
652                 return 0;
653         }
654         // TODO: (post hotplug): try without sanitizing
655         sanitized_path = sanitize_path(path);
656         if (sanitized_path == NULL) {
657                 return 0;
658         }
659         session_id = htab_hash(sanitized_path);
660         safe_free(sanitized_path);
661         return session_id;
662 }
663
664 /*
665  * Populate the endpoints addresses of the device_priv interface helper structs
666  */
667 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
668 {
669         int i, r;
670         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
671         struct libusb_config_descriptor *conf_desc;
672         const struct libusb_interface_descriptor *if_desc;
673         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
674
675         r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
676         if (r != LIBUSB_SUCCESS) {
677                 usbi_warn(ctx, "could not read config descriptor: error %d", r);
678                 return r;
679         }
680
681         if_desc = &conf_desc->interface[iface].altsetting[altsetting];
682         safe_free(priv->usb_interface[iface].endpoint);
683
684         if (if_desc->bNumEndpoints == 0) {
685                 usbi_dbg("no endpoints found for interface %d", iface);
686                 return LIBUSB_SUCCESS;
687         }
688
689         priv->usb_interface[iface].endpoint = (uint8_t*) malloc(if_desc->bNumEndpoints);
690         if (priv->usb_interface[iface].endpoint == NULL) {
691                 return LIBUSB_ERROR_NO_MEM;
692         }
693
694         priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
695         for (i=0; i<if_desc->bNumEndpoints; i++) {
696                 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
697                 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
698         }
699         libusb_free_config_descriptor(conf_desc);
700
701         // Extra init may be required to configure endpoints
702         return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
703 }
704
705 // Lookup for a match in the list of API driver names
706 // return -1 if not found, driver match number otherwise
707 static int get_sub_api(char* driver, int api){
708         int i;
709         const char sep_str[2] = {LIST_SEPARATOR, 0};
710         char *tok, *tmp_str;
711         size_t len = safe_strlen(driver);
712
713         if (len == 0) return SUB_API_NOTSET;
714         tmp_str = (char*) calloc(len+1, 1);
715         if (tmp_str == NULL) return SUB_API_NOTSET;
716         memcpy(tmp_str, driver, len+1);
717         tok = strtok(tmp_str, sep_str);
718         while (tok != NULL) {
719                 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
720                         if (safe_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
721                                 free(tmp_str);
722                                 return i;
723                         }
724                 }
725                 tok = strtok(NULL, sep_str);
726         }
727         free (tmp_str);
728         return SUB_API_NOTSET;
729 }
730
731 /*
732  * auto-claiming and auto-release helper functions
733  */
734 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
735 {
736         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
737         struct windows_device_handle_priv *handle_priv = _device_handle_priv(
738                 transfer->dev_handle);
739         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
740         int current_interface = *interface_number;
741         int r = LIBUSB_SUCCESS;
742
743         switch(api_type) {
744         case USB_API_WINUSBX:
745         case USB_API_HID:
746                 break;
747         default:
748                 return LIBUSB_ERROR_INVALID_PARAM;
749         }
750
751         usbi_mutex_lock(&autoclaim_lock);
752         if (current_interface < 0)      // No serviceable interface was found
753         {
754                 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
755                         // Must claim an interface of the same API type
756                         if ( (priv->usb_interface[current_interface].apib->id == api_type)
757                           && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
758                                 usbi_dbg("auto-claimed interface %d for control request", current_interface);
759                                 if (handle_priv->autoclaim_count[current_interface] != 0) {
760                                         usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
761                                 }
762                                 handle_priv->autoclaim_count[current_interface]++;
763                                 break;
764                         }
765                 }
766                 if (current_interface == USB_MAXINTERFACES) {
767                         usbi_err(ctx, "could not auto-claim any interface");
768                         r = LIBUSB_ERROR_NOT_FOUND;
769                 }
770         } else {
771                 // If we have a valid interface that was autoclaimed, we must increment
772                 // its autoclaim count so that we can prevent an early release.
773                 if (handle_priv->autoclaim_count[current_interface] != 0) {
774                         handle_priv->autoclaim_count[current_interface]++;
775                 }
776         }
777         usbi_mutex_unlock(&autoclaim_lock);
778
779         *interface_number = current_interface;
780         return r;
781
782 }
783
784 static void auto_release(struct usbi_transfer *itransfer)
785 {
786         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
787         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
788         libusb_device_handle *dev_handle = transfer->dev_handle;
789         struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
790         int r;
791
792         usbi_mutex_lock(&autoclaim_lock);
793         if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
794                 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
795                 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
796                         r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
797                         if (r == LIBUSB_SUCCESS) {
798                                 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
799                         } else {
800                                 usbi_dbg("failed to auto-release interface %d (%s)",
801                                         transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
802                         }
803                 }
804         }
805         usbi_mutex_unlock(&autoclaim_lock);
806 }
807
808 /* Windows version dtection */
809 static BOOL is_x64(void)
810 {
811         BOOL ret = FALSE;
812         // Detect if we're running a 32 or 64 bit system
813         if (sizeof(uintptr_t) < 8) {
814                 DLL_LOAD_PREFIXED(Kernel32.dll, p, IsWow64Process, FALSE);
815                 if (pIsWow64Process != NULL) {
816                         (*pIsWow64Process)(GetCurrentProcess(), &ret);
817                 }
818         } else {
819                 ret = TRUE;
820         }
821         return ret;
822 }
823
824 static void get_windows_version(void)
825 {
826         OSVERSIONINFOEXA vi, vi2;
827         const char* w = 0;
828         const char* w64 = "32 bit";
829         char* vptr;
830         size_t vlen;
831         unsigned major, minor;
832         ULONGLONG major_equal, minor_equal;
833         BOOL ws;
834
835         memset(&vi, 0, sizeof(vi));
836         vi.dwOSVersionInfoSize = sizeof(vi);
837         if (!GetVersionExA((OSVERSIONINFOA *)&vi)) {
838                 memset(&vi, 0, sizeof(vi));
839                 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
840                 if (!GetVersionExA((OSVERSIONINFOA *)&vi))
841                         return;
842         }
843
844         if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
845
846                 if (vi.dwMajorVersion > 6 || (vi.dwMajorVersion == 6 && vi.dwMinorVersion >= 2)) {
847                         // Starting with Windows 8.1 Preview, GetVersionEx() does no longer report the actual OS version
848                         // See: http://msdn.microsoft.com/en-us/library/windows/desktop/dn302074.aspx
849
850                         major_equal = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL);
851                         for (major = vi.dwMajorVersion; major <= 9; major++) {
852                                 memset(&vi2, 0, sizeof(vi2));
853                                 vi2.dwOSVersionInfoSize = sizeof(vi2); vi2.dwMajorVersion = major;
854                                 if (!VerifyVersionInfoA(&vi2, VER_MAJORVERSION, major_equal))
855                                         continue;
856                                 if (vi.dwMajorVersion < major) {
857                                         vi.dwMajorVersion = major; vi.dwMinorVersion = 0;
858                                 }
859
860                                 minor_equal = VerSetConditionMask(0, VER_MINORVERSION, VER_EQUAL);
861                                 for (minor = vi.dwMinorVersion; minor <= 9; minor++) {
862                                         memset(&vi2, 0, sizeof(vi2)); vi2.dwOSVersionInfoSize = sizeof(vi2);
863                                         vi2.dwMinorVersion = minor;
864                                         if (!VerifyVersionInfoA(&vi2, VER_MINORVERSION, minor_equal))
865                                                 continue;
866                                         vi.dwMinorVersion = minor;
867                                         break;
868                                 }
869
870                                 break;
871                         }
872                 }
873
874                 if (vi.dwMajorVersion <= 0xf && vi.dwMinorVersion <= 0xf) {
875                         ws = (vi.wProductType <= VER_NT_WORKSTATION);
876                         windows_version = vi.dwMajorVersion << 4 | vi.dwMinorVersion;
877                         switch (windows_version) {
878                         case 0x50: w = "2000";
879                                 break;
880                         case 0x51: w = "XP";
881                                 break;
882                         case 0x52: w = (!GetSystemMetrics(89)?"2003":"2003_R2");
883                                 break;
884                         case 0x60: w = (ws?"Vista":"2008");
885                                 break;
886                         case 0x61: w = (ws?"7":"2008_R2");
887                                 break;
888                         case 0x62: w = (ws?"8":"2012");
889                                 break;
890                         case 0x63: w = (ws?"8.1":"2012_R2");
891                                 break;
892                         case 0x64: w = (ws?"8.2":"2012_R3");
893                                 break;
894                         default:
895                                 if (windows_version < 0x50)
896                                         windows_version = WINDOWS_UNSUPPORTED;
897                                 else
898                                         w = "9 or later";
899                                 break;
900                         }
901                 }
902         }
903
904         if (is_x64())
905                 w64 = "64-bit";
906
907         vptr = &windows_version_str[sizeof("Windows ") - 1];
908         vlen = sizeof(windows_version_str) - sizeof("Windows ") - 1;
909         if (!w)
910                 safe_sprintf(vptr, vlen, "%s %u.%u %s", (vi.dwPlatformId==VER_PLATFORM_WIN32_NT?"NT":"??"),
911                         (unsigned)vi.dwMajorVersion, (unsigned)vi.dwMinorVersion, w64);
912         else if (vi.wServicePackMinor)
913                 safe_sprintf(vptr, vlen, "%s SP%u.%u %s", w, vi.wServicePackMajor, vi.wServicePackMinor, w64);
914         else if (vi.wServicePackMajor)
915                 safe_sprintf(vptr, vlen, "%s SP%u %s", w, vi.wServicePackMajor, w64);
916         else
917                 safe_sprintf(vptr, vlen, "%s %s", w, w64);
918 }
919
920 /*
921  * init: libusb backend init function
922  *
923  * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
924  * In our implementation, we equate Windows' "HCD" to libusb's "bus". Note that bus is zero indexed.
925  * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
926  */
927 static int windows_init(struct libusb_context *ctx)
928 {
929         int i, r = LIBUSB_ERROR_OTHER;
930         HANDLE semaphore;
931         char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
932
933         sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
934         semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
935         if (semaphore == NULL) {
936                 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
937                 return LIBUSB_ERROR_NO_MEM;
938         }
939
940         // A successful wait brings our semaphore count to 0 (unsignaled)
941         // => any concurent wait stalls until the semaphore's release
942         if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
943                 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
944                 CloseHandle(semaphore);
945                 return LIBUSB_ERROR_NO_MEM;
946         }
947
948         // NB: concurrent usage supposes that init calls are equally balanced with
949         // exit calls. If init is called more than exit, we will not exit properly
950         if ( ++concurrent_usage == 0 ) {        // First init?
951                 get_windows_version();
952                 usbi_dbg(windows_version_str);
953                 if (windows_version == WINDOWS_UNSUPPORTED) {
954                         usbi_err(ctx, "This version of Windows is NOT supported");
955                         r = LIBUSB_ERROR_NOT_SUPPORTED;
956                         goto init_exit;
957                 }
958
959                 // We need a lock for proper auto-release
960                 usbi_mutex_init(&autoclaim_lock, NULL);
961
962                 // Initialize pollable file descriptors
963                 init_polling();
964
965                 // Load DLL imports
966                 if (init_dlls() != LIBUSB_SUCCESS) {
967                         usbi_err(ctx, "could not resolve DLL functions");
968                         return LIBUSB_ERROR_NOT_FOUND;
969                 }
970
971                 // Initialize the low level APIs (we don't care about errors at this stage)
972                 for (i=0; i<USB_API_MAX; i++) {
973                         usb_api_backend[i].init(SUB_API_NOTSET, ctx);
974                 }
975
976                 // Because QueryPerformanceCounter might report different values when
977                 // running on different cores, we create a separate thread for the timer
978                 // calls, which we glue to the first core always to prevent timing discrepancies.
979                 r = LIBUSB_ERROR_NO_MEM;
980                 for (i = 0; i < 2; i++) {
981                         timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
982                         if (timer_request[i] == NULL) {
983                                 usbi_err(ctx, "could not create timer request event %d - aborting", i);
984                                 goto init_exit;
985                         }
986                 }
987                 timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
988                 if (timer_response == NULL) {
989                         usbi_err(ctx, "could not create timer response semaphore - aborting");
990                         goto init_exit;
991                 }
992                 timer_mutex = CreateMutex(NULL, FALSE, NULL);
993                 if (timer_mutex == NULL) {
994                         usbi_err(ctx, "could not create timer mutex - aborting");
995                         goto init_exit;
996                 }
997                 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
998                 if (timer_thread == NULL) {
999                         usbi_err(ctx, "Unable to create timer thread - aborting");
1000                         goto init_exit;
1001                 }
1002                 SetThreadAffinityMask(timer_thread, 0);
1003
1004                 // Wait for timer thread to init before continuing.
1005                 if (WaitForSingleObject(timer_response, INFINITE) != WAIT_OBJECT_0) {
1006                         usbi_err(ctx, "Failed to wait for timer thread to become ready - aborting");
1007                         goto init_exit;
1008                 }
1009
1010                 // Create a hash table to store session ids. Second parameter is better if prime
1011                 htab_create(ctx, HTAB_SIZE);
1012         }
1013         // At this stage, either we went through full init successfully, or didn't need to
1014         r = LIBUSB_SUCCESS;
1015
1016 init_exit: // Holds semaphore here.
1017         if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
1018                 if (timer_thread) {
1019                         SetEvent(timer_request[1]); // actually the signal to quit the thread.
1020                         if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1021                                 usbi_warn(ctx, "could not wait for timer thread to quit");
1022                                 TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
1023                                                                                                   // all objects it might have held anyway.
1024                         }
1025                         CloseHandle(timer_thread);
1026                         timer_thread = NULL;
1027                 }
1028                 for (i = 0; i < 2; i++) {
1029                         if (timer_request[i]) {
1030                                 CloseHandle(timer_request[i]);
1031                                 timer_request[i] = NULL;
1032                         }
1033                 }
1034                 if (timer_response) {
1035                         CloseHandle(timer_response);
1036                         timer_response = NULL;
1037                 }
1038                 if (timer_mutex) {
1039                         CloseHandle(timer_mutex);
1040                         timer_mutex = NULL;
1041                 }
1042                 htab_destroy();
1043         }
1044
1045         if (r != LIBUSB_SUCCESS)
1046                 --concurrent_usage; // Not expected to call libusb_exit if we failed.
1047
1048         ReleaseSemaphore(semaphore, 1, NULL);   // increase count back to 1
1049         CloseHandle(semaphore);
1050         return r;
1051 }
1052
1053 /*
1054  * HCD (root) hubs need to have their device descriptor manually populated
1055  *
1056  * Note that, like Microsoft does in the device manager, we populate the
1057  * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
1058  */
1059 static int force_hcd_device_descriptor(struct libusb_device *dev)
1060 {
1061         struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
1062         struct libusb_context *ctx = DEVICE_CTX(dev);
1063         int vid, pid;
1064
1065         dev->num_configurations = 1;
1066         priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
1067         priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
1068         priv->dev_descriptor.bNumConfigurations = 1;
1069         priv->active_config = 1;
1070
1071         if (priv->parent_dev == NULL) {
1072                 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
1073                 return LIBUSB_ERROR_NO_DEVICE;
1074         }
1075         parent_priv = _device_priv(priv->parent_dev);
1076         if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
1077                 priv->dev_descriptor.idVendor = (uint16_t)vid;
1078                 priv->dev_descriptor.idProduct = (uint16_t)pid;
1079         } else {
1080                 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
1081                 priv->dev_descriptor.idVendor = 0x1d6b;         // Linux Foundation root hub
1082                 priv->dev_descriptor.idProduct = 1;
1083         }
1084         return LIBUSB_SUCCESS;
1085 }
1086
1087 /*
1088  * fetch and cache all the config descriptors through I/O
1089  */
1090 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
1091 {
1092         DWORD size, ret_size;
1093         struct libusb_context *ctx = DEVICE_CTX(dev);
1094         struct windows_device_priv *priv = _device_priv(dev);
1095         int r;
1096         uint8_t i;
1097
1098         USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short;    // dummy request
1099         PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL;       // actual request
1100         PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
1101
1102         if (dev->num_configurations == 0)
1103                 return LIBUSB_ERROR_INVALID_PARAM;
1104
1105         priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(unsigned char*));
1106         if (priv->config_descriptor == NULL)
1107                 return LIBUSB_ERROR_NO_MEM;
1108         for (i=0; i<dev->num_configurations; i++)
1109                 priv->config_descriptor[i] = NULL;
1110
1111         for (i=0, r=LIBUSB_SUCCESS; ; i++)
1112         {
1113                 // safe loop: release all dynamic resources
1114                 safe_free(cd_buf_actual);
1115
1116                 // safe loop: end of loop condition
1117                 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
1118                         break;
1119
1120                 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
1121                 memset(&cd_buf_short, 0, size);
1122
1123                 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
1124                 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
1125                 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
1126                 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
1127                 cd_buf_short.req.SetupPacket.wIndex = i;
1128                 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
1129
1130                 // Dummy call to get the required data size. Initial failures are reported as info rather
1131                 // than error as they can occur for non-penalizing situations, such as with some hubs.
1132                 // coverity[tainted_data_argument]
1133                 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
1134                         &cd_buf_short, size, &ret_size, NULL)) {
1135                         usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
1136                         LOOP_BREAK(LIBUSB_ERROR_IO);
1137                 }
1138
1139                 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
1140                         usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
1141                         LOOP_BREAK(LIBUSB_ERROR_IO);
1142                 }
1143
1144                 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
1145                 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST) calloc(1, size)) == NULL) {
1146                         usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
1147                         LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1148                 }
1149                 memset(cd_buf_actual, 0, size);
1150
1151                 // Actual call
1152                 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
1153                 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
1154                 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
1155                 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
1156                 cd_buf_actual->SetupPacket.wIndex = i;
1157                 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
1158
1159                 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
1160                         cd_buf_actual, size, &ret_size, NULL)) {
1161                         usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
1162                         LOOP_BREAK(LIBUSB_ERROR_IO);
1163                 }
1164
1165                 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
1166
1167                 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
1168                         usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
1169                         LOOP_BREAK(LIBUSB_ERROR_IO);
1170                 }
1171
1172                 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
1173                         usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
1174                         LOOP_BREAK(LIBUSB_ERROR_IO);
1175                 }
1176
1177                 usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
1178                         i, cd_data->bConfigurationValue, cd_data->wTotalLength);
1179
1180                 // Cache the descriptor
1181                 priv->config_descriptor[i] = (unsigned char*) malloc(cd_data->wTotalLength);
1182                 if (priv->config_descriptor[i] == NULL)
1183                         LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1184                 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
1185         }
1186         return LIBUSB_SUCCESS;
1187 }
1188
1189 /*
1190  * Populate a libusb device structure
1191  */
1192 static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
1193                                            uint8_t port_number, char* device_id, DWORD devinst)
1194 {
1195         HANDLE handle;
1196         DWORD size;
1197         USB_NODE_CONNECTION_INFORMATION_EX conn_info;
1198         USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
1199         struct windows_device_priv *priv, *parent_priv;
1200         struct libusb_context *ctx;
1201         struct libusb_device* tmp_dev;
1202         unsigned i;
1203
1204         if ((dev == NULL) || (parent_dev == NULL)) {
1205                 return LIBUSB_ERROR_NOT_FOUND;
1206         }
1207         ctx = DEVICE_CTX(dev);
1208         priv = _device_priv(dev);
1209         parent_priv = _device_priv(parent_dev);
1210         if (parent_priv->apib->id != USB_API_HUB) {
1211                 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
1212                 return LIBUSB_ERROR_NOT_FOUND;
1213         }
1214
1215         // It is possible for the parent hub not to have been initialized yet
1216         // If that's the case, lookup the ancestors to set the bus number
1217         if (parent_dev->bus_number == 0) {
1218                 for (i=2; ; i++) {
1219                         tmp_dev = usbi_get_device_by_session_id(ctx, get_ancestor_session_id(devinst, i));
1220                         if (tmp_dev == NULL) break;
1221                         if (tmp_dev->bus_number != 0) {
1222                                 usbi_dbg("got bus number from ancestor #%d", i);
1223                                 parent_dev->bus_number = tmp_dev->bus_number;
1224                                 libusb_unref_device(tmp_dev);
1225                                 break;
1226                         }
1227                         libusb_unref_device(tmp_dev);
1228                 }
1229         }
1230         if (parent_dev->bus_number == 0) {
1231                 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1232                 return LIBUSB_ERROR_NOT_FOUND;
1233         }
1234         dev->bus_number = parent_dev->bus_number;
1235         priv->port = port_number;
1236         dev->port_number = port_number;
1237         priv->depth = parent_priv->depth + 1;
1238         priv->parent_dev = parent_dev;
1239         dev->parent_dev = parent_dev;
1240
1241         // If the device address is already set, we can stop here
1242         if (dev->device_address != 0) {
1243                 return LIBUSB_SUCCESS;
1244         }
1245         memset(&conn_info, 0, sizeof(conn_info));
1246         if (priv->depth != 0) { // Not a HCD hub
1247                 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1248                         FILE_FLAG_OVERLAPPED, NULL);
1249                 if (handle == INVALID_HANDLE_VALUE) {
1250                         usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1251                         return LIBUSB_ERROR_ACCESS;
1252                 }
1253                 size = sizeof(conn_info);
1254                 conn_info.ConnectionIndex = (ULONG)port_number;
1255                 // coverity[tainted_data_argument]
1256                 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1257                         &conn_info, size, &size, NULL)) {
1258                         usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1259                                 device_id, windows_error_str(0));
1260                         safe_closehandle(handle);
1261                         return LIBUSB_ERROR_NO_DEVICE;
1262                 }
1263                 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1264                         usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1265                         safe_closehandle(handle);
1266                         return LIBUSB_ERROR_NO_DEVICE;
1267                 }
1268                 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1269                 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1270                 priv->active_config = conn_info.CurrentConfigurationValue;
1271                 usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
1272                 // If we can't read the config descriptors, just set the number of confs to zero
1273                 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1274                         dev->num_configurations = 0;
1275                         priv->dev_descriptor.bNumConfigurations = 0;
1276                 }
1277
1278                 // In their great wisdom, Microsoft decided to BREAK the USB speed report between Windows 7 and Windows 8
1279                 if (windows_version >= WINDOWS_8) {
1280                         memset(&conn_info_v2, 0, sizeof(conn_info_v2));
1281                         size = sizeof(conn_info_v2);
1282                         conn_info_v2.ConnectionIndex = (ULONG)port_number;
1283                         conn_info_v2.Length = size;
1284                         conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
1285                         if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
1286                                 &conn_info_v2, size, &conn_info_v2, size, &size, NULL)) {
1287                                 usbi_warn(ctx, "could not get node connection information (V2) for device '%s': %s",
1288                                         device_id,  windows_error_str(0));
1289                         } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedOrHigher) {
1290                                 conn_info.Speed = 3;
1291                         }
1292                 }
1293
1294                 safe_closehandle(handle);
1295
1296                 if (conn_info.DeviceAddress > UINT8_MAX) {
1297                         usbi_err(ctx, "program assertion failed: device address overflow");
1298                 }
1299                 dev->device_address = (uint8_t)conn_info.DeviceAddress + 1;
1300                 if (dev->device_address == 1) {
1301                         usbi_err(ctx, "program assertion failed: device address collision with root hub");
1302                 }
1303                 switch (conn_info.Speed) {
1304                 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1305                 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1306                 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1307                 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1308                 default:
1309                         usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
1310                         break;
1311                 }
1312         } else {
1313                 dev->device_address = 1;        // root hubs are set to use device number 1
1314                 force_hcd_device_descriptor(dev);
1315         }
1316
1317         usbi_sanitize_device(dev);
1318
1319         usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
1320                 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1321
1322         return LIBUSB_SUCCESS;
1323 }
1324
1325 // Returns the api type, or 0 if not found/unsupported
1326 static void get_api_type(struct libusb_context *ctx, HDEVINFO *dev_info,
1327         SP_DEVINFO_DATA *dev_info_data, int *api, int *sub_api)
1328 {
1329         // Precedence for filter drivers vs driver is in the order of this array
1330         struct driver_lookup lookup[3] = {
1331                 {"\0\0", SPDRP_SERVICE, "driver"},
1332                 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1333                 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1334         };
1335         DWORD size, reg_type;
1336         unsigned k, l;
1337         int i, j;
1338
1339         *api = USB_API_UNSUPPORTED;
1340         *sub_api = SUB_API_NOTSET;
1341         // Check the service & filter names to know the API we should use
1342         for (k=0; k<3; k++) {
1343                 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1344                         &reg_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1345                         // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1346                         if (lookup[k].reg_prop == SPDRP_SERVICE) {
1347                                 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1348                                 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1349                         }
1350                         // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1351                         // NB: none of the driver names we check against contain LIST_SEPARATOR,
1352                         // (currently ';'), so even if an unsuported one does, it's not an issue
1353                         for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1354                                 if (lookup[k].list[l] == 0) {
1355                                         lookup[k].list[l] = LIST_SEPARATOR;
1356                                 }
1357                         }
1358                         usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1359                 } else {
1360                         if (GetLastError() != ERROR_INVALID_DATA) {
1361                                 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1362                         }
1363                         lookup[k].list[0] = 0;
1364                 }
1365         }
1366
1367         for (i=1; i<USB_API_MAX; i++) {
1368                 for (k=0; k<3; k++) {
1369                         j = get_sub_api(lookup[k].list, i);
1370                         if (j >= 0) {
1371                                 usbi_dbg("matched %s name against %s",
1372                                         lookup[k].designation, (i!=USB_API_WINUSBX)?usb_api_backend[i].designation:sub_api_name[j]);
1373                                 *api = i;
1374                                 *sub_api = j;
1375                                 return;
1376                         }
1377                 }
1378         }
1379 }
1380
1381 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
1382                                                         char* dev_interface_path, char* device_id, int api, int sub_api)
1383 {
1384         unsigned i;
1385         struct windows_device_priv *priv = _device_priv(dev);
1386         int interface_number;
1387
1388         if (priv->apib->id != USB_API_COMPOSITE) {
1389                 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1390                 return LIBUSB_ERROR_NO_DEVICE;
1391         }
1392
1393         // Because MI_## are not necessarily in sequential order (some composite
1394         // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1395         // interface number from the path's MI value
1396         interface_number = 0;
1397         for (i=0; device_id[i] != 0; ) {
1398                 if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
1399                   && (device_id[i++] == '_') ) {
1400                         interface_number = (device_id[i++] - '0')*10;
1401                         interface_number += device_id[i] - '0';
1402                         break;
1403                 }
1404         }
1405
1406         if (device_id[i] == 0) {
1407                 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1408                         device_id, interface_number);
1409         }
1410
1411         if (priv->usb_interface[interface_number].path != NULL) {
1412                 if (api == USB_API_HID) {
1413                         // HID devices can have multiple collections (COL##) for each MI_## interface
1414                         usbi_dbg("interface[%d] already set - ignoring HID collection: %s",
1415                                 interface_number, device_id);
1416                         return LIBUSB_ERROR_ACCESS;
1417                 }
1418                 // In other cases, just use the latest data
1419                 safe_free(priv->usb_interface[interface_number].path);
1420         }
1421
1422         usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1423         priv->usb_interface[interface_number].path = dev_interface_path;
1424         priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1425         priv->usb_interface[interface_number].sub_api = sub_api;
1426         if ((api == USB_API_HID) && (priv->hid == NULL)) {
1427                 priv->hid = (struct hid_device_priv*) calloc(1, sizeof(struct hid_device_priv));
1428                 if (priv->hid == NULL)
1429                         return LIBUSB_ERROR_NO_MEM;
1430         }
1431
1432         return LIBUSB_SUCCESS;
1433 }
1434
1435 static int set_hid_interface(struct libusb_context* ctx, struct libusb_device* dev,
1436                                                         char* dev_interface_path)
1437 {
1438         int i;
1439         struct windows_device_priv *priv = _device_priv(dev);
1440
1441         if (priv->hid == NULL) {
1442                 usbi_err(ctx, "program assertion failed: parent is not HID");
1443                 return LIBUSB_ERROR_NO_DEVICE;
1444         }
1445         if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
1446                 usbi_err(ctx, "program assertion failed: max USB interfaces reached for HID device");
1447                 return LIBUSB_ERROR_NO_DEVICE;
1448         }
1449         for (i=0; i<priv->hid->nb_interfaces; i++) {
1450                 if (safe_strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
1451                         usbi_dbg("interface[%d] already set to %s", i, dev_interface_path);
1452                         return LIBUSB_SUCCESS;
1453                 }
1454         }
1455
1456         priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
1457         priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
1458         usbi_dbg("interface[%d] = %s", priv->hid->nb_interfaces, dev_interface_path);
1459         priv->hid->nb_interfaces++;
1460         return LIBUSB_SUCCESS;
1461 }
1462
1463 /*
1464  * get_device_list: libusb backend device enumeration function
1465  */
1466 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1467 {
1468         struct discovered_devs *discdevs;
1469         HDEVINFO dev_info = { 0 };
1470         const char* usb_class[] = {"USB", "NUSB3", "IUSB3"};
1471         SP_DEVINFO_DATA dev_info_data = { 0 };
1472         SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1473         GUID hid_guid;
1474 #define MAX_ENUM_GUIDS 64
1475         const GUID* guid[MAX_ENUM_GUIDS];
1476 #define HCD_PASS 0
1477 #define HUB_PASS 1
1478 #define GEN_PASS 2
1479 #define DEV_PASS 3
1480 #define HID_PASS 4
1481         int r = LIBUSB_SUCCESS;
1482         int api, sub_api;
1483         size_t class_index = 0;
1484         unsigned int nb_guids, pass, i, j, ancestor;
1485         char path[MAX_PATH_LENGTH];
1486         char strbuf[MAX_PATH_LENGTH];
1487         struct libusb_device *dev, *parent_dev;
1488         struct windows_device_priv *priv, *parent_priv;
1489         char* dev_interface_path = NULL;
1490         char* dev_id_path = NULL;
1491         unsigned long session_id;
1492         DWORD size, reg_type, port_nr, install_state;
1493         HKEY key;
1494         WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1495         GUID* if_guid;
1496         LONG s;
1497         // Keep a list of newly allocated devs to unref
1498         libusb_device** unref_list;
1499         unsigned int unref_size = 64;
1500         unsigned int unref_cur = 0;
1501
1502         // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1503         // PASS 2 : (re)enumerate HUBS
1504         // PASS 3 : (re)enumerate generic USB devices (including driverless)
1505         //           and list additional USB device interface GUIDs to explore
1506         // PASS 4 : (re)enumerate master USB devices that have a device interface
1507         // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
1508         //           set the device interfaces.
1509
1510         // Init the GUID table
1511         guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1512         guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1513         guid[GEN_PASS] = NULL;
1514         guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1515         HidD_GetHidGuid(&hid_guid);
1516         guid[HID_PASS] = &hid_guid;
1517         nb_guids = HID_PASS+1;
1518
1519         unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
1520         if (unref_list == NULL) {
1521                 return LIBUSB_ERROR_NO_MEM;
1522         }
1523
1524         for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1525 //#define ENUM_DEBUG
1526 #ifdef ENUM_DEBUG
1527                 const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "HID", "EXT" };
1528                 usbi_dbg("\n#### PROCESSING %ss %s", passname[(pass<=HID_PASS)?pass:HID_PASS+1],
1529                         (pass!=GEN_PASS)?guid_to_string(guid[pass]):"");
1530 #endif
1531                 for (i = 0; ; i++) {
1532                         // safe loop: free up any (unprotected) dynamic resource
1533                         // NB: this is always executed before breaking the loop
1534                         safe_free(dev_interface_details);
1535                         safe_free(dev_interface_path);
1536                         safe_free(dev_id_path);
1537                         priv = parent_priv = NULL;
1538                         dev = parent_dev = NULL;
1539
1540                         // Safe loop: end of loop conditions
1541                         if (r != LIBUSB_SUCCESS) {
1542                                 break;
1543                         }
1544                         if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1545                                 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1546                                 break;
1547                         }
1548                         if (pass != GEN_PASS) {
1549                                 // Except for GEN, all passes deal with device interfaces
1550                                 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1551                                 if (dev_interface_details == NULL) {
1552                                         break;
1553                                 } else {
1554                                         dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1555                                         if (dev_interface_path == NULL) {
1556                                                 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1557                                                 continue;
1558                                         }
1559                                 }
1560                         } else {
1561                                 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1562                                 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
1563                                 // The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
1564                                 for (; class_index < ARRAYSIZE(usb_class); class_index++) {
1565                                         if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))
1566                                                 break;
1567                                         i = 0;
1568                                 }
1569                                 if (class_index >= ARRAYSIZE(usb_class))
1570                                         break;
1571                         }
1572
1573                         // Read the Device ID path. This is what we'll use as UID
1574                         // Note that if the device is plugged in a different port or hub, the Device ID changes
1575                         if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1576                                 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1577                                         dev_info_data.DevInst);
1578                                 continue;
1579                         }
1580                         dev_id_path = sanitize_path(path);
1581                         if (dev_id_path == NULL) {
1582                                 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1583                                         dev_info_data.DevInst);
1584                                 continue;
1585                         }
1586 #ifdef ENUM_DEBUG
1587                         usbi_dbg("PRO: %s", dev_id_path);
1588 #endif
1589
1590                         // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1591                         port_nr = 0;
1592                         if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1593                                 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1594                                         &reg_type, (BYTE*)&port_nr, 4, &size))
1595                                   || (size != 4) ) {
1596                                         usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1597                                                 dev_id_path, windows_error_str(0));
1598                                         continue;
1599                                 }
1600                         }
1601
1602                         // Set API to use or get additional data from generic pass
1603                         api = USB_API_UNSUPPORTED;
1604                         sub_api = SUB_API_NOTSET;
1605                         switch (pass) {
1606                         case HCD_PASS:
1607                                 break;
1608                         case GEN_PASS:
1609                                 // We use the GEN pass to detect driverless devices...
1610                                 size = sizeof(strbuf);
1611                                 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1612                                         &reg_type, (BYTE*)strbuf, size, &size)) {
1613                                                 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1614                                                 usbi_info(ctx, "libusb will not be able to access it.");
1615                                 }
1616                                 // ...and to add the additional device interface GUIDs
1617                                 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1618                                 if (key != INVALID_HANDLE_VALUE) {
1619                                         size = sizeof(guid_string_w);
1620                                         s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &reg_type,
1621                                                 (BYTE*)guid_string_w, &size);
1622                                         pRegCloseKey(key);
1623                                         if (s == ERROR_SUCCESS) {
1624                                                 if (nb_guids >= MAX_ENUM_GUIDS) {
1625                                                         // If this assert is ever reported, grow a GUID table dynamically
1626                                                         usbi_err(ctx, "program assertion failed: too many GUIDs");
1627                                                         LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1628                                                 }
1629                                                 if_guid = (GUID*) calloc(1, sizeof(GUID));
1630                                                 pCLSIDFromString(guid_string_w, if_guid);
1631                                                 guid[nb_guids++] = if_guid;
1632                                                 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1633                                         }
1634                                 }
1635                                 break;
1636                         case HID_PASS:
1637                                 api = USB_API_HID;
1638                                 break;
1639                         default:
1640                                 // Get the API type (after checking that the driver installation is OK)
1641                                 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1642                                         &reg_type, (BYTE*)&install_state, 4, &size))
1643                                   || (size != 4) ){
1644                                         usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1645                                                 dev_id_path, windows_error_str(0));
1646                                 } else if (install_state != 0) {
1647                                         usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
1648                                                 dev_id_path, install_state);
1649                                         continue;
1650                                 }
1651                                 get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api);
1652                                 break;
1653                         }
1654
1655                         // Find parent device (for the passes that need it)
1656                         switch (pass) {
1657                         case HCD_PASS:
1658                         case DEV_PASS:
1659                         case HUB_PASS:
1660                                 break;
1661                         default:
1662                                 // Go through the ancestors until we see a face we recognize
1663                                 parent_dev = NULL;
1664                                 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1665                                         session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1666                                         if (session_id == 0) {
1667                                                 break;
1668                                         }
1669                                         parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1670                                 }
1671                                 if (parent_dev == NULL) {
1672                                         usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
1673                                         continue;
1674                                 }
1675                                 parent_priv = _device_priv(parent_dev);
1676                                 // virtual USB devices are also listed during GEN - don't process these yet
1677                                 if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
1678                                         libusb_unref_device(parent_dev);
1679                                         continue;
1680                                 }
1681                                 break;
1682                         }
1683
1684                         // Create new or match existing device, using the (hashed) device_id as session id
1685                         if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1686                                 // These are the passes that create "new" devices
1687                                 session_id = htab_hash(dev_id_path);
1688                                 dev = usbi_get_device_by_session_id(ctx, session_id);
1689                                 if (dev == NULL) {
1690                                         if (pass == DEV_PASS) {
1691                                                 // This can occur if the OS only reports a newly plugged device after we started enum
1692                                                 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1693                                                         " - ignoring", dev_id_path);
1694                                                 continue;
1695                                         }
1696                                         usbi_dbg("allocating new device for session [%X]", session_id);
1697                                         if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1698                                                 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1699                                         }
1700                                         windows_device_priv_init(dev);
1701                                 } else {
1702                                         usbi_dbg("found existing device for session [%X] (%d.%d)",
1703                                                 session_id, dev->bus_number, dev->device_address);
1704                                 }
1705                                 // Keep track of devices that need unref
1706                                 unref_list[unref_cur++] = dev;
1707                                 if (unref_cur >= unref_size) {
1708                                         unref_size += 64;
1709                                         unref_list = usbi_reallocf(unref_list, unref_size*sizeof(libusb_device*));
1710                                         if (unref_list == NULL) {
1711                                                 usbi_err(ctx, "could not realloc list for unref - aborting.");
1712                                                 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1713                                         }
1714                                 }
1715                                 priv = _device_priv(dev);
1716                         }
1717
1718                         // Setup device
1719                         switch (pass) {
1720                         case HCD_PASS:
1721                                 dev->bus_number = (uint8_t)(i + 1);     // bus 0 is reserved for disconnected
1722                                 dev->device_address = 0;
1723                                 dev->num_configurations = 0;
1724                                 priv->apib = &usb_api_backend[USB_API_HUB];
1725                                 priv->sub_api = SUB_API_NOTSET;
1726                                 priv->depth = UINT8_MAX;        // Overflow to 0 for HCD Hubs
1727                                 priv->path = dev_interface_path; dev_interface_path = NULL;
1728                                 break;
1729                         case HUB_PASS:
1730                         case DEV_PASS:
1731                                 // If the device has already been setup, don't do it again
1732                                 if (priv->path != NULL)
1733                                         break;
1734                                 // Take care of API initialization
1735                                 priv->path = dev_interface_path; dev_interface_path = NULL;
1736                                 priv->apib = &usb_api_backend[api];
1737                                 priv->sub_api = sub_api;
1738                                 switch(api) {
1739                                 case USB_API_COMPOSITE:
1740                                 case USB_API_HUB:
1741                                         break;
1742                                 case USB_API_HID:
1743                                         priv->hid = calloc(1, sizeof(struct hid_device_priv));
1744                                         if (priv->hid == NULL) {
1745                                                 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1746                                         }
1747                                         priv->hid->nb_interfaces = 0;
1748                                         break;
1749                                 default:
1750                                         // For other devices, the first interface is the same as the device
1751                                         priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
1752                                         if (priv->usb_interface[0].path != NULL) {
1753                                                 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1754                                         } else {
1755                                                 usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
1756                                         }
1757                                         // The following is needed if we want API calls to work for both simple
1758                                         // and composite devices.
1759                                         for(j=0; j<USB_MAXINTERFACES; j++) {
1760                                                 priv->usb_interface[j].apib = &usb_api_backend[api];
1761                                         }
1762                                         break;
1763                                 }
1764                                 break;
1765                         case GEN_PASS:
1766                                 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1767                                 if (r == LIBUSB_SUCCESS) {
1768                                         // Append device to the list of discovered devices
1769                                         discdevs = discovered_devs_append(*_discdevs, dev);
1770                                         if (!discdevs) {
1771                                                 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1772                                         }
1773                                         *_discdevs = discdevs;
1774                                 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1775                                         // This can occur if the device was disconnected but Windows hasn't
1776                                         // refreshed its enumeration yet - in that case, we ignore the device
1777                                         r = LIBUSB_SUCCESS;
1778                                 }
1779                                 break;
1780                         default:        // HID_PASS and later
1781                                 if (parent_priv->apib->id == USB_API_HID) {
1782                                         usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data);
1783                                         r = set_hid_interface(ctx, parent_dev, dev_interface_path);
1784                                         if (r != LIBUSB_SUCCESS) LOOP_BREAK(r);
1785                                         dev_interface_path = NULL;
1786                                 } else if (parent_priv->apib->id == USB_API_COMPOSITE) {
1787                                         usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1788                                         switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api)) {
1789                                         case LIBUSB_SUCCESS:
1790                                                 dev_interface_path = NULL;
1791                                                 break;
1792                                         case LIBUSB_ERROR_ACCESS:
1793                                                 // interface has already been set => make sure dev_interface_path is freed then
1794                                                 break;
1795                                         default:
1796                                                 LOOP_BREAK(r);
1797                                                 break;
1798                                         }
1799                                 }
1800                                 libusb_unref_device(parent_dev);
1801                                 break;
1802                         }
1803                 }
1804         }
1805
1806         // Free any additional GUIDs
1807         for (pass = HID_PASS+1; pass < nb_guids; pass++) {
1808                 safe_free(guid[pass]);
1809         }
1810
1811         // Unref newly allocated devs
1812         if (unref_list != NULL) {
1813                 for (i=0; i<unref_cur; i++) {
1814                         safe_unref_device(unref_list[i]);
1815                 }
1816                 free(unref_list);
1817         }
1818
1819         return r;
1820 }
1821
1822 /*
1823  * exit: libusb backend deinitialization function
1824  */
1825 static void windows_exit(void)
1826 {
1827         int i;
1828         HANDLE semaphore;
1829         char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1830
1831         sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1832         semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1833         if (semaphore == NULL) {
1834                 return;
1835         }
1836
1837         // A successful wait brings our semaphore count to 0 (unsignaled)
1838         // => any concurent wait stalls until the semaphore release
1839         if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1840                 CloseHandle(semaphore);
1841                 return;
1842         }
1843
1844         // Only works if exits and inits are balanced exactly
1845         if (--concurrent_usage < 0) {   // Last exit
1846                 for (i=0; i<USB_API_MAX; i++) {
1847                         usb_api_backend[i].exit(SUB_API_NOTSET);
1848                 }
1849                 exit_polling();
1850
1851                 if (timer_thread) {
1852                         SetEvent(timer_request[1]); // actually the signal to quit the thread.
1853                         if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1854                                 usbi_dbg("could not wait for timer thread to quit");
1855                                 TerminateThread(timer_thread, 1);
1856                         }
1857                         CloseHandle(timer_thread);
1858                         timer_thread = NULL;
1859                 }
1860                 for (i = 0; i < 2; i++) {
1861                         if (timer_request[i]) {
1862                                 CloseHandle(timer_request[i]);
1863                                 timer_request[i] = NULL;
1864                         }
1865                 }
1866                 if (timer_response) {
1867                         CloseHandle(timer_response);
1868                         timer_response = NULL;
1869                 }
1870                 if (timer_mutex) {
1871                         CloseHandle(timer_mutex);
1872                         timer_mutex = NULL;
1873                 }
1874                 htab_destroy();
1875         }
1876
1877         ReleaseSemaphore(semaphore, 1, NULL);   // increase count back to 1
1878         CloseHandle(semaphore);
1879 }
1880
1881 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1882 {
1883         struct windows_device_priv *priv = _device_priv(dev);
1884
1885         memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1886         *host_endian = 0;
1887
1888         return LIBUSB_SUCCESS;
1889 }
1890
1891 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1892 {
1893         struct windows_device_priv *priv = _device_priv(dev);
1894         PUSB_CONFIGURATION_DESCRIPTOR config_header;
1895         size_t size;
1896
1897         // config index is zero based
1898         if (config_index >= dev->num_configurations)
1899                 return LIBUSB_ERROR_INVALID_PARAM;
1900
1901         if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1902                 return LIBUSB_ERROR_NOT_FOUND;
1903
1904         config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1905
1906         size = min(config_header->wTotalLength, len);
1907         memcpy(buffer, priv->config_descriptor[config_index], size);
1908         *host_endian = 0;
1909
1910         return (int)size;
1911 }
1912
1913 /*
1914  * return the cached copy of the active config descriptor
1915  */
1916 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1917 {
1918         struct windows_device_priv *priv = _device_priv(dev);
1919
1920         if (priv->active_config == 0)
1921                 return LIBUSB_ERROR_NOT_FOUND;
1922
1923         // config index is zero based
1924         return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1925 }
1926
1927 static int windows_open(struct libusb_device_handle *dev_handle)
1928 {
1929         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1930         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1931
1932         if (priv->apib == NULL) {
1933                 usbi_err(ctx, "program assertion failed - device is not initialized");
1934                 return LIBUSB_ERROR_NO_DEVICE;
1935         }
1936
1937         return priv->apib->open(SUB_API_NOTSET, dev_handle);
1938 }
1939
1940 static void windows_close(struct libusb_device_handle *dev_handle)
1941 {
1942         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1943
1944         priv->apib->close(SUB_API_NOTSET, dev_handle);
1945 }
1946
1947 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1948 {
1949         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1950
1951         if (priv->active_config == 0) {
1952                 *config = 0;
1953                 return LIBUSB_ERROR_NOT_FOUND;
1954         }
1955
1956         *config = priv->active_config;
1957         return LIBUSB_SUCCESS;
1958 }
1959
1960 /*
1961  * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1962  * does not currently expose a service that allows higher-level drivers to set
1963  * the configuration."
1964  */
1965 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1966 {
1967         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1968         int r = LIBUSB_SUCCESS;
1969
1970         if (config >= USB_MAXCONFIG)
1971                 return LIBUSB_ERROR_INVALID_PARAM;
1972
1973         r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1974                 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1975                 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1976                 0, NULL, 0, 1000);
1977
1978         if (r == LIBUSB_SUCCESS) {
1979                 priv->active_config = (uint8_t)config;
1980         }
1981         return r;
1982 }
1983
1984 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1985 {
1986         int r = LIBUSB_SUCCESS;
1987         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1988
1989         if (iface >= USB_MAXINTERFACES)
1990                 return LIBUSB_ERROR_INVALID_PARAM;
1991
1992         safe_free(priv->usb_interface[iface].endpoint);
1993         priv->usb_interface[iface].nb_endpoints= 0;
1994
1995         r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
1996
1997         if (r == LIBUSB_SUCCESS) {
1998                 r = windows_assign_endpoints(dev_handle, iface, 0);
1999         }
2000
2001         return r;
2002 }
2003
2004 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2005 {
2006         int r = LIBUSB_SUCCESS;
2007         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2008
2009         safe_free(priv->usb_interface[iface].endpoint);
2010         priv->usb_interface[iface].nb_endpoints= 0;
2011
2012         r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
2013
2014         if (r == LIBUSB_SUCCESS) {
2015                 r = windows_assign_endpoints(dev_handle, iface, altsetting);
2016         }
2017
2018         return r;
2019 }
2020
2021 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
2022 {
2023         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2024
2025         return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
2026 }
2027
2028 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2029 {
2030         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2031         return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
2032 }
2033
2034 static int windows_reset_device(struct libusb_device_handle *dev_handle)
2035 {
2036         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2037         return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
2038 }
2039
2040 // The 3 functions below are unlikely to ever get supported on Windows
2041 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
2042 {
2043         return LIBUSB_ERROR_NOT_SUPPORTED;
2044 }
2045
2046 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
2047 {
2048         return LIBUSB_ERROR_NOT_SUPPORTED;
2049 }
2050
2051 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
2052 {
2053         return LIBUSB_ERROR_NOT_SUPPORTED;
2054 }
2055
2056 static void windows_destroy_device(struct libusb_device *dev)
2057 {
2058         windows_device_priv_release(dev);
2059 }
2060
2061 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
2062 {
2063         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2064
2065         usbi_free_fd(&transfer_priv->pollable_fd);
2066         safe_free(transfer_priv->hid_buffer);
2067         // When auto claim is in use, attempt to release the auto-claimed interface
2068         auto_release(itransfer);
2069 }
2070
2071 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
2072 {
2073         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2074         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2075         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2076         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2077         int r;
2078
2079         r = priv->apib->submit_bulk_transfer(SUB_API_NOTSET, itransfer);
2080         if (r != LIBUSB_SUCCESS) {
2081                 return r;
2082         }
2083
2084         usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
2085                 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
2086
2087         itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
2088         return LIBUSB_SUCCESS;
2089 }
2090
2091 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2092 {
2093         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2094         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2095         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2096         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2097         int r;
2098
2099         r = priv->apib->submit_iso_transfer(SUB_API_NOTSET, itransfer);
2100         if (r != LIBUSB_SUCCESS) {
2101                 return r;
2102         }
2103
2104         usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
2105                 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
2106
2107         itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
2108         return LIBUSB_SUCCESS;
2109 }
2110
2111 static int submit_control_transfer(struct usbi_transfer *itransfer)
2112 {
2113         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2114         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2115         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2116         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2117         int r;
2118
2119         r = priv->apib->submit_control_transfer(SUB_API_NOTSET, itransfer);
2120         if (r != LIBUSB_SUCCESS) {
2121                 return r;
2122         }
2123
2124         usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
2125
2126         itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
2127         return LIBUSB_SUCCESS;
2128
2129 }
2130
2131 static int windows_submit_transfer(struct usbi_transfer *itransfer)
2132 {
2133         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2134
2135         switch (transfer->type) {
2136         case LIBUSB_TRANSFER_TYPE_CONTROL:
2137                 return submit_control_transfer(itransfer);
2138         case LIBUSB_TRANSFER_TYPE_BULK:
2139         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2140                 if (IS_XFEROUT(transfer) &&
2141                     transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2142                         return LIBUSB_ERROR_NOT_SUPPORTED;
2143                 return submit_bulk_transfer(itransfer);
2144         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2145                 return submit_iso_transfer(itransfer);
2146         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2147                 return LIBUSB_ERROR_NOT_SUPPORTED;
2148         default:
2149                 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2150                 return LIBUSB_ERROR_INVALID_PARAM;
2151         }
2152 }
2153
2154 static int windows_abort_control(struct usbi_transfer *itransfer)
2155 {
2156         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2157         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2158
2159         return priv->apib->abort_control(SUB_API_NOTSET, itransfer);
2160 }
2161
2162 static int windows_abort_transfers(struct usbi_transfer *itransfer)
2163 {
2164         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2165         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2166
2167         return priv->apib->abort_transfers(SUB_API_NOTSET, itransfer);
2168 }
2169
2170 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
2171 {
2172         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2173
2174         switch (transfer->type) {
2175         case LIBUSB_TRANSFER_TYPE_CONTROL:
2176                 return windows_abort_control(itransfer);
2177         case LIBUSB_TRANSFER_TYPE_BULK:
2178         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2179         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2180                 return windows_abort_transfers(itransfer);
2181         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2182                 return LIBUSB_ERROR_NOT_SUPPORTED;
2183         default:
2184                 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2185                 return LIBUSB_ERROR_INVALID_PARAM;
2186         }
2187 }
2188
2189 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2190 {
2191         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2192         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2193         int status, istatus;
2194
2195         usbi_dbg("handling I/O completion with errcode %d, size %d", io_result, io_size);
2196
2197         switch(io_result) {
2198         case NO_ERROR:
2199                 status = priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
2200                 break;
2201         case ERROR_GEN_FAILURE:
2202                 usbi_dbg("detected endpoint stall");
2203                 status = LIBUSB_TRANSFER_STALL;
2204                 break;
2205         case ERROR_SEM_TIMEOUT:
2206                 usbi_dbg("detected semaphore timeout");
2207                 status = LIBUSB_TRANSFER_TIMED_OUT;
2208                 break;
2209         case ERROR_OPERATION_ABORTED:
2210                 istatus = priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
2211                 if (istatus != LIBUSB_TRANSFER_COMPLETED) {
2212                         usbi_dbg("Failed to copy partial data in aborted operation: %d", istatus);
2213                 }
2214                 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
2215                         usbi_dbg("detected timeout");
2216                         status = LIBUSB_TRANSFER_TIMED_OUT;
2217                 } else {
2218                         usbi_dbg("detected operation aborted");
2219                         status = LIBUSB_TRANSFER_CANCELLED;
2220                 }
2221                 break;
2222         default:
2223                 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error %d: %s", io_result, windows_error_str(io_result));
2224                 status = LIBUSB_TRANSFER_ERROR;
2225                 break;
2226         }
2227         windows_clear_transfer_priv(itransfer); // Cancel polling
2228         usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
2229 }
2230
2231 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2232 {
2233         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2234
2235         switch (transfer->type) {
2236         case LIBUSB_TRANSFER_TYPE_CONTROL:
2237         case LIBUSB_TRANSFER_TYPE_BULK:
2238         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2239         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2240                 windows_transfer_callback (itransfer, io_result, io_size);
2241                 break;
2242         case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2243                 usbi_warn(ITRANSFER_CTX(itransfer), "bulk stream transfers are not yet supported on this platform");
2244                 break;
2245         default:
2246                 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2247         }
2248 }
2249
2250 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2251 {
2252         struct windows_transfer_priv* transfer_priv = NULL;
2253         POLL_NFDS_TYPE i = 0;
2254         bool found = false;
2255         struct usbi_transfer *transfer;
2256         DWORD io_size, io_result;
2257
2258         usbi_mutex_lock(&ctx->open_devs_lock);
2259         for (i = 0; i < nfds && num_ready > 0; i++) {
2260
2261                 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
2262
2263                 if (!fds[i].revents) {
2264                         continue;
2265                 }
2266
2267                 num_ready--;
2268
2269                 // Because a Windows OVERLAPPED is used for poll emulation,
2270                 // a pollable fd is created and stored with each transfer
2271                 usbi_mutex_lock(&ctx->flying_transfers_lock);
2272                 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2273                         transfer_priv = usbi_transfer_get_os_priv(transfer);
2274                         if (transfer_priv->pollable_fd.fd == fds[i].fd) {
2275                                 found = true;
2276                                 break;
2277                         }
2278                 }
2279                 usbi_mutex_unlock(&ctx->flying_transfers_lock);
2280
2281                 if (found) {
2282                         // Handle async requests that completed synchronously first
2283                         if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
2284                                 io_result = NO_ERROR;
2285                                 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
2286                         // Regular async overlapped
2287                         } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
2288                                 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
2289                                 io_result = NO_ERROR;
2290                         } else {
2291                                 io_result = GetLastError();
2292                         }
2293                         usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
2294                         // let handle_callback free the event using the transfer wfd
2295                         // If you don't use the transfer wfd, you run a risk of trying to free a
2296                         // newly allocated wfd that took the place of the one from the transfer.
2297                         windows_handle_callback(transfer, io_result, io_size);
2298                 } else {
2299                         usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2300                         return LIBUSB_ERROR_NOT_FOUND;
2301                 }
2302         }
2303
2304         usbi_mutex_unlock(&ctx->open_devs_lock);
2305         return LIBUSB_SUCCESS;
2306 }
2307
2308 /*
2309  * Monotonic and real time functions
2310  */
2311 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2312 {
2313         LARGE_INTEGER hires_counter, li_frequency;
2314         LONG nb_responses;
2315         int timer_index;
2316
2317         // Init - find out if we have access to a monotonic (hires) timer
2318         if (!QueryPerformanceFrequency(&li_frequency)) {
2319                 usbi_dbg("no hires timer available on this platform");
2320                 hires_frequency = 0;
2321                 hires_ticks_to_ps = UINT64_C(0);
2322         } else {
2323                 hires_frequency = li_frequency.QuadPart;
2324                 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2325                 // to picoseconds to compute the tv_nsecs part in clock_gettime
2326                 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2327                 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2328         }
2329
2330         // Signal windows_init() that we're ready to service requests
2331         if (ReleaseSemaphore(timer_response, 1, NULL) == 0) {
2332                 usbi_dbg("unable to release timer semaphore: %s", windows_error_str(0));
2333         }
2334
2335         // Main loop - wait for requests
2336         while (1) {
2337                 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2338                 if ( (timer_index != 0) && (timer_index != 1) ) {
2339                         usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2340                         continue;
2341                 }
2342                 if (request_count[timer_index] == 0) {
2343                         // Request already handled
2344                         ResetEvent(timer_request[timer_index]);
2345                         // There's still a possiblity that a thread sends a request between the
2346                         // time we test request_count[] == 0 and we reset the event, in which case
2347                         // the request would be ignored. The simple solution to that is to test
2348                         // request_count again and process requests if non zero.
2349                         if (request_count[timer_index] == 0)
2350                                 continue;
2351                 }
2352                 switch (timer_index) {
2353                 case 0:
2354                         WaitForSingleObject(timer_mutex, INFINITE);
2355                         // Requests to this thread are for hires always
2356                         if ((QueryPerformanceCounter(&hires_counter) != 0) && (hires_frequency != 0)) {
2357                                 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2358                                 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2359                         } else {
2360                                 // Fallback to real-time if we can't get monotonic value
2361                                 // Note that real-time clock does not wait on the mutex or this thread.
2362                                 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2363                         }
2364                         ReleaseMutex(timer_mutex);
2365
2366                         nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2367                         if ( (nb_responses)
2368                           && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2369                                 usbi_dbg("unable to release timer semaphore: %s", windows_error_str(0));
2370                         }
2371                         continue;
2372                 case 1: // time to quit
2373                         usbi_dbg("timer thread quitting");
2374                         return 0;
2375                 }
2376         }
2377 }
2378
2379 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2380 {
2381         FILETIME filetime;
2382         ULARGE_INTEGER rtime;
2383         DWORD r;
2384         switch(clk_id) {
2385         case USBI_CLOCK_MONOTONIC:
2386                 if (hires_frequency != 0) {
2387                         while (1) {
2388                                 InterlockedIncrement((LONG*)&request_count[0]);
2389                                 SetEvent(timer_request[0]);
2390                                 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2391                                 switch(r) {
2392                                 case WAIT_OBJECT_0:
2393                                         WaitForSingleObject(timer_mutex, INFINITE);
2394                                         *tp = timer_tp;
2395                                         ReleaseMutex(timer_mutex);
2396                                         return LIBUSB_SUCCESS;
2397                                 case WAIT_TIMEOUT:
2398                                         usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2399                                         break; // Retry until successful
2400                                 default:
2401                                         usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2402                                         return LIBUSB_ERROR_OTHER;
2403                                 }
2404                         }
2405                 }
2406                 // Fall through and return real-time if monotonic was not detected @ timer init
2407         case USBI_CLOCK_REALTIME:
2408                 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2409                 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2410                 // Note however that our resolution is bounded by the Windows system time
2411                 // functions and is at best of the order of 1 ms (or, usually, worse)
2412                 GetSystemTimeAsFileTime(&filetime);
2413                 rtime.LowPart = filetime.dwLowDateTime;
2414                 rtime.HighPart = filetime.dwHighDateTime;
2415                 rtime.QuadPart -= epoch_time;
2416                 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2417                 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2418                 return LIBUSB_SUCCESS;
2419         default:
2420                 return LIBUSB_ERROR_INVALID_PARAM;
2421         }
2422 }
2423
2424
2425 // NB: MSVC6 does not support named initializers.
2426 const struct usbi_os_backend windows_backend = {
2427         "Windows",
2428         USBI_CAP_HAS_HID_ACCESS,
2429         windows_init,
2430         windows_exit,
2431
2432         windows_get_device_list,
2433         NULL,                           /* hotplug_poll */
2434         windows_open,
2435         windows_close,
2436
2437         windows_get_device_descriptor,
2438         windows_get_active_config_descriptor,
2439         windows_get_config_descriptor,
2440         NULL,                           /* get_config_descriptor_by_value() */
2441
2442         windows_get_configuration,
2443         windows_set_configuration,
2444         windows_claim_interface,
2445         windows_release_interface,
2446
2447         windows_set_interface_altsetting,
2448         windows_clear_halt,
2449         windows_reset_device,
2450
2451         NULL,                           /* alloc_streams */
2452         NULL,                           /* free_streams */
2453
2454         windows_kernel_driver_active,
2455         windows_detach_kernel_driver,
2456         windows_attach_kernel_driver,
2457
2458         windows_destroy_device,
2459
2460         windows_submit_transfer,
2461         windows_cancel_transfer,
2462         windows_clear_transfer_priv,
2463
2464         windows_handle_events,
2465
2466         windows_clock_gettime,
2467 #if defined(USBI_TIMERFD_AVAILABLE)
2468         NULL,
2469 #endif
2470         sizeof(struct windows_device_priv),
2471         sizeof(struct windows_device_handle_priv),
2472         sizeof(struct windows_transfer_priv),
2473         0,
2474 };
2475
2476
2477 /*
2478  * USB API backends
2479  */
2480 static int unsupported_init(int sub_api, struct libusb_context *ctx) {
2481         return LIBUSB_SUCCESS;
2482 }
2483 static int unsupported_exit(int sub_api) {
2484         return LIBUSB_SUCCESS;
2485 }
2486 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle) {
2487         PRINT_UNSUPPORTED_API(open);
2488 }
2489 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle) {
2490         usbi_dbg("unsupported API call for 'close'");
2491 }
2492 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2493         PRINT_UNSUPPORTED_API(configure_endpoints);
2494 }
2495 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2496         PRINT_UNSUPPORTED_API(claim_interface);
2497 }
2498 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2499         PRINT_UNSUPPORTED_API(set_interface_altsetting);
2500 }
2501 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2502         PRINT_UNSUPPORTED_API(release_interface);
2503 }
2504 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2505         PRINT_UNSUPPORTED_API(clear_halt);
2506 }
2507 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle) {
2508         PRINT_UNSUPPORTED_API(reset_device);
2509 }
2510 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
2511         PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2512 }
2513 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
2514         PRINT_UNSUPPORTED_API(submit_iso_transfer);
2515 }
2516 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer) {
2517         PRINT_UNSUPPORTED_API(submit_control_transfer);
2518 }
2519 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer) {
2520         PRINT_UNSUPPORTED_API(abort_control);
2521 }
2522 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer) {
2523         PRINT_UNSUPPORTED_API(abort_transfers);
2524 }
2525 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) {
2526         PRINT_UNSUPPORTED_API(copy_transfer_data);
2527 }
2528 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2529         return LIBUSB_SUCCESS;
2530 }
2531 // These names must be uppercase
2532 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30"};
2533 const char* composite_driver_names[] = {"USBCCGP"};
2534 const char* winusbx_driver_names[] = WINUSBX_DRV_NAMES;
2535 const char* hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2536 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2537         {
2538                 USB_API_UNSUPPORTED,
2539                 "Unsupported API",
2540                 NULL,
2541                 0,
2542                 unsupported_init,
2543                 unsupported_exit,
2544                 unsupported_open,
2545                 unsupported_close,
2546                 unsupported_configure_endpoints,
2547                 unsupported_claim_interface,
2548                 unsupported_set_interface_altsetting,
2549                 unsupported_release_interface,
2550                 unsupported_clear_halt,
2551                 unsupported_reset_device,
2552                 unsupported_submit_bulk_transfer,
2553                 unsupported_submit_iso_transfer,
2554                 unsupported_submit_control_transfer,
2555                 unsupported_abort_control,
2556                 unsupported_abort_transfers,
2557                 unsupported_copy_transfer_data,
2558         }, {
2559                 USB_API_HUB,
2560                 "HUB API",
2561                 hub_driver_names,
2562                 ARRAYSIZE(hub_driver_names),
2563                 unsupported_init,
2564                 unsupported_exit,
2565                 unsupported_open,
2566                 unsupported_close,
2567                 unsupported_configure_endpoints,
2568                 unsupported_claim_interface,
2569                 unsupported_set_interface_altsetting,
2570                 unsupported_release_interface,
2571                 unsupported_clear_halt,
2572                 unsupported_reset_device,
2573                 unsupported_submit_bulk_transfer,
2574                 unsupported_submit_iso_transfer,
2575                 unsupported_submit_control_transfer,
2576                 unsupported_abort_control,
2577                 unsupported_abort_transfers,
2578                 unsupported_copy_transfer_data,
2579         }, {
2580                 USB_API_COMPOSITE,
2581                 "Composite API",
2582                 composite_driver_names,
2583                 ARRAYSIZE(composite_driver_names),
2584                 composite_init,
2585                 composite_exit,
2586                 composite_open,
2587                 composite_close,
2588                 common_configure_endpoints,
2589                 composite_claim_interface,
2590                 composite_set_interface_altsetting,
2591                 composite_release_interface,
2592                 composite_clear_halt,
2593                 composite_reset_device,
2594                 composite_submit_bulk_transfer,
2595                 composite_submit_iso_transfer,
2596                 composite_submit_control_transfer,
2597                 composite_abort_control,
2598                 composite_abort_transfers,
2599                 composite_copy_transfer_data,
2600         }, {
2601                 USB_API_WINUSBX,
2602                 "WinUSB-like APIs",
2603                 winusbx_driver_names,
2604                 ARRAYSIZE(winusbx_driver_names),
2605                 winusbx_init,
2606                 winusbx_exit,
2607                 winusbx_open,
2608                 winusbx_close,
2609                 winusbx_configure_endpoints,
2610                 winusbx_claim_interface,
2611                 winusbx_set_interface_altsetting,
2612                 winusbx_release_interface,
2613                 winusbx_clear_halt,
2614                 winusbx_reset_device,
2615                 winusbx_submit_bulk_transfer,
2616                 unsupported_submit_iso_transfer,
2617                 winusbx_submit_control_transfer,
2618                 winusbx_abort_control,
2619                 winusbx_abort_transfers,
2620                 winusbx_copy_transfer_data,
2621         }, {
2622                 USB_API_HID,
2623                 "HID API",
2624                 hid_driver_names,
2625                 ARRAYSIZE(hid_driver_names),
2626                 hid_init,
2627                 hid_exit,
2628                 hid_open,
2629                 hid_close,
2630                 common_configure_endpoints,
2631                 hid_claim_interface,
2632                 hid_set_interface_altsetting,
2633                 hid_release_interface,
2634                 hid_clear_halt,
2635                 hid_reset_device,
2636                 hid_submit_bulk_transfer,
2637                 unsupported_submit_iso_transfer,
2638                 hid_submit_control_transfer,
2639                 hid_abort_transfers,
2640                 hid_abort_transfers,
2641                 hid_copy_transfer_data,
2642         },
2643 };
2644
2645
2646 /*
2647  * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2648  */
2649 #define WinUSBX_Set(fn) do { if (native_winusb) WinUSBX[i].fn = (WinUsb_##fn##_t) GetProcAddress(h, "WinUsb_" #fn); \
2650         else pLibK_GetProcAddress((PVOID*)&WinUSBX[i].fn, i, KUSB_FNID_##fn); } while (0)
2651
2652 static int winusbx_init(int sub_api, struct libusb_context *ctx)
2653 {
2654         HMODULE h = NULL;
2655         bool native_winusb = false;
2656         int i;
2657         KLIB_VERSION LibK_Version;
2658         LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
2659         LibK_GetVersion_t pLibK_GetVersion = NULL;
2660
2661         h = GetModuleHandleA("libusbK");
2662         if (h == NULL) {
2663                 h = LoadLibraryA("libusbK");
2664         }
2665         if (h == NULL) {
2666                 usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
2667                 h = GetModuleHandleA("WinUSB");
2668                 if (h == NULL) {
2669                         h = LoadLibraryA("WinUSB");
2670                 }               if (h == NULL) {
2671                         usbi_warn(ctx, "WinUSB DLL is not available either,\n"
2672                                 "you will not be able to access devices outside of enumeration");
2673                         return LIBUSB_ERROR_NOT_FOUND;
2674                 }
2675         } else {
2676                 usbi_dbg("using libusbK DLL for universal access");
2677                 pLibK_GetVersion = (LibK_GetVersion_t) GetProcAddress(h, "LibK_GetVersion");
2678                 if (pLibK_GetVersion != NULL) {
2679                         pLibK_GetVersion(&LibK_Version);
2680                         usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2681                                 LibK_Version.Micro, LibK_Version.Nano);
2682                 }
2683                 pLibK_GetProcAddress = (LibK_GetProcAddress_t) GetProcAddress(h, "LibK_GetProcAddress");
2684                 if (pLibK_GetProcAddress == NULL) {
2685                         usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2686                         return LIBUSB_ERROR_NOT_FOUND;
2687                 }
2688         }
2689         native_winusb = (pLibK_GetProcAddress == NULL);
2690         for (i=SUB_API_LIBUSBK; i<SUB_API_MAX; i++) {
2691                 WinUSBX_Set(AbortPipe);
2692                 WinUSBX_Set(ControlTransfer);
2693                 WinUSBX_Set(FlushPipe);
2694                 WinUSBX_Set(Free);
2695                 WinUSBX_Set(GetAssociatedInterface);
2696                 WinUSBX_Set(GetCurrentAlternateSetting);
2697                 WinUSBX_Set(GetDescriptor);
2698                 WinUSBX_Set(GetOverlappedResult);
2699                 WinUSBX_Set(GetPipePolicy);
2700                 WinUSBX_Set(GetPowerPolicy);
2701                 WinUSBX_Set(Initialize);
2702                 WinUSBX_Set(QueryDeviceInformation);
2703                 WinUSBX_Set(QueryInterfaceSettings);
2704                 WinUSBX_Set(QueryPipe);
2705                 WinUSBX_Set(ReadPipe);
2706                 WinUSBX_Set(ResetPipe);
2707                 WinUSBX_Set(SetCurrentAlternateSetting);
2708                 WinUSBX_Set(SetPipePolicy);
2709                 WinUSBX_Set(SetPowerPolicy);
2710                 WinUSBX_Set(WritePipe);
2711                 if (!native_winusb) {
2712                         WinUSBX_Set(ResetDevice);
2713                 }
2714                 if (WinUSBX[i].Initialize != NULL) {
2715                         WinUSBX[i].initialized = true;
2716                         usbi_dbg("initalized sub API %s", sub_api_name[i]);
2717                 } else {
2718                         usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
2719                         WinUSBX[i].initialized = false;
2720                 }
2721         }
2722         return LIBUSB_SUCCESS;
2723 }
2724
2725 static int winusbx_exit(int sub_api)
2726 {
2727         return LIBUSB_SUCCESS;
2728 }
2729
2730 // NB: open and close must ensure that they only handle interface of
2731 // the right API type, as these functions can be called wholesale from
2732 // composite_open(), with interfaces belonging to different APIs
2733 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2734 {
2735         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2736         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2737         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2738
2739         HANDLE file_handle;
2740         int i;
2741
2742         CHECK_WINUSBX_AVAILABLE(sub_api);
2743
2744         // WinUSB requires a seperate handle for each interface
2745         for (i = 0; i < USB_MAXINTERFACES; i++) {
2746                 if ( (priv->usb_interface[i].path != NULL)
2747                   && (priv->usb_interface[i].apib->id == USB_API_WINUSBX) ) {
2748                         file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2749                                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2750                         if (file_handle == INVALID_HANDLE_VALUE) {
2751                                 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2752                                 switch(GetLastError()) {
2753                                 case ERROR_FILE_NOT_FOUND:      // The device was disconnected
2754                                         return LIBUSB_ERROR_NO_DEVICE;
2755                                 case ERROR_ACCESS_DENIED:
2756                                         return LIBUSB_ERROR_ACCESS;
2757                                 default:
2758                                         return LIBUSB_ERROR_IO;
2759                                 }
2760                         }
2761                         handle_priv->interface_handle[i].dev_handle = file_handle;
2762                 }
2763         }
2764
2765         return LIBUSB_SUCCESS;
2766 }
2767
2768 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2769 {
2770         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2771         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2772         HANDLE file_handle;
2773         int i;
2774
2775         if (sub_api == SUB_API_NOTSET)
2776                 sub_api = priv->sub_api;
2777         if (!WinUSBX[sub_api].initialized)
2778                 return;
2779
2780         for (i = 0; i < USB_MAXINTERFACES; i++) {
2781                 if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2782                         file_handle = handle_priv->interface_handle[i].dev_handle;
2783                         if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2784                                 CloseHandle(file_handle);
2785                         }
2786                 }
2787         }
2788 }
2789
2790 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2791 {
2792         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2793         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2794         HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2795         UCHAR policy;
2796         ULONG timeout = 0;
2797         uint8_t endpoint_address;
2798         int i;
2799
2800         CHECK_WINUSBX_AVAILABLE(sub_api);
2801
2802         // With handle and enpoints set (in parent), we can setup the default pipe properties
2803         // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2804         for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2805                 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2806                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2807                         PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2808                         usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2809                 }
2810                 if ((i == -1) || (sub_api == SUB_API_LIBUSB0)) {
2811                         continue;       // Other policies don't apply to control endpoint or libusb0
2812                 }
2813                 policy = false;
2814                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2815                         SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2816                         usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2817                 }
2818                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2819                         IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2820                         usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2821                 }
2822                 policy = true;
2823                 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2824                    https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2825                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2826                         ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2827                         usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2828                 }
2829                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2830                         AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2831                         usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2832                 }
2833         }
2834
2835         return LIBUSB_SUCCESS;
2836 }
2837
2838 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2839 {
2840         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2841         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2842         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2843         bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2844         HANDLE file_handle, winusb_handle;
2845         DWORD err;
2846         int i;
2847         SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
2848         HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2849         SP_DEVINFO_DATA dev_info_data;
2850         char* dev_path_no_guid = NULL;
2851         char filter_path[] = "\\\\.\\libusb0-0000";
2852         bool found_filter = false;
2853
2854         CHECK_WINUSBX_AVAILABLE(sub_api);
2855
2856         // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2857         // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2858         if ((is_using_usbccgp) || (iface == 0)) {
2859                 // composite device (independent interfaces) or interface 0
2860                 file_handle = handle_priv->interface_handle[iface].dev_handle;
2861                 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2862                         return LIBUSB_ERROR_NOT_FOUND;
2863                 }
2864
2865                 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2866                         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2867                         err = GetLastError();
2868                         switch(err) {
2869                         case ERROR_BAD_COMMAND:
2870                                 // The device was disconnected
2871                                 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2872                                 return LIBUSB_ERROR_NO_DEVICE;
2873                         default:
2874                                 // it may be that we're using the libusb0 filter driver.
2875                                 // TODO: can we move this whole business into the K/0 DLL?
2876                                 for (i = 0; ; i++) {
2877                                         safe_free(dev_interface_details);
2878                                         safe_free(dev_path_no_guid);
2879                                         dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
2880                                         if ((found_filter) || (dev_interface_details == NULL)) {
2881                                                 break;
2882                                         }
2883                                         // ignore GUID part
2884                                         dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
2885                                         if (safe_strncmp(dev_path_no_guid, priv->usb_interface[iface].path, safe_strlen(dev_path_no_guid)) == 0) {
2886                                                 file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2887                                                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2888                                                 if (file_handle == INVALID_HANDLE_VALUE) {
2889                                                         usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2890                                                 } else {
2891                                                         WinUSBX[sub_api].Free(winusb_handle);
2892                                                         if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle))
2893                                                                 found_filter = true;
2894                                                         else
2895                                                                 usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
2896                                                 }
2897                                         }
2898                                 }
2899                                 if (!found_filter) {
2900                                         usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
2901                                         return LIBUSB_ERROR_ACCESS;
2902                                 }
2903                         }
2904                 }
2905                 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2906         } else {
2907                 // For all other interfaces, use GetAssociatedInterface()
2908                 winusb_handle = handle_priv->interface_handle[0].api_handle;
2909                 // It is a requirement for multiple interface devices on Windows that, to you
2910                 // must first claim the first interface before you claim the others
2911                 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2912                         file_handle = handle_priv->interface_handle[0].dev_handle;
2913                         if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2914                                 handle_priv->interface_handle[0].api_handle = winusb_handle;
2915                                 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2916                         } else {
2917                                 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
2918                                 return LIBUSB_ERROR_ACCESS;
2919                         }
2920                 }
2921                 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2922                         &handle_priv->interface_handle[iface].api_handle)) {
2923                         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2924                         switch(GetLastError()) {
2925                         case ERROR_NO_MORE_ITEMS:   // invalid iface
2926                                 return LIBUSB_ERROR_NOT_FOUND;
2927                         case ERROR_BAD_COMMAND:     // The device was disconnected
2928                                 return LIBUSB_ERROR_NO_DEVICE;
2929                         case ERROR_ALREADY_EXISTS:  // already claimed
2930                                 return LIBUSB_ERROR_BUSY;
2931                         default:
2932                                 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2933                                 return LIBUSB_ERROR_ACCESS;
2934                         }
2935                 }
2936         }
2937         usbi_dbg("claimed interface %d", iface);
2938         handle_priv->active_interface = iface;
2939
2940         return LIBUSB_SUCCESS;
2941 }
2942
2943 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2944 {
2945         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2946         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2947         HANDLE winusb_handle;
2948
2949         CHECK_WINUSBX_AVAILABLE(sub_api);
2950
2951         winusb_handle = handle_priv->interface_handle[iface].api_handle;
2952         if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2953                 return LIBUSB_ERROR_NOT_FOUND;
2954         }
2955
2956         WinUSBX[sub_api].Free(winusb_handle);
2957         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2958
2959         return LIBUSB_SUCCESS;
2960 }
2961
2962 /*
2963  * Return the first valid interface (of the same API type), for control transfers
2964  */
2965 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2966 {
2967         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2968         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2969         int i;
2970
2971         if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2972                 usbi_dbg("unsupported API ID");
2973                 return -1;
2974         }
2975
2976         for (i=0; i<USB_MAXINTERFACES; i++) {
2977                 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2978                   && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2979                   && (handle_priv->interface_handle[i].api_handle != 0)
2980                   && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
2981                   && (priv->usb_interface[i].apib->id == api_id) ) {
2982                         return i;
2983                 }
2984         }
2985         return -1;
2986 }
2987
2988 /*
2989  * Lookup interface by endpoint address. -1 if not found
2990  */
2991 static int interface_by_endpoint(struct windows_device_priv *priv,
2992         struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2993 {
2994         int i, j;
2995         for (i=0; i<USB_MAXINTERFACES; i++) {
2996                 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2997                         continue;
2998                 if (handle_priv->interface_handle[i].api_handle == 0)
2999                         continue;
3000                 if (priv->usb_interface[i].endpoint == NULL)
3001                         continue;
3002                 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
3003                         if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
3004                                 return i;
3005                         }
3006                 }
3007         }
3008         return -1;
3009 }
3010
3011 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3012 {
3013         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3014         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3015         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3016         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3017         struct windows_device_handle_priv *handle_priv = _device_handle_priv(
3018                 transfer->dev_handle);
3019         WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
3020         ULONG size;
3021         HANDLE winusb_handle;
3022         int current_interface;
3023         struct winfd wfd;
3024
3025         CHECK_WINUSBX_AVAILABLE(sub_api);
3026
3027         transfer_priv->pollable_fd = INVALID_WINFD;
3028         size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3029
3030         if (size > MAX_CTRL_BUFFER_LENGTH)
3031                 return LIBUSB_ERROR_INVALID_PARAM;
3032
3033         current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
3034         if (current_interface < 0) {
3035                 if (auto_claim(transfer, &current_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS) {
3036                         return LIBUSB_ERROR_NOT_FOUND;
3037                 }
3038         }
3039
3040         usbi_dbg("will use interface %d", current_interface);
3041         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3042
3043         wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
3044         // Always use the handle returned from usbi_create_fd (wfd.handle)
3045         if (wfd.fd < 0) {
3046                 return LIBUSB_ERROR_NO_MEM;
3047         }
3048
3049         // Sending of set configuration control requests from WinUSB creates issues
3050         if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
3051           && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
3052                 if (setup->value != priv->active_config) {
3053                         usbi_warn(ctx, "cannot set configuration other than the default one");
3054                         usbi_free_fd(&wfd);
3055                         return LIBUSB_ERROR_INVALID_PARAM;
3056                 }
3057                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3058                 wfd.overlapped->InternalHigh = 0;
3059         } else {
3060                 if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
3061                         if(GetLastError() != ERROR_IO_PENDING) {
3062                                 usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
3063                                 usbi_free_fd(&wfd);
3064                                 return LIBUSB_ERROR_IO;
3065                         }
3066                 } else {
3067                         wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3068                         wfd.overlapped->InternalHigh = (DWORD)size;
3069                 }
3070         }
3071
3072         // Use priv_transfer to store data needed for async polling
3073         transfer_priv->pollable_fd = wfd;
3074         transfer_priv->interface_number = (uint8_t)current_interface;
3075
3076         return LIBUSB_SUCCESS;
3077 }
3078
3079 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
3080 {
3081         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3082         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3083         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3084         HANDLE winusb_handle;
3085
3086         CHECK_WINUSBX_AVAILABLE(sub_api);
3087
3088         if (altsetting > 255) {
3089                 return LIBUSB_ERROR_INVALID_PARAM;
3090         }
3091
3092         winusb_handle = handle_priv->interface_handle[iface].api_handle;
3093         if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
3094                 usbi_err(ctx, "interface must be claimed first");
3095                 return LIBUSB_ERROR_NOT_FOUND;
3096         }
3097
3098         if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
3099                 usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
3100                 return LIBUSB_ERROR_IO;
3101         }
3102
3103         return LIBUSB_SUCCESS;
3104 }
3105
3106 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
3107 {
3108         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3109         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3110         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3111         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3112         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3113         HANDLE winusb_handle;
3114         bool ret;
3115         int current_interface;
3116         struct winfd wfd;
3117
3118         CHECK_WINUSBX_AVAILABLE(sub_api);
3119
3120         transfer_priv->pollable_fd = INVALID_WINFD;
3121
3122         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3123         if (current_interface < 0) {
3124                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3125                 return LIBUSB_ERROR_NOT_FOUND;
3126         }
3127
3128         usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3129
3130         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3131
3132         wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
3133         // Always use the handle returned from usbi_create_fd (wfd.handle)
3134         if (wfd.fd < 0) {
3135                 return LIBUSB_ERROR_NO_MEM;
3136         }
3137
3138         if (IS_XFERIN(transfer)) {
3139                 usbi_dbg("reading %d bytes", transfer->length);
3140                 ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
3141         } else {
3142                 usbi_dbg("writing %d bytes", transfer->length);
3143                 ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
3144         }
3145         if (!ret) {
3146                 if(GetLastError() != ERROR_IO_PENDING) {
3147                         usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
3148                         usbi_free_fd(&wfd);
3149                         return LIBUSB_ERROR_IO;
3150                 }
3151         } else {
3152                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3153                 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
3154         }
3155
3156         transfer_priv->pollable_fd = wfd;
3157         transfer_priv->interface_number = (uint8_t)current_interface;
3158
3159         return LIBUSB_SUCCESS;
3160 }
3161
3162 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3163 {
3164         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3165         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3166         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3167         HANDLE winusb_handle;
3168         int current_interface;
3169
3170         CHECK_WINUSBX_AVAILABLE(sub_api);
3171
3172         current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3173         if (current_interface < 0) {
3174                 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3175                 return LIBUSB_ERROR_NOT_FOUND;
3176         }
3177
3178         usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3179         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3180
3181         if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
3182                 usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
3183                 return LIBUSB_ERROR_NO_DEVICE;
3184         }
3185
3186         return LIBUSB_SUCCESS;
3187 }
3188
3189 /*
3190  * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
3191  * through testing as well):
3192  * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
3193  * the control transfer using CancelIo"
3194  */
3195 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
3196 {
3197         // Cancelling of the I/O is done in the parent
3198         return LIBUSB_SUCCESS;
3199 }
3200
3201 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
3202 {
3203         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3204         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3205         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3206         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3207         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3208         HANDLE winusb_handle;
3209         int current_interface;
3210
3211         CHECK_WINUSBX_AVAILABLE(sub_api);
3212
3213         current_interface = transfer_priv->interface_number;
3214         if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
3215                 usbi_err(ctx, "program assertion failed: invalid interface_number");
3216                 return LIBUSB_ERROR_NOT_FOUND;
3217         }
3218         usbi_dbg("will use interface %d", current_interface);
3219
3220         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3221
3222         if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
3223                 usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
3224                 return LIBUSB_ERROR_NO_DEVICE;
3225         }
3226
3227         return LIBUSB_SUCCESS;
3228 }
3229
3230 /*
3231  * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
3232  * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
3233  * "WinUSB does not support host-initiated reset port and cycle port operations" and
3234  * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
3235  * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
3236  * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
3237  */
3238 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
3239 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3240 {
3241         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3242         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3243         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3244         struct winfd wfd;
3245         HANDLE winusb_handle;
3246         int i, j;
3247
3248         CHECK_WINUSBX_AVAILABLE(sub_api);
3249
3250         // Reset any available pipe (except control)
3251         for (i=0; i<USB_MAXINTERFACES; i++) {
3252                 winusb_handle = handle_priv->interface_handle[i].api_handle;
3253                 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
3254                 {
3255                         // Cancel any pollable I/O
3256                         usbi_remove_pollfd(ctx, wfd.fd);
3257                         usbi_free_fd(&wfd);
3258                         wfd = handle_to_winfd(winusb_handle);
3259                 }
3260
3261                 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
3262                         for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
3263                                 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
3264                                 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
3265                                         usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
3266                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3267                                 }
3268                                 // FlushPipe seems to fail on OUT pipes
3269                                 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
3270                                   && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
3271                                         usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
3272                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3273                                 }
3274                                 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
3275                                         usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
3276                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3277                                 }
3278                         }
3279                 }
3280         }
3281
3282         // libusbK & libusb0 have the ability to issue an actual device reset
3283         if (WinUSBX[sub_api].ResetDevice != NULL) {
3284                 winusb_handle = handle_priv->interface_handle[0].api_handle;
3285                 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
3286                         WinUSBX[sub_api].ResetDevice(winusb_handle);
3287                 }
3288         }
3289         return LIBUSB_SUCCESS;
3290 }
3291
3292 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
3293 {
3294         itransfer->transferred += io_size;
3295         return LIBUSB_TRANSFER_COMPLETED;
3296 }
3297
3298 /*
3299  * Internal HID Support functions (from libusb-win32)
3300  * Note that functions that complete data transfer synchronously must return
3301  * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
3302  */
3303 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
3304 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
3305
3306 static int _hid_wcslen(WCHAR *str)
3307 {
3308         int i = 0;
3309         while (str[i] && (str[i] != 0x409)) {
3310                 i++;
3311         }
3312         return i;
3313 }
3314
3315 static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3316 {
3317         struct libusb_device_descriptor d;
3318
3319         d.bLength = LIBUSB_DT_DEVICE_SIZE;
3320         d.bDescriptorType = LIBUSB_DT_DEVICE;
3321         d.bcdUSB = 0x0200; /* 2.00 */
3322         d.bDeviceClass = 0;
3323         d.bDeviceSubClass = 0;
3324         d.bDeviceProtocol = 0;
3325         d.bMaxPacketSize0 = 64; /* fix this! */
3326         d.idVendor = (uint16_t)dev->vid;
3327         d.idProduct = (uint16_t)dev->pid;
3328         d.bcdDevice = 0x0100;
3329         d.iManufacturer = dev->string_index[0];
3330         d.iProduct = dev->string_index[1];
3331         d.iSerialNumber = dev->string_index[2];
3332         d.bNumConfigurations = 1;
3333
3334         if (*size > LIBUSB_DT_DEVICE_SIZE)
3335                 *size = LIBUSB_DT_DEVICE_SIZE;
3336         memcpy(data, &d, *size);
3337         return LIBUSB_COMPLETED;
3338 }
3339
3340 static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3341 {
3342         char num_endpoints = 0;
3343         size_t config_total_len = 0;
3344         char tmp[HID_MAX_CONFIG_DESC_SIZE];
3345         struct libusb_config_descriptor *cd;
3346         struct libusb_interface_descriptor *id;
3347         struct libusb_hid_descriptor *hd;
3348         struct libusb_endpoint_descriptor *ed;
3349         size_t tmp_size;
3350
3351         if (dev->input_report_size)
3352                 num_endpoints++;
3353         if (dev->output_report_size)
3354                 num_endpoints++;
3355
3356         config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3357                 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3358
3359
3360         cd = (struct libusb_config_descriptor *)tmp;
3361         id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3362         hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3363                 + LIBUSB_DT_INTERFACE_SIZE);
3364         ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3365                 + LIBUSB_DT_INTERFACE_SIZE
3366                 + LIBUSB_DT_HID_SIZE);
3367
3368         cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3369         cd->bDescriptorType = LIBUSB_DT_CONFIG;
3370         cd->wTotalLength = (uint16_t) config_total_len;
3371         cd->bNumInterfaces = 1;
3372         cd->bConfigurationValue = 1;
3373         cd->iConfiguration = 0;
3374         cd->bmAttributes = 1 << 7; /* bus powered */
3375         cd->MaxPower = 50;
3376
3377         id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3378         id->bDescriptorType = LIBUSB_DT_INTERFACE;
3379         id->bInterfaceNumber = 0;
3380         id->bAlternateSetting = 0;
3381         id->bNumEndpoints = num_endpoints;
3382         id->bInterfaceClass = 3;
3383         id->bInterfaceSubClass = 0;
3384         id->bInterfaceProtocol = 0;
3385         id->iInterface = 0;
3386
3387         tmp_size = LIBUSB_DT_HID_SIZE;
3388         _hid_get_hid_descriptor(dev, hd, &tmp_size);
3389
3390         if (dev->input_report_size) {
3391                 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3392                 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3393                 ed->bEndpointAddress = HID_IN_EP;
3394                 ed->bmAttributes = 3;
3395                 ed->wMaxPacketSize = dev->input_report_size - 1;
3396                 ed->bInterval = 10;
3397                 ed = (struct libusb_endpoint_descriptor *)((char*)ed + LIBUSB_DT_ENDPOINT_SIZE);
3398         }
3399
3400         if (dev->output_report_size) {
3401                 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3402                 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3403                 ed->bEndpointAddress = HID_OUT_EP;
3404                 ed->bmAttributes = 3;
3405                 ed->wMaxPacketSize = dev->output_report_size - 1;
3406                 ed->bInterval = 10;
3407         }
3408
3409         if (*size > config_total_len)
3410                 *size = config_total_len;
3411         memcpy(data, tmp, *size);
3412         return LIBUSB_COMPLETED;
3413 }
3414
3415 static int _hid_get_string_descriptor(struct hid_device_priv* dev, int _index,
3416                                                                           void *data, size_t *size)
3417 {
3418         void *tmp = NULL;
3419         size_t tmp_size = 0;
3420         int i;
3421
3422         /* language ID, EN-US */
3423         char string_langid[] = {
3424                 0x09,
3425                 0x04
3426         };
3427
3428         if ((*size < 2) || (*size > 255)) {
3429                 return LIBUSB_ERROR_OVERFLOW;
3430         }
3431
3432         if (_index == 0) {
3433                 tmp = string_langid;
3434                 tmp_size = sizeof(string_langid)+2;
3435         } else {
3436                 for (i=0; i<3; i++) {
3437                         if (_index == (dev->string_index[i])) {
3438                                 tmp = dev->string[i];
3439                                 tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
3440                                 break;
3441                         }
3442                 }
3443                 if (i == 3) {   // not found
3444                         return LIBUSB_ERROR_INVALID_PARAM;
3445                 }
3446         }
3447
3448         if(!tmp_size) {
3449                 return LIBUSB_ERROR_INVALID_PARAM;
3450         }
3451
3452         if (tmp_size < *size) {
3453                 *size = tmp_size;
3454         }
3455         // 2 byte header
3456         ((uint8_t*)data)[0] = (uint8_t)*size;
3457         ((uint8_t*)data)[1] = LIBUSB_DT_STRING;
3458         memcpy((uint8_t*)data+2, tmp, *size-2);
3459         return LIBUSB_COMPLETED;
3460 }
3461
3462 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3463 {
3464         struct libusb_hid_descriptor d;
3465         uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3466         size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3467
3468         _hid_get_report_descriptor(dev, tmp, &report_len);
3469
3470         d.bLength = LIBUSB_DT_HID_SIZE;
3471         d.bDescriptorType = LIBUSB_DT_HID;
3472         d.bcdHID = 0x0110; /* 1.10 */
3473         d.bCountryCode = 0;
3474         d.bNumDescriptors = 1;
3475         d.bClassDescriptorType = LIBUSB_DT_REPORT;
3476         d.wClassDescriptorLength = (uint16_t)report_len;
3477
3478         if (*size > LIBUSB_DT_HID_SIZE)
3479                 *size = LIBUSB_DT_HID_SIZE;
3480         memcpy(data, &d, *size);
3481         return LIBUSB_COMPLETED;
3482 }
3483
3484 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3485 {
3486         uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3487         size_t i = 0;
3488
3489         /* usage page (0xFFA0 == vendor defined) */
3490         d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3491         /* usage (vendor defined) */
3492         d[i++] = 0x09; d[i++] = 0x01;
3493         /* start collection (application) */
3494         d[i++] = 0xA1; d[i++] = 0x01;
3495         /* input report */
3496         if (dev->input_report_size) {
3497                 /* usage (vendor defined) */
3498                 d[i++] = 0x09; d[i++] = 0x01;
3499                 /* logical minimum (0) */
3500                 d[i++] = 0x15; d[i++] = 0x00;
3501                 /* logical maximum (255) */
3502                 d[i++] = 0x25; d[i++] = 0xFF;
3503                 /* report size (8 bits) */
3504                 d[i++] = 0x75; d[i++] = 0x08;
3505                 /* report count */
3506                 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3507                 /* input (data, variable, absolute) */
3508                 d[i++] = 0x81; d[i++] = 0x00;
3509         }
3510         /* output report */
3511         if (dev->output_report_size) {
3512                 /* usage (vendor defined) */
3513                 d[i++] = 0x09; d[i++] = 0x02;
3514                 /* logical minimum (0) */
3515                 d[i++] = 0x15; d[i++] = 0x00;
3516                 /* logical maximum (255) */
3517                 d[i++] = 0x25; d[i++] = 0xFF;
3518                 /* report size (8 bits) */
3519                 d[i++] = 0x75; d[i++] = 0x08;
3520                 /* report count */
3521                 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3522                 /* output (data, variable, absolute) */
3523                 d[i++] = 0x91; d[i++] = 0x00;
3524         }
3525         /* feature report */
3526         if (dev->feature_report_size) {
3527                 /* usage (vendor defined) */
3528                 d[i++] = 0x09; d[i++] = 0x03;
3529                 /* logical minimum (0) */
3530                 d[i++] = 0x15; d[i++] = 0x00;
3531                 /* logical maximum (255) */
3532                 d[i++] = 0x25; d[i++] = 0xFF;
3533                 /* report size (8 bits) */
3534                 d[i++] = 0x75; d[i++] = 0x08;
3535                 /* report count */
3536                 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3537                 /* feature (data, variable, absolute) */
3538                 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3539         }
3540
3541         /* end collection */
3542         d[i++] = 0xC0;
3543
3544         if (*size > i)
3545                 *size = i;
3546         memcpy(data, d, *size);
3547         return LIBUSB_COMPLETED;
3548 }
3549
3550 static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
3551                                                            int type, int _index, void *data, size_t *size)
3552 {
3553         switch(type) {
3554         case LIBUSB_DT_DEVICE:
3555                 usbi_dbg("LIBUSB_DT_DEVICE");
3556                 return _hid_get_device_descriptor(dev, data, size);
3557         case LIBUSB_DT_CONFIG:
3558                 usbi_dbg("LIBUSB_DT_CONFIG");
3559                 if (!_index)
3560                         return _hid_get_config_descriptor(dev, data, size);
3561                 return LIBUSB_ERROR_INVALID_PARAM;
3562         case LIBUSB_DT_STRING:
3563                 usbi_dbg("LIBUSB_DT_STRING");
3564                 return _hid_get_string_descriptor(dev, _index, data, size);
3565         case LIBUSB_DT_HID:
3566                 usbi_dbg("LIBUSB_DT_HID");
3567                 if (!_index)
3568                         return _hid_get_hid_descriptor(dev, data, size);
3569                 return LIBUSB_ERROR_INVALID_PARAM;
3570         case LIBUSB_DT_REPORT:
3571                 usbi_dbg("LIBUSB_DT_REPORT");
3572                 if (!_index)
3573                         return _hid_get_report_descriptor(dev, data, size);
3574                 return LIBUSB_ERROR_INVALID_PARAM;
3575         case LIBUSB_DT_PHYSICAL:
3576                 usbi_dbg("LIBUSB_DT_PHYSICAL");
3577                 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3578                         return LIBUSB_COMPLETED;
3579                 return LIBUSB_ERROR_OTHER;
3580         }
3581         usbi_dbg("unsupported");
3582         return LIBUSB_ERROR_INVALID_PARAM;
3583 }
3584
3585 static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3586                                                    struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3587                                                    int report_type)
3588 {
3589         uint8_t *buf;
3590         DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3591         int r = LIBUSB_SUCCESS;
3592
3593         if (tp->hid_buffer != NULL) {
3594                 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3595         }
3596
3597         if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3598                 usbi_dbg("invalid size (%d)", *size);
3599                 return LIBUSB_ERROR_INVALID_PARAM;
3600         }
3601
3602         switch (report_type) {
3603                 case HID_REPORT_TYPE_INPUT:
3604                         ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3605                         break;
3606                 case HID_REPORT_TYPE_FEATURE:
3607                         ioctl_code = IOCTL_HID_GET_FEATURE;
3608                         break;
3609                 default:
3610                         usbi_dbg("unknown HID report type %d", report_type);
3611                         return LIBUSB_ERROR_INVALID_PARAM;
3612         }
3613
3614         // Add a trailing byte to detect overflows
3615         buf = (uint8_t*)calloc(expected_size+1, 1);
3616         if (buf == NULL) {
3617                 return LIBUSB_ERROR_NO_MEM;
3618         }
3619         buf[0] = (uint8_t)id;   // Must be set always
3620         usbi_dbg("report ID: 0x%02X", buf[0]);
3621
3622         tp->hid_expected_size = expected_size;
3623         read_size = expected_size;
3624
3625         // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3626         if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
3627                 buf, expected_size+1, &read_size, overlapped)) {
3628                 if (GetLastError() != ERROR_IO_PENDING) {
3629                         usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3630                         safe_free(buf);
3631                         return LIBUSB_ERROR_IO;
3632                 }
3633                 // Asynchronous wait
3634                 tp->hid_buffer = buf;
3635                 tp->hid_dest = (uint8_t*)data; // copy dest, as not necessarily the start of the transfer buffer
3636                 return LIBUSB_SUCCESS;
3637         }
3638
3639         // Transfer completed synchronously => copy and discard extra buffer
3640         if (read_size == 0) {
3641                 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3642                 *size = 0;
3643         } else {
3644                 if (buf[0] != id) {
3645                         usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3646                 }
3647                 if ((size_t)read_size > expected_size) {
3648                         r = LIBUSB_ERROR_OVERFLOW;
3649                         usbi_dbg("OVERFLOW!");
3650                 } else {
3651                         r = LIBUSB_COMPLETED;
3652                 }
3653
3654                 *size = MIN((size_t)read_size, *size);
3655                 if (id == 0) {
3656                         // Discard report ID
3657                         memcpy(data, buf+1, *size);
3658                 } else {
3659                         memcpy(data, buf, *size);
3660                 }
3661         }
3662         safe_free(buf);
3663         return r;
3664 }
3665
3666 static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3667                                                    struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3668                                                    int report_type)
3669 {
3670         uint8_t *buf = NULL;
3671         DWORD ioctl_code, write_size= (DWORD)*size;
3672
3673         if (tp->hid_buffer != NULL) {
3674                 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3675         }
3676
3677         if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3678                 usbi_dbg("invalid size (%d)", *size);
3679                 return LIBUSB_ERROR_INVALID_PARAM;
3680         }
3681
3682         switch (report_type) {
3683                 case HID_REPORT_TYPE_OUTPUT:
3684                         ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3685                         break;
3686                 case HID_REPORT_TYPE_FEATURE:
3687                         ioctl_code = IOCTL_HID_SET_FEATURE;
3688                         break;
3689                 default:
3690                         usbi_dbg("unknown HID report type %d", report_type);
3691                         return LIBUSB_ERROR_INVALID_PARAM;
3692         }
3693
3694         usbi_dbg("report ID: 0x%02X", id);
3695         // When report IDs are not used (i.e. when id == 0), we must add
3696         // a null report ID. Otherwise, we just use original data buffer
3697         if (id == 0) {
3698                 write_size++;
3699         }
3700         buf = (uint8_t*) malloc(write_size);
3701         if (buf == NULL) {
3702                 return LIBUSB_ERROR_NO_MEM;
3703         }
3704         if (id == 0) {
3705                 buf[0] = 0;
3706                 memcpy(buf + 1, data, *size);
3707         } else {
3708                 // This seems like a waste, but if we don't duplicate the
3709                 // data, we'll get issues when freeing hid_buffer
3710                 memcpy(buf, data, *size);
3711                 if (buf[0] != id) {
3712                         usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3713                 }
3714         }
3715
3716         // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3717         if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3718                 buf, write_size, &write_size, overlapped)) {
3719                 if (GetLastError() != ERROR_IO_PENDING) {
3720                         usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3721                         safe_free(buf);
3722                         return LIBUSB_ERROR_IO;
3723                 }
3724                 tp->hid_buffer = buf;
3725                 tp->hid_dest = NULL;
3726                 return LIBUSB_SUCCESS;
3727         }
3728
3729         // Transfer completed synchronously
3730         *size = write_size;
3731         if (write_size == 0) {
3732                 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3733         }
3734         safe_free(buf);
3735         return LIBUSB_COMPLETED;
3736 }
3737
3738 static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
3739                                                           int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3740                                                           size_t *size, OVERLAPPED* overlapped)
3741 {
3742         int report_type = (value >> 8) & 0xFF;
3743         int report_id = value & 0xFF;
3744
3745         if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3746           && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
3747                 return LIBUSB_ERROR_INVALID_PARAM;
3748
3749         if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3750                 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3751
3752         if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3753                 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3754
3755         return LIBUSB_ERROR_INVALID_PARAM;
3756 }
3757
3758
3759 /*
3760  * HID API functions
3761  */
3762 static int hid_init(int sub_api, struct libusb_context *ctx)
3763 {
3764         DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
3765         DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
3766         DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
3767         DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
3768         DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
3769         DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
3770         DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
3771         DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
3772         DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
3773         DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
3774         DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
3775         DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
3776         DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
3777         DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
3778         DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
3779         DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
3780
3781         api_hid_available = true;
3782         return LIBUSB_SUCCESS;
3783 }
3784
3785 static int hid_exit(int sub_api)
3786 {
3787         return LIBUSB_SUCCESS;
3788 }
3789
3790 // NB: open and close must ensure that they only handle interface of
3791 // the right API type, as these functions can be called wholesale from
3792 // composite_open(), with interfaces belonging to different APIs
3793 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3794 {
3795         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3796         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3797         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3798
3799         HIDD_ATTRIBUTES hid_attributes;
3800         PHIDP_PREPARSED_DATA preparsed_data = NULL;
3801         HIDP_CAPS capabilities;
3802         HIDP_VALUE_CAPS *value_caps;
3803
3804         HANDLE hid_handle = INVALID_HANDLE_VALUE;
3805         int i, j;
3806         // report IDs handling
3807         ULONG size[3];
3808         const char* type[3] = {"input", "output", "feature"};
3809         int nb_ids[2];  // zero and nonzero report IDs
3810
3811         CHECK_HID_AVAILABLE;
3812         if (priv->hid == NULL) {
3813                 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3814                 return LIBUSB_ERROR_NOT_FOUND;
3815         }
3816
3817         for (i = 0; i < USB_MAXINTERFACES; i++) {
3818                 if ( (priv->usb_interface[i].path != NULL)
3819                   && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
3820                         hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3821                                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3822                         /*
3823                          * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3824                          * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3825                          * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3826                          * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3827                          * HidD_GetFeature (if the device supports Feature reports)."
3828                          */
3829                         if (hid_handle == INVALID_HANDLE_VALUE) {
3830                                 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3831                                 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3832                                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3833                                 if (hid_handle == INVALID_HANDLE_VALUE) {
3834                                         usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3835                                         switch(GetLastError()) {
3836                                         case ERROR_FILE_NOT_FOUND:      // The device was disconnected
3837                                                 return LIBUSB_ERROR_NO_DEVICE;
3838                                         case ERROR_ACCESS_DENIED:
3839                                                 return LIBUSB_ERROR_ACCESS;
3840                                         default:
3841                                                 return LIBUSB_ERROR_IO;
3842                                         }
3843                                 }
3844                                 priv->usb_interface[i].restricted_functionality = true;
3845                         }
3846                         handle_priv->interface_handle[i].api_handle = hid_handle;
3847                 }
3848         }
3849
3850         hid_attributes.Size = sizeof(hid_attributes);
3851         do {
3852                 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3853                         usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3854                         break;
3855                 }
3856
3857                 priv->hid->vid = hid_attributes.VendorID;
3858                 priv->hid->pid = hid_attributes.ProductID;
3859
3860                 // Set the maximum available input buffer size
3861                 for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
3862                 usbi_dbg("set maximum input buffer size to %d", i/2);
3863
3864                 // Get the maximum input and output report size
3865                 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3866                         usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3867                         break;
3868                 }
3869                 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3870                         usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3871                         break;
3872                 }
3873
3874                 // Find out if interrupt will need report IDs
3875                 size[0] = capabilities.NumberInputValueCaps;
3876                 size[1] = capabilities.NumberOutputValueCaps;
3877                 size[2] = capabilities.NumberFeatureValueCaps;
3878                 for (j=HidP_Input; j<=HidP_Feature; j++) {
3879                         usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
3880                         priv->hid->uses_report_ids[j] = false;
3881                         if (size[j] > 0) {
3882                                 value_caps = (HIDP_VALUE_CAPS*) calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3883                                 if ( (value_caps != NULL)
3884                                   && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3885                                   && (size[j] >= 1) ) {
3886                                         nb_ids[0] = 0;
3887                                         nb_ids[1] = 0;
3888                                         for (i=0; i<(int)size[j]; i++) {
3889                                                 usbi_dbg("  Report ID: 0x%02X", value_caps[i].ReportID);
3890                                                 if (value_caps[i].ReportID != 0) {
3891                                                         nb_ids[1]++;
3892                                                 } else {
3893                                                         nb_ids[0]++;
3894                                                 }
3895                                         }
3896                                         if (nb_ids[1] != 0) {
3897                                                 if (nb_ids[0] != 0) {
3898                                                         usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3899                                                                 type[j]);
3900                                                 }
3901                                                 priv->hid->uses_report_ids[j] = true;
3902                                         }
3903                                 } else {
3904                                         usbi_warn(ctx, "  could not process %s report IDs", type[j]);
3905                                 }
3906                                 safe_free(value_caps);
3907                         }
3908                 }
3909
3910                 // Set the report sizes
3911                 priv->hid->input_report_size = capabilities.InputReportByteLength;
3912                 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3913                 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3914
3915                 // Fetch string descriptors
3916                 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3917                 if (priv->hid->string_index[0] != 0) {
3918                         HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
3919                                 sizeof(priv->hid->string[0]));
3920                 } else {
3921                         priv->hid->string[0][0] = 0;
3922                 }
3923                 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3924                 if (priv->hid->string_index[1] != 0) {
3925                         HidD_GetProductString(hid_handle, priv->hid->string[1],
3926                                 sizeof(priv->hid->string[1]));
3927                 } else {
3928                         priv->hid->string[1][0] = 0;
3929                 }
3930                 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3931                 if (priv->hid->string_index[2] != 0) {
3932                         HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
3933                                 sizeof(priv->hid->string[2]));
3934                 } else {
3935                         priv->hid->string[2][0] = 0;
3936                 }
3937         } while(0);
3938
3939         if (preparsed_data) {
3940                 HidD_FreePreparsedData(preparsed_data);
3941         }
3942
3943         return LIBUSB_SUCCESS;
3944 }
3945
3946 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3947 {
3948         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3949         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3950         HANDLE file_handle;
3951         int i;
3952
3953         if (!api_hid_available)
3954                 return;
3955
3956         for (i = 0; i < USB_MAXINTERFACES; i++) {
3957                 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3958                         file_handle = handle_priv->interface_handle[i].api_handle;
3959                         if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
3960                                 CloseHandle(file_handle);
3961                         }
3962                 }
3963         }
3964 }
3965
3966 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3967 {
3968         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3969         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3970
3971         CHECK_HID_AVAILABLE;
3972
3973         // NB: Disconnection detection is not possible in this function
3974         if (priv->usb_interface[iface].path == NULL) {
3975                 return LIBUSB_ERROR_NOT_FOUND;  // invalid iface
3976         }
3977
3978         // We use dev_handle as a flag for interface claimed
3979         if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
3980                 return LIBUSB_ERROR_BUSY;       // already claimed
3981         }
3982
3983         handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3984
3985         usbi_dbg("claimed interface %d", iface);
3986         handle_priv->active_interface = iface;
3987
3988         return LIBUSB_SUCCESS;
3989 }
3990
3991 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3992 {
3993         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3994         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3995
3996         CHECK_HID_AVAILABLE;
3997
3998         if (priv->usb_interface[iface].path == NULL) {
3999                 return LIBUSB_ERROR_NOT_FOUND;  // invalid iface
4000         }
4001
4002         if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
4003                 return LIBUSB_ERROR_NOT_FOUND;  // invalid iface
4004         }
4005
4006         handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
4007
4008         return LIBUSB_SUCCESS;
4009 }
4010
4011 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4012 {
4013         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4014
4015         CHECK_HID_AVAILABLE;
4016
4017         if (altsetting > 255) {
4018                 return LIBUSB_ERROR_INVALID_PARAM;
4019         }
4020
4021         if (altsetting != 0) {
4022                 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
4023                 return LIBUSB_ERROR_NOT_SUPPORTED;
4024         }
4025
4026         return LIBUSB_SUCCESS;
4027 }
4028
4029 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4030 {
4031         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4032         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
4033         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4034         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4035         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4036         WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
4037         HANDLE hid_handle;
4038         struct winfd wfd;
4039         int current_interface, config;
4040         size_t size;
4041         int r = LIBUSB_ERROR_INVALID_PARAM;
4042
4043         CHECK_HID_AVAILABLE;
4044
4045         transfer_priv->pollable_fd = INVALID_WINFD;
4046         safe_free(transfer_priv->hid_buffer);
4047         transfer_priv->hid_dest = NULL;
4048         size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
4049
4050         if (size > MAX_CTRL_BUFFER_LENGTH) {
4051                 return LIBUSB_ERROR_INVALID_PARAM;
4052         }
4053
4054         current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
4055         if (current_interface < 0) {
4056                 if (auto_claim(transfer, &current_interface, USB_API_HID) != LIBUSB_SUCCESS) {
4057                         return LIBUSB_ERROR_NOT_FOUND;
4058                 }
4059         }
4060
4061         usbi_dbg("will use interface %d", current_interface);
4062         hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4063         // Always use the handle returned from usbi_create_fd (wfd.handle)
4064         wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
4065         if (wfd.fd < 0) {
4066                 return LIBUSB_ERROR_NOT_FOUND;
4067         }
4068
4069         switch(LIBUSB_REQ_TYPE(setup->request_type)) {
4070         case LIBUSB_REQUEST_TYPE_STANDARD:
4071                 switch(setup->request) {
4072                 case LIBUSB_REQUEST_GET_DESCRIPTOR:
4073                         r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
4074                                 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
4075                         break;
4076                 case LIBUSB_REQUEST_GET_CONFIGURATION:
4077                         r = windows_get_configuration(transfer->dev_handle, &config);
4078                         if (r == LIBUSB_SUCCESS) {
4079                                 size = 1;
4080                                 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
4081                                 r = LIBUSB_COMPLETED;
4082                         }
4083                         break;
4084                 case LIBUSB_REQUEST_SET_CONFIGURATION:
4085                         if (setup->value == priv->active_config) {
4086                                 r = LIBUSB_COMPLETED;
4087                         } else {
4088                                 usbi_warn(ctx, "cannot set configuration other than the default one");
4089                                 r = LIBUSB_ERROR_INVALID_PARAM;
4090                         }
4091                         break;
4092                 case LIBUSB_REQUEST_GET_INTERFACE:
4093                         size = 1;
4094                         ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
4095                         r = LIBUSB_COMPLETED;
4096                         break;
4097                 case LIBUSB_REQUEST_SET_INTERFACE:
4098                         r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->index, setup->value);
4099                         if (r == LIBUSB_SUCCESS) {
4100                                 r = LIBUSB_COMPLETED;
4101                         }
4102                         break;
4103                 default:
4104                         usbi_warn(ctx, "unsupported HID control request");
4105                         r = LIBUSB_ERROR_INVALID_PARAM;
4106                         break;
4107                 }
4108                 break;
4109         case LIBUSB_REQUEST_TYPE_CLASS:
4110                 r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
4111                         setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
4112                         &size, wfd.overlapped);
4113                 break;
4114         default:
4115                 usbi_warn(ctx, "unsupported HID control request");
4116                 r = LIBUSB_ERROR_INVALID_PARAM;
4117                 break;
4118         }
4119
4120         if (r == LIBUSB_COMPLETED) {
4121                 // Force request to be completed synchronously. Transferred size has been set by previous call
4122                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
4123                 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
4124                 // set InternalHigh to the number of bytes transferred
4125                 wfd.overlapped->InternalHigh = (DWORD)size;
4126                 r = LIBUSB_SUCCESS;
4127         }
4128
4129         if (r == LIBUSB_SUCCESS) {
4130                 // Use priv_transfer to store data needed for async polling
4131                 transfer_priv->pollable_fd = wfd;
4132                 transfer_priv->interface_number = (uint8_t)current_interface;
4133         } else {
4134                 usbi_free_fd(&wfd);
4135         }
4136
4137         return r;
4138 }
4139
4140 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4141         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4142         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
4143         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4144         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4145         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4146         struct winfd wfd;
4147         HANDLE hid_handle;
4148         bool direction_in, ret;
4149         int current_interface, length;
4150         DWORD size;
4151         int r = LIBUSB_SUCCESS;
4152
4153         CHECK_HID_AVAILABLE;
4154
4155         transfer_priv->pollable_fd = INVALID_WINFD;
4156         transfer_priv->hid_dest = NULL;
4157         safe_free(transfer_priv->hid_buffer);
4158
4159         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4160         if (current_interface < 0) {
4161                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4162                 return LIBUSB_ERROR_NOT_FOUND;
4163         }
4164
4165         usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
4166
4167         hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4168         direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
4169
4170         wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
4171         // Always use the handle returned from usbi_create_fd (wfd.handle)
4172         if (wfd.fd < 0) {
4173                 return LIBUSB_ERROR_NO_MEM;
4174         }
4175
4176         // If report IDs are not in use, an extra prefix byte must be added
4177         if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
4178           || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
4179                 length = transfer->length+1;
4180         } else {
4181                 length = transfer->length;
4182         }
4183         // Add a trailing byte to detect overflows on input
4184         transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
4185         if (transfer_priv->hid_buffer == NULL) {
4186                 return LIBUSB_ERROR_NO_MEM;
4187         }
4188         transfer_priv->hid_expected_size = length;
4189
4190         if (direction_in) {
4191                 transfer_priv->hid_dest = transfer->buffer;
4192                 usbi_dbg("reading %d bytes (report ID: 0x00)", length);
4193                 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
4194         } else {
4195                 if (!priv->hid->uses_report_ids[1]) {
4196                         memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
4197                 } else {
4198                         // We could actually do without the calloc and memcpy in this case
4199                         memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
4200                 }
4201                 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
4202                 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
4203         }
4204         if (!ret) {
4205                 if (GetLastError() != ERROR_IO_PENDING) {
4206                         usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
4207                         usbi_free_fd(&wfd);
4208                         safe_free(transfer_priv->hid_buffer);
4209                         return LIBUSB_ERROR_IO;
4210                 }
4211         } else {
4212                 // Only write operations that completed synchronously need to free up
4213                 // hid_buffer. For reads, copy_transfer_data() handles that process.
4214                 if (!direction_in) {
4215                         safe_free(transfer_priv->hid_buffer);
4216                 }
4217                 if (size == 0) {
4218                         usbi_err(ctx, "program assertion failed - no data was transferred");
4219                         size = 1;
4220                 }
4221                 if (size > (size_t)length) {
4222                         usbi_err(ctx, "OVERFLOW!");
4223                         r = LIBUSB_ERROR_OVERFLOW;
4224                 }
4225                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
4226                 wfd.overlapped->InternalHigh = size;
4227         }
4228
4229         transfer_priv->pollable_fd = wfd;
4230         transfer_priv->interface_number = (uint8_t)current_interface;
4231
4232         return r;
4233 }
4234
4235 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4236 {
4237         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4238         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
4239         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4240         HANDLE hid_handle;
4241         int current_interface;
4242
4243         CHECK_HID_AVAILABLE;
4244
4245         current_interface = transfer_priv->interface_number;
4246         hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4247         CancelIo(hid_handle);
4248
4249         return LIBUSB_SUCCESS;
4250 }
4251
4252 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4253 {
4254         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4255         HANDLE hid_handle;
4256         int current_interface;
4257
4258         CHECK_HID_AVAILABLE;
4259
4260         // Flushing the queues on all interfaces is the best we can achieve
4261         for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
4262                 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4263                 if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
4264                         HidD_FlushQueue(hid_handle);
4265                 }
4266         }
4267         return LIBUSB_SUCCESS;
4268 }
4269
4270 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4271 {
4272         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4273         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4274         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4275         HANDLE hid_handle;
4276         int current_interface;
4277
4278         CHECK_HID_AVAILABLE;
4279
4280         current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4281         if (current_interface < 0) {
4282                 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4283                 return LIBUSB_ERROR_NOT_FOUND;
4284         }
4285
4286         usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
4287         hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4288
4289         // No endpoint selection with Microsoft's implementation, so we try to flush the
4290         // whole interface. Should be OK for most case scenarios
4291         if (!HidD_FlushQueue(hid_handle)) {
4292                 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
4293                 // Device was probably disconnected
4294                 return LIBUSB_ERROR_NO_DEVICE;
4295         }
4296
4297         return LIBUSB_SUCCESS;
4298 }
4299
4300 // This extra function is only needed for HID
4301 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) {
4302         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4303         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4304         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4305         int r = LIBUSB_TRANSFER_COMPLETED;
4306         uint32_t corrected_size = io_size;
4307
4308         if (transfer_priv->hid_buffer != NULL) {
4309                 // If we have a valid hid_buffer, it means the transfer was async
4310                 if (transfer_priv->hid_dest != NULL) {  // Data readout
4311                         if (corrected_size > 0) {
4312                                 // First, check for overflow
4313                                 if (corrected_size > transfer_priv->hid_expected_size) {
4314                                         usbi_err(ctx, "OVERFLOW!");
4315                                         corrected_size = (uint32_t)transfer_priv->hid_expected_size;
4316                                         r = LIBUSB_TRANSFER_OVERFLOW;
4317                                 }
4318
4319                                 if (transfer_priv->hid_buffer[0] == 0) {
4320                                         // Discard the 1 byte report ID prefix
4321                                         corrected_size--;
4322                                         memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
4323                                 } else {
4324                                         memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
4325                                 }
4326                         }
4327                         transfer_priv->hid_dest = NULL;
4328                 }
4329                 // For write, we just need to free the hid buffer
4330                 safe_free(transfer_priv->hid_buffer);
4331         }
4332         itransfer->transferred += corrected_size;
4333         return r;
4334 }
4335
4336
4337 /*
4338  * Composite API functions
4339  */
4340 static int composite_init(int sub_api, struct libusb_context *ctx)
4341 {
4342         return LIBUSB_SUCCESS;
4343 }
4344
4345 static int composite_exit(int sub_api)
4346 {
4347         return LIBUSB_SUCCESS;
4348 }
4349
4350 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
4351 {
4352         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4353         int r = LIBUSB_ERROR_NOT_FOUND;
4354         uint8_t i;
4355         // SUB_API_MAX+1 as the SUB_API_MAX pos is used to indicate availability of HID
4356         bool available[SUB_API_MAX+1] = {0};
4357
4358         for (i=0; i<USB_MAXINTERFACES; i++) {
4359                 switch (priv->usb_interface[i].apib->id) {
4360                 case USB_API_WINUSBX:
4361                         if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4362                                 available[priv->usb_interface[i].sub_api] = true;
4363                         break;
4364                 case USB_API_HID:
4365                         available[SUB_API_MAX] = true;
4366                         break;
4367                 default:
4368                         break;
4369                 }
4370         }
4371
4372         for (i=0; i<SUB_API_MAX; i++) { // WinUSB-like drivers
4373                 if (available[i]) {
4374                         r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4375                         if (r != LIBUSB_SUCCESS) {
4376                                 return r;
4377                         }
4378                 }
4379         }
4380         if (available[SUB_API_MAX]) {   // HID driver
4381                 r = hid_open(SUB_API_NOTSET, dev_handle);
4382         }
4383         return r;
4384 }
4385
4386 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4387 {
4388         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4389         uint8_t i;
4390         bool available[SUB_API_MAX];
4391
4392         for (i = 0; i<SUB_API_MAX; i++) {
4393                 available[i] = false;
4394         }
4395
4396         for (i=0; i<USB_MAXINTERFACES; i++) {
4397                 if ( (priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4398                   && (priv->usb_interface[i].sub_api != SUB_API_NOTSET) ) {
4399                         available[priv->usb_interface[i].sub_api] = true;
4400                 }
4401         }
4402
4403         for (i=0; i<SUB_API_MAX; i++) {
4404                 if (available[i]) {
4405                         usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4406                 }
4407         }
4408 }
4409
4410 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4411 {
4412         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4413         return priv->usb_interface[iface].apib->
4414                 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4415 }
4416
4417 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4418 {
4419         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4420         return priv->usb_interface[iface].apib->
4421                 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4422 }
4423
4424 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4425 {
4426         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4427         return priv->usb_interface[iface].apib->
4428                 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4429 }
4430
4431 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4432 {
4433         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4434         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4435         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4436         int i, pass;
4437
4438         // Interface shouldn't matter for control, but it does in practice, with Windows'
4439         // restrictions with regards to accessing HID keyboards and mice. Try a 2 pass approach
4440         for (pass = 0; pass < 2; pass++) {
4441                 for (i=0; i<USB_MAXINTERFACES; i++) {
4442                         if (priv->usb_interface[i].path != NULL) {
4443                                 if ((pass == 0) && (priv->usb_interface[i].restricted_functionality)) {
4444                                         usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", i);
4445                                         continue;
4446                                 }
4447                                 usbi_dbg("using interface %d", i);
4448                                 return priv->usb_interface[i].apib->submit_control_transfer(priv->usb_interface[i].sub_api, itransfer);
4449                         }
4450                 }
4451         }
4452
4453         usbi_err(ctx, "no libusb supported interfaces to complete request");
4454         return LIBUSB_ERROR_NOT_FOUND;
4455 }
4456
4457 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4458         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4459         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4460         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4461         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4462         int current_interface;
4463
4464         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4465         if (current_interface < 0) {
4466                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4467                 return LIBUSB_ERROR_NOT_FOUND;
4468         }
4469
4470         return priv->usb_interface[current_interface].apib->
4471                 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);}
4472
4473 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
4474         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4475         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4476         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4477         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4478         int current_interface;
4479
4480         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4481         if (current_interface < 0) {
4482                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4483                 return LIBUSB_ERROR_NOT_FOUND;
4484         }
4485
4486         return priv->usb_interface[current_interface].apib->
4487                 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);}
4488
4489 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4490 {
4491         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4492         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4493         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4494         int current_interface;
4495
4496         current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4497         if (current_interface < 0) {
4498                 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4499                 return LIBUSB_ERROR_NOT_FOUND;
4500         }
4501
4502         return priv->usb_interface[current_interface].apib->
4503                 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);}
4504
4505 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
4506 {
4507         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4508         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4509         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4510
4511         return priv->usb_interface[transfer_priv->interface_number].apib->
4512                 abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);}
4513
4514 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4515 {
4516         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4517         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4518         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4519
4520         return priv->usb_interface[transfer_priv->interface_number].apib->
4521                 abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);}
4522
4523 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4524 {
4525         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4526         int r;
4527         uint8_t i; 
4528         bool available[SUB_API_MAX];
4529         for (i = 0; i<SUB_API_MAX; i++) {
4530                 available[i] = false;
4531         }
4532         for (i=0; i<USB_MAXINTERFACES; i++) {
4533                 if ( (priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4534                   && (priv->usb_interface[i].sub_api != SUB_API_NOTSET) ) {
4535                         available[priv->usb_interface[i].sub_api] = true;
4536                 }
4537         }
4538         for (i=0; i<SUB_API_MAX; i++) {
4539                 if (available[i]) {
4540                         r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4541                         if (r != LIBUSB_SUCCESS) {
4542                                 return r;
4543                         }
4544                 }
4545         }
4546         return LIBUSB_SUCCESS;
4547 }
4548
4549 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
4550 {
4551         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4552         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4553         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4554
4555         return priv->usb_interface[transfer_priv->interface_number].apib->
4556                 copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);
4557 }