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