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