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