core: Add provisions for per-context private backend data
[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         0,
2099         sizeof(struct windows_device_priv),
2100         sizeof(struct windows_device_handle_priv),
2101         sizeof(struct windows_transfer_priv),
2102 };
2103
2104
2105 /*
2106  * USB API backends
2107  */
2108 static int unsupported_init(int sub_api, struct libusb_context *ctx)
2109 {
2110         return LIBUSB_SUCCESS;
2111 }
2112
2113 static int unsupported_exit(int sub_api)
2114 {
2115         return LIBUSB_SUCCESS;
2116 }
2117
2118 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle)
2119 {
2120         PRINT_UNSUPPORTED_API(open);
2121 }
2122
2123 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle)
2124 {
2125         usbi_dbg("unsupported API call for 'close'");
2126 }
2127
2128 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2129 {
2130         PRINT_UNSUPPORTED_API(configure_endpoints);
2131 }
2132
2133 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2134 {
2135         PRINT_UNSUPPORTED_API(claim_interface);
2136 }
2137
2138 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2139 {
2140         PRINT_UNSUPPORTED_API(set_interface_altsetting);
2141 }
2142
2143 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2144 {
2145         PRINT_UNSUPPORTED_API(release_interface);
2146 }
2147
2148 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2149 {
2150         PRINT_UNSUPPORTED_API(clear_halt);
2151 }
2152
2153 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2154 {
2155         PRINT_UNSUPPORTED_API(reset_device);
2156 }
2157
2158 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2159 {
2160         PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2161 }
2162
2163 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
2164 {
2165         PRINT_UNSUPPORTED_API(submit_iso_transfer);
2166 }
2167
2168 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2169 {
2170         PRINT_UNSUPPORTED_API(submit_control_transfer);
2171 }
2172
2173 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer)
2174 {
2175         PRINT_UNSUPPORTED_API(abort_control);
2176 }
2177
2178 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2179 {
2180         PRINT_UNSUPPORTED_API(abort_transfers);
2181 }
2182
2183 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2184 {
2185         PRINT_UNSUPPORTED_API(copy_transfer_data);
2186 }
2187
2188 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2189 {
2190         return LIBUSB_SUCCESS;
2191 }
2192
2193 // These names must be uppercase
2194 static const char *hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30", "VHHUB", "AUSB3HUB"};
2195 static const char *composite_driver_names[] = {"USBCCGP"};
2196 static const char *winusbx_driver_names[] = WINUSBX_DRV_NAMES;
2197 static const char *hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2198 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2199         {
2200                 USB_API_UNSUPPORTED,
2201                 "Unsupported API",
2202                 NULL,
2203                 0,
2204                 unsupported_init,
2205                 unsupported_exit,
2206                 unsupported_open,
2207                 unsupported_close,
2208                 unsupported_configure_endpoints,
2209                 unsupported_claim_interface,
2210                 unsupported_set_interface_altsetting,
2211                 unsupported_release_interface,
2212                 unsupported_clear_halt,
2213                 unsupported_reset_device,
2214                 unsupported_submit_bulk_transfer,
2215                 unsupported_submit_iso_transfer,
2216                 unsupported_submit_control_transfer,
2217                 unsupported_abort_control,
2218                 unsupported_abort_transfers,
2219                 unsupported_copy_transfer_data,
2220         },
2221         {
2222                 USB_API_HUB,
2223                 "HUB API",
2224                 hub_driver_names,
2225                 ARRAYSIZE(hub_driver_names),
2226                 unsupported_init,
2227                 unsupported_exit,
2228                 unsupported_open,
2229                 unsupported_close,
2230                 unsupported_configure_endpoints,
2231                 unsupported_claim_interface,
2232                 unsupported_set_interface_altsetting,
2233                 unsupported_release_interface,
2234                 unsupported_clear_halt,
2235                 unsupported_reset_device,
2236                 unsupported_submit_bulk_transfer,
2237                 unsupported_submit_iso_transfer,
2238                 unsupported_submit_control_transfer,
2239                 unsupported_abort_control,
2240                 unsupported_abort_transfers,
2241                 unsupported_copy_transfer_data,
2242         },
2243         {
2244                 USB_API_COMPOSITE,
2245                 "Composite API",
2246                 composite_driver_names,
2247                 ARRAYSIZE(composite_driver_names),
2248                 composite_init,
2249                 composite_exit,
2250                 composite_open,
2251                 composite_close,
2252                 common_configure_endpoints,
2253                 composite_claim_interface,
2254                 composite_set_interface_altsetting,
2255                 composite_release_interface,
2256                 composite_clear_halt,
2257                 composite_reset_device,
2258                 composite_submit_bulk_transfer,
2259                 composite_submit_iso_transfer,
2260                 composite_submit_control_transfer,
2261                 composite_abort_control,
2262                 composite_abort_transfers,
2263                 composite_copy_transfer_data,
2264         },
2265         {
2266                 USB_API_WINUSBX,
2267                 "WinUSB-like APIs",
2268                 winusbx_driver_names,
2269                 ARRAYSIZE(winusbx_driver_names),
2270                 winusbx_init,
2271                 winusbx_exit,
2272                 winusbx_open,
2273                 winusbx_close,
2274                 winusbx_configure_endpoints,
2275                 winusbx_claim_interface,
2276                 winusbx_set_interface_altsetting,
2277                 winusbx_release_interface,
2278                 winusbx_clear_halt,
2279                 winusbx_reset_device,
2280                 winusbx_submit_bulk_transfer,
2281                 unsupported_submit_iso_transfer,
2282                 winusbx_submit_control_transfer,
2283                 winusbx_abort_control,
2284                 winusbx_abort_transfers,
2285                 winusbx_copy_transfer_data,
2286         },
2287         {
2288                 USB_API_HID,
2289                 "HID API",
2290                 hid_driver_names,
2291                 ARRAYSIZE(hid_driver_names),
2292                 hid_init,
2293                 hid_exit,
2294                 hid_open,
2295                 hid_close,
2296                 common_configure_endpoints,
2297                 hid_claim_interface,
2298                 hid_set_interface_altsetting,
2299                 hid_release_interface,
2300                 hid_clear_halt,
2301                 hid_reset_device,
2302                 hid_submit_bulk_transfer,
2303                 unsupported_submit_iso_transfer,
2304                 hid_submit_control_transfer,
2305                 hid_abort_transfers,
2306                 hid_abort_transfers,
2307                 hid_copy_transfer_data,
2308         },
2309 };
2310
2311
2312 /*
2313  * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2314  */
2315 #define WinUSBX_Set(fn)                                                                         \
2316         do {                                                                                    \
2317                 if (native_winusb)                                                              \
2318                         WinUSBX[i].fn = (WinUsb_##fn##_t)GetProcAddress(h, "WinUsb_" #fn);      \
2319                 else                                                                            \
2320                         pLibK_GetProcAddress((PVOID *)&WinUSBX[i].fn, i, KUSB_FNID_##fn);       \
2321         } while (0)
2322
2323 static int winusbx_init(int sub_api, struct libusb_context *ctx)
2324 {
2325         HMODULE h;
2326         bool native_winusb;
2327         int i;
2328         KLIB_VERSION LibK_Version;
2329         LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
2330         LibK_GetVersion_t pLibK_GetVersion;
2331
2332         h = LoadLibraryA("libusbK");
2333
2334         if (h == NULL) {
2335                 usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
2336                 h = LoadLibraryA("WinUSB");
2337
2338                 if (h == NULL) {
2339                         usbi_warn(ctx, "WinUSB DLL is not available either, "
2340                                 "you will not be able to access devices outside of enumeration");
2341                         return LIBUSB_ERROR_NOT_FOUND;
2342                 }
2343         } else {
2344                 usbi_dbg("using libusbK DLL for universal access");
2345                 pLibK_GetVersion = (LibK_GetVersion_t)GetProcAddress(h, "LibK_GetVersion");
2346                 if (pLibK_GetVersion != NULL) {
2347                         pLibK_GetVersion(&LibK_Version);
2348                         usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2349                                 LibK_Version.Micro, LibK_Version.Nano);
2350                 }
2351                 pLibK_GetProcAddress = (LibK_GetProcAddress_t)GetProcAddress(h, "LibK_GetProcAddress");
2352                 if (pLibK_GetProcAddress == NULL) {
2353                         usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2354                         FreeLibrary(h);
2355                         return LIBUSB_ERROR_NOT_FOUND;
2356                 }
2357         }
2358
2359         native_winusb = (pLibK_GetProcAddress == NULL);
2360         for (i = SUB_API_LIBUSBK; i < SUB_API_MAX; i++) {
2361                 WinUSBX_Set(AbortPipe);
2362                 WinUSBX_Set(ControlTransfer);
2363                 WinUSBX_Set(FlushPipe);
2364                 WinUSBX_Set(Free);
2365                 WinUSBX_Set(GetAssociatedInterface);
2366                 WinUSBX_Set(GetCurrentAlternateSetting);
2367                 WinUSBX_Set(GetDescriptor);
2368                 WinUSBX_Set(GetOverlappedResult);
2369                 WinUSBX_Set(GetPipePolicy);
2370                 WinUSBX_Set(GetPowerPolicy);
2371                 WinUSBX_Set(Initialize);
2372                 WinUSBX_Set(QueryDeviceInformation);
2373                 WinUSBX_Set(QueryInterfaceSettings);
2374                 WinUSBX_Set(QueryPipe);
2375                 WinUSBX_Set(ReadPipe);
2376                 WinUSBX_Set(ResetPipe);
2377                 WinUSBX_Set(SetCurrentAlternateSetting);
2378                 WinUSBX_Set(SetPipePolicy);
2379                 WinUSBX_Set(SetPowerPolicy);
2380                 WinUSBX_Set(WritePipe);
2381                 if (!native_winusb)
2382                         WinUSBX_Set(ResetDevice);
2383
2384                 if (WinUSBX[i].Initialize != NULL) {
2385                         WinUSBX[i].initialized = true;
2386                         usbi_dbg("initalized sub API %s", sub_api_name[i]);
2387                 } else {
2388                         usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
2389                         WinUSBX[i].initialized = false;
2390                 }
2391         }
2392
2393         WinUSBX_handle = h;
2394         return LIBUSB_SUCCESS;
2395 }
2396
2397 static int winusbx_exit(int sub_api)
2398 {
2399         if (WinUSBX_handle != NULL) {
2400                 FreeLibrary(WinUSBX_handle);
2401                 WinUSBX_handle = NULL;
2402
2403                 /* Reset the WinUSBX API structures */
2404                 memset(&WinUSBX, 0, sizeof(WinUSBX));
2405         }
2406
2407         return LIBUSB_SUCCESS;
2408 }
2409
2410 // NB: open and close must ensure that they only handle interface of
2411 // the right API type, as these functions can be called wholesale from
2412 // composite_open(), with interfaces belonging to different APIs
2413 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2414 {
2415         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2416         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2417         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2418
2419         HANDLE file_handle;
2420         int i;
2421
2422         CHECK_WINUSBX_AVAILABLE(sub_api);
2423
2424         // WinUSB requires a separate handle for each interface
2425         for (i = 0; i < USB_MAXINTERFACES; i++) {
2426                 if ((priv->usb_interface[i].path != NULL)
2427                                 && (priv->usb_interface[i].apib->id == USB_API_WINUSBX)) {
2428                         file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2429                                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2430                         if (file_handle == INVALID_HANDLE_VALUE) {
2431                                 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2432                                 switch(GetLastError()) {
2433                                 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2434                                         return LIBUSB_ERROR_NO_DEVICE;
2435                                 case ERROR_ACCESS_DENIED:
2436                                         return LIBUSB_ERROR_ACCESS;
2437                                 default:
2438                                         return LIBUSB_ERROR_IO;
2439                                 }
2440                         }
2441                         handle_priv->interface_handle[i].dev_handle = file_handle;
2442                 }
2443         }
2444
2445         return LIBUSB_SUCCESS;
2446 }
2447
2448 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2449 {
2450         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2451         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2452         HANDLE handle;
2453         int i;
2454
2455         if (sub_api == SUB_API_NOTSET)
2456                 sub_api = priv->sub_api;
2457
2458         if (!WinUSBX[sub_api].initialized)
2459                 return;
2460
2461         if (priv->apib->id == USB_API_COMPOSITE) {
2462                 // If this is a composite device, just free and close all WinUSB-like
2463                 // interfaces directly (each is independent and not associated with another)
2464                 for (i = 0; i < USB_MAXINTERFACES; i++) {
2465                         if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2466                                 handle = handle_priv->interface_handle[i].api_handle;
2467                                 if (HANDLE_VALID(handle))
2468                                         WinUSBX[sub_api].Free(handle);
2469
2470                                 handle = handle_priv->interface_handle[i].dev_handle;
2471                                 if (HANDLE_VALID(handle))
2472                                         CloseHandle(handle);
2473                         }
2474                 }
2475         } else {
2476                 // If this is a WinUSB device, free all interfaces above interface 0,
2477                 // then free and close interface 0 last
2478                 for (i = 1; i < USB_MAXINTERFACES; i++) {
2479                         handle = handle_priv->interface_handle[i].api_handle;
2480                         if (HANDLE_VALID(handle))
2481                                 WinUSBX[sub_api].Free(handle);
2482                 }
2483                 handle = handle_priv->interface_handle[0].api_handle;
2484                 if (HANDLE_VALID(handle))
2485                         WinUSBX[sub_api].Free(handle);
2486
2487                 handle = handle_priv->interface_handle[0].dev_handle;
2488                 if (HANDLE_VALID(handle))
2489                         CloseHandle(handle);
2490         }
2491 }
2492
2493 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2494 {
2495         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2496         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2497         HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2498         UCHAR policy;
2499         ULONG timeout = 0;
2500         uint8_t endpoint_address;
2501         int i;
2502
2503         CHECK_WINUSBX_AVAILABLE(sub_api);
2504
2505         // With handle and enpoints set (in parent), we can setup the default pipe properties
2506         // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2507         for (i = -1; i < priv->usb_interface[iface].nb_endpoints; i++) {
2508                 endpoint_address = (i == -1) ? 0 : priv->usb_interface[iface].endpoint[i];
2509                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2510                         PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout))
2511                         usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2512
2513                 if ((i == -1) || (sub_api == SUB_API_LIBUSB0))
2514                         continue; // Other policies don't apply to control endpoint or libusb0
2515
2516                 policy = false;
2517                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2518                         SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy))
2519                         usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2520
2521                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2522                         IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy))
2523                         usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2524
2525                 policy = true;
2526                 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2527                    https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2528                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2529                         ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy))
2530                         usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2531
2532                 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2533                         AUTO_CLEAR_STALL, sizeof(UCHAR), &policy))
2534                         usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2535         }
2536
2537         return LIBUSB_SUCCESS;
2538 }
2539
2540 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2541 {
2542         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2543         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2544         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2545         bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2546         SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
2547         HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2548         SP_DEVINFO_DATA dev_info_data;
2549         char *dev_path_no_guid = NULL;
2550         char filter_path[] = "\\\\.\\libusb0-0000";
2551         bool found_filter = false;
2552         HANDLE file_handle, winusb_handle;
2553         DWORD err;
2554         int i;
2555
2556         CHECK_WINUSBX_AVAILABLE(sub_api);
2557
2558         // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2559         // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2560         if ((is_using_usbccgp) || (iface == 0)) {
2561                 // composite device (independent interfaces) or interface 0
2562                 file_handle = handle_priv->interface_handle[iface].dev_handle;
2563                 if (!HANDLE_VALID(file_handle))
2564                         return LIBUSB_ERROR_NOT_FOUND;
2565
2566                 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2567                         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2568                         err = GetLastError();
2569                         switch(err) {
2570                         case ERROR_BAD_COMMAND:
2571                                 // The device was disconnected
2572                                 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2573                                 return LIBUSB_ERROR_NO_DEVICE;
2574                         default:
2575                                 // it may be that we're using the libusb0 filter driver.
2576                                 // TODO: can we move this whole business into the K/0 DLL?
2577                                 for (i = 0; ; i++) {
2578                                         safe_free(dev_interface_details);
2579                                         safe_free(dev_path_no_guid);
2580
2581                                         dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
2582                                         if ((found_filter) || (dev_interface_details == NULL))
2583                                                 break;
2584
2585                                         // ignore GUID part
2586                                         dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
2587                                         if (dev_path_no_guid == NULL)
2588                                                 continue;
2589
2590                                         if (strncmp(dev_path_no_guid, priv->usb_interface[iface].path, strlen(dev_path_no_guid)) == 0) {
2591                                                 file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2592                                                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2593                                                 if (file_handle != INVALID_HANDLE_VALUE) {
2594                                                         if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2595                                                                 // Replace the existing file handle with the working one
2596                                                                 CloseHandle(handle_priv->interface_handle[iface].dev_handle);
2597                                                                 handle_priv->interface_handle[iface].dev_handle = file_handle;
2598                                                                 found_filter = true;
2599                                                         } else {
2600                                                                 usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
2601                                                                 CloseHandle(file_handle);
2602                                                         }
2603                                                 } else {
2604                                                         usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2605                                                 }
2606                                         }
2607                                 }
2608                                 free(dev_interface_details);
2609                                 if (!found_filter) {
2610                                         usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
2611                                         return LIBUSB_ERROR_ACCESS;
2612                                 }
2613                         }
2614                 }
2615                 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2616         } else {
2617                 // For all other interfaces, use GetAssociatedInterface()
2618                 winusb_handle = handle_priv->interface_handle[0].api_handle;
2619                 // It is a requirement for multiple interface devices on Windows that, to you
2620                 // must first claim the first interface before you claim the others
2621                 if (!HANDLE_VALID(winusb_handle)) {
2622                         file_handle = handle_priv->interface_handle[0].dev_handle;
2623                         if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2624                                 handle_priv->interface_handle[0].api_handle = winusb_handle;
2625                                 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2626                         } else {
2627                                 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
2628                                 return LIBUSB_ERROR_ACCESS;
2629                         }
2630                 }
2631                 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface - 1),
2632                         &handle_priv->interface_handle[iface].api_handle)) {
2633                         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2634                         switch(GetLastError()) {
2635                         case ERROR_NO_MORE_ITEMS:   // invalid iface
2636                                 return LIBUSB_ERROR_NOT_FOUND;
2637                         case ERROR_BAD_COMMAND:     // The device was disconnected
2638                                 return LIBUSB_ERROR_NO_DEVICE;
2639                         case ERROR_ALREADY_EXISTS:  // already claimed
2640                                 return LIBUSB_ERROR_BUSY;
2641                         default:
2642                                 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2643                                 return LIBUSB_ERROR_ACCESS;
2644                         }
2645                 }
2646         }
2647         usbi_dbg("claimed interface %d", iface);
2648         handle_priv->active_interface = iface;
2649
2650         return LIBUSB_SUCCESS;
2651 }
2652
2653 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2654 {
2655         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2656         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2657         HANDLE winusb_handle;
2658
2659         CHECK_WINUSBX_AVAILABLE(sub_api);
2660
2661         winusb_handle = handle_priv->interface_handle[iface].api_handle;
2662         if (!HANDLE_VALID(winusb_handle))
2663                 return LIBUSB_ERROR_NOT_FOUND;
2664
2665         WinUSBX[sub_api].Free(winusb_handle);
2666         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2667
2668         return LIBUSB_SUCCESS;
2669 }
2670
2671 /*
2672  * Return the first valid interface (of the same API type), for control transfers
2673  */
2674 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2675 {
2676         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2677         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2678         int i;
2679
2680         if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2681                 usbi_dbg("unsupported API ID");
2682                 return -1;
2683         }
2684
2685         for (i = 0; i < USB_MAXINTERFACES; i++) {
2686                 if (HANDLE_VALID(handle_priv->interface_handle[i].dev_handle)
2687                                 && HANDLE_VALID(handle_priv->interface_handle[i].api_handle)
2688                                 && (priv->usb_interface[i].apib->id == api_id))
2689                         return i;
2690         }
2691
2692         return -1;
2693 }
2694
2695 /*
2696  * Lookup interface by endpoint address. -1 if not found
2697  */
2698 static int interface_by_endpoint(struct windows_device_priv *priv,
2699         struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2700 {
2701         int i, j;
2702
2703         for (i = 0; i < USB_MAXINTERFACES; i++) {
2704                 if (!HANDLE_VALID(handle_priv->interface_handle[i].api_handle))
2705                         continue;
2706                 if (priv->usb_interface[i].endpoint == NULL)
2707                         continue;
2708                 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2709                         if (priv->usb_interface[i].endpoint[j] == endpoint_address)
2710                                 return i;
2711                 }
2712         }
2713
2714         return -1;
2715 }
2716
2717 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2718 {
2719         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2720         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2721         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2722         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2723         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2724         WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
2725         ULONG size;
2726         HANDLE winusb_handle;
2727         int current_interface;
2728         struct winfd wfd;
2729
2730         CHECK_WINUSBX_AVAILABLE(sub_api);
2731
2732         transfer_priv->pollable_fd = INVALID_WINFD;
2733         size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2734
2735         // Windows places upper limits on the control transfer size
2736         // See: https://msdn.microsoft.com/en-us/library/windows/hardware/ff538112.aspx
2737         if (size > MAX_CTRL_BUFFER_LENGTH)
2738                 return LIBUSB_ERROR_INVALID_PARAM;
2739
2740         current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
2741         if (current_interface < 0) {
2742                 if (auto_claim(transfer, &current_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS)
2743                         return LIBUSB_ERROR_NOT_FOUND;
2744         }
2745
2746         usbi_dbg("will use interface %d", current_interface);
2747         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2748
2749         wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
2750         // Always use the handle returned from usbi_create_fd (wfd.handle)
2751         if (wfd.fd < 0)
2752                 return LIBUSB_ERROR_NO_MEM;
2753
2754         // Sending of set configuration control requests from WinUSB creates issues
2755         if ((LIBUSB_REQ_TYPE(setup->RequestType) == LIBUSB_REQUEST_TYPE_STANDARD)
2756                         && (setup->Request == LIBUSB_REQUEST_SET_CONFIGURATION)) {
2757                 if (setup->Value != priv->active_config) {
2758                         usbi_warn(ctx, "cannot set configuration other than the default one");
2759                         usbi_free_fd(&wfd);
2760                         return LIBUSB_ERROR_INVALID_PARAM;
2761                 }
2762                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2763                 wfd.overlapped->InternalHigh = 0;
2764         } else {
2765                 if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2766                         if (GetLastError() != ERROR_IO_PENDING) {
2767                                 usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
2768                                 usbi_free_fd(&wfd);
2769                                 return LIBUSB_ERROR_IO;
2770                         }
2771                 } else {
2772                         wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2773                         wfd.overlapped->InternalHigh = (DWORD)size;
2774                 }
2775         }
2776
2777         // Use priv_transfer to store data needed for async polling
2778         transfer_priv->pollable_fd = wfd;
2779         transfer_priv->interface_number = (uint8_t)current_interface;
2780
2781         return LIBUSB_SUCCESS;
2782 }
2783
2784 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2785 {
2786         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2787         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2788         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2789         HANDLE winusb_handle;
2790
2791         CHECK_WINUSBX_AVAILABLE(sub_api);
2792
2793         if (altsetting > 255)
2794                 return LIBUSB_ERROR_INVALID_PARAM;
2795
2796         winusb_handle = handle_priv->interface_handle[iface].api_handle;
2797         if (!HANDLE_VALID(winusb_handle)) {
2798                 usbi_err(ctx, "interface must be claimed first");
2799                 return LIBUSB_ERROR_NOT_FOUND;
2800         }
2801
2802         if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2803                 usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2804                 return LIBUSB_ERROR_IO;
2805         }
2806
2807         return LIBUSB_SUCCESS;
2808 }
2809
2810 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2811 {
2812         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2813         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2814         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2815         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2816         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2817         HANDLE winusb_handle;
2818         bool ret;
2819         int current_interface;
2820         struct winfd wfd;
2821
2822         CHECK_WINUSBX_AVAILABLE(sub_api);
2823
2824         transfer_priv->pollable_fd = INVALID_WINFD;
2825
2826         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2827         if (current_interface < 0) {
2828                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2829                 return LIBUSB_ERROR_NOT_FOUND;
2830         }
2831
2832         usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2833
2834         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2835
2836         wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
2837         // Always use the handle returned from usbi_create_fd (wfd.handle)
2838         if (wfd.fd < 0)
2839                 return LIBUSB_ERROR_NO_MEM;
2840
2841         if (IS_XFERIN(transfer)) {
2842                 usbi_dbg("reading %d bytes", transfer->length);
2843                 ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2844         } else {
2845                 usbi_dbg("writing %d bytes", transfer->length);
2846                 ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2847         }
2848
2849         if (!ret) {
2850                 if (GetLastError() != ERROR_IO_PENDING) {
2851                         usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
2852                         usbi_free_fd(&wfd);
2853                         return LIBUSB_ERROR_IO;
2854                 }
2855         } else {
2856                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2857                 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2858         }
2859
2860         transfer_priv->pollable_fd = wfd;
2861         transfer_priv->interface_number = (uint8_t)current_interface;
2862
2863         return LIBUSB_SUCCESS;
2864 }
2865
2866 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2867 {
2868         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2869         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2870         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2871         HANDLE winusb_handle;
2872         int current_interface;
2873
2874         CHECK_WINUSBX_AVAILABLE(sub_api);
2875
2876         current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2877         if (current_interface < 0) {
2878                 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2879                 return LIBUSB_ERROR_NOT_FOUND;
2880         }
2881
2882         usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2883         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2884
2885         if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
2886                 usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
2887                 return LIBUSB_ERROR_NO_DEVICE;
2888         }
2889
2890         return LIBUSB_SUCCESS;
2891 }
2892
2893 /*
2894  * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2895  * through testing as well):
2896  * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2897  * the control transfer using CancelIo"
2898  */
2899 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
2900 {
2901         // Cancelling of the I/O is done in the parent
2902         return LIBUSB_SUCCESS;
2903 }
2904
2905 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2906 {
2907         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2908         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2909         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2910         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2911         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2912         HANDLE winusb_handle;
2913         int current_interface;
2914
2915         CHECK_WINUSBX_AVAILABLE(sub_api);
2916
2917         current_interface = transfer_priv->interface_number;
2918         if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2919                 usbi_err(ctx, "program assertion failed: invalid interface_number");
2920                 return LIBUSB_ERROR_NOT_FOUND;
2921         }
2922         usbi_dbg("will use interface %d", current_interface);
2923
2924         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2925
2926         if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
2927                 usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
2928                 return LIBUSB_ERROR_NO_DEVICE;
2929         }
2930
2931         return LIBUSB_SUCCESS;
2932 }
2933
2934 /*
2935  * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2936  * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2937  * "WinUSB does not support host-initiated reset port and cycle port operations" and
2938  * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2939  * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2940  * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2941  */
2942 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2943 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2944 {
2945         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2946         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2947         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2948         struct winfd wfd;
2949         HANDLE winusb_handle;
2950         int i, j;
2951
2952         CHECK_WINUSBX_AVAILABLE(sub_api);
2953
2954         // Reset any available pipe (except control)
2955         for (i = 0; i < USB_MAXINTERFACES; i++) {
2956                 winusb_handle = handle_priv->interface_handle[i].api_handle;
2957                 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0; ) {
2958                         // Cancel any pollable I/O
2959                         usbi_remove_pollfd(ctx, wfd.fd);
2960                         usbi_free_fd(&wfd);
2961                         wfd = handle_to_winfd(winusb_handle);
2962                 }
2963
2964                 if (HANDLE_VALID(winusb_handle)) {
2965                         for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2966                                 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2967                                 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2968                                         usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
2969                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2970
2971                                 // FlushPipe seems to fail on OUT pipes
2972                                 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
2973                                                 && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])))
2974                                         usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
2975                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2976
2977                                 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2978                                         usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
2979                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2980                         }
2981                 }
2982         }
2983
2984         // libusbK & libusb0 have the ability to issue an actual device reset
2985         if (WinUSBX[sub_api].ResetDevice != NULL) {
2986                 winusb_handle = handle_priv->interface_handle[0].api_handle;
2987                 if (HANDLE_VALID(winusb_handle))
2988                         WinUSBX[sub_api].ResetDevice(winusb_handle);
2989         }
2990
2991         return LIBUSB_SUCCESS;
2992 }
2993
2994 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2995 {
2996         itransfer->transferred += io_size;
2997         return LIBUSB_TRANSFER_COMPLETED;
2998 }
2999
3000 /*
3001  * Internal HID Support functions (from libusb-win32)
3002  * Note that functions that complete data transfer synchronously must return
3003  * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
3004  */
3005 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3006 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3007
3008 static int _hid_wcslen(WCHAR *str)
3009 {
3010         int i = 0;
3011
3012         while (str[i] && (str[i] != 0x409))
3013                 i++;
3014
3015         return i;
3016 }
3017
3018 static int _hid_get_device_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3019 {
3020         struct libusb_device_descriptor d;
3021
3022         d.bLength = LIBUSB_DT_DEVICE_SIZE;
3023         d.bDescriptorType = LIBUSB_DT_DEVICE;
3024         d.bcdUSB = 0x0200; /* 2.00 */
3025         d.bDeviceClass = 0;
3026         d.bDeviceSubClass = 0;
3027         d.bDeviceProtocol = 0;
3028         d.bMaxPacketSize0 = 64; /* fix this! */
3029         d.idVendor = (uint16_t)dev->vid;
3030         d.idProduct = (uint16_t)dev->pid;
3031         d.bcdDevice = 0x0100;
3032         d.iManufacturer = dev->string_index[0];
3033         d.iProduct = dev->string_index[1];
3034         d.iSerialNumber = dev->string_index[2];
3035         d.bNumConfigurations = 1;
3036
3037         if (*size > LIBUSB_DT_DEVICE_SIZE)
3038                 *size = LIBUSB_DT_DEVICE_SIZE;
3039         memcpy(data, &d, *size);
3040
3041         return LIBUSB_COMPLETED;
3042 }
3043
3044 static int _hid_get_config_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3045 {
3046         char num_endpoints = 0;
3047         size_t config_total_len = 0;
3048         char tmp[HID_MAX_CONFIG_DESC_SIZE];
3049         struct libusb_config_descriptor *cd;
3050         struct libusb_interface_descriptor *id;
3051         struct libusb_hid_descriptor *hd;
3052         struct libusb_endpoint_descriptor *ed;
3053         size_t tmp_size;
3054
3055         if (dev->input_report_size)
3056                 num_endpoints++;
3057         if (dev->output_report_size)
3058                 num_endpoints++;
3059
3060         config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3061                 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3062
3063         cd = (struct libusb_config_descriptor *)tmp;
3064         id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3065         hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3066                 + LIBUSB_DT_INTERFACE_SIZE);
3067         ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3068                 + LIBUSB_DT_INTERFACE_SIZE
3069                 + LIBUSB_DT_HID_SIZE);
3070
3071         cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3072         cd->bDescriptorType = LIBUSB_DT_CONFIG;
3073         cd->wTotalLength = (uint16_t)config_total_len;
3074         cd->bNumInterfaces = 1;
3075         cd->bConfigurationValue = 1;
3076         cd->iConfiguration = 0;
3077         cd->bmAttributes = 1 << 7; /* bus powered */
3078         cd->MaxPower = 50;
3079
3080         id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3081         id->bDescriptorType = LIBUSB_DT_INTERFACE;
3082         id->bInterfaceNumber = 0;
3083         id->bAlternateSetting = 0;
3084         id->bNumEndpoints = num_endpoints;
3085         id->bInterfaceClass = 3;
3086         id->bInterfaceSubClass = 0;
3087         id->bInterfaceProtocol = 0;
3088         id->iInterface = 0;
3089
3090         tmp_size = LIBUSB_DT_HID_SIZE;
3091         _hid_get_hid_descriptor(dev, hd, &tmp_size);
3092
3093         if (dev->input_report_size) {
3094                 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3095                 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3096                 ed->bEndpointAddress = HID_IN_EP;
3097                 ed->bmAttributes = 3;
3098                 ed->wMaxPacketSize = dev->input_report_size - 1;
3099                 ed->bInterval = 10;
3100                 ed = (struct libusb_endpoint_descriptor *)((char *)ed + LIBUSB_DT_ENDPOINT_SIZE);
3101         }
3102
3103         if (dev->output_report_size) {
3104                 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3105                 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3106                 ed->bEndpointAddress = HID_OUT_EP;
3107                 ed->bmAttributes = 3;
3108                 ed->wMaxPacketSize = dev->output_report_size - 1;
3109                 ed->bInterval = 10;
3110         }
3111
3112         if (*size > config_total_len)
3113                 *size = config_total_len;
3114         memcpy(data, tmp, *size);
3115
3116         return LIBUSB_COMPLETED;
3117 }
3118
3119 static int _hid_get_string_descriptor(struct hid_device_priv *dev, int _index,
3120         void *data, size_t *size)
3121 {
3122         void *tmp = NULL;
3123         size_t tmp_size = 0;
3124         int i;
3125
3126         /* language ID, EN-US */
3127         char string_langid[] = {0x09, 0x04};
3128
3129         if ((*size < 2) || (*size > 255))
3130                 return LIBUSB_ERROR_OVERFLOW;
3131
3132         if (_index == 0) {
3133                 tmp = string_langid;
3134                 tmp_size = sizeof(string_langid) + 2;
3135         } else {
3136                 for (i = 0; i < 3; i++) {
3137                         if (_index == (dev->string_index[i])) {
3138                                 tmp = dev->string[i];
3139                                 tmp_size = (_hid_wcslen(dev->string[i]) + 1) * sizeof(WCHAR);
3140                                 break;
3141                         }
3142                 }
3143
3144                 if (i == 3) // not found
3145                         return LIBUSB_ERROR_INVALID_PARAM;
3146         }
3147
3148         if (!tmp_size)
3149                 return LIBUSB_ERROR_INVALID_PARAM;
3150
3151         if (tmp_size < *size)
3152                 *size = tmp_size;
3153
3154         // 2 byte header
3155         ((uint8_t *)data)[0] = (uint8_t)*size;
3156         ((uint8_t *)data)[1] = LIBUSB_DT_STRING;
3157         memcpy((uint8_t *)data + 2, tmp, *size - 2);
3158
3159         return LIBUSB_COMPLETED;
3160 }
3161
3162 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3163 {
3164         struct libusb_hid_descriptor d;
3165         uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3166         size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3167
3168         _hid_get_report_descriptor(dev, tmp, &report_len);
3169
3170         d.bLength = LIBUSB_DT_HID_SIZE;
3171         d.bDescriptorType = LIBUSB_DT_HID;
3172         d.bcdHID = 0x0110; /* 1.10 */
3173         d.bCountryCode = 0;
3174         d.bNumDescriptors = 1;
3175         d.bClassDescriptorType = LIBUSB_DT_REPORT;
3176         d.wClassDescriptorLength = (uint16_t)report_len;
3177
3178         if (*size > LIBUSB_DT_HID_SIZE)
3179                 *size = LIBUSB_DT_HID_SIZE;
3180         memcpy(data, &d, *size);
3181
3182         return LIBUSB_COMPLETED;
3183 }
3184
3185 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3186 {
3187         uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3188         size_t i = 0;
3189
3190         /* usage page (0xFFA0 == vendor defined) */
3191         d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3192         /* usage (vendor defined) */
3193         d[i++] = 0x09; d[i++] = 0x01;
3194         /* start collection (application) */
3195         d[i++] = 0xA1; d[i++] = 0x01;
3196         /* input report */
3197         if (dev->input_report_size) {
3198                 /* usage (vendor defined) */
3199                 d[i++] = 0x09; d[i++] = 0x01;
3200                 /* logical minimum (0) */
3201                 d[i++] = 0x15; d[i++] = 0x00;
3202                 /* logical maximum (255) */
3203                 d[i++] = 0x25; d[i++] = 0xFF;
3204                 /* report size (8 bits) */
3205                 d[i++] = 0x75; d[i++] = 0x08;
3206                 /* report count */
3207                 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3208                 /* input (data, variable, absolute) */
3209                 d[i++] = 0x81; d[i++] = 0x00;
3210         }
3211         /* output report */
3212         if (dev->output_report_size) {
3213                 /* usage (vendor defined) */
3214                 d[i++] = 0x09; d[i++] = 0x02;
3215                 /* logical minimum (0) */
3216                 d[i++] = 0x15; d[i++] = 0x00;
3217                 /* logical maximum (255) */
3218                 d[i++] = 0x25; d[i++] = 0xFF;
3219                 /* report size (8 bits) */
3220                 d[i++] = 0x75; d[i++] = 0x08;
3221                 /* report count */
3222                 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3223                 /* output (data, variable, absolute) */
3224                 d[i++] = 0x91; d[i++] = 0x00;
3225         }
3226         /* feature report */
3227         if (dev->feature_report_size) {
3228                 /* usage (vendor defined) */
3229                 d[i++] = 0x09; d[i++] = 0x03;
3230                 /* logical minimum (0) */
3231                 d[i++] = 0x15; d[i++] = 0x00;
3232                 /* logical maximum (255) */
3233                 d[i++] = 0x25; d[i++] = 0xFF;
3234                 /* report size (8 bits) */
3235                 d[i++] = 0x75; d[i++] = 0x08;
3236                 /* report count */
3237                 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3238                 /* feature (data, variable, absolute) */
3239                 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3240         }
3241
3242         /* end collection */
3243         d[i++] = 0xC0;
3244
3245         if (*size > i)
3246                 *size = i;
3247         memcpy(data, d, *size);
3248
3249         return LIBUSB_COMPLETED;
3250 }
3251
3252 static int _hid_get_descriptor(struct hid_device_priv *dev, HANDLE hid_handle, int recipient,
3253         int type, int _index, void *data, size_t *size)
3254 {
3255         switch(type) {
3256         case LIBUSB_DT_DEVICE:
3257                 usbi_dbg("LIBUSB_DT_DEVICE");
3258                 return _hid_get_device_descriptor(dev, data, size);
3259         case LIBUSB_DT_CONFIG:
3260                 usbi_dbg("LIBUSB_DT_CONFIG");
3261                 if (!_index)
3262                         return _hid_get_config_descriptor(dev, data, size);
3263                 return LIBUSB_ERROR_INVALID_PARAM;
3264         case LIBUSB_DT_STRING:
3265                 usbi_dbg("LIBUSB_DT_STRING");
3266                 return _hid_get_string_descriptor(dev, _index, data, size);
3267         case LIBUSB_DT_HID:
3268                 usbi_dbg("LIBUSB_DT_HID");
3269                 if (!_index)
3270                         return _hid_get_hid_descriptor(dev, data, size);
3271                 return LIBUSB_ERROR_INVALID_PARAM;
3272         case LIBUSB_DT_REPORT:
3273                 usbi_dbg("LIBUSB_DT_REPORT");
3274                 if (!_index)
3275                         return _hid_get_report_descriptor(dev, data, size);
3276                 return LIBUSB_ERROR_INVALID_PARAM;
3277         case LIBUSB_DT_PHYSICAL:
3278                 usbi_dbg("LIBUSB_DT_PHYSICAL");
3279                 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3280                         return LIBUSB_COMPLETED;
3281                 return LIBUSB_ERROR_OTHER;
3282         }
3283
3284         usbi_dbg("unsupported");
3285         return LIBUSB_ERROR_NOT_SUPPORTED;
3286 }
3287
3288 static int _hid_get_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3289         struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3290 {
3291         uint8_t *buf;
3292         DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3293         int r = LIBUSB_SUCCESS;
3294
3295         if (tp->hid_buffer != NULL)
3296                 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3297
3298         if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3299                 usbi_dbg("invalid size (%u)", *size);
3300                 return LIBUSB_ERROR_INVALID_PARAM;
3301         }
3302
3303         switch (report_type) {
3304         case HID_REPORT_TYPE_INPUT:
3305                 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3306                 break;
3307         case HID_REPORT_TYPE_FEATURE:
3308                 ioctl_code = IOCTL_HID_GET_FEATURE;
3309                 break;
3310         default:
3311                 usbi_dbg("unknown HID report type %d", report_type);
3312                 return LIBUSB_ERROR_INVALID_PARAM;
3313         }
3314
3315         // Add a trailing byte to detect overflows
3316         buf = calloc(1, expected_size + 1);
3317         if (buf == NULL)
3318                 return LIBUSB_ERROR_NO_MEM;
3319
3320         buf[0] = (uint8_t)id; // Must be set always
3321         usbi_dbg("report ID: 0x%02X", buf[0]);
3322
3323         tp->hid_expected_size = expected_size;
3324         read_size = expected_size;
3325
3326         // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3327         if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size + 1,
3328                 buf, expected_size + 1, &read_size, overlapped)) {
3329                 if (GetLastError() != ERROR_IO_PENDING) {
3330                         usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3331                         free(buf);
3332                         return LIBUSB_ERROR_IO;
3333                 }
3334                 // Asynchronous wait
3335                 tp->hid_buffer = buf;
3336                 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3337                 return LIBUSB_SUCCESS;
3338         }
3339
3340         // Transfer completed synchronously => copy and discard extra buffer
3341         if (read_size == 0) {
3342                 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3343                 *size = 0;
3344         } else {
3345                 if (buf[0] != id)
3346                         usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3347
3348                 if ((size_t)read_size > expected_size) {
3349                         r = LIBUSB_ERROR_OVERFLOW;
3350                         usbi_dbg("OVERFLOW!");
3351                 } else {
3352                         r = LIBUSB_COMPLETED;
3353                 }
3354
3355                 *size = MIN((size_t)read_size, *size);
3356                 if (id == 0)
3357                         memcpy(data, buf + 1, *size); // Discard report ID
3358                 else
3359                         memcpy(data, buf, *size);
3360         }
3361
3362         free(buf);
3363         return r;
3364 }
3365
3366 static int _hid_set_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3367         struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3368 {
3369         uint8_t *buf = NULL;
3370         DWORD ioctl_code, write_size = (DWORD)*size;
3371         // If an id is reported, we must allow MAX_HID_REPORT_SIZE + 1
3372         size_t max_report_size = MAX_HID_REPORT_SIZE + (id ? 1 : 0);
3373
3374         if (tp->hid_buffer != NULL)
3375                 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3376
3377         if ((*size == 0) || (*size > max_report_size)) {
3378                 usbi_dbg("invalid size (%u)", *size);
3379                 return LIBUSB_ERROR_INVALID_PARAM;
3380         }
3381
3382         switch (report_type) {
3383         case HID_REPORT_TYPE_OUTPUT:
3384                 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3385                 break;
3386         case HID_REPORT_TYPE_FEATURE:
3387                 ioctl_code = IOCTL_HID_SET_FEATURE;
3388                 break;
3389         default:
3390                 usbi_dbg("unknown HID report type %d", report_type);
3391                 return LIBUSB_ERROR_INVALID_PARAM;
3392         }
3393
3394         usbi_dbg("report ID: 0x%02X", id);
3395         // When report IDs are not used (i.e. when id == 0), we must add
3396         // a null report ID. Otherwise, we just use original data buffer
3397         if (id == 0)
3398                 write_size++;
3399
3400         buf = malloc(write_size);
3401         if (buf == NULL)
3402                 return LIBUSB_ERROR_NO_MEM;
3403
3404         if (id == 0) {
3405                 buf[0] = 0;
3406                 memcpy(buf + 1, data, *size);
3407         } else {
3408                 // This seems like a waste, but if we don't duplicate the
3409                 // data, we'll get issues when freeing hid_buffer
3410                 memcpy(buf, data, *size);
3411                 if (buf[0] != id)
3412                         usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3413         }
3414
3415         // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3416         if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3417                 buf, write_size, &write_size, overlapped)) {
3418                 if (GetLastError() != ERROR_IO_PENDING) {
3419                         usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3420                         free(buf);
3421                         return LIBUSB_ERROR_IO;
3422                 }
3423                 tp->hid_buffer = buf;
3424                 tp->hid_dest = NULL;
3425                 return LIBUSB_SUCCESS;
3426         }
3427
3428         // Transfer completed synchronously
3429         *size = write_size;
3430         if (write_size == 0)
3431                 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3432
3433         free(buf);
3434         return LIBUSB_COMPLETED;
3435 }
3436
3437 static int _hid_class_request(struct hid_device_priv *dev, HANDLE hid_handle, int request_type,
3438         int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3439         size_t *size, OVERLAPPED *overlapped)
3440 {
3441         int report_type = (value >> 8) & 0xFF;
3442         int report_id = value & 0xFF;
3443
3444         if ((LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3445                         && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE))
3446                 return LIBUSB_ERROR_INVALID_PARAM;
3447
3448         if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3449                 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3450
3451         if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3452                 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3453
3454         return LIBUSB_ERROR_INVALID_PARAM;
3455 }
3456
3457
3458 /*
3459  * HID API functions
3460  */
3461 static int hid_init(int sub_api, struct libusb_context *ctx)
3462 {
3463         DLL_GET_HANDLE(hid);
3464         DLL_LOAD_FUNC(hid, HidD_GetAttributes, TRUE);
3465         DLL_LOAD_FUNC(hid, HidD_GetHidGuid, TRUE);
3466         DLL_LOAD_FUNC(hid, HidD_GetPreparsedData, TRUE);
3467         DLL_LOAD_FUNC(hid, HidD_FreePreparsedData, TRUE);
3468         DLL_LOAD_FUNC(hid, HidD_GetManufacturerString, TRUE);
3469         DLL_LOAD_FUNC(hid, HidD_GetProductString, TRUE);
3470         DLL_LOAD_FUNC(hid, HidD_GetSerialNumberString, TRUE);
3471         DLL_LOAD_FUNC(hid, HidP_GetCaps, TRUE);
3472         DLL_LOAD_FUNC(hid, HidD_SetNumInputBuffers, TRUE);
3473         DLL_LOAD_FUNC(hid, HidD_SetFeature, TRUE);
3474         DLL_LOAD_FUNC(hid, HidD_GetFeature, TRUE);
3475         DLL_LOAD_FUNC(hid, HidD_GetPhysicalDescriptor, TRUE);
3476         DLL_LOAD_FUNC(hid, HidD_GetInputReport, FALSE);
3477         DLL_LOAD_FUNC(hid, HidD_SetOutputReport, FALSE);
3478         DLL_LOAD_FUNC(hid, HidD_FlushQueue, TRUE);
3479         DLL_LOAD_FUNC(hid, HidP_GetValueCaps, TRUE);
3480
3481         api_hid_available = true;
3482         return LIBUSB_SUCCESS;
3483 }
3484
3485 static int hid_exit(int sub_api)
3486 {
3487         DLL_FREE_HANDLE(hid);
3488
3489         return LIBUSB_SUCCESS;
3490 }
3491
3492 // NB: open and close must ensure that they only handle interface of
3493 // the right API type, as these functions can be called wholesale from
3494 // composite_open(), with interfaces belonging to different APIs
3495 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3496 {
3497         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3498         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3499         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3500         HIDD_ATTRIBUTES hid_attributes;
3501         PHIDP_PREPARSED_DATA preparsed_data = NULL;
3502         HIDP_CAPS capabilities;
3503         HIDP_VALUE_CAPS *value_caps;
3504         HANDLE hid_handle = INVALID_HANDLE_VALUE;
3505         int i, j;
3506         // report IDs handling
3507         ULONG size[3];
3508         int nb_ids[2]; // zero and nonzero report IDs
3509 #if defined(ENABLE_LOGGING)
3510         const char *type[3] = {"input", "output", "feature"};
3511 #endif
3512
3513         CHECK_HID_AVAILABLE;
3514
3515         if (priv->hid == NULL) {
3516                 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3517                 return LIBUSB_ERROR_NOT_FOUND;
3518         }
3519
3520         for (i = 0; i < USB_MAXINTERFACES; i++) {
3521                 if ((priv->usb_interface[i].path != NULL)
3522                                 && (priv->usb_interface[i].apib->id == USB_API_HID)) {
3523                         hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3524                                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3525                         /*
3526                          * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3527                          * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3528                          * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3529                          * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3530                          * HidD_GetFeature (if the device supports Feature reports)."
3531                          */
3532                         if (hid_handle == INVALID_HANDLE_VALUE) {
3533                                 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3534                                 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3535                                         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3536                                 if (hid_handle == INVALID_HANDLE_VALUE) {
3537                                         usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3538                                         switch(GetLastError()) {
3539                                         case ERROR_FILE_NOT_FOUND: // The device was disconnected
3540                                                 return LIBUSB_ERROR_NO_DEVICE;
3541                                         case ERROR_ACCESS_DENIED:
3542                                                 return LIBUSB_ERROR_ACCESS;
3543                                         default:
3544                                                 return LIBUSB_ERROR_IO;
3545                                         }
3546                                 }
3547                                 priv->usb_interface[i].restricted_functionality = true;
3548                         }
3549                         handle_priv->interface_handle[i].api_handle = hid_handle;
3550                 }
3551         }
3552
3553         hid_attributes.Size = sizeof(hid_attributes);
3554         do {
3555                 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3556                         usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3557                         break;
3558                 }
3559
3560                 priv->hid->vid = hid_attributes.VendorID;
3561                 priv->hid->pid = hid_attributes.ProductID;
3562
3563                 // Set the maximum available input buffer size
3564                 for (i = 32; HidD_SetNumInputBuffers(hid_handle, i); i *= 2);
3565                 usbi_dbg("set maximum input buffer size to %d", i / 2);
3566
3567                 // Get the maximum input and output report size
3568                 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3569                         usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3570                         break;
3571                 }
3572                 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3573                         usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3574                         break;
3575                 }
3576
3577                 // Find out if interrupt will need report IDs
3578                 size[0] = capabilities.NumberInputValueCaps;
3579                 size[1] = capabilities.NumberOutputValueCaps;
3580                 size[2] = capabilities.NumberFeatureValueCaps;
3581                 for (j = HidP_Input; j <= HidP_Feature; j++) {
3582                         usbi_dbg("%u HID %s report value(s) found", (unsigned int)size[j], type[j]);
3583                         priv->hid->uses_report_ids[j] = false;
3584                         if (size[j] > 0) {
3585                                 value_caps = calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3586                                 if ((value_caps != NULL)
3587                                                 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3588                                                 && (size[j] >= 1)) {
3589                                         nb_ids[0] = 0;
3590                                         nb_ids[1] = 0;
3591                                         for (i = 0; i < (int)size[j]; i++) {
3592                                                 usbi_dbg("  Report ID: 0x%02X", value_caps[i].ReportID);
3593                                                 if (value_caps[i].ReportID != 0)
3594                                                         nb_ids[1]++;
3595                                                 else
3596                                                         nb_ids[0]++;
3597                                         }
3598                                         if (nb_ids[1] != 0) {
3599                                                 if (nb_ids[0] != 0)
3600                                                         usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3601                                                                 type[j]);
3602                                                 priv->hid->uses_report_ids[j] = true;
3603                                         }
3604                                 } else {
3605                                         usbi_warn(ctx, "  could not process %s report IDs", type[j]);
3606                                 }
3607                                 free(value_caps);
3608                         }
3609                 }
3610
3611                 // Set the report sizes
3612                 priv->hid->input_report_size = capabilities.InputReportByteLength;
3613                 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3614                 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3615
3616                 // Fetch string descriptors
3617                 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3618                 if (priv->hid->string_index[0] != 0)
3619                         HidD_GetManufacturerString(hid_handle, priv->hid->string[0], sizeof(priv->hid->string[0]));
3620                 else
3621                         priv->hid->string[0][0] = 0;
3622
3623                 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3624                 if (priv->hid->string_index[1] != 0)
3625                         HidD_GetProductString(hid_handle, priv->hid->string[1], sizeof(priv->hid->string[1]));
3626                 else
3627                         priv->hid->string[1][0] = 0;
3628
3629                 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3630                 if (priv->hid->string_index[2] != 0)
3631                         HidD_GetSerialNumberString(hid_handle, priv->hid->string[2], sizeof(priv->hid->string[2]));
3632                 else
3633                         priv->hid->string[2][0] = 0;
3634         } while(0);
3635
3636         if (preparsed_data)
3637                 HidD_FreePreparsedData(preparsed_data);
3638
3639         return LIBUSB_SUCCESS;
3640 }
3641
3642 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3643 {
3644         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3645         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3646         HANDLE file_handle;
3647         int i;
3648
3649         if (!api_hid_available)
3650                 return;
3651
3652         for (i = 0; i < USB_MAXINTERFACES; i++) {
3653                 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3654                         file_handle = handle_priv->interface_handle[i].api_handle;
3655                         if (HANDLE_VALID(file_handle))
3656                                 CloseHandle(file_handle);
3657                 }
3658         }
3659 }
3660
3661 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3662 {
3663         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3664         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3665
3666         CHECK_HID_AVAILABLE;
3667
3668         // NB: Disconnection detection is not possible in this function
3669         if (priv->usb_interface[iface].path == NULL)
3670                 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3671
3672         // We use dev_handle as a flag for interface claimed
3673         if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED)
3674                 return LIBUSB_ERROR_BUSY; // already claimed
3675
3676
3677         handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3678
3679         usbi_dbg("claimed interface %d", iface);
3680         handle_priv->active_interface = iface;
3681
3682         return LIBUSB_SUCCESS;
3683 }
3684
3685 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3686 {
3687         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3688         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3689
3690         CHECK_HID_AVAILABLE;
3691
3692         if (priv->usb_interface[iface].path == NULL)
3693                 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3694
3695         if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED)
3696                 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3697
3698         handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3699
3700         return LIBUSB_SUCCESS;
3701 }
3702
3703 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
3704 {
3705         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3706
3707         CHECK_HID_AVAILABLE;
3708
3709         if (altsetting > 255)
3710                 return LIBUSB_ERROR_INVALID_PARAM;
3711
3712         if (altsetting != 0) {
3713                 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3714                 return LIBUSB_ERROR_NOT_SUPPORTED;
3715         }
3716
3717         return LIBUSB_SUCCESS;
3718 }
3719
3720 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3721 {
3722         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3723         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3724         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3725         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3726         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3727         WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
3728         HANDLE hid_handle;
3729         struct winfd wfd;
3730         int current_interface, config;
3731         size_t size;
3732         int r = LIBUSB_ERROR_INVALID_PARAM;
3733
3734         CHECK_HID_AVAILABLE;
3735
3736         transfer_priv->pollable_fd = INVALID_WINFD;
3737         safe_free(transfer_priv->hid_buffer);
3738         transfer_priv->hid_dest = NULL;
3739         size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3740
3741         if (size > MAX_CTRL_BUFFER_LENGTH)
3742                 return LIBUSB_ERROR_INVALID_PARAM;
3743
3744         current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3745         if (current_interface < 0) {
3746                 if (auto_claim(transfer, &current_interface, USB_API_HID) != LIBUSB_SUCCESS)
3747                         return LIBUSB_ERROR_NOT_FOUND;
3748         }
3749
3750         usbi_dbg("will use interface %d", current_interface);
3751         hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3752         // Always use the handle returned from usbi_create_fd (wfd.handle)
3753         wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
3754         if (wfd.fd < 0)
3755                 return LIBUSB_ERROR_NOT_FOUND;
3756
3757         switch(LIBUSB_REQ_TYPE(setup->RequestType)) {
3758         case LIBUSB_REQUEST_TYPE_STANDARD:
3759                 switch(setup->Request) {
3760                 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3761                         r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->RequestType),
3762                                 (setup->Value >> 8) & 0xFF, setup->Value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3763                         break;
3764                 case LIBUSB_REQUEST_GET_CONFIGURATION:
3765                         r = windows_get_configuration(transfer->dev_handle, &config);
3766                         if (r == LIBUSB_SUCCESS) {
3767                                 size = 1;
3768                                 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3769                                 r = LIBUSB_COMPLETED;
3770                         }
3771                         break;
3772                 case LIBUSB_REQUEST_SET_CONFIGURATION:
3773                         if (setup->Value == priv->active_config) {
3774                                 r = LIBUSB_COMPLETED;
3775                         } else {
3776                                 usbi_warn(ctx, "cannot set configuration other than the default one");
3777                                 r = LIBUSB_ERROR_NOT_SUPPORTED;
3778                         }
3779                         break;
3780                 case LIBUSB_REQUEST_GET_INTERFACE:
3781                         size = 1;
3782                         ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3783                         r = LIBUSB_COMPLETED;
3784                         break;
3785                 case LIBUSB_REQUEST_SET_INTERFACE:
3786                         r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->Index, setup->Value);
3787                         if (r == LIBUSB_SUCCESS)
3788                                 r = LIBUSB_COMPLETED;
3789                         break;
3790                 default:
3791                         usbi_warn(ctx, "unsupported HID control request");
3792                         r = LIBUSB_ERROR_NOT_SUPPORTED;
3793                         break;
3794                 }
3795                 break;
3796         case LIBUSB_REQUEST_TYPE_CLASS:
3797                 r = _hid_class_request(priv->hid, wfd.handle, setup->RequestType, setup->Request, setup->Value,
3798                         setup->Index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3799                         &size, wfd.overlapped);
3800                 break;
3801         default:
3802                 usbi_warn(ctx, "unsupported HID control request");
3803                 r = LIBUSB_ERROR_NOT_SUPPORTED;
3804                 break;
3805         }
3806
3807         if (r == LIBUSB_COMPLETED) {
3808                 // Force request to be completed synchronously. Transferred size has been set by previous call
3809                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3810                 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3811                 // set InternalHigh to the number of bytes transferred
3812                 wfd.overlapped->InternalHigh = (DWORD)size;
3813                 r = LIBUSB_SUCCESS;
3814         }
3815
3816         if (r == LIBUSB_SUCCESS) {
3817                 // Use priv_transfer to store data needed for async polling
3818                 transfer_priv->pollable_fd = wfd;
3819                 transfer_priv->interface_number = (uint8_t)current_interface;
3820         } else {
3821                 usbi_free_fd(&wfd);
3822         }
3823
3824         return r;
3825 }
3826
3827 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
3828 {
3829         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3830         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3831         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3832         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3833         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3834         struct winfd wfd;
3835         HANDLE hid_handle;
3836         bool direction_in, ret;
3837         int current_interface, length;
3838         DWORD size;
3839         int r = LIBUSB_SUCCESS;
3840
3841         CHECK_HID_AVAILABLE;
3842
3843         transfer_priv->pollable_fd = INVALID_WINFD;
3844         transfer_priv->hid_dest = NULL;
3845         safe_free(transfer_priv->hid_buffer);
3846
3847         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3848         if (current_interface < 0) {
3849                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3850                 return LIBUSB_ERROR_NOT_FOUND;
3851         }
3852
3853         usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3854
3855         hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3856         direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3857
3858         wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
3859         // Always use the handle returned from usbi_create_fd (wfd.handle)
3860         if (wfd.fd < 0)
3861                 return LIBUSB_ERROR_NO_MEM;
3862
3863         // If report IDs are not in use, an extra prefix byte must be added
3864         if (((direction_in) && (!priv->hid->uses_report_ids[0]))
3865                         || ((!direction_in) && (!priv->hid->uses_report_ids[1])))
3866                 length = transfer->length + 1;
3867         else
3868                 length = transfer->length;
3869
3870         // Add a trailing byte to detect overflows on input
3871         transfer_priv->hid_buffer = calloc(1, length + 1);
3872         if (transfer_priv->hid_buffer == NULL)
3873                 return LIBUSB_ERROR_NO_MEM;
3874
3875         transfer_priv->hid_expected_size = length;
3876
3877         if (direction_in) {
3878                 transfer_priv->hid_dest = transfer->buffer;
3879                 usbi_dbg("reading %d bytes (report ID: 0x00)", length);
3880                 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length + 1, &size, wfd.overlapped);
3881         } else {
3882                 if (!priv->hid->uses_report_ids[1])
3883                         memcpy(transfer_priv->hid_buffer + 1, transfer->buffer, transfer->length);
3884                 else
3885                         // We could actually do without the calloc and memcpy in this case
3886                         memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3887
3888                 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3889                 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3890         }
3891
3892         if (!ret) {
3893                 if (GetLastError() != ERROR_IO_PENDING) {
3894                         usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3895                         usbi_free_fd(&wfd);
3896                         safe_free(transfer_priv->hid_buffer);
3897                         return LIBUSB_ERROR_IO;
3898                 }
3899         } else {
3900                 // Only write operations that completed synchronously need to free up
3901                 // hid_buffer. For reads, copy_transfer_data() handles that process.
3902                 if (!direction_in)
3903                         safe_free(transfer_priv->hid_buffer);
3904
3905                 if (size == 0) {
3906                         usbi_err(ctx, "program assertion failed - no data was transferred");
3907                         size = 1;
3908                 }
3909                 if (size > (size_t)length) {
3910                         usbi_err(ctx, "OVERFLOW!");
3911                         r = LIBUSB_ERROR_OVERFLOW;
3912                 }
3913                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3914                 wfd.overlapped->InternalHigh = size;
3915         }
3916
3917         transfer_priv->pollable_fd = wfd;
3918         transfer_priv->interface_number = (uint8_t)current_interface;
3919
3920         return r;
3921 }
3922
3923 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
3924 {
3925         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3926         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3927         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3928         HANDLE hid_handle;
3929         int current_interface;
3930
3931         CHECK_HID_AVAILABLE;
3932
3933         current_interface = transfer_priv->interface_number;
3934         hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3935         CancelIo(hid_handle);
3936
3937         return LIBUSB_SUCCESS;
3938 }
3939
3940 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3941 {
3942         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3943         HANDLE hid_handle;
3944         int current_interface;
3945
3946         CHECK_HID_AVAILABLE;
3947
3948         // Flushing the queues on all interfaces is the best we can achieve
3949         for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3950                 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3951                 if (HANDLE_VALID(hid_handle))
3952                         HidD_FlushQueue(hid_handle);
3953         }
3954
3955         return LIBUSB_SUCCESS;
3956 }
3957
3958 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3959 {
3960         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3961         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3962         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3963         HANDLE hid_handle;
3964         int current_interface;
3965
3966         CHECK_HID_AVAILABLE;
3967
3968         current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3969         if (current_interface < 0) {
3970                 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3971                 return LIBUSB_ERROR_NOT_FOUND;
3972         }
3973
3974         usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3975         hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3976
3977         // No endpoint selection with Microsoft's implementation, so we try to flush the
3978         // whole interface. Should be OK for most case scenarios
3979         if (!HidD_FlushQueue(hid_handle)) {
3980                 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3981                 // Device was probably disconnected
3982                 return LIBUSB_ERROR_NO_DEVICE;
3983         }
3984
3985         return LIBUSB_SUCCESS;
3986 }
3987
3988 // This extra function is only needed for HID
3989 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
3990 {
3991         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3992         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3993         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3994         int r = LIBUSB_TRANSFER_COMPLETED;
3995         uint32_t corrected_size = io_size;
3996
3997         if (transfer_priv->hid_buffer != NULL) {
3998                 // If we have a valid hid_buffer, it means the transfer was async
3999                 if (transfer_priv->hid_dest != NULL) { // Data readout
4000                         if (corrected_size > 0) {
4001                                 // First, check for overflow
4002                                 if (corrected_size > transfer_priv->hid_expected_size) {
4003                                         usbi_err(ctx, "OVERFLOW!");
4004                                         corrected_size = (uint32_t)transfer_priv->hid_expected_size;
4005                                         r = LIBUSB_TRANSFER_OVERFLOW;
4006                                 }
4007
4008                                 if (transfer_priv->hid_buffer[0] == 0) {
4009                                         // Discard the 1 byte report ID prefix
4010                                         corrected_size--;
4011                                         memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer + 1, corrected_size);
4012                                 } else {
4013                                         memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
4014                                 }
4015                         }
4016                         transfer_priv->hid_dest = NULL;
4017                 }
4018                 // For write, we just need to free the hid buffer
4019                 safe_free(transfer_priv->hid_buffer);
4020         }
4021
4022         itransfer->transferred += corrected_size;
4023         return r;
4024 }
4025
4026
4027 /*
4028  * Composite API functions
4029  */
4030 static int composite_init(int sub_api, struct libusb_context *ctx)
4031 {
4032         return LIBUSB_SUCCESS;
4033 }
4034
4035 static int composite_exit(int sub_api)
4036 {
4037         return LIBUSB_SUCCESS;
4038 }
4039
4040 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
4041 {
4042         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4043         int r = LIBUSB_ERROR_NOT_FOUND;
4044         uint8_t i;
4045         // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4046         bool available[SUB_API_MAX + 1] = { 0 };
4047
4048         for (i = 0; i < USB_MAXINTERFACES; i++) {
4049                 switch (priv->usb_interface[i].apib->id) {
4050                 case USB_API_WINUSBX:
4051                         if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4052                                 available[priv->usb_interface[i].sub_api] = true;
4053                         break;
4054                 case USB_API_HID:
4055                         available[SUB_API_MAX] = true;
4056                         break;
4057                 default:
4058                         break;
4059                 }
4060         }
4061
4062         for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4063                 if (available[i]) {
4064                         r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4065                         if (r != LIBUSB_SUCCESS)
4066                                 return r;
4067                 }
4068         }
4069
4070         if (available[SUB_API_MAX]) // HID driver
4071                 r = hid_open(SUB_API_NOTSET, dev_handle);
4072
4073         return r;
4074 }
4075
4076 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4077 {
4078         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4079         uint8_t i;
4080         // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4081         bool available[SUB_API_MAX + 1] = { 0 };
4082
4083         for (i = 0; i < USB_MAXINTERFACES; i++) {
4084                 switch (priv->usb_interface[i].apib->id) {
4085                 case USB_API_WINUSBX:
4086                         if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4087                                 available[priv->usb_interface[i].sub_api] = true;
4088                         break;
4089                 case USB_API_HID:
4090                         available[SUB_API_MAX] = true;
4091                         break;
4092                 default:
4093                         break;
4094                 }
4095         }
4096
4097         for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4098                 if (available[i])
4099                         usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4100         }
4101
4102         if (available[SUB_API_MAX]) // HID driver
4103                 hid_close(SUB_API_NOTSET, dev_handle);
4104 }
4105
4106 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4107 {
4108         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4109
4110         return priv->usb_interface[iface].apib->
4111                 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4112 }
4113
4114 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4115 {
4116         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4117
4118         return priv->usb_interface[iface].apib->
4119                 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4120 }
4121
4122 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4123 {
4124         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4125
4126         return priv->usb_interface[iface].apib->
4127                 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4128 }
4129
4130 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4131 {
4132         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4133         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4134         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4135         struct libusb_config_descriptor *conf_desc;
4136         WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
4137         int iface, pass, r;
4138
4139         // Interface shouldn't matter for control, but it does in practice, with Windows'
4140         // restrictions with regards to accessing HID keyboards and mice. Try to target
4141         // a specific interface first, if possible.
4142         switch (LIBUSB_REQ_RECIPIENT(setup->RequestType)) {
4143         case LIBUSB_RECIPIENT_INTERFACE:
4144                 iface = setup->Index & 0xFF;
4145                 break;
4146         case LIBUSB_RECIPIENT_ENDPOINT:
4147                 r = libusb_get_active_config_descriptor(transfer->dev_handle->dev, &conf_desc);
4148                 if (r == LIBUSB_SUCCESS) {
4149                         iface = get_interface_by_endpoint(conf_desc, (setup->Index & 0xFF));
4150                         libusb_free_config_descriptor(conf_desc);
4151                         break;
4152                 }
4153                 // Fall through if not able to determine interface
4154         default:
4155                 iface = -1;
4156                 break;
4157         }
4158
4159         // Try and target a specific interface if the control setup indicates such
4160         if ((iface >= 0) && (iface < USB_MAXINTERFACES)) {
4161                 usbi_dbg("attempting control transfer targeted to interface %d", iface);
4162                 if (priv->usb_interface[iface].path != NULL) {
4163                         r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4164                         if (r == LIBUSB_SUCCESS)
4165                                 return r;
4166                 }
4167         }
4168
4169         // Either not targeted to a specific interface or no luck in doing so.
4170         // Try a 2 pass approach with all interfaces.
4171         for (pass = 0; pass < 2; pass++) {
4172                 for (iface = 0; iface < USB_MAXINTERFACES; iface++) {
4173                         if (priv->usb_interface[iface].path != NULL) {
4174                                 if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) {
4175                                         usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", iface);
4176                                         continue;
4177                                 }
4178                                 usbi_dbg("using interface %d", iface);
4179                                 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4180                                 // If not supported on this API, it may be supported on another, so don't give up yet!!
4181                                 if (r == LIBUSB_ERROR_NOT_SUPPORTED)
4182                                         continue;
4183                                 return r;
4184                         }
4185                 }
4186         }
4187
4188         usbi_err(ctx, "no libusb supported interfaces to complete request");
4189         return LIBUSB_ERROR_NOT_FOUND;
4190 }
4191
4192 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4193         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4194         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4195         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4196         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4197         int current_interface;
4198
4199         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4200         if (current_interface < 0) {
4201                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4202                 return LIBUSB_ERROR_NOT_FOUND;
4203         }
4204
4205         return priv->usb_interface[current_interface].apib->
4206                 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4207 }
4208
4209 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
4210         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4211         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4212         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4213         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4214         int current_interface;
4215
4216         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4217         if (current_interface < 0) {
4218                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4219                 return LIBUSB_ERROR_NOT_FOUND;
4220         }
4221
4222         return priv->usb_interface[current_interface].apib->
4223                 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4224 }
4225
4226 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4227 {
4228         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4229         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4230         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4231         int current_interface;
4232
4233         current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4234         if (current_interface < 0) {
4235                 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4236                 return LIBUSB_ERROR_NOT_FOUND;
4237         }
4238
4239         return priv->usb_interface[current_interface].apib->
4240                 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);
4241 }
4242
4243 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
4244 {
4245         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4246         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4247         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4248
4249         return priv->usb_interface[transfer_priv->interface_number].apib->
4250                 abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4251 }
4252
4253 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4254 {
4255         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4256         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4257         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4258
4259         return priv->usb_interface[transfer_priv->interface_number].apib->
4260                 abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4261 }
4262
4263 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4264 {
4265         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4266         int r;
4267         uint8_t i;
4268         bool available[SUB_API_MAX];
4269
4270         for (i = 0; i < SUB_API_MAX; i++)
4271                 available[i] = false;
4272
4273         for (i = 0; i < USB_MAXINTERFACES; i++) {
4274                 if ((priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4275                                 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET))
4276                         available[priv->usb_interface[i].sub_api] = true;
4277         }
4278
4279         for (i = 0; i < SUB_API_MAX; i++) {
4280                 if (available[i]) {
4281                         r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4282                         if (r != LIBUSB_SUCCESS)
4283                                 return r;
4284                 }
4285         }
4286
4287         return LIBUSB_SUCCESS;
4288 }
4289
4290 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
4291 {
4292         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4293         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4294         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4295
4296         return priv->usb_interface[transfer_priv->interface_number].apib->
4297                 copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);
4298 }
4299
4300 #endif /* !USE_USBDK */