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