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
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.
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.
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
27 #if !defined(USE_USBDK)
41 #include "poll_windows.h"
42 #include "windows_winusb.h"
44 #define HANDLE_VALID(h) (((h) != 0) && ((h) != INVALID_HANDLE_VALUE))
46 // The 2 macros below are used in conjunction with safe loops.
47 #define LOOP_CHECK(fcall) \
50 if (r != LIBUSB_SUCCESS) \
53 #define LOOP_BREAK(err) \
60 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
62 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
64 // WinUSB-like API prototypes
65 static int winusbx_init(int sub_api, struct libusb_context *ctx);
66 static int winusbx_exit(int sub_api);
67 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
68 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
69 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
70 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
71 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
72 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
73 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
74 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
75 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
76 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
77 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer);
78 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
79 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
81 static int hid_init(int sub_api, struct libusb_context *ctx);
82 static int hid_exit(int sub_api);
83 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
84 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
85 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
86 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
87 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
88 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
89 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
90 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
91 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
92 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
93 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
94 // Composite API prototypes
95 static int composite_init(int sub_api, struct libusb_context *ctx);
96 static int composite_exit(int sub_api);
97 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
98 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
99 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
100 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
101 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
102 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
103 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
104 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
105 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
106 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
107 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer);
108 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
109 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
113 int windows_version = WINDOWS_UNDEFINED;
114 static char windows_version_str[128] = "Windows Undefined";
116 static int concurrent_usage = -1;
117 static usbi_mutex_t autoclaim_lock;
119 #define CHECK_WINUSBX_AVAILABLE(sub_api) \
121 if (sub_api == SUB_API_NOTSET) \
122 sub_api = priv->sub_api; \
123 if (!WinUSBX[sub_api].initialized) \
124 return LIBUSB_ERROR_ACCESS; \
127 static HMODULE WinUSBX_handle = NULL;
128 static struct winusb_interface WinUSBX[SUB_API_MAX];
129 static const char *sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES;
131 static bool api_hid_available = false;
132 #define CHECK_HID_AVAILABLE \
134 if (!api_hid_available) \
135 return LIBUSB_ERROR_ACCESS; \
138 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2)
140 if ((guid1 != NULL) && (guid2 != NULL))
141 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
146 #if defined(ENABLE_LOGGING)
147 static char *guid_to_string(const GUID *guid)
149 static char guid_string[MAX_GUID_STRING_LENGTH];
154 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
155 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
156 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
157 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
164 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
165 * Return an allocated sanitized string or NULL on error.
167 static char *sanitize_path(const char *path)
169 const char root_prefix[] = "\\\\.\\";
170 size_t j, size, root_size;
171 char *ret_path = NULL;
177 size = safe_strlen(path) + 1;
178 root_size = sizeof(root_prefix) - 1;
180 // Microsoft indiscriminately uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
181 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\'))
182 || ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
183 add_root = root_size;
187 ret_path = calloc(1, size);
188 if (ret_path == NULL)
191 safe_strcpy(&ret_path[add_root], size-add_root, path);
193 // Ensure consistency with root prefix
194 for (j = 0; j < root_size; j++)
195 ret_path[j] = root_prefix[j];
197 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
198 for (j = root_size; j < size; j++) {
199 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
200 if (ret_path[j] == '\\')
208 * Cfgmgr32, OLE32 and SetupAPI DLL functions
210 static int init_dlls(void)
212 DLL_GET_HANDLE(Cfgmgr32);
213 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Parent, TRUE);
214 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Child, TRUE);
215 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Sibling, TRUE);
216 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Device_IDA, TRUE);
218 // Prefixed to avoid conflict with header files
219 DLL_GET_HANDLE(AdvAPI32);
220 DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegQueryValueExW, TRUE);
221 DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegCloseKey, TRUE);
223 DLL_GET_HANDLE(Kernel32);
224 DLL_LOAD_FUNC_PREFIXED(Kernel32, p, IsWow64Process, FALSE);
226 DLL_GET_HANDLE(OLE32);
227 DLL_LOAD_FUNC_PREFIXED(OLE32, p, CLSIDFromString, TRUE);
229 DLL_GET_HANDLE(SetupAPI);
230 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetClassDevsA, TRUE);
231 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInfo, TRUE);
232 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInterfaces, TRUE);
233 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
234 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiDestroyDeviceInfoList, TRUE);
235 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDevRegKey, TRUE);
236 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
237 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDeviceInterfaceRegKey, TRUE);
239 return LIBUSB_SUCCESS;
242 static void exit_dlls(void)
244 DLL_FREE_HANDLE(Cfgmgr32);
245 DLL_FREE_HANDLE(AdvAPI32);
246 DLL_FREE_HANDLE(Kernel32);
247 DLL_FREE_HANDLE(OLE32);
248 DLL_FREE_HANDLE(SetupAPI);
252 * enumerate interfaces for the whole USB class
255 * dev_info: a pointer to a dev_info list
256 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
257 * usb_class: the generic USB class for which to retrieve interface details
258 * index: zero based index of the interface in the device info list
260 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
261 * structure returned and call this function repeatedly using the same guid (with an
262 * incremented index starting at zero) until all interfaces have been returned.
264 static bool get_devinfo_data(struct libusb_context *ctx,
265 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char *usb_class, unsigned _index)
268 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
269 if (*dev_info == INVALID_HANDLE_VALUE)
273 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
274 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
275 if (GetLastError() != ERROR_NO_MORE_ITEMS)
276 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
277 _index, windows_error_str(0));
279 pSetupDiDestroyDeviceInfoList(*dev_info);
280 *dev_info = INVALID_HANDLE_VALUE;
287 * enumerate interfaces for a specific GUID
290 * dev_info: a pointer to a dev_info list
291 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
292 * guid: the GUID for which to retrieve interface details
293 * index: zero based index of the interface in the device info list
295 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
296 * structure returned and call this function repeatedly using the same guid (with an
297 * incremented index starting at zero) until all interfaces have been returned.
299 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
300 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID *guid, unsigned _index)
302 SP_DEVICE_INTERFACE_DATA dev_interface_data;
303 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
307 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
309 if (dev_info_data != NULL) {
310 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
311 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
312 if (GetLastError() != ERROR_NO_MORE_ITEMS)
313 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
314 _index, windows_error_str(0));
316 pSetupDiDestroyDeviceInfoList(*dev_info);
317 *dev_info = INVALID_HANDLE_VALUE;
322 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
323 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
324 if (GetLastError() != ERROR_NO_MORE_ITEMS)
325 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
326 _index, windows_error_str(0));
328 pSetupDiDestroyDeviceInfoList(*dev_info);
329 *dev_info = INVALID_HANDLE_VALUE;
333 // Read interface data (dummy + actual) to access the device path
334 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
335 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
336 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
337 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
338 _index, windows_error_str(0));
342 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
346 dev_interface_details = calloc(1, size);
347 if (dev_interface_details == NULL) {
348 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
352 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
353 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
354 dev_interface_details, size, &size, NULL)) {
355 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
356 _index, windows_error_str(0));
359 return dev_interface_details;
362 pSetupDiDestroyDeviceInfoList(*dev_info);
363 *dev_info = INVALID_HANDLE_VALUE;
367 /* For libusb0 filter */
368 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx,
369 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID *guid, unsigned _index, char *filter_path)
371 SP_DEVICE_INTERFACE_DATA dev_interface_data;
372 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
376 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
378 if (dev_info_data != NULL) {
379 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
380 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
381 if (GetLastError() != ERROR_NO_MORE_ITEMS)
382 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
383 _index, windows_error_str(0));
385 pSetupDiDestroyDeviceInfoList(*dev_info);
386 *dev_info = INVALID_HANDLE_VALUE;
391 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
392 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
393 if (GetLastError() != ERROR_NO_MORE_ITEMS)
394 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
395 _index, windows_error_str(0));
397 pSetupDiDestroyDeviceInfoList(*dev_info);
398 *dev_info = INVALID_HANDLE_VALUE;
402 // Read interface data (dummy + actual) to access the device path
403 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
404 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
405 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
406 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
407 _index, windows_error_str(0));
411 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
415 dev_interface_details = calloc(1, size);
416 if (dev_interface_details == NULL) {
417 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
421 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
422 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, dev_interface_details, size, &size, NULL))
423 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
424 _index, windows_error_str(0));
426 // [trobinso] lookup the libusb0 symbolic index.
427 if (dev_interface_details) {
428 HKEY hkey_device_interface = pSetupDiOpenDeviceInterfaceRegKey(*dev_info, &dev_interface_data, 0, KEY_READ);
429 if (hkey_device_interface != INVALID_HANDLE_VALUE) {
430 DWORD libusb0_symboliclink_index = 0;
431 DWORD value_length = sizeof(DWORD);
432 DWORD value_type = 0;
435 status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type,
436 (LPBYTE)&libusb0_symboliclink_index, &value_length);
437 if (status == ERROR_SUCCESS) {
438 if (libusb0_symboliclink_index < 256) {
439 // libusb0.sys is connected to this device instance.
440 // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
441 safe_sprintf(filter_path, sizeof("\\\\.\\libusb0-0000"), "\\\\.\\libusb0-%04u", (unsigned int)libusb0_symboliclink_index);
442 usbi_dbg("assigned libusb0 symbolic link %s", filter_path);
444 // libusb0.sys was connected to this device instance at one time; but not anymore.
447 pRegCloseKey(hkey_device_interface);
451 return dev_interface_details;
454 pSetupDiDestroyDeviceInfoList(*dev_info);
455 *dev_info = INVALID_HANDLE_VALUE;
460 * Returns the session ID of a device's nth level ancestor
461 * If there's no device at the nth level, return 0
463 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
465 DWORD parent_devinst;
466 unsigned long session_id = 0;
467 char *sanitized_path = NULL;
468 char path[MAX_PATH_LENGTH];
474 for (i = 0; i < level; i++) {
475 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS)
477 devinst = parent_devinst;
480 if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS)
483 // TODO: (post hotplug): try without sanitizing
484 sanitized_path = sanitize_path(path);
485 if (sanitized_path == NULL)
488 session_id = htab_hash(sanitized_path);
489 safe_free(sanitized_path);
494 * Determine which interface the given endpoint address belongs to
496 static int get_interface_by_endpoint(struct libusb_config_descriptor *conf_desc, uint8_t ep)
498 const struct libusb_interface *intf;
499 const struct libusb_interface_descriptor *intf_desc;
502 for (i = 0; i < conf_desc->bNumInterfaces; i++) {
503 intf = &conf_desc->interface[i];
504 for (j = 0; j < intf->num_altsetting; j++) {
505 intf_desc = &intf->altsetting[j];
506 for (k = 0; k < intf_desc->bNumEndpoints; k++) {
507 if (intf_desc->endpoint[k].bEndpointAddress == ep) {
508 usbi_dbg("found endpoint %02X on interface %d", intf_desc->bInterfaceNumber, i);
509 return intf_desc->bInterfaceNumber;
515 usbi_dbg("endpoint %02X not found on any interface", ep);
516 return LIBUSB_ERROR_NOT_FOUND;
520 * Populate the endpoints addresses of the device_priv interface helper structs
522 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
525 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
526 struct libusb_config_descriptor *conf_desc;
527 const struct libusb_interface_descriptor *if_desc;
528 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
530 r = libusb_get_config_descriptor(dev_handle->dev, (uint8_t)(priv->active_config-1), &conf_desc);
531 if (r != LIBUSB_SUCCESS) {
532 usbi_warn(ctx, "could not read config descriptor: error %d", r);
536 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
537 safe_free(priv->usb_interface[iface].endpoint);
539 if (if_desc->bNumEndpoints == 0) {
540 usbi_dbg("no endpoints found for interface %d", iface);
541 libusb_free_config_descriptor(conf_desc);
542 return LIBUSB_SUCCESS;
545 priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints);
546 if (priv->usb_interface[iface].endpoint == NULL) {
547 libusb_free_config_descriptor(conf_desc);
548 return LIBUSB_ERROR_NO_MEM;
551 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
552 for (i = 0; i < if_desc->bNumEndpoints; i++) {
553 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
554 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
556 libusb_free_config_descriptor(conf_desc);
558 // Extra init may be required to configure endpoints
559 return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
562 // Lookup for a match in the list of API driver names
563 // return -1 if not found, driver match number otherwise
564 static int get_sub_api(char *driver, int api)
567 const char sep_str[2] = {LIST_SEPARATOR, 0};
569 size_t len = safe_strlen(driver);
572 return SUB_API_NOTSET;
574 tmp_str = _strdup(driver);
576 return SUB_API_NOTSET;
578 tok = strtok(tmp_str, sep_str);
579 while (tok != NULL) {
580 for (i = 0; i < usb_api_backend[api].nb_driver_names; i++) {
581 if (safe_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
586 tok = strtok(NULL, sep_str);
590 return SUB_API_NOTSET;
594 * auto-claiming and auto-release helper functions
596 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
598 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
599 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
600 transfer->dev_handle);
601 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
602 int current_interface = *interface_number;
603 int r = LIBUSB_SUCCESS;
606 case USB_API_WINUSBX:
610 return LIBUSB_ERROR_INVALID_PARAM;
613 usbi_mutex_lock(&autoclaim_lock);
614 if (current_interface < 0) { // No serviceable interface was found
615 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
616 // Must claim an interface of the same API type
617 if ((priv->usb_interface[current_interface].apib->id == api_type)
618 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS)) {
619 usbi_dbg("auto-claimed interface %d for control request", current_interface);
620 if (handle_priv->autoclaim_count[current_interface] != 0)
621 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
622 handle_priv->autoclaim_count[current_interface]++;
626 if (current_interface == USB_MAXINTERFACES) {
627 usbi_err(ctx, "could not auto-claim any interface");
628 r = LIBUSB_ERROR_NOT_FOUND;
631 // If we have a valid interface that was autoclaimed, we must increment
632 // its autoclaim count so that we can prevent an early release.
633 if (handle_priv->autoclaim_count[current_interface] != 0)
634 handle_priv->autoclaim_count[current_interface]++;
636 usbi_mutex_unlock(&autoclaim_lock);
638 *interface_number = current_interface;
642 static void auto_release(struct usbi_transfer *itransfer)
644 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
645 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
646 libusb_device_handle *dev_handle = transfer->dev_handle;
647 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
650 usbi_mutex_lock(&autoclaim_lock);
651 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
652 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
653 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
654 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
655 if (r == LIBUSB_SUCCESS)
656 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
658 usbi_dbg("failed to auto-release interface %d (%s)",
659 transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
662 usbi_mutex_unlock(&autoclaim_lock);
665 /* Windows version dtection */
666 static BOOL is_x64(void)
670 // Detect if we're running a 32 or 64 bit system
671 if (sizeof(uintptr_t) < 8) {
672 if (pIsWow64Process != NULL)
673 pIsWow64Process(GetCurrentProcess(), &ret);
681 static void get_windows_version(void)
683 OSVERSIONINFOEXA vi, vi2;
685 const char *w64 = "32 bit";
688 unsigned major, minor;
689 ULONGLONG major_equal, minor_equal;
692 memset(&vi, 0, sizeof(vi));
693 vi.dwOSVersionInfoSize = sizeof(vi);
694 if (!GetVersionExA((OSVERSIONINFOA *)&vi)) {
695 memset(&vi, 0, sizeof(vi));
696 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
697 if (!GetVersionExA((OSVERSIONINFOA *)&vi))
701 if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
702 if (vi.dwMajorVersion > 6 || (vi.dwMajorVersion == 6 && vi.dwMinorVersion >= 2)) {
703 // Starting with Windows 8.1 Preview, GetVersionEx() does no longer report the actual OS version
704 // See: http://msdn.microsoft.com/en-us/library/windows/desktop/dn302074.aspx
706 major_equal = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL);
707 for (major = vi.dwMajorVersion; major <= 9; major++) {
708 memset(&vi2, 0, sizeof(vi2));
709 vi2.dwOSVersionInfoSize = sizeof(vi2);
710 vi2.dwMajorVersion = major;
711 if (!VerifyVersionInfoA(&vi2, VER_MAJORVERSION, major_equal))
714 if (vi.dwMajorVersion < major) {
715 vi.dwMajorVersion = major;
716 vi.dwMinorVersion = 0;
719 minor_equal = VerSetConditionMask(0, VER_MINORVERSION, VER_EQUAL);
720 for (minor = vi.dwMinorVersion; minor <= 9; minor++) {
721 memset(&vi2, 0, sizeof(vi2));
722 vi2.dwOSVersionInfoSize = sizeof(vi2);
723 vi2.dwMinorVersion = minor;
724 if (!VerifyVersionInfoA(&vi2, VER_MINORVERSION, minor_equal))
727 vi.dwMinorVersion = minor;
735 if (vi.dwMajorVersion <= 0xf && vi.dwMinorVersion <= 0xf) {
736 ws = (vi.wProductType <= VER_NT_WORKSTATION);
737 windows_version = vi.dwMajorVersion << 4 | vi.dwMinorVersion;
738 switch (windows_version) {
739 case 0x50: w = "2000"; break;
740 case 0x51: w = "XP"; break;
741 case 0x52: w = ("2003"); break;
742 case 0x60: w = (ws ? "Vista" : "2008"); break;
743 case 0x61: w = (ws ? "7" : "2008_R2"); break;
744 case 0x62: w = (ws ? "8" : "2012"); break;
745 case 0x63: w = (ws ? "8.1": "2012_R2"); break;
746 case 0x64: w = (ws ? "10": "2015"); break;
748 if (windows_version < 0x50)
749 windows_version = WINDOWS_UNSUPPORTED;
760 vptr = &windows_version_str[sizeof("Windows ") - 1];
761 vlen = sizeof(windows_version_str) - sizeof("Windows ") - 1;
763 safe_sprintf(vptr, vlen, "%s %u.%u %s", (vi.dwPlatformId == VER_PLATFORM_WIN32_NT ? "NT" : "??"),
764 (unsigned int)vi.dwMajorVersion, (unsigned int)vi.dwMinorVersion, w64);
765 else if (vi.wServicePackMinor)
766 safe_sprintf(vptr, vlen, "%s SP%u.%u %s", w, vi.wServicePackMajor, vi.wServicePackMinor, w64);
767 else if (vi.wServicePackMajor)
768 safe_sprintf(vptr, vlen, "%s SP%u %s", w, vi.wServicePackMajor, w64);
770 safe_sprintf(vptr, vlen, "%s %s", w, w64);
774 * init: libusb backend init function
776 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
777 * In our implementation, we equate Windows' "HCD" to libusb's "bus". Note that bus is zero indexed.
778 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
780 static int windows_init(struct libusb_context *ctx)
782 int i, r = LIBUSB_ERROR_OTHER;
784 char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0'
786 sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF));
787 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
788 if (semaphore == NULL) {
789 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
790 return LIBUSB_ERROR_NO_MEM;
793 // A successful wait brings our semaphore count to 0 (unsignaled)
794 // => any concurent wait stalls until the semaphore's release
795 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
796 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
797 CloseHandle(semaphore);
798 return LIBUSB_ERROR_NO_MEM;
801 // NB: concurrent usage supposes that init calls are equally balanced with
802 // exit calls. If init is called more than exit, we will not exit properly
803 if (++concurrent_usage == 0) { // First init?
804 get_windows_version();
805 usbi_dbg(windows_version_str);
807 if (windows_version == WINDOWS_UNSUPPORTED) {
808 usbi_err(ctx, "This version of Windows is NOT supported");
809 r = LIBUSB_ERROR_NOT_SUPPORTED;
813 // We need a lock for proper auto-release
814 usbi_mutex_init(&autoclaim_lock);
816 // Initialize pollable file descriptors
820 if (init_dlls() != LIBUSB_SUCCESS) {
821 usbi_err(ctx, "could not resolve DLL functions");
825 // Initialize the low level APIs (we don't care about errors at this stage)
826 for (i = 0; i < USB_API_MAX; i++)
827 usb_api_backend[i].init(SUB_API_NOTSET, ctx);
829 r = windows_common_init(ctx);
833 // At this stage, either we went through full init successfully, or didn't need to
836 init_exit: // Holds semaphore here.
837 if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
838 for (i = 0; i < USB_API_MAX; i++)
839 usb_api_backend[i].exit(SUB_API_NOTSET);
842 windows_common_exit();
843 usbi_mutex_destroy(&autoclaim_lock);
846 if (r != LIBUSB_SUCCESS)
847 --concurrent_usage; // Not expected to call libusb_exit if we failed.
849 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
850 CloseHandle(semaphore);
855 * HCD (root) hubs need to have their device descriptor manually populated
857 * Note that, like Microsoft does in the device manager, we populate the
858 * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
860 static int force_hcd_device_descriptor(struct libusb_device *dev)
862 struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
863 struct libusb_context *ctx = DEVICE_CTX(dev);
866 dev->num_configurations = 1;
867 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
868 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
869 priv->dev_descriptor.bNumConfigurations = 1;
870 priv->active_config = 1;
872 if (priv->parent_dev == NULL) {
873 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
874 return LIBUSB_ERROR_NO_DEVICE;
877 parent_priv = _device_priv(priv->parent_dev);
878 if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
879 priv->dev_descriptor.idVendor = (uint16_t)vid;
880 priv->dev_descriptor.idProduct = (uint16_t)pid;
882 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
883 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
884 priv->dev_descriptor.idProduct = 1;
887 return LIBUSB_SUCCESS;
891 * fetch and cache all the config descriptors through I/O
893 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char *device_id)
895 DWORD size, ret_size;
896 struct libusb_context *ctx = DEVICE_CTX(dev);
897 struct windows_device_priv *priv = _device_priv(dev);
901 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
902 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
903 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
905 if (dev->num_configurations == 0)
906 return LIBUSB_ERROR_INVALID_PARAM;
908 priv->config_descriptor = calloc(dev->num_configurations, sizeof(unsigned char *));
909 if (priv->config_descriptor == NULL)
910 return LIBUSB_ERROR_NO_MEM;
912 for (i = 0; i < dev->num_configurations; i++)
913 priv->config_descriptor[i] = NULL;
915 for (i = 0, r = LIBUSB_SUCCESS; ; i++) {
916 // safe loop: release all dynamic resources
917 safe_free(cd_buf_actual);
919 // safe loop: end of loop condition
920 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
923 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
924 memset(&cd_buf_short, 0, size);
926 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
927 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
928 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
929 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
930 cd_buf_short.req.SetupPacket.wIndex = 0;
931 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
933 // Dummy call to get the required data size. Initial failures are reported as info rather
934 // than error as they can occur for non-penalizing situations, such as with some hubs.
935 // coverity[tainted_data_argument]
936 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
937 &cd_buf_short, size, &ret_size, NULL)) {
938 usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
939 LOOP_BREAK(LIBUSB_ERROR_IO);
942 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
943 usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
944 LOOP_BREAK(LIBUSB_ERROR_IO);
947 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
948 cd_buf_actual = calloc(1, size);
949 if (cd_buf_actual == NULL) {
950 usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
951 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
955 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
956 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
957 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
958 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
959 cd_buf_actual->SetupPacket.wIndex = 0;
960 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
962 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
963 cd_buf_actual, size, &ret_size, NULL)) {
964 usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
965 LOOP_BREAK(LIBUSB_ERROR_IO);
968 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR *)cd_buf_actual + sizeof(USB_DESCRIPTOR_REQUEST));
970 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
971 usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
972 LOOP_BREAK(LIBUSB_ERROR_IO);
975 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
976 usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
977 LOOP_BREAK(LIBUSB_ERROR_IO);
980 usbi_dbg("cached config descriptor %d (bConfigurationValue=%u, %u bytes)",
981 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
983 // Cache the descriptor
984 priv->config_descriptor[i] = malloc(cd_data->wTotalLength);
985 if (priv->config_descriptor[i] == NULL)
986 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
987 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
989 return LIBUSB_SUCCESS;
993 * Populate a libusb device structure
995 static int init_device(struct libusb_device *dev, struct libusb_device *parent_dev,
996 uint8_t port_number, char *device_id, DWORD devinst)
1000 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
1001 USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
1002 struct windows_device_priv *priv, *parent_priv;
1003 struct libusb_context *ctx;
1004 struct libusb_device *tmp_dev;
1005 unsigned long tmp_id;
1008 if ((dev == NULL) || (parent_dev == NULL))
1009 return LIBUSB_ERROR_NOT_FOUND;
1011 ctx = DEVICE_CTX(dev);
1012 priv = _device_priv(dev);
1013 parent_priv = _device_priv(parent_dev);
1014 if (parent_priv->apib->id != USB_API_HUB) {
1015 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
1016 return LIBUSB_ERROR_NOT_FOUND;
1019 // It is possible for the parent hub not to have been initialized yet
1020 // If that's the case, lookup the ancestors to set the bus number
1021 if (parent_dev->bus_number == 0) {
1022 for (i = 2; ; i++) {
1023 tmp_id = get_ancestor_session_id(devinst, i);
1027 tmp_dev = usbi_get_device_by_session_id(ctx, tmp_id);
1028 if (tmp_dev == NULL)
1031 if (tmp_dev->bus_number != 0) {
1032 usbi_dbg("got bus number from ancestor #%u", i);
1033 parent_dev->bus_number = tmp_dev->bus_number;
1034 libusb_unref_device(tmp_dev);
1038 libusb_unref_device(tmp_dev);
1042 if (parent_dev->bus_number == 0) {
1043 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1044 return LIBUSB_ERROR_NOT_FOUND;
1047 dev->bus_number = parent_dev->bus_number;
1048 priv->port = port_number;
1049 dev->port_number = port_number;
1050 priv->depth = parent_priv->depth + 1;
1051 priv->parent_dev = parent_dev;
1052 dev->parent_dev = parent_dev;
1054 // If the device address is already set, we can stop here
1055 if (dev->device_address != 0)
1056 return LIBUSB_SUCCESS;
1058 memset(&conn_info, 0, sizeof(conn_info));
1059 if (priv->depth != 0) { // Not a HCD hub
1060 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1061 FILE_FLAG_OVERLAPPED, NULL);
1062 if (handle == INVALID_HANDLE_VALUE) {
1063 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1064 return LIBUSB_ERROR_ACCESS;
1067 size = sizeof(conn_info);
1068 conn_info.ConnectionIndex = (ULONG)port_number;
1069 // coverity[tainted_data_argument]
1070 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1071 &conn_info, size, &size, NULL)) {
1072 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1073 device_id, windows_error_str(0));
1074 safe_closehandle(handle);
1075 return LIBUSB_ERROR_NO_DEVICE;
1078 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1079 usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1080 safe_closehandle(handle);
1081 return LIBUSB_ERROR_NO_DEVICE;
1084 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1085 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1086 priv->active_config = conn_info.CurrentConfigurationValue;
1087 usbi_dbg("found %u configurations (active conf: %u)", dev->num_configurations, priv->active_config);
1089 // If we can't read the config descriptors, just set the number of confs to zero
1090 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1091 dev->num_configurations = 0;
1092 priv->dev_descriptor.bNumConfigurations = 0;
1095 // In their great wisdom, Microsoft decided to BREAK the USB speed report between Windows 7 and Windows 8
1096 if (windows_version >= WINDOWS_8) {
1097 memset(&conn_info_v2, 0, sizeof(conn_info_v2));
1098 size = sizeof(conn_info_v2);
1099 conn_info_v2.ConnectionIndex = (ULONG)port_number;
1100 conn_info_v2.Length = size;
1101 conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
1102 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
1103 &conn_info_v2, size, &conn_info_v2, size, &size, NULL)) {
1104 usbi_warn(ctx, "could not get node connection information (V2) for device '%s': %s",
1105 device_id, windows_error_str(0));
1106 } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedOrHigher) {
1107 conn_info.Speed = 3;
1111 safe_closehandle(handle);
1113 if (conn_info.DeviceAddress > UINT8_MAX)
1114 usbi_err(ctx, "program assertion failed: device address overflow");
1116 dev->device_address = (uint8_t)conn_info.DeviceAddress + 1;
1117 if (dev->device_address == 1)
1118 usbi_err(ctx, "program assertion failed: device address collision with root hub");
1120 switch (conn_info.Speed) {
1121 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1122 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1123 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1124 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1126 usbi_warn(ctx, "Got unknown device speed %u", conn_info.Speed);
1130 dev->device_address = 1; // root hubs are set to use device number 1
1131 force_hcd_device_descriptor(dev);
1134 usbi_sanitize_device(dev);
1136 usbi_dbg("(bus: %u, addr: %u, depth: %u, port: %u): '%s'",
1137 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1139 return LIBUSB_SUCCESS;
1142 // Returns the api type, or 0 if not found/unsupported
1143 static void get_api_type(struct libusb_context *ctx, HDEVINFO *dev_info,
1144 SP_DEVINFO_DATA *dev_info_data, int *api, int *sub_api)
1146 // Precedence for filter drivers vs driver is in the order of this array
1147 struct driver_lookup lookup[3] = {
1148 {"\0\0", SPDRP_SERVICE, "driver"},
1149 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1150 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1152 DWORD size, reg_type;
1156 *api = USB_API_UNSUPPORTED;
1157 *sub_api = SUB_API_NOTSET;
1159 // Check the service & filter names to know the API we should use
1160 for (k = 0; k < 3; k++) {
1161 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1162 ®_type, (BYTE *)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1163 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1164 if (lookup[k].reg_prop == SPDRP_SERVICE)
1165 // our buffers are MAX_KEY_LENGTH + 1 so we can overflow if needed
1166 lookup[k].list[safe_strlen(lookup[k].list) + 1] = 0;
1168 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1169 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1170 // (currently ';'), so even if an unsuported one does, it's not an issue
1171 for (l = 0; (lookup[k].list[l] != 0) || (lookup[k].list[l + 1] != 0); l++) {
1172 if (lookup[k].list[l] == 0)
1173 lookup[k].list[l] = LIST_SEPARATOR;
1175 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1177 if (GetLastError() != ERROR_INVALID_DATA)
1178 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1179 lookup[k].list[0] = 0;
1183 for (i = 1; i < USB_API_MAX; i++) {
1184 for (k = 0; k < 3; k++) {
1185 j = get_sub_api(lookup[k].list, i);
1187 usbi_dbg("matched %s name against %s", lookup[k].designation,
1188 (i != USB_API_WINUSBX) ? usb_api_backend[i].designation : sub_api_name[j]);
1197 static int set_composite_interface(struct libusb_context *ctx, struct libusb_device *dev,
1198 char *dev_interface_path, char *device_id, int api, int sub_api)
1201 struct windows_device_priv *priv = _device_priv(dev);
1202 int interface_number;
1204 if (priv->apib->id != USB_API_COMPOSITE) {
1205 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1206 return LIBUSB_ERROR_NO_DEVICE;
1209 // Because MI_## are not necessarily in sequential order (some composite
1210 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1211 // interface number from the path's MI value
1212 interface_number = 0;
1213 for (i = 0; device_id[i] != 0; ) {
1214 if ((device_id[i++] == 'M') && (device_id[i++] == 'I')
1215 && (device_id[i++] == '_')) {
1216 interface_number = (device_id[i++] - '0') * 10;
1217 interface_number += device_id[i] - '0';
1222 if (device_id[i] == 0)
1223 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1224 device_id, interface_number);
1226 if (priv->usb_interface[interface_number].path != NULL) {
1227 if (api == USB_API_HID) {
1228 // HID devices can have multiple collections (COL##) for each MI_## interface
1229 usbi_dbg("interface[%d] already set - ignoring HID collection: %s",
1230 interface_number, device_id);
1231 return LIBUSB_ERROR_ACCESS;
1233 // In other cases, just use the latest data
1234 safe_free(priv->usb_interface[interface_number].path);
1237 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1238 priv->usb_interface[interface_number].path = dev_interface_path;
1239 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1240 priv->usb_interface[interface_number].sub_api = sub_api;
1241 if ((api == USB_API_HID) && (priv->hid == NULL)) {
1242 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1243 if (priv->hid == NULL)
1244 return LIBUSB_ERROR_NO_MEM;
1247 return LIBUSB_SUCCESS;
1250 static int set_hid_interface(struct libusb_context *ctx, struct libusb_device *dev,
1251 char *dev_interface_path)
1254 struct windows_device_priv *priv = _device_priv(dev);
1256 if (priv->hid == NULL) {
1257 usbi_err(ctx, "program assertion failed: parent is not HID");
1258 return LIBUSB_ERROR_NO_DEVICE;
1259 } else if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
1260 usbi_err(ctx, "program assertion failed: max USB interfaces reached for HID device");
1261 return LIBUSB_ERROR_NO_DEVICE;
1264 for (i = 0; i < priv->hid->nb_interfaces; i++) {
1265 if (safe_strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
1266 usbi_dbg("interface[%d] already set to %s", i, dev_interface_path);
1267 return LIBUSB_SUCCESS;
1271 priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
1272 priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
1273 usbi_dbg("interface[%u] = %s", priv->hid->nb_interfaces, dev_interface_path);
1274 priv->hid->nb_interfaces++;
1275 return LIBUSB_SUCCESS;
1279 * get_device_list: libusb backend device enumeration function
1281 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1283 struct discovered_devs *discdevs;
1284 HDEVINFO dev_info = { 0 };
1285 const char *usb_class[] = {"USB", "NUSB3", "IUSB3"};
1286 SP_DEVINFO_DATA dev_info_data = { 0 };
1287 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1289 #define MAX_ENUM_GUIDS 64
1290 const GUID *guid[MAX_ENUM_GUIDS];
1296 int r = LIBUSB_SUCCESS;
1298 size_t class_index = 0;
1299 unsigned int nb_guids, pass, i, j, ancestor;
1300 char path[MAX_PATH_LENGTH];
1301 char strbuf[MAX_PATH_LENGTH];
1302 struct libusb_device *dev, *parent_dev;
1303 struct windows_device_priv *priv, *parent_priv;
1304 char *dev_interface_path = NULL;
1305 char *dev_id_path = NULL;
1306 unsigned long session_id;
1307 DWORD size, reg_type, port_nr, install_state;
1309 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1312 // Keep a list of newly allocated devs to unref
1313 libusb_device **unref_list;
1314 unsigned int unref_size = 64;
1315 unsigned int unref_cur = 0;
1317 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1318 // PASS 2 : (re)enumerate HUBS
1319 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1320 // and list additional USB device interface GUIDs to explore
1321 // PASS 4 : (re)enumerate master USB devices that have a device interface
1322 // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
1323 // set the device interfaces.
1325 // Init the GUID table
1326 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1327 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1328 guid[GEN_PASS] = NULL;
1329 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1330 HidD_GetHidGuid(&hid_guid);
1331 guid[HID_PASS] = &hid_guid;
1332 nb_guids = HID_PASS + 1;
1334 unref_list = calloc(unref_size, sizeof(libusb_device *));
1335 if (unref_list == NULL)
1336 return LIBUSB_ERROR_NO_MEM;
1338 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1339 //#define ENUM_DEBUG
1340 #if defined(ENABLE_LOGGING) && defined(ENUM_DEBUG)
1341 const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "HID", "EXT" };
1342 usbi_dbg("#### PROCESSING %ss %s", passname[(pass <= HID_PASS) ? pass : (HID_PASS + 1)],
1343 (pass != GEN_PASS) ? guid_to_string(guid[pass]) : "");
1345 for (i = 0; ; i++) {
1346 // safe loop: free up any (unprotected) dynamic resource
1347 // NB: this is always executed before breaking the loop
1348 safe_free(dev_interface_details);
1349 safe_free(dev_interface_path);
1350 safe_free(dev_id_path);
1351 priv = parent_priv = NULL;
1352 dev = parent_dev = NULL;
1354 // Safe loop: end of loop conditions
1355 if (r != LIBUSB_SUCCESS)
1358 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1359 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1363 if (pass != GEN_PASS) {
1364 // Except for GEN, all passes deal with device interfaces
1365 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1366 if (dev_interface_details == NULL)
1369 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1370 if (dev_interface_path == NULL) {
1371 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1375 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1376 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
1377 // The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
1378 for (; class_index < ARRAYSIZE(usb_class); class_index++) {
1379 if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))
1383 if (class_index >= ARRAYSIZE(usb_class))
1387 // Read the Device ID path. This is what we'll use as UID
1388 // Note that if the device is plugged in a different port or hub, the Device ID changes
1389 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1390 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1391 (unsigned int)dev_info_data.DevInst);
1395 dev_id_path = sanitize_path(path);
1396 if (dev_id_path == NULL) {
1397 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1398 (unsigned int)dev_info_data.DevInst);
1402 usbi_dbg("PRO: %s", dev_id_path);
1405 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1407 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1408 if ((!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1409 ®_type, (BYTE *)&port_nr, 4, &size)) || (size != 4)) {
1410 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1411 dev_id_path, windows_error_str(0));
1416 // Set API to use or get additional data from generic pass
1417 api = USB_API_UNSUPPORTED;
1418 sub_api = SUB_API_NOTSET;
1423 // We use the GEN pass to detect driverless devices...
1424 size = sizeof(strbuf);
1425 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1426 ®_type, (BYTE *)strbuf, size, &size)) {
1427 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1428 usbi_info(ctx, "libusb will not be able to access it.");
1430 // ...and to add the additional device interface GUIDs
1431 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1432 if (key != INVALID_HANDLE_VALUE) {
1433 size = sizeof(guid_string_w);
1434 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1435 (BYTE *)guid_string_w, &size);
1437 if (s == ERROR_SUCCESS) {
1438 if (nb_guids >= MAX_ENUM_GUIDS) {
1439 // If this assert is ever reported, grow a GUID table dynamically
1440 usbi_err(ctx, "program assertion failed: too many GUIDs");
1441 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1443 if_guid = calloc(1, sizeof(GUID));
1444 if (if_guid == NULL) {
1445 usbi_err(ctx, "could not calloc for if_guid: not enough memory");
1446 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1448 pCLSIDFromString(guid_string_w, if_guid);
1449 guid[nb_guids++] = if_guid;
1450 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1458 // Get the API type (after checking that the driver installation is OK)
1459 if ((!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1460 ®_type, (BYTE *)&install_state, 4, &size)) || (size != 4)) {
1461 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1462 dev_id_path, windows_error_str(0));
1463 } else if (install_state != 0) {
1464 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %u) - skipping",
1465 dev_id_path, (unsigned int)install_state);
1468 get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api);
1472 // Find parent device (for the passes that need it)
1479 // Go through the ancestors until we see a face we recognize
1481 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1482 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1483 if (session_id == 0)
1486 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1489 if (parent_dev == NULL) {
1490 usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
1494 parent_priv = _device_priv(parent_dev);
1495 // virtual USB devices are also listed during GEN - don't process these yet
1496 if ((pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB)) {
1497 libusb_unref_device(parent_dev);
1504 // Create new or match existing device, using the (hashed) device_id as session id
1505 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1506 // These are the passes that create "new" devices
1507 session_id = htab_hash(dev_id_path);
1508 dev = usbi_get_device_by_session_id(ctx, session_id);
1510 if (pass == DEV_PASS) {
1511 // This can occur if the OS only reports a newly plugged device after we started enum
1512 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1513 " - ignoring", dev_id_path);
1517 usbi_dbg("allocating new device for session [%lX]", session_id);
1518 dev = usbi_alloc_device(ctx, session_id);
1520 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1522 windows_device_priv_init(dev);
1524 usbi_dbg("found existing device for session [%lX] (%u.%u)",
1525 session_id, dev->bus_number, dev->device_address);
1526 if (_device_priv(dev)->parent_dev != parent_dev) {
1527 usbi_err(ctx,"program assertion failed - existing device should share parent");
1529 // We hold a reference to parent_dev instance, but this device already
1530 // has a parent_dev reference (only one per child)
1531 libusb_unref_device(parent_dev);
1535 // Keep track of devices that need unref
1536 unref_list[unref_cur++] = dev;
1537 if (unref_cur >= unref_size) {
1539 unref_list = usbi_reallocf(unref_list, unref_size * sizeof(libusb_device *));
1540 if (unref_list == NULL) {
1541 usbi_err(ctx, "could not realloc list for unref - aborting.");
1542 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1545 priv = _device_priv(dev);
1551 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1552 dev->device_address = 0;
1553 dev->num_configurations = 0;
1554 priv->apib = &usb_api_backend[USB_API_HUB];
1555 priv->sub_api = SUB_API_NOTSET;
1556 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1557 priv->path = dev_interface_path;
1558 dev_interface_path = NULL;
1562 // If the device has already been setup, don't do it again
1563 if (priv->path != NULL)
1565 // Take care of API initialization
1566 priv->path = dev_interface_path;
1567 dev_interface_path = NULL;
1568 priv->apib = &usb_api_backend[api];
1569 priv->sub_api = sub_api;
1571 case USB_API_COMPOSITE:
1575 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1576 if (priv->hid == NULL)
1577 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1579 priv->hid->nb_interfaces = 0;
1582 // For other devices, the first interface is the same as the device
1583 priv->usb_interface[0].path = _strdup(priv->path);
1584 if (priv->usb_interface[0].path == NULL)
1585 usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
1586 // The following is needed if we want API calls to work for both simple
1587 // and composite devices.
1588 for(j = 0; j < USB_MAXINTERFACES; j++)
1589 priv->usb_interface[j].apib = &usb_api_backend[api];
1595 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1596 if (r == LIBUSB_SUCCESS) {
1597 // Append device to the list of discovered devices
1598 discdevs = discovered_devs_append(*_discdevs, dev);
1600 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1602 *_discdevs = discdevs;
1603 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1604 // This can occur if the device was disconnected but Windows hasn't
1605 // refreshed its enumeration yet - in that case, we ignore the device
1609 default: // HID_PASS and later
1610 if (parent_priv->apib->id == USB_API_HID) {
1611 usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data);
1612 r = set_hid_interface(ctx, parent_dev, dev_interface_path);
1613 if (r != LIBUSB_SUCCESS)
1616 dev_interface_path = NULL;
1617 } else if (parent_priv->apib->id == USB_API_COMPOSITE) {
1618 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1619 switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api)) {
1620 case LIBUSB_SUCCESS:
1621 dev_interface_path = NULL;
1623 case LIBUSB_ERROR_ACCESS:
1624 // interface has already been set => make sure dev_interface_path is freed then
1631 libusb_unref_device(parent_dev);
1637 // Free any additional GUIDs
1638 for (pass = HID_PASS + 1; pass < nb_guids; pass++)
1639 safe_free(guid[pass]);
1641 // Unref newly allocated devs
1642 if (unref_list != NULL) {
1643 for (i = 0; i < unref_cur; i++)
1644 safe_unref_device(unref_list[i]);
1652 * exit: libusb backend deinitialization function
1654 static void windows_exit(void)
1658 char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0'
1660 sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF));
1661 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1662 if (semaphore == NULL)
1665 // A successful wait brings our semaphore count to 0 (unsignaled)
1666 // => any concurent wait stalls until the semaphore release
1667 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1668 CloseHandle(semaphore);
1672 // Only works if exits and inits are balanced exactly
1673 if (--concurrent_usage < 0) { // Last exit
1674 for (i = 0; i < USB_API_MAX; i++)
1675 usb_api_backend[i].exit(SUB_API_NOTSET);
1678 windows_common_exit();
1679 usbi_mutex_destroy(&autoclaim_lock);
1682 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1683 CloseHandle(semaphore);
1686 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1688 struct windows_device_priv *priv = _device_priv(dev);
1690 memcpy(buffer, &priv->dev_descriptor, DEVICE_DESC_LENGTH);
1693 return LIBUSB_SUCCESS;
1696 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1698 struct windows_device_priv *priv = _device_priv(dev);
1699 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1702 // config index is zero based
1703 if (config_index >= dev->num_configurations)
1704 return LIBUSB_ERROR_INVALID_PARAM;
1706 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1707 return LIBUSB_ERROR_NOT_FOUND;
1709 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1711 size = MIN(config_header->wTotalLength, len);
1712 memcpy(buffer, priv->config_descriptor[config_index], size);
1719 * return the cached copy of the active config descriptor
1721 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1723 struct windows_device_priv *priv = _device_priv(dev);
1725 if (priv->active_config == 0)
1726 return LIBUSB_ERROR_NOT_FOUND;
1728 // config index is zero based
1729 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1732 static int windows_open(struct libusb_device_handle *dev_handle)
1734 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1735 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1737 if (priv->apib == NULL) {
1738 usbi_err(ctx, "program assertion failed - device is not initialized");
1739 return LIBUSB_ERROR_NO_DEVICE;
1742 return priv->apib->open(SUB_API_NOTSET, dev_handle);
1745 static void windows_close(struct libusb_device_handle *dev_handle)
1747 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1749 priv->apib->close(SUB_API_NOTSET, dev_handle);
1752 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1754 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1756 if (priv->active_config == 0) {
1758 return LIBUSB_ERROR_NOT_FOUND;
1761 *config = priv->active_config;
1762 return LIBUSB_SUCCESS;
1766 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1767 * does not currently expose a service that allows higher-level drivers to set
1768 * the configuration."
1770 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1772 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1773 int r = LIBUSB_SUCCESS;
1775 if (config >= USB_MAXCONFIG)
1776 return LIBUSB_ERROR_INVALID_PARAM;
1778 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1779 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1780 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1783 if (r == LIBUSB_SUCCESS)
1784 priv->active_config = (uint8_t)config;
1789 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1791 int r = LIBUSB_SUCCESS;
1792 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1794 safe_free(priv->usb_interface[iface].endpoint);
1795 priv->usb_interface[iface].nb_endpoints = 0;
1797 r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
1799 if (r == LIBUSB_SUCCESS)
1800 r = windows_assign_endpoints(dev_handle, iface, 0);
1805 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1807 int r = LIBUSB_SUCCESS;
1808 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1810 safe_free(priv->usb_interface[iface].endpoint);
1811 priv->usb_interface[iface].nb_endpoints = 0;
1813 r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
1815 if (r == LIBUSB_SUCCESS)
1816 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1821 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1823 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1825 return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
1828 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1830 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1831 return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
1834 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1836 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1837 return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
1840 // The 3 functions below are unlikely to ever get supported on Windows
1841 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1843 return LIBUSB_ERROR_NOT_SUPPORTED;
1846 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1848 return LIBUSB_ERROR_NOT_SUPPORTED;
1851 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1853 return LIBUSB_ERROR_NOT_SUPPORTED;
1856 static void windows_destroy_device(struct libusb_device *dev)
1858 windows_device_priv_release(dev);
1861 void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1863 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1865 usbi_free_fd(&transfer_priv->pollable_fd);
1866 safe_free(transfer_priv->hid_buffer);
1867 // When auto claim is in use, attempt to release the auto-claimed interface
1868 auto_release(itransfer);
1871 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1873 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1874 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1875 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1876 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1879 r = priv->apib->submit_bulk_transfer(SUB_API_NOTSET, itransfer);
1880 if (r != LIBUSB_SUCCESS)
1883 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1884 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1886 return LIBUSB_SUCCESS;
1889 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1891 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1892 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1893 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1894 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1897 r = priv->apib->submit_iso_transfer(SUB_API_NOTSET, itransfer);
1898 if (r != LIBUSB_SUCCESS)
1901 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1902 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1904 return LIBUSB_SUCCESS;
1907 static int submit_control_transfer(struct usbi_transfer *itransfer)
1909 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1910 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1911 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1912 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1915 r = priv->apib->submit_control_transfer(SUB_API_NOTSET, itransfer);
1916 if (r != LIBUSB_SUCCESS)
1919 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1921 return LIBUSB_SUCCESS;
1924 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1926 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1928 switch (transfer->type) {
1929 case LIBUSB_TRANSFER_TYPE_CONTROL:
1930 return submit_control_transfer(itransfer);
1931 case LIBUSB_TRANSFER_TYPE_BULK:
1932 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1933 if (IS_XFEROUT(transfer) && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
1934 return LIBUSB_ERROR_NOT_SUPPORTED;
1935 return submit_bulk_transfer(itransfer);
1936 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1937 return submit_iso_transfer(itransfer);
1938 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1939 return LIBUSB_ERROR_NOT_SUPPORTED;
1941 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1942 return LIBUSB_ERROR_INVALID_PARAM;
1946 static int windows_abort_control(struct usbi_transfer *itransfer)
1948 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1949 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1951 return priv->apib->abort_control(SUB_API_NOTSET, itransfer);
1954 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1956 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1957 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1959 return priv->apib->abort_transfers(SUB_API_NOTSET, itransfer);
1962 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1964 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1966 switch (transfer->type) {
1967 case LIBUSB_TRANSFER_TYPE_CONTROL:
1968 return windows_abort_control(itransfer);
1969 case LIBUSB_TRANSFER_TYPE_BULK:
1970 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1971 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1972 return windows_abort_transfers(itransfer);
1973 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1974 return LIBUSB_ERROR_NOT_SUPPORTED;
1976 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1977 return LIBUSB_ERROR_INVALID_PARAM;
1981 int windows_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
1983 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1984 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1985 return priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
1988 struct winfd *windows_get_fd(struct usbi_transfer *transfer)
1990 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(transfer);
1991 return &transfer_priv->pollable_fd;
1994 void windows_get_overlapped_result(struct usbi_transfer *transfer, struct winfd *pollable_fd, DWORD *io_result, DWORD *io_size)
1996 if (HasOverlappedIoCompletedSync(pollable_fd->overlapped)) {
1997 *io_result = NO_ERROR;
1998 *io_size = (DWORD)pollable_fd->overlapped->InternalHigh;
2000 else if (GetOverlappedResult(pollable_fd->handle, pollable_fd->overlapped, io_size, false)) {
2001 // Regular async overlapped
2002 *io_result = NO_ERROR;
2005 *io_result = GetLastError();
2009 // NB: MSVC6 does not support named initializers.
2010 const struct usbi_os_backend windows_backend = {
2012 USBI_CAP_HAS_HID_ACCESS,
2016 windows_get_device_list,
2017 NULL, /* hotplug_poll */
2021 windows_get_device_descriptor,
2022 windows_get_active_config_descriptor,
2023 windows_get_config_descriptor,
2024 NULL, /* get_config_descriptor_by_value() */
2026 windows_get_configuration,
2027 windows_set_configuration,
2028 windows_claim_interface,
2029 windows_release_interface,
2031 windows_set_interface_altsetting,
2033 windows_reset_device,
2035 NULL, /* alloc_streams */
2036 NULL, /* free_streams */
2038 windows_kernel_driver_active,
2039 windows_detach_kernel_driver,
2040 windows_attach_kernel_driver,
2042 windows_destroy_device,
2044 windows_submit_transfer,
2045 windows_cancel_transfer,
2046 windows_clear_transfer_priv,
2048 windows_handle_events,
2051 windows_clock_gettime,
2052 #if defined(USBI_TIMERFD_AVAILABLE)
2055 sizeof(struct windows_device_priv),
2056 sizeof(struct windows_device_handle_priv),
2057 sizeof(struct windows_transfer_priv),
2064 static int unsupported_init(int sub_api, struct libusb_context *ctx)
2066 return LIBUSB_SUCCESS;
2069 static int unsupported_exit(int sub_api)
2071 return LIBUSB_SUCCESS;
2074 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle)
2076 PRINT_UNSUPPORTED_API(open);
2079 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle)
2081 usbi_dbg("unsupported API call for 'close'");
2084 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2086 PRINT_UNSUPPORTED_API(configure_endpoints);
2089 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2091 PRINT_UNSUPPORTED_API(claim_interface);
2094 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2096 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2099 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2101 PRINT_UNSUPPORTED_API(release_interface);
2104 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2106 PRINT_UNSUPPORTED_API(clear_halt);
2109 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2111 PRINT_UNSUPPORTED_API(reset_device);
2114 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2116 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2119 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
2121 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2124 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2126 PRINT_UNSUPPORTED_API(submit_control_transfer);
2129 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer)
2131 PRINT_UNSUPPORTED_API(abort_control);
2134 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2136 PRINT_UNSUPPORTED_API(abort_transfers);
2139 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2141 PRINT_UNSUPPORTED_API(copy_transfer_data);
2144 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2146 return LIBUSB_SUCCESS;
2149 // These names must be uppercase
2150 static const char *hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30", "VHHUB"};
2151 static const char *composite_driver_names[] = {"USBCCGP"};
2152 static const char *winusbx_driver_names[] = WINUSBX_DRV_NAMES;
2153 static const char *hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2154 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2156 USB_API_UNSUPPORTED,
2164 unsupported_configure_endpoints,
2165 unsupported_claim_interface,
2166 unsupported_set_interface_altsetting,
2167 unsupported_release_interface,
2168 unsupported_clear_halt,
2169 unsupported_reset_device,
2170 unsupported_submit_bulk_transfer,
2171 unsupported_submit_iso_transfer,
2172 unsupported_submit_control_transfer,
2173 unsupported_abort_control,
2174 unsupported_abort_transfers,
2175 unsupported_copy_transfer_data,
2181 ARRAYSIZE(hub_driver_names),
2186 unsupported_configure_endpoints,
2187 unsupported_claim_interface,
2188 unsupported_set_interface_altsetting,
2189 unsupported_release_interface,
2190 unsupported_clear_halt,
2191 unsupported_reset_device,
2192 unsupported_submit_bulk_transfer,
2193 unsupported_submit_iso_transfer,
2194 unsupported_submit_control_transfer,
2195 unsupported_abort_control,
2196 unsupported_abort_transfers,
2197 unsupported_copy_transfer_data,
2202 composite_driver_names,
2203 ARRAYSIZE(composite_driver_names),
2208 common_configure_endpoints,
2209 composite_claim_interface,
2210 composite_set_interface_altsetting,
2211 composite_release_interface,
2212 composite_clear_halt,
2213 composite_reset_device,
2214 composite_submit_bulk_transfer,
2215 composite_submit_iso_transfer,
2216 composite_submit_control_transfer,
2217 composite_abort_control,
2218 composite_abort_transfers,
2219 composite_copy_transfer_data,
2224 winusbx_driver_names,
2225 ARRAYSIZE(winusbx_driver_names),
2230 winusbx_configure_endpoints,
2231 winusbx_claim_interface,
2232 winusbx_set_interface_altsetting,
2233 winusbx_release_interface,
2235 winusbx_reset_device,
2236 winusbx_submit_bulk_transfer,
2237 unsupported_submit_iso_transfer,
2238 winusbx_submit_control_transfer,
2239 winusbx_abort_control,
2240 winusbx_abort_transfers,
2241 winusbx_copy_transfer_data,
2247 ARRAYSIZE(hid_driver_names),
2252 common_configure_endpoints,
2253 hid_claim_interface,
2254 hid_set_interface_altsetting,
2255 hid_release_interface,
2258 hid_submit_bulk_transfer,
2259 unsupported_submit_iso_transfer,
2260 hid_submit_control_transfer,
2261 hid_abort_transfers,
2262 hid_abort_transfers,
2263 hid_copy_transfer_data,
2269 * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2271 #define WinUSBX_Set(fn) \
2273 if (native_winusb) \
2274 WinUSBX[i].fn = (WinUsb_##fn##_t)GetProcAddress(h, "WinUsb_" #fn); \
2276 pLibK_GetProcAddress((PVOID *)&WinUSBX[i].fn, i, KUSB_FNID_##fn); \
2279 static int winusbx_init(int sub_api, struct libusb_context *ctx)
2284 KLIB_VERSION LibK_Version;
2285 LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
2286 LibK_GetVersion_t pLibK_GetVersion;
2288 h = LoadLibraryA("libusbK");
2291 usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
2292 h = LoadLibraryA("WinUSB");
2295 usbi_warn(ctx, "WinUSB DLL is not available either, "
2296 "you will not be able to access devices outside of enumeration");
2297 return LIBUSB_ERROR_NOT_FOUND;
2300 usbi_dbg("using libusbK DLL for universal access");
2301 pLibK_GetVersion = (LibK_GetVersion_t)GetProcAddress(h, "LibK_GetVersion");
2302 if (pLibK_GetVersion != NULL) {
2303 pLibK_GetVersion(&LibK_Version);
2304 usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2305 LibK_Version.Micro, LibK_Version.Nano);
2307 pLibK_GetProcAddress = (LibK_GetProcAddress_t)GetProcAddress(h, "LibK_GetProcAddress");
2308 if (pLibK_GetProcAddress == NULL) {
2309 usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2311 return LIBUSB_ERROR_NOT_FOUND;
2315 native_winusb = (pLibK_GetProcAddress == NULL);
2316 for (i = SUB_API_LIBUSBK; i < SUB_API_MAX; i++) {
2317 WinUSBX_Set(AbortPipe);
2318 WinUSBX_Set(ControlTransfer);
2319 WinUSBX_Set(FlushPipe);
2321 WinUSBX_Set(GetAssociatedInterface);
2322 WinUSBX_Set(GetCurrentAlternateSetting);
2323 WinUSBX_Set(GetDescriptor);
2324 WinUSBX_Set(GetOverlappedResult);
2325 WinUSBX_Set(GetPipePolicy);
2326 WinUSBX_Set(GetPowerPolicy);
2327 WinUSBX_Set(Initialize);
2328 WinUSBX_Set(QueryDeviceInformation);
2329 WinUSBX_Set(QueryInterfaceSettings);
2330 WinUSBX_Set(QueryPipe);
2331 WinUSBX_Set(ReadPipe);
2332 WinUSBX_Set(ResetPipe);
2333 WinUSBX_Set(SetCurrentAlternateSetting);
2334 WinUSBX_Set(SetPipePolicy);
2335 WinUSBX_Set(SetPowerPolicy);
2336 WinUSBX_Set(WritePipe);
2338 WinUSBX_Set(ResetDevice);
2340 if (WinUSBX[i].Initialize != NULL) {
2341 WinUSBX[i].initialized = true;
2342 usbi_dbg("initalized sub API %s", sub_api_name[i]);
2344 usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
2345 WinUSBX[i].initialized = false;
2350 return LIBUSB_SUCCESS;
2353 static int winusbx_exit(int sub_api)
2355 if (WinUSBX_handle != NULL) {
2356 FreeLibrary(WinUSBX_handle);
2357 WinUSBX_handle = NULL;
2359 /* Reset the WinUSBX API structures */
2360 memset(&WinUSBX, 0, sizeof(WinUSBX));
2363 return LIBUSB_SUCCESS;
2366 // NB: open and close must ensure that they only handle interface of
2367 // the right API type, as these functions can be called wholesale from
2368 // composite_open(), with interfaces belonging to different APIs
2369 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2371 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2372 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2373 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2378 CHECK_WINUSBX_AVAILABLE(sub_api);
2380 // WinUSB requires a separate handle for each interface
2381 for (i = 0; i < USB_MAXINTERFACES; i++) {
2382 if ((priv->usb_interface[i].path != NULL)
2383 && (priv->usb_interface[i].apib->id == USB_API_WINUSBX)) {
2384 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2385 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2386 if (file_handle == INVALID_HANDLE_VALUE) {
2387 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2388 switch(GetLastError()) {
2389 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2390 return LIBUSB_ERROR_NO_DEVICE;
2391 case ERROR_ACCESS_DENIED:
2392 return LIBUSB_ERROR_ACCESS;
2394 return LIBUSB_ERROR_IO;
2397 handle_priv->interface_handle[i].dev_handle = file_handle;
2401 return LIBUSB_SUCCESS;
2404 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2406 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2407 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2411 if (sub_api == SUB_API_NOTSET)
2412 sub_api = priv->sub_api;
2414 if (!WinUSBX[sub_api].initialized)
2417 if (priv->apib->id == USB_API_COMPOSITE) {
2418 // If this is a composite device, just free and close all WinUSB-like
2419 // interfaces directly (each is independent and not associated with another)
2420 for (i = 0; i < USB_MAXINTERFACES; i++) {
2421 if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2422 handle = handle_priv->interface_handle[i].api_handle;
2423 if (HANDLE_VALID(handle))
2424 WinUSBX[sub_api].Free(handle);
2426 handle = handle_priv->interface_handle[i].dev_handle;
2427 if (HANDLE_VALID(handle))
2428 CloseHandle(handle);
2433 // If this is a WinUSB device, free all interfaces above interface 0,
2434 // then free and close interface 0 last
2435 for (i = 1; i < USB_MAXINTERFACES; i++) {
2436 handle = handle_priv->interface_handle[i].api_handle;
2437 if (HANDLE_VALID(handle))
2438 WinUSBX[sub_api].Free(handle);
2440 handle = handle_priv->interface_handle[0].api_handle;
2441 if (HANDLE_VALID(handle))
2442 WinUSBX[sub_api].Free(handle);
2444 handle = handle_priv->interface_handle[0].dev_handle;
2445 if (HANDLE_VALID(handle))
2446 CloseHandle(handle);
2450 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2452 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2453 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2454 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2457 uint8_t endpoint_address;
2460 CHECK_WINUSBX_AVAILABLE(sub_api);
2462 // With handle and enpoints set (in parent), we can setup the default pipe properties
2463 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2464 for (i = -1; i < priv->usb_interface[iface].nb_endpoints; i++) {
2465 endpoint_address = (i == -1) ? 0 : priv->usb_interface[iface].endpoint[i];
2466 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2467 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout))
2468 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2470 if ((i == -1) || (sub_api == SUB_API_LIBUSB0))
2471 continue; // Other policies don't apply to control endpoint or libusb0
2474 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2475 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy))
2476 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2478 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2479 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy))
2480 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2483 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2484 https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2485 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2486 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy))
2487 usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2489 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2490 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy))
2491 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2494 return LIBUSB_SUCCESS;
2497 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2499 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2500 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2501 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2502 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2503 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
2504 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2505 SP_DEVINFO_DATA dev_info_data;
2506 char *dev_path_no_guid = NULL;
2507 char filter_path[] = "\\\\.\\libusb0-0000";
2508 bool found_filter = false;
2509 HANDLE file_handle, winusb_handle;
2513 CHECK_WINUSBX_AVAILABLE(sub_api);
2515 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2516 // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2517 if ((is_using_usbccgp) || (iface == 0)) {
2518 // composite device (independent interfaces) or interface 0
2519 file_handle = handle_priv->interface_handle[iface].dev_handle;
2520 if (!HANDLE_VALID(file_handle))
2521 return LIBUSB_ERROR_NOT_FOUND;
2523 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2524 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2525 err = GetLastError();
2527 case ERROR_BAD_COMMAND:
2528 // The device was disconnected
2529 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2530 return LIBUSB_ERROR_NO_DEVICE;
2532 // it may be that we're using the libusb0 filter driver.
2533 // TODO: can we move this whole business into the K/0 DLL?
2534 for (i = 0; ; i++) {
2535 safe_free(dev_interface_details);
2536 safe_free(dev_path_no_guid);
2537 dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
2538 if ((found_filter) || (dev_interface_details == NULL))
2542 dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
2543 if (safe_strncmp(dev_path_no_guid, priv->usb_interface[iface].path, safe_strlen(dev_path_no_guid)) == 0) {
2544 file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2545 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2546 if (file_handle == INVALID_HANDLE_VALUE) {
2547 usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2549 WinUSBX[sub_api].Free(winusb_handle);
2550 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle))
2551 found_filter = true;
2553 usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
2557 if (!found_filter) {
2558 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
2559 return LIBUSB_ERROR_ACCESS;
2563 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2565 // For all other interfaces, use GetAssociatedInterface()
2566 winusb_handle = handle_priv->interface_handle[0].api_handle;
2567 // It is a requirement for multiple interface devices on Windows that, to you
2568 // must first claim the first interface before you claim the others
2569 if (!HANDLE_VALID(winusb_handle)) {
2570 file_handle = handle_priv->interface_handle[0].dev_handle;
2571 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2572 handle_priv->interface_handle[0].api_handle = winusb_handle;
2573 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2575 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
2576 return LIBUSB_ERROR_ACCESS;
2579 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface - 1),
2580 &handle_priv->interface_handle[iface].api_handle)) {
2581 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2582 switch(GetLastError()) {
2583 case ERROR_NO_MORE_ITEMS: // invalid iface
2584 return LIBUSB_ERROR_NOT_FOUND;
2585 case ERROR_BAD_COMMAND: // The device was disconnected
2586 return LIBUSB_ERROR_NO_DEVICE;
2587 case ERROR_ALREADY_EXISTS: // already claimed
2588 return LIBUSB_ERROR_BUSY;
2590 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2591 return LIBUSB_ERROR_ACCESS;
2595 usbi_dbg("claimed interface %d", iface);
2596 handle_priv->active_interface = iface;
2598 return LIBUSB_SUCCESS;
2601 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2603 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2604 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2605 HANDLE winusb_handle;
2607 CHECK_WINUSBX_AVAILABLE(sub_api);
2609 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2610 if (!HANDLE_VALID(winusb_handle))
2611 return LIBUSB_ERROR_NOT_FOUND;
2613 WinUSBX[sub_api].Free(winusb_handle);
2614 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2616 return LIBUSB_SUCCESS;
2620 * Return the first valid interface (of the same API type), for control transfers
2622 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2624 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2625 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2628 if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2629 usbi_dbg("unsupported API ID");
2633 for (i = 0; i < USB_MAXINTERFACES; i++) {
2634 if (HANDLE_VALID(handle_priv->interface_handle[i].dev_handle)
2635 && HANDLE_VALID(handle_priv->interface_handle[i].api_handle)
2636 && (priv->usb_interface[i].apib->id == api_id))
2644 * Lookup interface by endpoint address. -1 if not found
2646 static int interface_by_endpoint(struct windows_device_priv *priv,
2647 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2651 for (i = 0; i < USB_MAXINTERFACES; i++) {
2652 if (!HANDLE_VALID(handle_priv->interface_handle[i].api_handle))
2654 if (priv->usb_interface[i].endpoint == NULL)
2656 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2657 if (priv->usb_interface[i].endpoint[j] == endpoint_address)
2665 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2667 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2668 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2669 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2670 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2671 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2672 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
2674 HANDLE winusb_handle;
2675 int current_interface;
2678 CHECK_WINUSBX_AVAILABLE(sub_api);
2680 transfer_priv->pollable_fd = INVALID_WINFD;
2681 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2683 // Windows places upper limits on the control transfer size
2684 // See: https://msdn.microsoft.com/en-us/library/windows/hardware/ff538112.aspx
2685 if (size > MAX_CTRL_BUFFER_LENGTH)
2686 return LIBUSB_ERROR_INVALID_PARAM;
2688 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
2689 if (current_interface < 0) {
2690 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS)
2691 return LIBUSB_ERROR_NOT_FOUND;
2694 usbi_dbg("will use interface %d", current_interface);
2695 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2697 wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
2698 // Always use the handle returned from usbi_create_fd (wfd.handle)
2700 return LIBUSB_ERROR_NO_MEM;
2702 // Sending of set configuration control requests from WinUSB creates issues
2703 if (((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
2704 && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION)) {
2705 if (setup->value != priv->active_config) {
2706 usbi_warn(ctx, "cannot set configuration other than the default one");
2708 return LIBUSB_ERROR_INVALID_PARAM;
2710 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2711 wfd.overlapped->InternalHigh = 0;
2713 if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2714 if (GetLastError() != ERROR_IO_PENDING) {
2715 usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
2717 return LIBUSB_ERROR_IO;
2720 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2721 wfd.overlapped->InternalHigh = (DWORD)size;
2725 // Use priv_transfer to store data needed for async polling
2726 transfer_priv->pollable_fd = wfd;
2727 transfer_priv->interface_number = (uint8_t)current_interface;
2729 return LIBUSB_SUCCESS;
2732 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2734 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2735 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2736 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2737 HANDLE winusb_handle;
2739 CHECK_WINUSBX_AVAILABLE(sub_api);
2741 if (altsetting > 255)
2742 return LIBUSB_ERROR_INVALID_PARAM;
2744 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2745 if (!HANDLE_VALID(winusb_handle)) {
2746 usbi_err(ctx, "interface must be claimed first");
2747 return LIBUSB_ERROR_NOT_FOUND;
2750 if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2751 usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2752 return LIBUSB_ERROR_IO;
2755 return LIBUSB_SUCCESS;
2758 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2760 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2761 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2762 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2763 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2764 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2765 HANDLE winusb_handle;
2767 int current_interface;
2770 CHECK_WINUSBX_AVAILABLE(sub_api);
2772 transfer_priv->pollable_fd = INVALID_WINFD;
2774 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2775 if (current_interface < 0) {
2776 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2777 return LIBUSB_ERROR_NOT_FOUND;
2780 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2782 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2784 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
2785 // Always use the handle returned from usbi_create_fd (wfd.handle)
2787 return LIBUSB_ERROR_NO_MEM;
2789 if (IS_XFERIN(transfer)) {
2790 usbi_dbg("reading %d bytes", transfer->length);
2791 ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2793 usbi_dbg("writing %d bytes", transfer->length);
2794 ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2798 if (GetLastError() != ERROR_IO_PENDING) {
2799 usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
2801 return LIBUSB_ERROR_IO;
2804 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2805 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2808 transfer_priv->pollable_fd = wfd;
2809 transfer_priv->interface_number = (uint8_t)current_interface;
2811 return LIBUSB_SUCCESS;
2814 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2816 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2817 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2818 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2819 HANDLE winusb_handle;
2820 int current_interface;
2822 CHECK_WINUSBX_AVAILABLE(sub_api);
2824 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2825 if (current_interface < 0) {
2826 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2827 return LIBUSB_ERROR_NOT_FOUND;
2830 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2831 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2833 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
2834 usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
2835 return LIBUSB_ERROR_NO_DEVICE;
2838 return LIBUSB_SUCCESS;
2842 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2843 * through testing as well):
2844 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2845 * the control transfer using CancelIo"
2847 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
2849 // Cancelling of the I/O is done in the parent
2850 return LIBUSB_SUCCESS;
2853 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2855 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2856 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2857 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2858 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2859 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2860 HANDLE winusb_handle;
2861 int current_interface;
2863 CHECK_WINUSBX_AVAILABLE(sub_api);
2865 current_interface = transfer_priv->interface_number;
2866 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2867 usbi_err(ctx, "program assertion failed: invalid interface_number");
2868 return LIBUSB_ERROR_NOT_FOUND;
2870 usbi_dbg("will use interface %d", current_interface);
2872 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2874 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
2875 usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
2876 return LIBUSB_ERROR_NO_DEVICE;
2879 return LIBUSB_SUCCESS;
2883 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2884 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2885 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2886 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2887 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2888 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2890 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2891 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2893 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2894 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2895 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2897 HANDLE winusb_handle;
2900 CHECK_WINUSBX_AVAILABLE(sub_api);
2902 // Reset any available pipe (except control)
2903 for (i = 0; i < USB_MAXINTERFACES; i++) {
2904 winusb_handle = handle_priv->interface_handle[i].api_handle;
2905 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0; ) {
2906 // Cancel any pollable I/O
2907 usbi_remove_pollfd(ctx, wfd.fd);
2909 wfd = handle_to_winfd(winusb_handle);
2912 if (HANDLE_VALID(winusb_handle)) {
2913 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2914 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2915 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2916 usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
2917 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2919 // FlushPipe seems to fail on OUT pipes
2920 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
2921 && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])))
2922 usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
2923 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2925 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2926 usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
2927 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2932 // libusbK & libusb0 have the ability to issue an actual device reset
2933 if (WinUSBX[sub_api].ResetDevice != NULL) {
2934 winusb_handle = handle_priv->interface_handle[0].api_handle;
2935 if (HANDLE_VALID(winusb_handle))
2936 WinUSBX[sub_api].ResetDevice(winusb_handle);
2939 return LIBUSB_SUCCESS;
2942 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2944 itransfer->transferred += io_size;
2945 return LIBUSB_TRANSFER_COMPLETED;
2949 * Internal HID Support functions (from libusb-win32)
2950 * Note that functions that complete data transfer synchronously must return
2951 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
2953 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
2954 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
2956 static int _hid_wcslen(WCHAR *str)
2960 while (str[i] && (str[i] != 0x409))
2966 static int _hid_get_device_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
2968 struct libusb_device_descriptor d;
2970 d.bLength = LIBUSB_DT_DEVICE_SIZE;
2971 d.bDescriptorType = LIBUSB_DT_DEVICE;
2972 d.bcdUSB = 0x0200; /* 2.00 */
2974 d.bDeviceSubClass = 0;
2975 d.bDeviceProtocol = 0;
2976 d.bMaxPacketSize0 = 64; /* fix this! */
2977 d.idVendor = (uint16_t)dev->vid;
2978 d.idProduct = (uint16_t)dev->pid;
2979 d.bcdDevice = 0x0100;
2980 d.iManufacturer = dev->string_index[0];
2981 d.iProduct = dev->string_index[1];
2982 d.iSerialNumber = dev->string_index[2];
2983 d.bNumConfigurations = 1;
2985 if (*size > LIBUSB_DT_DEVICE_SIZE)
2986 *size = LIBUSB_DT_DEVICE_SIZE;
2987 memcpy(data, &d, *size);
2989 return LIBUSB_COMPLETED;
2992 static int _hid_get_config_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
2994 char num_endpoints = 0;
2995 size_t config_total_len = 0;
2996 char tmp[HID_MAX_CONFIG_DESC_SIZE];
2997 struct libusb_config_descriptor *cd;
2998 struct libusb_interface_descriptor *id;
2999 struct libusb_hid_descriptor *hd;
3000 struct libusb_endpoint_descriptor *ed;
3003 if (dev->input_report_size)
3005 if (dev->output_report_size)
3008 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3009 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3011 cd = (struct libusb_config_descriptor *)tmp;
3012 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3013 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3014 + LIBUSB_DT_INTERFACE_SIZE);
3015 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3016 + LIBUSB_DT_INTERFACE_SIZE
3017 + LIBUSB_DT_HID_SIZE);
3019 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3020 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3021 cd->wTotalLength = (uint16_t)config_total_len;
3022 cd->bNumInterfaces = 1;
3023 cd->bConfigurationValue = 1;
3024 cd->iConfiguration = 0;
3025 cd->bmAttributes = 1 << 7; /* bus powered */
3028 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3029 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3030 id->bInterfaceNumber = 0;
3031 id->bAlternateSetting = 0;
3032 id->bNumEndpoints = num_endpoints;
3033 id->bInterfaceClass = 3;
3034 id->bInterfaceSubClass = 0;
3035 id->bInterfaceProtocol = 0;
3038 tmp_size = LIBUSB_DT_HID_SIZE;
3039 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3041 if (dev->input_report_size) {
3042 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3043 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3044 ed->bEndpointAddress = HID_IN_EP;
3045 ed->bmAttributes = 3;
3046 ed->wMaxPacketSize = dev->input_report_size - 1;
3048 ed = (struct libusb_endpoint_descriptor *)((char *)ed + LIBUSB_DT_ENDPOINT_SIZE);
3051 if (dev->output_report_size) {
3052 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3053 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3054 ed->bEndpointAddress = HID_OUT_EP;
3055 ed->bmAttributes = 3;
3056 ed->wMaxPacketSize = dev->output_report_size - 1;
3060 if (*size > config_total_len)
3061 *size = config_total_len;
3062 memcpy(data, tmp, *size);
3064 return LIBUSB_COMPLETED;
3067 static int _hid_get_string_descriptor(struct hid_device_priv *dev, int _index,
3068 void *data, size_t *size)
3071 size_t tmp_size = 0;
3074 /* language ID, EN-US */
3075 char string_langid[] = {0x09, 0x04};
3077 if ((*size < 2) || (*size > 255))
3078 return LIBUSB_ERROR_OVERFLOW;
3081 tmp = string_langid;
3082 tmp_size = sizeof(string_langid) + 2;
3084 for (i = 0; i < 3; i++) {
3085 if (_index == (dev->string_index[i])) {
3086 tmp = dev->string[i];
3087 tmp_size = (_hid_wcslen(dev->string[i]) + 1) * sizeof(WCHAR);
3092 if (i == 3) // not found
3093 return LIBUSB_ERROR_INVALID_PARAM;
3097 return LIBUSB_ERROR_INVALID_PARAM;
3099 if (tmp_size < *size)
3103 ((uint8_t *)data)[0] = (uint8_t)*size;
3104 ((uint8_t *)data)[1] = LIBUSB_DT_STRING;
3105 memcpy((uint8_t *)data + 2, tmp, *size - 2);
3107 return LIBUSB_COMPLETED;
3110 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3112 struct libusb_hid_descriptor d;
3113 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3114 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3116 _hid_get_report_descriptor(dev, tmp, &report_len);
3118 d.bLength = LIBUSB_DT_HID_SIZE;
3119 d.bDescriptorType = LIBUSB_DT_HID;
3120 d.bcdHID = 0x0110; /* 1.10 */
3122 d.bNumDescriptors = 1;
3123 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3124 d.wClassDescriptorLength = (uint16_t)report_len;
3126 if (*size > LIBUSB_DT_HID_SIZE)
3127 *size = LIBUSB_DT_HID_SIZE;
3128 memcpy(data, &d, *size);
3130 return LIBUSB_COMPLETED;
3133 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3135 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3138 /* usage page (0xFFA0 == vendor defined) */
3139 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3140 /* usage (vendor defined) */
3141 d[i++] = 0x09; d[i++] = 0x01;
3142 /* start collection (application) */
3143 d[i++] = 0xA1; d[i++] = 0x01;
3145 if (dev->input_report_size) {
3146 /* usage (vendor defined) */
3147 d[i++] = 0x09; d[i++] = 0x01;
3148 /* logical minimum (0) */
3149 d[i++] = 0x15; d[i++] = 0x00;
3150 /* logical maximum (255) */
3151 d[i++] = 0x25; d[i++] = 0xFF;
3152 /* report size (8 bits) */
3153 d[i++] = 0x75; d[i++] = 0x08;
3155 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3156 /* input (data, variable, absolute) */
3157 d[i++] = 0x81; d[i++] = 0x00;
3160 if (dev->output_report_size) {
3161 /* usage (vendor defined) */
3162 d[i++] = 0x09; d[i++] = 0x02;
3163 /* logical minimum (0) */
3164 d[i++] = 0x15; d[i++] = 0x00;
3165 /* logical maximum (255) */
3166 d[i++] = 0x25; d[i++] = 0xFF;
3167 /* report size (8 bits) */
3168 d[i++] = 0x75; d[i++] = 0x08;
3170 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3171 /* output (data, variable, absolute) */
3172 d[i++] = 0x91; d[i++] = 0x00;
3174 /* feature report */
3175 if (dev->feature_report_size) {
3176 /* usage (vendor defined) */
3177 d[i++] = 0x09; d[i++] = 0x03;
3178 /* logical minimum (0) */
3179 d[i++] = 0x15; d[i++] = 0x00;
3180 /* logical maximum (255) */
3181 d[i++] = 0x25; d[i++] = 0xFF;
3182 /* report size (8 bits) */
3183 d[i++] = 0x75; d[i++] = 0x08;
3185 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3186 /* feature (data, variable, absolute) */
3187 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3190 /* end collection */
3195 memcpy(data, d, *size);
3197 return LIBUSB_COMPLETED;
3200 static int _hid_get_descriptor(struct hid_device_priv *dev, HANDLE hid_handle, int recipient,
3201 int type, int _index, void *data, size_t *size)
3204 case LIBUSB_DT_DEVICE:
3205 usbi_dbg("LIBUSB_DT_DEVICE");
3206 return _hid_get_device_descriptor(dev, data, size);
3207 case LIBUSB_DT_CONFIG:
3208 usbi_dbg("LIBUSB_DT_CONFIG");
3210 return _hid_get_config_descriptor(dev, data, size);
3211 return LIBUSB_ERROR_INVALID_PARAM;
3212 case LIBUSB_DT_STRING:
3213 usbi_dbg("LIBUSB_DT_STRING");
3214 return _hid_get_string_descriptor(dev, _index, data, size);
3216 usbi_dbg("LIBUSB_DT_HID");
3218 return _hid_get_hid_descriptor(dev, data, size);
3219 return LIBUSB_ERROR_INVALID_PARAM;
3220 case LIBUSB_DT_REPORT:
3221 usbi_dbg("LIBUSB_DT_REPORT");
3223 return _hid_get_report_descriptor(dev, data, size);
3224 return LIBUSB_ERROR_INVALID_PARAM;
3225 case LIBUSB_DT_PHYSICAL:
3226 usbi_dbg("LIBUSB_DT_PHYSICAL");
3227 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3228 return LIBUSB_COMPLETED;
3229 return LIBUSB_ERROR_OTHER;
3232 usbi_dbg("unsupported");
3233 return LIBUSB_ERROR_NOT_SUPPORTED;
3236 static int _hid_get_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3237 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3240 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3241 int r = LIBUSB_SUCCESS;
3243 if (tp->hid_buffer != NULL)
3244 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3246 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3247 usbi_dbg("invalid size (%u)", *size);
3248 return LIBUSB_ERROR_INVALID_PARAM;
3251 switch (report_type) {
3252 case HID_REPORT_TYPE_INPUT:
3253 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3255 case HID_REPORT_TYPE_FEATURE:
3256 ioctl_code = IOCTL_HID_GET_FEATURE;
3259 usbi_dbg("unknown HID report type %d", report_type);
3260 return LIBUSB_ERROR_INVALID_PARAM;
3263 // Add a trailing byte to detect overflows
3264 buf = calloc(1, expected_size + 1);
3266 return LIBUSB_ERROR_NO_MEM;
3268 buf[0] = (uint8_t)id; // Must be set always
3269 usbi_dbg("report ID: 0x%02X", buf[0]);
3271 tp->hid_expected_size = expected_size;
3272 read_size = expected_size;
3274 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3275 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size + 1,
3276 buf, expected_size + 1, &read_size, overlapped)) {
3277 if (GetLastError() != ERROR_IO_PENDING) {
3278 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3280 return LIBUSB_ERROR_IO;
3282 // Asynchronous wait
3283 tp->hid_buffer = buf;
3284 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3285 return LIBUSB_SUCCESS;
3288 // Transfer completed synchronously => copy and discard extra buffer
3289 if (read_size == 0) {
3290 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3294 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3296 if ((size_t)read_size > expected_size) {
3297 r = LIBUSB_ERROR_OVERFLOW;
3298 usbi_dbg("OVERFLOW!");
3300 r = LIBUSB_COMPLETED;
3303 *size = MIN((size_t)read_size, *size);
3305 memcpy(data, buf + 1, *size); // Discard report ID
3307 memcpy(data, buf, *size);
3314 static int _hid_set_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3315 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3317 uint8_t *buf = NULL;
3318 DWORD ioctl_code, write_size = (DWORD)*size;
3320 if (tp->hid_buffer != NULL)
3321 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3323 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3324 usbi_dbg("invalid size (%u)", *size);
3325 return LIBUSB_ERROR_INVALID_PARAM;
3328 switch (report_type) {
3329 case HID_REPORT_TYPE_OUTPUT:
3330 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3332 case HID_REPORT_TYPE_FEATURE:
3333 ioctl_code = IOCTL_HID_SET_FEATURE;
3336 usbi_dbg("unknown HID report type %d", report_type);
3337 return LIBUSB_ERROR_INVALID_PARAM;
3340 usbi_dbg("report ID: 0x%02X", id);
3341 // When report IDs are not used (i.e. when id == 0), we must add
3342 // a null report ID. Otherwise, we just use original data buffer
3346 buf = malloc(write_size);
3348 return LIBUSB_ERROR_NO_MEM;
3352 memcpy(buf + 1, data, *size);
3354 // This seems like a waste, but if we don't duplicate the
3355 // data, we'll get issues when freeing hid_buffer
3356 memcpy(buf, data, *size);
3358 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3361 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3362 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3363 buf, write_size, &write_size, overlapped)) {
3364 if (GetLastError() != ERROR_IO_PENDING) {
3365 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3367 return LIBUSB_ERROR_IO;
3369 tp->hid_buffer = buf;
3370 tp->hid_dest = NULL;
3371 return LIBUSB_SUCCESS;
3374 // Transfer completed synchronously
3376 if (write_size == 0)
3377 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3380 return LIBUSB_COMPLETED;
3383 static int _hid_class_request(struct hid_device_priv *dev, HANDLE hid_handle, int request_type,
3384 int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3385 size_t *size, OVERLAPPED *overlapped)
3387 int report_type = (value >> 8) & 0xFF;
3388 int report_id = value & 0xFF;
3390 if ((LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3391 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE))
3392 return LIBUSB_ERROR_INVALID_PARAM;
3394 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3395 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3397 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3398 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3400 return LIBUSB_ERROR_INVALID_PARAM;
3407 static int hid_init(int sub_api, struct libusb_context *ctx)
3409 DLL_GET_HANDLE(hid);
3410 DLL_LOAD_FUNC(hid, HidD_GetAttributes, TRUE);
3411 DLL_LOAD_FUNC(hid, HidD_GetHidGuid, TRUE);
3412 DLL_LOAD_FUNC(hid, HidD_GetPreparsedData, TRUE);
3413 DLL_LOAD_FUNC(hid, HidD_FreePreparsedData, TRUE);
3414 DLL_LOAD_FUNC(hid, HidD_GetManufacturerString, TRUE);
3415 DLL_LOAD_FUNC(hid, HidD_GetProductString, TRUE);
3416 DLL_LOAD_FUNC(hid, HidD_GetSerialNumberString, TRUE);
3417 DLL_LOAD_FUNC(hid, HidP_GetCaps, TRUE);
3418 DLL_LOAD_FUNC(hid, HidD_SetNumInputBuffers, TRUE);
3419 DLL_LOAD_FUNC(hid, HidD_SetFeature, TRUE);
3420 DLL_LOAD_FUNC(hid, HidD_GetFeature, TRUE);
3421 DLL_LOAD_FUNC(hid, HidD_GetPhysicalDescriptor, TRUE);
3422 DLL_LOAD_FUNC(hid, HidD_GetInputReport, FALSE);
3423 DLL_LOAD_FUNC(hid, HidD_SetOutputReport, FALSE);
3424 DLL_LOAD_FUNC(hid, HidD_FlushQueue, TRUE);
3425 DLL_LOAD_FUNC(hid, HidP_GetValueCaps, TRUE);
3427 api_hid_available = true;
3428 return LIBUSB_SUCCESS;
3431 static int hid_exit(int sub_api)
3433 DLL_FREE_HANDLE(hid);
3435 return LIBUSB_SUCCESS;
3438 // NB: open and close must ensure that they only handle interface of
3439 // the right API type, as these functions can be called wholesale from
3440 // composite_open(), with interfaces belonging to different APIs
3441 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3443 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3444 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3445 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3446 HIDD_ATTRIBUTES hid_attributes;
3447 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3448 HIDP_CAPS capabilities;
3449 HIDP_VALUE_CAPS *value_caps;
3450 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3452 // report IDs handling
3454 int nb_ids[2]; // zero and nonzero report IDs
3455 #if defined(ENABLE_LOGGING)
3456 const char *type[3] = {"input", "output", "feature"};
3459 CHECK_HID_AVAILABLE;
3461 if (priv->hid == NULL) {
3462 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3463 return LIBUSB_ERROR_NOT_FOUND;
3466 for (i = 0; i < USB_MAXINTERFACES; i++) {
3467 if ((priv->usb_interface[i].path != NULL)
3468 && (priv->usb_interface[i].apib->id == USB_API_HID)) {
3469 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3470 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3472 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3473 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3474 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3475 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3476 * HidD_GetFeature (if the device supports Feature reports)."
3478 if (hid_handle == INVALID_HANDLE_VALUE) {
3479 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3480 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3481 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3482 if (hid_handle == INVALID_HANDLE_VALUE) {
3483 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3484 switch(GetLastError()) {
3485 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3486 return LIBUSB_ERROR_NO_DEVICE;
3487 case ERROR_ACCESS_DENIED:
3488 return LIBUSB_ERROR_ACCESS;
3490 return LIBUSB_ERROR_IO;
3493 priv->usb_interface[i].restricted_functionality = true;
3495 handle_priv->interface_handle[i].api_handle = hid_handle;
3499 hid_attributes.Size = sizeof(hid_attributes);
3501 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3502 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3506 priv->hid->vid = hid_attributes.VendorID;
3507 priv->hid->pid = hid_attributes.ProductID;
3509 // Set the maximum available input buffer size
3510 for (i = 32; HidD_SetNumInputBuffers(hid_handle, i); i *= 2);
3511 usbi_dbg("set maximum input buffer size to %d", i / 2);
3513 // Get the maximum input and output report size
3514 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3515 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3518 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3519 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3523 // Find out if interrupt will need report IDs
3524 size[0] = capabilities.NumberInputValueCaps;
3525 size[1] = capabilities.NumberOutputValueCaps;
3526 size[2] = capabilities.NumberFeatureValueCaps;
3527 for (j = HidP_Input; j <= HidP_Feature; j++) {
3528 usbi_dbg("%u HID %s report value(s) found", (unsigned int)size[j], type[j]);
3529 priv->hid->uses_report_ids[j] = false;
3531 value_caps = calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3532 if ((value_caps != NULL)
3533 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3534 && (size[j] >= 1)) {
3537 for (i = 0; i < (int)size[j]; i++) {
3538 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3539 if (value_caps[i].ReportID != 0)
3544 if (nb_ids[1] != 0) {
3546 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3548 priv->hid->uses_report_ids[j] = true;
3551 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3553 safe_free(value_caps);
3557 // Set the report sizes
3558 priv->hid->input_report_size = capabilities.InputReportByteLength;
3559 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3560 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3562 // Fetch string descriptors
3563 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3564 if (priv->hid->string_index[0] != 0)
3565 HidD_GetManufacturerString(hid_handle, priv->hid->string[0], sizeof(priv->hid->string[0]));
3567 priv->hid->string[0][0] = 0;
3569 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3570 if (priv->hid->string_index[1] != 0)
3571 HidD_GetProductString(hid_handle, priv->hid->string[1], sizeof(priv->hid->string[1]));
3573 priv->hid->string[1][0] = 0;
3575 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3576 if (priv->hid->string_index[2] != 0)
3577 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2], sizeof(priv->hid->string[2]));
3579 priv->hid->string[2][0] = 0;
3583 HidD_FreePreparsedData(preparsed_data);
3585 return LIBUSB_SUCCESS;
3588 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3590 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3591 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3595 if (!api_hid_available)
3598 for (i = 0; i < USB_MAXINTERFACES; i++) {
3599 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3600 file_handle = handle_priv->interface_handle[i].api_handle;
3601 if (HANDLE_VALID(file_handle))
3602 CloseHandle(file_handle);
3607 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3609 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3610 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3612 CHECK_HID_AVAILABLE;
3614 // NB: Disconnection detection is not possible in this function
3615 if (priv->usb_interface[iface].path == NULL)
3616 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3618 // We use dev_handle as a flag for interface claimed
3619 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED)
3620 return LIBUSB_ERROR_BUSY; // already claimed
3623 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3625 usbi_dbg("claimed interface %d", iface);
3626 handle_priv->active_interface = iface;
3628 return LIBUSB_SUCCESS;
3631 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3633 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3634 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3636 CHECK_HID_AVAILABLE;
3638 if (priv->usb_interface[iface].path == NULL)
3639 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3641 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED)
3642 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3644 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3646 return LIBUSB_SUCCESS;
3649 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
3651 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3653 CHECK_HID_AVAILABLE;
3655 if (altsetting > 255)
3656 return LIBUSB_ERROR_INVALID_PARAM;
3658 if (altsetting != 0) {
3659 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3660 return LIBUSB_ERROR_NOT_SUPPORTED;
3663 return LIBUSB_SUCCESS;
3666 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3668 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3669 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3670 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3671 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3672 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3673 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
3676 int current_interface, config;
3678 int r = LIBUSB_ERROR_INVALID_PARAM;
3680 CHECK_HID_AVAILABLE;
3682 transfer_priv->pollable_fd = INVALID_WINFD;
3683 safe_free(transfer_priv->hid_buffer);
3684 transfer_priv->hid_dest = NULL;
3685 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3687 if (size > MAX_CTRL_BUFFER_LENGTH)
3688 return LIBUSB_ERROR_INVALID_PARAM;
3690 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3691 if (current_interface < 0) {
3692 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS)
3693 return LIBUSB_ERROR_NOT_FOUND;
3696 usbi_dbg("will use interface %d", current_interface);
3697 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3698 // Always use the handle returned from usbi_create_fd (wfd.handle)
3699 wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
3701 return LIBUSB_ERROR_NOT_FOUND;
3703 switch(LIBUSB_REQ_TYPE(setup->request_type)) {
3704 case LIBUSB_REQUEST_TYPE_STANDARD:
3705 switch(setup->request) {
3706 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3707 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
3708 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3710 case LIBUSB_REQUEST_GET_CONFIGURATION:
3711 r = windows_get_configuration(transfer->dev_handle, &config);
3712 if (r == LIBUSB_SUCCESS) {
3714 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3715 r = LIBUSB_COMPLETED;
3718 case LIBUSB_REQUEST_SET_CONFIGURATION:
3719 if (setup->value == priv->active_config) {
3720 r = LIBUSB_COMPLETED;
3722 usbi_warn(ctx, "cannot set configuration other than the default one");
3723 r = LIBUSB_ERROR_NOT_SUPPORTED;
3726 case LIBUSB_REQUEST_GET_INTERFACE:
3728 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3729 r = LIBUSB_COMPLETED;
3731 case LIBUSB_REQUEST_SET_INTERFACE:
3732 r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->index, setup->value);
3733 if (r == LIBUSB_SUCCESS)
3734 r = LIBUSB_COMPLETED;
3737 usbi_warn(ctx, "unsupported HID control request");
3738 r = LIBUSB_ERROR_NOT_SUPPORTED;
3742 case LIBUSB_REQUEST_TYPE_CLASS:
3743 r = _hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
3744 setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3745 &size, wfd.overlapped);
3748 usbi_warn(ctx, "unsupported HID control request");
3749 r = LIBUSB_ERROR_NOT_SUPPORTED;
3753 if (r == LIBUSB_COMPLETED) {
3754 // Force request to be completed synchronously. Transferred size has been set by previous call
3755 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3756 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3757 // set InternalHigh to the number of bytes transferred
3758 wfd.overlapped->InternalHigh = (DWORD)size;
3762 if (r == LIBUSB_SUCCESS) {
3763 // Use priv_transfer to store data needed for async polling
3764 transfer_priv->pollable_fd = wfd;
3765 transfer_priv->interface_number = (uint8_t)current_interface;
3773 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
3775 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3776 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3777 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3778 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3779 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3782 bool direction_in, ret;
3783 int current_interface, length;
3785 int r = LIBUSB_SUCCESS;
3787 CHECK_HID_AVAILABLE;
3789 transfer_priv->pollable_fd = INVALID_WINFD;
3790 transfer_priv->hid_dest = NULL;
3791 safe_free(transfer_priv->hid_buffer);
3793 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3794 if (current_interface < 0) {
3795 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3796 return LIBUSB_ERROR_NOT_FOUND;
3799 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3801 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3802 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3804 wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
3805 // Always use the handle returned from usbi_create_fd (wfd.handle)
3807 return LIBUSB_ERROR_NO_MEM;
3809 // If report IDs are not in use, an extra prefix byte must be added
3810 if (((direction_in) && (!priv->hid->uses_report_ids[0]))
3811 || ((!direction_in) && (!priv->hid->uses_report_ids[1])))
3812 length = transfer->length + 1;
3814 length = transfer->length;
3816 // Add a trailing byte to detect overflows on input
3817 transfer_priv->hid_buffer = calloc(1, length + 1);
3818 if (transfer_priv->hid_buffer == NULL)
3819 return LIBUSB_ERROR_NO_MEM;
3821 transfer_priv->hid_expected_size = length;
3824 transfer_priv->hid_dest = transfer->buffer;
3825 usbi_dbg("reading %d bytes (report ID: 0x00)", length);
3826 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length + 1, &size, wfd.overlapped);
3828 if (!priv->hid->uses_report_ids[1])
3829 memcpy(transfer_priv->hid_buffer + 1, transfer->buffer, transfer->length);
3831 // We could actually do without the calloc and memcpy in this case
3832 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3834 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3835 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3839 if (GetLastError() != ERROR_IO_PENDING) {
3840 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3842 safe_free(transfer_priv->hid_buffer);
3843 return LIBUSB_ERROR_IO;
3846 // Only write operations that completed synchronously need to free up
3847 // hid_buffer. For reads, copy_transfer_data() handles that process.
3849 safe_free(transfer_priv->hid_buffer);
3852 usbi_err(ctx, "program assertion failed - no data was transferred");
3855 if (size > (size_t)length) {
3856 usbi_err(ctx, "OVERFLOW!");
3857 r = LIBUSB_ERROR_OVERFLOW;
3859 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3860 wfd.overlapped->InternalHigh = size;
3863 transfer_priv->pollable_fd = wfd;
3864 transfer_priv->interface_number = (uint8_t)current_interface;
3869 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
3871 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3872 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3873 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3875 int current_interface;
3877 CHECK_HID_AVAILABLE;
3879 current_interface = transfer_priv->interface_number;
3880 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3881 CancelIo(hid_handle);
3883 return LIBUSB_SUCCESS;
3886 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3888 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3890 int current_interface;
3892 CHECK_HID_AVAILABLE;
3894 // Flushing the queues on all interfaces is the best we can achieve
3895 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3896 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3897 if (HANDLE_VALID(hid_handle))
3898 HidD_FlushQueue(hid_handle);
3901 return LIBUSB_SUCCESS;
3904 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3906 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3907 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3908 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3910 int current_interface;
3912 CHECK_HID_AVAILABLE;
3914 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3915 if (current_interface < 0) {
3916 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3917 return LIBUSB_ERROR_NOT_FOUND;
3920 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3921 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3923 // No endpoint selection with Microsoft's implementation, so we try to flush the
3924 // whole interface. Should be OK for most case scenarios
3925 if (!HidD_FlushQueue(hid_handle)) {
3926 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3927 // Device was probably disconnected
3928 return LIBUSB_ERROR_NO_DEVICE;
3931 return LIBUSB_SUCCESS;
3934 // This extra function is only needed for HID
3935 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
3937 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3938 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3939 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3940 int r = LIBUSB_TRANSFER_COMPLETED;
3941 uint32_t corrected_size = io_size;
3943 if (transfer_priv->hid_buffer != NULL) {
3944 // If we have a valid hid_buffer, it means the transfer was async
3945 if (transfer_priv->hid_dest != NULL) { // Data readout
3946 if (corrected_size > 0) {
3947 // First, check for overflow
3948 if (corrected_size > transfer_priv->hid_expected_size) {
3949 usbi_err(ctx, "OVERFLOW!");
3950 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
3951 r = LIBUSB_TRANSFER_OVERFLOW;
3954 if (transfer_priv->hid_buffer[0] == 0) {
3955 // Discard the 1 byte report ID prefix
3957 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer + 1, corrected_size);
3959 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
3962 transfer_priv->hid_dest = NULL;
3964 // For write, we just need to free the hid buffer
3965 safe_free(transfer_priv->hid_buffer);
3968 itransfer->transferred += corrected_size;
3974 * Composite API functions
3976 static int composite_init(int sub_api, struct libusb_context *ctx)
3978 return LIBUSB_SUCCESS;
3981 static int composite_exit(int sub_api)
3983 return LIBUSB_SUCCESS;
3986 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
3988 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3989 int r = LIBUSB_ERROR_NOT_FOUND;
3991 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
3992 bool available[SUB_API_MAX + 1] = { 0 };
3994 for (i = 0; i < USB_MAXINTERFACES; i++) {
3995 switch (priv->usb_interface[i].apib->id) {
3996 case USB_API_WINUSBX:
3997 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
3998 available[priv->usb_interface[i].sub_api] = true;
4001 available[SUB_API_MAX] = true;
4008 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4010 r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4011 if (r != LIBUSB_SUCCESS)
4016 if (available[SUB_API_MAX]) // HID driver
4017 r = hid_open(SUB_API_NOTSET, dev_handle);
4022 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4024 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4026 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4027 bool available[SUB_API_MAX + 1] = { 0 };
4029 for (i = 0; i < USB_MAXINTERFACES; i++) {
4030 switch (priv->usb_interface[i].apib->id) {
4031 case USB_API_WINUSBX:
4032 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4033 available[priv->usb_interface[i].sub_api] = true;
4036 available[SUB_API_MAX] = true;
4043 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4045 usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4048 if (available[SUB_API_MAX]) // HID driver
4049 hid_close(SUB_API_NOTSET, dev_handle);
4052 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4054 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4056 return priv->usb_interface[iface].apib->
4057 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4060 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4062 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4064 return priv->usb_interface[iface].apib->
4065 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4068 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4070 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4072 return priv->usb_interface[iface].apib->
4073 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4076 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4078 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4079 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4080 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4081 struct libusb_config_descriptor *conf_desc;
4082 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
4085 // Interface shouldn't matter for control, but it does in practice, with Windows'
4086 // restrictions with regards to accessing HID keyboards and mice. Try to target
4087 // a specific interface first, if possible.
4088 switch (LIBUSB_REQ_RECIPIENT(setup->request_type)) {
4089 case LIBUSB_RECIPIENT_INTERFACE:
4090 iface = setup->index & 0xFF;
4092 case LIBUSB_RECIPIENT_ENDPOINT:
4093 r = libusb_get_config_descriptor(transfer->dev_handle->dev, (uint8_t)(priv->active_config - 1), &conf_desc);
4094 if (r == LIBUSB_SUCCESS) {
4095 iface = get_interface_by_endpoint(conf_desc, (setup->index & 0xFF));
4096 libusb_free_config_descriptor(conf_desc);
4099 // Fall through if not able to determine interface
4105 // Try and target a specific interface if the control setup indicates such
4106 if ((iface >= 0) && (iface < USB_MAXINTERFACES)) {
4107 usbi_dbg("attempting control transfer targeted to interface %d", iface);
4108 if (priv->usb_interface[iface].path != NULL) {
4109 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4110 if (r == LIBUSB_SUCCESS)
4115 // Either not targeted to a specific interface or no luck in doing so.
4116 // Try a 2 pass approach with all interfaces.
4117 for (pass = 0; pass < 2; pass++) {
4118 for (iface = 0; iface < USB_MAXINTERFACES; iface++) {
4119 if (priv->usb_interface[iface].path != NULL) {
4120 if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) {
4121 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", iface);
4124 usbi_dbg("using interface %d", iface);
4125 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4126 // If not supported on this API, it may be supported on another, so don't give up yet!!
4127 if (r == LIBUSB_ERROR_NOT_SUPPORTED)
4134 usbi_err(ctx, "no libusb supported interfaces to complete request");
4135 return LIBUSB_ERROR_NOT_FOUND;
4138 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4139 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4140 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4141 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4142 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4143 int current_interface;
4145 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4146 if (current_interface < 0) {
4147 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4148 return LIBUSB_ERROR_NOT_FOUND;
4151 return priv->usb_interface[current_interface].apib->
4152 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4155 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
4156 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4157 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4158 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4159 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4160 int current_interface;
4162 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4163 if (current_interface < 0) {
4164 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4165 return LIBUSB_ERROR_NOT_FOUND;
4168 return priv->usb_interface[current_interface].apib->
4169 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4172 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4174 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4175 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4176 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4177 int current_interface;
4179 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4180 if (current_interface < 0) {
4181 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4182 return LIBUSB_ERROR_NOT_FOUND;
4185 return priv->usb_interface[current_interface].apib->
4186 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);
4189 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
4191 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4192 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4193 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4195 return priv->usb_interface[transfer_priv->interface_number].apib->
4196 abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4199 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4201 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4202 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4203 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4205 return priv->usb_interface[transfer_priv->interface_number].apib->
4206 abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4209 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4211 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4214 bool available[SUB_API_MAX];
4216 for (i = 0; i < SUB_API_MAX; i++)
4217 available[i] = false;
4219 for (i = 0; i < USB_MAXINTERFACES; i++) {
4220 if ((priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4221 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET))
4222 available[priv->usb_interface[i].sub_api] = true;
4225 for (i = 0; i < SUB_API_MAX; i++) {
4227 r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4228 if (r != LIBUSB_SUCCESS)
4233 return LIBUSB_SUCCESS;
4236 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
4238 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4239 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4240 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4242 return priv->usb_interface[transfer_priv->interface_number].apib->
4243 copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);
4246 #endif /* !USE_USBDK */