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