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