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