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