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