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