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