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