• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * xusb: Generic USB test program
3  * Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
4  * Contributions to Mass Storage by Alan Stern.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include <stdarg.h>
22 #include <stdbool.h>
23 #include <stdio.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <time.h>
28 
29 #include "libusb.h"
30 
31 #if defined(_MSC_VER)
32 #define snprintf _snprintf
33 #define putenv _putenv
34 #endif
35 
36 // Future versions of libusb will use usb_interface instead of interface
37 // in libusb_config_descriptor => catter for that
38 #define usb_interface interface
39 
40 #ifndef ARRAYSIZE
41 #define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))
42 #endif
43 
44 // Global variables
45 static bool binary_dump = false;
46 static bool extra_info = false;
47 static bool force_device_request = false;	// For WCID descriptor queries
48 static const char* binary_name = NULL;
49 
msleep(int msecs)50 static inline void msleep(int msecs)
51 {
52 #if defined(_WIN32)
53 	Sleep(msecs);
54 #else
55 	const struct timespec ts = { msecs / 1000, (msecs % 1000) * 1000000L };
56 	nanosleep(&ts, NULL);
57 #endif
58 }
59 
perr(char const * format,...)60 static void perr(char const *format, ...)
61 {
62 	va_list args;
63 
64 	va_start (args, format);
65 	vfprintf(stderr, format, args);
66 	va_end(args);
67 }
68 
69 #define ERR_EXIT(errcode) do { perr("   %s\n", libusb_strerror((enum libusb_error)errcode)); return -1; } while (0)
70 #define CALL_CHECK(fcall) do { int _r=fcall; if (_r < 0) ERR_EXIT(_r); } while (0)
71 #define CALL_CHECK_CLOSE(fcall, hdl) do { int _r=fcall; if (_r < 0) { libusb_close(hdl); ERR_EXIT(_r); } } while (0)
72 #define B(x) (((x)!=0)?1:0)
73 #define be_to_int32(buf) (((buf)[0]<<24)|((buf)[1]<<16)|((buf)[2]<<8)|(buf)[3])
74 
75 #define RETRY_MAX                     5
76 #define REQUEST_SENSE_LENGTH          0x12
77 #define INQUIRY_LENGTH                0x24
78 #define READ_CAPACITY_LENGTH          0x08
79 
80 // HID Class-Specific Requests values. See section 7.2 of the HID specifications
81 #define HID_GET_REPORT                0x01
82 #define HID_GET_IDLE                  0x02
83 #define HID_GET_PROTOCOL              0x03
84 #define HID_SET_REPORT                0x09
85 #define HID_SET_IDLE                  0x0A
86 #define HID_SET_PROTOCOL              0x0B
87 #define HID_REPORT_TYPE_INPUT         0x01
88 #define HID_REPORT_TYPE_OUTPUT        0x02
89 #define HID_REPORT_TYPE_FEATURE       0x03
90 
91 // Mass Storage Requests values. See section 3 of the Bulk-Only Mass Storage Class specifications
92 #define BOMS_RESET                    0xFF
93 #define BOMS_GET_MAX_LUN              0xFE
94 
95 // Microsoft OS Descriptor
96 #define MS_OS_DESC_STRING_INDEX		0xEE
97 #define MS_OS_DESC_STRING_LENGTH	0x12
98 #define MS_OS_DESC_VENDOR_CODE_OFFSET	0x10
99 static const uint8_t ms_os_desc_string[] = {
100 	MS_OS_DESC_STRING_LENGTH,
101 	LIBUSB_DT_STRING,
102 	'M', 0, 'S', 0, 'F', 0, 'T', 0, '1', 0, '0', 0, '0', 0,
103 };
104 
105 // Section 5.1: Command Block Wrapper (CBW)
106 struct command_block_wrapper {
107 	uint8_t dCBWSignature[4];
108 	uint32_t dCBWTag;
109 	uint32_t dCBWDataTransferLength;
110 	uint8_t bmCBWFlags;
111 	uint8_t bCBWLUN;
112 	uint8_t bCBWCBLength;
113 	uint8_t CBWCB[16];
114 };
115 
116 // Section 5.2: Command Status Wrapper (CSW)
117 struct command_status_wrapper {
118 	uint8_t dCSWSignature[4];
119 	uint32_t dCSWTag;
120 	uint32_t dCSWDataResidue;
121 	uint8_t bCSWStatus;
122 };
123 
124 static const uint8_t cdb_length[256] = {
125 //	 0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
126 	06,06,06,06,06,06,06,06,06,06,06,06,06,06,06,06,  //  0
127 	06,06,06,06,06,06,06,06,06,06,06,06,06,06,06,06,  //  1
128 	10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,  //  2
129 	10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,  //  3
130 	10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,  //  4
131 	10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,  //  5
132 	00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  6
133 	00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  7
134 	16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,  //  8
135 	16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,  //  9
136 	12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,  //  A
137 	12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,  //  B
138 	00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  C
139 	00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  D
140 	00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  E
141 	00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  F
142 };
143 
144 static enum test_type {
145 	USE_GENERIC,
146 	USE_PS3,
147 	USE_XBOX,
148 	USE_SCSI,
149 	USE_HID,
150 } test_mode;
151 static uint16_t VID, PID;
152 
display_buffer_hex(unsigned char * buffer,unsigned size)153 static void display_buffer_hex(unsigned char *buffer, unsigned size)
154 {
155 	unsigned i, j, k;
156 
157 	for (i=0; i<size; i+=16) {
158 		printf("\n  %08x  ", i);
159 		for(j=0,k=0; k<16; j++,k++) {
160 			if (i+j < size) {
161 				printf("%02x", buffer[i+j]);
162 			} else {
163 				printf("  ");
164 			}
165 			printf(" ");
166 		}
167 		printf(" ");
168 		for(j=0,k=0; k<16; j++,k++) {
169 			if (i+j < size) {
170 				if ((buffer[i+j] < 32) || (buffer[i+j] > 126)) {
171 					printf(".");
172 				} else {
173 					printf("%c", buffer[i+j]);
174 				}
175 			}
176 		}
177 	}
178 	printf("\n" );
179 }
180 
uuid_to_string(const uint8_t * uuid)181 static char* uuid_to_string(const uint8_t* uuid)
182 {
183 	static char uuid_string[40];
184 	if (uuid == NULL) return NULL;
185 	snprintf(uuid_string, sizeof(uuid_string),
186 		"{%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
187 		uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
188 		uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
189 	return uuid_string;
190 }
191 
192 // The PS3 Controller is really a HID device that got its HID Report Descriptors
193 // removed by Sony
display_ps3_status(libusb_device_handle * handle)194 static int display_ps3_status(libusb_device_handle *handle)
195 {
196 	uint8_t input_report[49];
197 	uint8_t master_bt_address[8];
198 	uint8_t device_bt_address[18];
199 
200 	// Get the controller's bluetooth address of its master device
201 	CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
202 		HID_GET_REPORT, 0x03f5, 0, master_bt_address, sizeof(master_bt_address), 100));
203 	printf("\nMaster's bluetooth address: %02X:%02X:%02X:%02X:%02X:%02X\n", master_bt_address[2], master_bt_address[3],
204 		master_bt_address[4], master_bt_address[5], master_bt_address[6], master_bt_address[7]);
205 
206 	// Get the controller's bluetooth address
207 	CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
208 		HID_GET_REPORT, 0x03f2, 0, device_bt_address, sizeof(device_bt_address), 100));
209 	printf("\nMaster's bluetooth address: %02X:%02X:%02X:%02X:%02X:%02X\n", device_bt_address[4], device_bt_address[5],
210 		device_bt_address[6], device_bt_address[7], device_bt_address[8], device_bt_address[9]);
211 
212 	// Get the status of the controller's buttons via its HID report
213 	printf("\nReading PS3 Input Report...\n");
214 	CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
215 		HID_GET_REPORT, (HID_REPORT_TYPE_INPUT<<8)|0x01, 0, input_report, sizeof(input_report), 1000));
216 	switch(input_report[2]){	/** Direction pad plus start, select, and joystick buttons */
217 		case 0x01:
218 			printf("\tSELECT pressed\n");
219 			break;
220 		case 0x02:
221 			printf("\tLEFT 3 pressed\n");
222 			break;
223 		case 0x04:
224 			printf("\tRIGHT 3 pressed\n");
225 			break;
226 		case 0x08:
227 			printf("\tSTART pressed\n");
228 			break;
229 		case 0x10:
230 			printf("\tUP pressed\n");
231 			break;
232 		case 0x20:
233 			printf("\tRIGHT pressed\n");
234 			break;
235 		case 0x40:
236 			printf("\tDOWN pressed\n");
237 			break;
238 		case 0x80:
239 			printf("\tLEFT pressed\n");
240 			break;
241 	}
242 	switch(input_report[3]){	/** Shapes plus top right and left buttons */
243 		case 0x01:
244 			printf("\tLEFT 2 pressed\n");
245 			break;
246 		case 0x02:
247 			printf("\tRIGHT 2 pressed\n");
248 			break;
249 		case 0x04:
250 			printf("\tLEFT 1 pressed\n");
251 			break;
252 		case 0x08:
253 			printf("\tRIGHT 1 pressed\n");
254 			break;
255 		case 0x10:
256 			printf("\tTRIANGLE pressed\n");
257 			break;
258 		case 0x20:
259 			printf("\tCIRCLE pressed\n");
260 			break;
261 		case 0x40:
262 			printf("\tCROSS pressed\n");
263 			break;
264 		case 0x80:
265 			printf("\tSQUARE pressed\n");
266 			break;
267 	}
268 	printf("\tPS button: %d\n", input_report[4]);
269 	printf("\tLeft Analog (X,Y): (%d,%d)\n", input_report[6], input_report[7]);
270 	printf("\tRight Analog (X,Y): (%d,%d)\n", input_report[8], input_report[9]);
271 	printf("\tL2 Value: %d\tR2 Value: %d\n", input_report[18], input_report[19]);
272 	printf("\tL1 Value: %d\tR1 Value: %d\n", input_report[20], input_report[21]);
273 	printf("\tRoll (x axis): %d Yaw (y axis): %d Pitch (z axis) %d\n",
274 			//(((input_report[42] + 128) % 256) - 128),
275 			(int8_t)(input_report[42]),
276 			(int8_t)(input_report[44]),
277 			(int8_t)(input_report[46]));
278 	printf("\tAcceleration: %d\n\n", (int8_t)(input_report[48]));
279 	return 0;
280 }
281 // The XBOX Controller is really a HID device that got its HID Report Descriptors
282 // removed by Microsoft.
283 // Input/Output reports described at http://euc.jp/periphs/xbox-controller.ja.html
display_xbox_status(libusb_device_handle * handle)284 static int display_xbox_status(libusb_device_handle *handle)
285 {
286 	uint8_t input_report[20];
287 	printf("\nReading XBox Input Report...\n");
288 	CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
289 		HID_GET_REPORT, (HID_REPORT_TYPE_INPUT<<8)|0x00, 0, input_report, 20, 1000));
290 	printf("   D-pad: %02X\n", input_report[2]&0x0F);
291 	printf("   Start:%d, Back:%d, Left Stick Press:%d, Right Stick Press:%d\n", B(input_report[2]&0x10), B(input_report[2]&0x20),
292 		B(input_report[2]&0x40), B(input_report[2]&0x80));
293 	// A, B, X, Y, Black, White are pressure sensitive
294 	printf("   A:%d, B:%d, X:%d, Y:%d, White:%d, Black:%d\n", input_report[4], input_report[5],
295 		input_report[6], input_report[7], input_report[9], input_report[8]);
296 	printf("   Left Trigger: %d, Right Trigger: %d\n", input_report[10], input_report[11]);
297 	printf("   Left Analog (X,Y): (%d,%d)\n", (int16_t)((input_report[13]<<8)|input_report[12]),
298 		(int16_t)((input_report[15]<<8)|input_report[14]));
299 	printf("   Right Analog (X,Y): (%d,%d)\n", (int16_t)((input_report[17]<<8)|input_report[16]),
300 		(int16_t)((input_report[19]<<8)|input_report[18]));
301 	return 0;
302 }
303 
set_xbox_actuators(libusb_device_handle * handle,uint8_t left,uint8_t right)304 static int set_xbox_actuators(libusb_device_handle *handle, uint8_t left, uint8_t right)
305 {
306 	uint8_t output_report[6];
307 
308 	printf("\nWriting XBox Controller Output Report...\n");
309 
310 	memset(output_report, 0, sizeof(output_report));
311 	output_report[1] = sizeof(output_report);
312 	output_report[3] = left;
313 	output_report[5] = right;
314 
315 	CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_OUT|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
316 		HID_SET_REPORT, (HID_REPORT_TYPE_OUTPUT<<8)|0x00, 0, output_report, 06, 1000));
317 	return 0;
318 }
319 
send_mass_storage_command(libusb_device_handle * handle,uint8_t endpoint,uint8_t lun,uint8_t * cdb,uint8_t direction,int data_length,uint32_t * ret_tag)320 static int send_mass_storage_command(libusb_device_handle *handle, uint8_t endpoint, uint8_t lun,
321 	uint8_t *cdb, uint8_t direction, int data_length, uint32_t *ret_tag)
322 {
323 	static uint32_t tag = 1;
324 	uint8_t cdb_len;
325 	int i, r, size;
326 	struct command_block_wrapper cbw;
327 
328 	if (cdb == NULL) {
329 		return -1;
330 	}
331 
332 	if (endpoint & LIBUSB_ENDPOINT_IN) {
333 		perr("send_mass_storage_command: cannot send command on IN endpoint\n");
334 		return -1;
335 	}
336 
337 	cdb_len = cdb_length[cdb[0]];
338 	if ((cdb_len == 0) || (cdb_len > sizeof(cbw.CBWCB))) {
339 		perr("send_mass_storage_command: don't know how to handle this command (%02X, length %d)\n",
340 			cdb[0], cdb_len);
341 		return -1;
342 	}
343 
344 	memset(&cbw, 0, sizeof(cbw));
345 	cbw.dCBWSignature[0] = 'U';
346 	cbw.dCBWSignature[1] = 'S';
347 	cbw.dCBWSignature[2] = 'B';
348 	cbw.dCBWSignature[3] = 'C';
349 	*ret_tag = tag;
350 	cbw.dCBWTag = tag++;
351 	cbw.dCBWDataTransferLength = data_length;
352 	cbw.bmCBWFlags = direction;
353 	cbw.bCBWLUN = lun;
354 	// Subclass is 1 or 6 => cdb_len
355 	cbw.bCBWCBLength = cdb_len;
356 	memcpy(cbw.CBWCB, cdb, cdb_len);
357 
358 	i = 0;
359 	do {
360 		// The transfer length must always be exactly 31 bytes.
361 		r = libusb_bulk_transfer(handle, endpoint, (unsigned char*)&cbw, 31, &size, 1000);
362 		if (r == LIBUSB_ERROR_PIPE) {
363 			libusb_clear_halt(handle, endpoint);
364 		}
365 		i++;
366 	} while ((r == LIBUSB_ERROR_PIPE) && (i<RETRY_MAX));
367 	if (r != LIBUSB_SUCCESS) {
368 		perr("   send_mass_storage_command: %s\n", libusb_strerror((enum libusb_error)r));
369 		return -1;
370 	}
371 
372 	printf("   sent %d CDB bytes\n", cdb_len);
373 	return 0;
374 }
375 
get_mass_storage_status(libusb_device_handle * handle,uint8_t endpoint,uint32_t expected_tag)376 static int get_mass_storage_status(libusb_device_handle *handle, uint8_t endpoint, uint32_t expected_tag)
377 {
378 	int i, r, size;
379 	struct command_status_wrapper csw;
380 
381 	// The device is allowed to STALL this transfer. If it does, you have to
382 	// clear the stall and try again.
383 	i = 0;
384 	do {
385 		r = libusb_bulk_transfer(handle, endpoint, (unsigned char*)&csw, 13, &size, 1000);
386 		if (r == LIBUSB_ERROR_PIPE) {
387 			libusb_clear_halt(handle, endpoint);
388 		}
389 		i++;
390 	} while ((r == LIBUSB_ERROR_PIPE) && (i<RETRY_MAX));
391 	if (r != LIBUSB_SUCCESS) {
392 		perr("   get_mass_storage_status: %s\n", libusb_strerror((enum libusb_error)r));
393 		return -1;
394 	}
395 	if (size != 13) {
396 		perr("   get_mass_storage_status: received %d bytes (expected 13)\n", size);
397 		return -1;
398 	}
399 	if (csw.dCSWTag != expected_tag) {
400 		perr("   get_mass_storage_status: mismatched tags (expected %08X, received %08X)\n",
401 			expected_tag, csw.dCSWTag);
402 		return -1;
403 	}
404 	// For this test, we ignore the dCSWSignature check for validity...
405 	printf("   Mass Storage Status: %02X (%s)\n", csw.bCSWStatus, csw.bCSWStatus?"FAILED":"Success");
406 	if (csw.dCSWTag != expected_tag)
407 		return -1;
408 	if (csw.bCSWStatus) {
409 		// REQUEST SENSE is appropriate only if bCSWStatus is 1, meaning that the
410 		// command failed somehow.  Larger values (2 in particular) mean that
411 		// the command couldn't be understood.
412 		if (csw.bCSWStatus == 1)
413 			return -2;	// request Get Sense
414 		else
415 			return -1;
416 	}
417 
418 	// In theory we also should check dCSWDataResidue.  But lots of devices
419 	// set it wrongly.
420 	return 0;
421 }
422 
get_sense(libusb_device_handle * handle,uint8_t endpoint_in,uint8_t endpoint_out)423 static void get_sense(libusb_device_handle *handle, uint8_t endpoint_in, uint8_t endpoint_out)
424 {
425 	uint8_t cdb[16];	// SCSI Command Descriptor Block
426 	uint8_t sense[18];
427 	uint32_t expected_tag;
428 	int size;
429 	int rc;
430 
431 	// Request Sense
432 	printf("Request Sense:\n");
433 	memset(sense, 0, sizeof(sense));
434 	memset(cdb, 0, sizeof(cdb));
435 	cdb[0] = 0x03;	// Request Sense
436 	cdb[4] = REQUEST_SENSE_LENGTH;
437 
438 	send_mass_storage_command(handle, endpoint_out, 0, cdb, LIBUSB_ENDPOINT_IN, REQUEST_SENSE_LENGTH, &expected_tag);
439 	rc = libusb_bulk_transfer(handle, endpoint_in, (unsigned char*)&sense, REQUEST_SENSE_LENGTH, &size, 1000);
440 	if (rc < 0)
441 	{
442 		printf("libusb_bulk_transfer failed: %s\n", libusb_error_name(rc));
443 		return;
444 	}
445 	printf("   received %d bytes\n", size);
446 
447 	if ((sense[0] != 0x70) && (sense[0] != 0x71)) {
448 		perr("   ERROR No sense data\n");
449 	} else {
450 		perr("   ERROR Sense: %02X %02X %02X\n", sense[2]&0x0F, sense[12], sense[13]);
451 	}
452 	// Strictly speaking, the get_mass_storage_status() call should come
453 	// before these perr() lines.  If the status is nonzero then we must
454 	// assume there's no data in the buffer.  For xusb it doesn't matter.
455 	get_mass_storage_status(handle, endpoint_in, expected_tag);
456 }
457 
458 // Mass Storage device to test bulk transfers (non destructive test)
test_mass_storage(libusb_device_handle * handle,uint8_t endpoint_in,uint8_t endpoint_out)459 static int test_mass_storage(libusb_device_handle *handle, uint8_t endpoint_in, uint8_t endpoint_out)
460 {
461 	int r, size;
462 	uint8_t lun;
463 	uint32_t expected_tag;
464 	uint32_t i, max_lba, block_size;
465 	double device_size;
466 	uint8_t cdb[16];	// SCSI Command Descriptor Block
467 	uint8_t buffer[64];
468 	unsigned char vid[9], pid[9], rev[5];
469 	unsigned char *data;
470 	FILE *fd;
471 
472 	printf("\nReading Max LUN:\n");
473 	r = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
474 		BOMS_GET_MAX_LUN, 0, 0, &lun, 1, 1000);
475 	// Some devices send a STALL instead of the actual value.
476 	// In such cases we should set lun to 0.
477 	if (r == LIBUSB_ERROR_PIPE) {
478 		lun = 0;
479 		printf("   Stalled, setting Max LUN to 0\n");
480 	} else if (r < 0) {
481 		perr("   Failed.\n");
482 		return r;
483 	} else {
484 		printf("   Max LUN = %d\n", lun);
485 	}
486 
487 	// Send Inquiry
488 	printf("\nSending Inquiry:\n");
489 	memset(buffer, 0, sizeof(buffer));
490 	memset(cdb, 0, sizeof(cdb));
491 	cdb[0] = 0x12;	// Inquiry
492 	cdb[4] = INQUIRY_LENGTH;
493 
494 	send_mass_storage_command(handle, endpoint_out, lun, cdb, LIBUSB_ENDPOINT_IN, INQUIRY_LENGTH, &expected_tag);
495 	CALL_CHECK(libusb_bulk_transfer(handle, endpoint_in, (unsigned char*)&buffer, INQUIRY_LENGTH, &size, 1000));
496 	printf("   received %d bytes\n", size);
497 	// The following strings are not zero terminated
498 	for (i=0; i<8; i++) {
499 		vid[i] = buffer[8+i];
500 		pid[i] = buffer[16+i];
501 		rev[i/2] = buffer[32+i/2];	// instead of another loop
502 	}
503 	vid[8] = 0;
504 	pid[8] = 0;
505 	rev[4] = 0;
506 	printf("   VID:PID:REV \"%8s\":\"%8s\":\"%4s\"\n", vid, pid, rev);
507 	if (get_mass_storage_status(handle, endpoint_in, expected_tag) == -2) {
508 		get_sense(handle, endpoint_in, endpoint_out);
509 	}
510 
511 	// Read capacity
512 	printf("\nReading Capacity:\n");
513 	memset(buffer, 0, sizeof(buffer));
514 	memset(cdb, 0, sizeof(cdb));
515 	cdb[0] = 0x25;	// Read Capacity
516 
517 	send_mass_storage_command(handle, endpoint_out, lun, cdb, LIBUSB_ENDPOINT_IN, READ_CAPACITY_LENGTH, &expected_tag);
518 	CALL_CHECK(libusb_bulk_transfer(handle, endpoint_in, (unsigned char*)&buffer, READ_CAPACITY_LENGTH, &size, 1000));
519 	printf("   received %d bytes\n", size);
520 	max_lba = be_to_int32(&buffer[0]);
521 	block_size = be_to_int32(&buffer[4]);
522 	device_size = ((double)(max_lba+1))*block_size/(1024*1024*1024);
523 	printf("   Max LBA: %08X, Block Size: %08X (%.2f GB)\n", max_lba, block_size, device_size);
524 	if (get_mass_storage_status(handle, endpoint_in, expected_tag) == -2) {
525 		get_sense(handle, endpoint_in, endpoint_out);
526 	}
527 
528 	// coverity[tainted_data]
529 	data = (unsigned char*) calloc(1, block_size);
530 	if (data == NULL) {
531 		perr("   unable to allocate data buffer\n");
532 		return -1;
533 	}
534 
535 	// Send Read
536 	printf("\nAttempting to read %u bytes:\n", block_size);
537 	memset(cdb, 0, sizeof(cdb));
538 
539 	cdb[0] = 0x28;	// Read(10)
540 	cdb[8] = 0x01;	// 1 block
541 
542 	send_mass_storage_command(handle, endpoint_out, lun, cdb, LIBUSB_ENDPOINT_IN, block_size, &expected_tag);
543 	libusb_bulk_transfer(handle, endpoint_in, data, block_size, &size, 5000);
544 	printf("   READ: received %d bytes\n", size);
545 	if (get_mass_storage_status(handle, endpoint_in, expected_tag) == -2) {
546 		get_sense(handle, endpoint_in, endpoint_out);
547 	} else {
548 		display_buffer_hex(data, size);
549 		if ((binary_dump) && ((fd = fopen(binary_name, "w")) != NULL)) {
550 			if (fwrite(data, 1, (size_t)size, fd) != (unsigned int)size) {
551 				perr("   unable to write binary data\n");
552 			}
553 			fclose(fd);
554 		}
555 	}
556 	free(data);
557 
558 	return 0;
559 }
560 
561 // HID
get_hid_record_size(uint8_t * hid_report_descriptor,int size,int type)562 static int get_hid_record_size(uint8_t *hid_report_descriptor, int size, int type)
563 {
564 	uint8_t i, j = 0;
565 	uint8_t offset;
566 	int record_size[3] = {0, 0, 0};
567 	unsigned int nb_bits = 0, nb_items = 0;
568 	bool found_record_marker;
569 
570 	found_record_marker = false;
571 	for (i = hid_report_descriptor[0]+1; i < size; i += offset) {
572 		offset = (hid_report_descriptor[i]&0x03) + 1;
573 		if (offset == 4)
574 			offset = 5;
575 		switch (hid_report_descriptor[i] & 0xFC) {
576 		case 0x74:	// bitsize
577 			nb_bits = hid_report_descriptor[i+1];
578 			break;
579 		case 0x94:	// count
580 			nb_items = 0;
581 			for (j=1; j<offset; j++) {
582 				nb_items = ((unsigned int)hid_report_descriptor[i+j]) << (8U*(j-1U));
583 			}
584 			break;
585 		case 0x80:	// input
586 			found_record_marker = true;
587 			j = 0;
588 			break;
589 		case 0x90:	// output
590 			found_record_marker = true;
591 			j = 1;
592 			break;
593 		case 0xb0:	// feature
594 			found_record_marker = true;
595 			j = 2;
596 			break;
597 		case 0xC0:	// end of collection
598 			nb_items = 0;
599 			nb_bits = 0;
600 			break;
601 		default:
602 			continue;
603 		}
604 		if (found_record_marker) {
605 			found_record_marker = false;
606 			record_size[j] += nb_items*nb_bits;
607 		}
608 	}
609 	if ((type < HID_REPORT_TYPE_INPUT) || (type > HID_REPORT_TYPE_FEATURE)) {
610 		return 0;
611 	} else {
612 		return (record_size[type - HID_REPORT_TYPE_INPUT]+7)/8;
613 	}
614 }
615 
test_hid(libusb_device_handle * handle,uint8_t endpoint_in)616 static int test_hid(libusb_device_handle *handle, uint8_t endpoint_in)
617 {
618 	int r, size, descriptor_size;
619 	uint8_t hid_report_descriptor[256];
620 	uint8_t *report_buffer;
621 	FILE *fd;
622 
623 	printf("\nReading HID Report Descriptors:\n");
624 	descriptor_size = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_STANDARD|LIBUSB_RECIPIENT_INTERFACE,
625 		LIBUSB_REQUEST_GET_DESCRIPTOR, LIBUSB_DT_REPORT<<8, 0, hid_report_descriptor, sizeof(hid_report_descriptor), 1000);
626 	if (descriptor_size < 0) {
627 		printf("   Failed\n");
628 		return -1;
629 	}
630 	display_buffer_hex(hid_report_descriptor, (unsigned int)descriptor_size);
631 	if ((binary_dump) && ((fd = fopen(binary_name, "w")) != NULL)) {
632 		if (fwrite(hid_report_descriptor, 1, (size_t)descriptor_size, fd) != (size_t)descriptor_size) {
633 			printf("   Error writing descriptor to file\n");
634 		}
635 		fclose(fd);
636 	}
637 
638 	size = get_hid_record_size(hid_report_descriptor, descriptor_size, HID_REPORT_TYPE_FEATURE);
639 	if (size <= 0) {
640 		printf("\nSkipping Feature Report readout (None detected)\n");
641 	} else if (size > UINT16_MAX) {
642 		printf("\nSkipping Feature Report readout (bigger than UINT16_MAX)\n");
643 	} else {
644 		report_buffer = (uint8_t*) calloc(1, (size_t)size);
645 		if (report_buffer == NULL) {
646 			return -1;
647 		}
648 
649 		printf("\nReading Feature Report (length %d)...\n", size);
650 		r = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
651 			HID_GET_REPORT, (HID_REPORT_TYPE_FEATURE<<8)|0, 0, report_buffer, (uint16_t)size, 5000);
652 		if (r >= 0) {
653 			display_buffer_hex(report_buffer, (unsigned int)size);
654 		} else {
655 			switch(r) {
656 			case LIBUSB_ERROR_NOT_FOUND:
657 				printf("   No Feature Report available for this device\n");
658 				break;
659 			case LIBUSB_ERROR_PIPE:
660 				printf("   Detected stall - resetting pipe...\n");
661 				libusb_clear_halt(handle, 0);
662 				break;
663 			default:
664 				printf("   Error: %s\n", libusb_strerror((enum libusb_error)r));
665 				break;
666 			}
667 		}
668 		free(report_buffer);
669 	}
670 
671 	size = get_hid_record_size(hid_report_descriptor, descriptor_size, HID_REPORT_TYPE_INPUT);
672 	if (size <= 0) {
673 		printf("\nSkipping Input Report readout (None detected)\n");
674 	} else if (size > UINT16_MAX) {
675 		printf("\nSkipping Input Report readout (bigger than UINT16_MAX)\n");
676 	} else {
677 		report_buffer = (uint8_t*) calloc(1, (size_t)size);
678 		if (report_buffer == NULL) {
679 			return -1;
680 		}
681 
682 		printf("\nReading Input Report (length %d)...\n", size);
683 		r = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
684 			HID_GET_REPORT, (HID_REPORT_TYPE_INPUT<<8)|0x00, 0, report_buffer, (uint16_t)size, 5000);
685 		if (r >= 0) {
686 			display_buffer_hex(report_buffer, (unsigned int)size);
687 		} else {
688 			switch(r) {
689 			case LIBUSB_ERROR_TIMEOUT:
690 				printf("   Timeout! Please make sure you act on the device within the 5 seconds allocated...\n");
691 				break;
692 			case LIBUSB_ERROR_PIPE:
693 				printf("   Detected stall - resetting pipe...\n");
694 				libusb_clear_halt(handle, 0);
695 				break;
696 			default:
697 				printf("   Error: %s\n", libusb_strerror((enum libusb_error)r));
698 				break;
699 			}
700 		}
701 
702 		// Attempt a bulk read from endpoint 0 (this should just return a raw input report)
703 		printf("\nTesting interrupt read using endpoint %02X...\n", endpoint_in);
704 		r = libusb_interrupt_transfer(handle, endpoint_in, report_buffer, size, &size, 5000);
705 		if (r >= 0) {
706 			display_buffer_hex(report_buffer, (unsigned int)size);
707 		} else {
708 			printf("   %s\n", libusb_strerror((enum libusb_error)r));
709 		}
710 
711 		free(report_buffer);
712 	}
713 	return 0;
714 }
715 
716 // Read the MS WinUSB Feature Descriptors, that are used on Windows 8 for automated driver installation
read_ms_winsub_feature_descriptors(libusb_device_handle * handle,uint8_t bRequest,int iface_number)717 static void read_ms_winsub_feature_descriptors(libusb_device_handle *handle, uint8_t bRequest, int iface_number)
718 {
719 #define MAX_OS_FD_LENGTH 256
720 	int i, r;
721 	uint8_t os_desc[MAX_OS_FD_LENGTH];
722 	uint32_t length;
723 	void* le_type_punning_IS_fine;
724 	struct {
725 		const char* desc;
726 		uint8_t recipient;
727 		uint16_t index;
728 		uint16_t header_size;
729 	} os_fd[2] = {
730 		{"Extended Compat ID", LIBUSB_RECIPIENT_DEVICE, 0x0004, 0x10},
731 		{"Extended Properties", LIBUSB_RECIPIENT_INTERFACE, 0x0005, 0x0A}
732 	};
733 
734 	if (iface_number < 0) return;
735 	// WinUSB has a limitation that forces wIndex to the interface number when issuing
736 	// an Interface Request. To work around that, we can force a Device Request for
737 	// the Extended Properties, assuming the device answers both equally.
738 	if (force_device_request)
739 		os_fd[1].recipient = LIBUSB_RECIPIENT_DEVICE;
740 
741 	for (i=0; i<2; i++) {
742 		printf("\nReading %s OS Feature Descriptor (wIndex = 0x%04d):\n", os_fd[i].desc, os_fd[i].index);
743 
744 		// Read the header part
745 		r = libusb_control_transfer(handle, (uint8_t)(LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_VENDOR|os_fd[i].recipient),
746 			bRequest, (uint16_t)(((iface_number)<< 8)|0x00), os_fd[i].index, os_desc, os_fd[i].header_size, 1000);
747 		if (r < os_fd[i].header_size) {
748 			perr("   Failed: %s", (r<0)?libusb_strerror((enum libusb_error)r):"header size is too small");
749 			return;
750 		}
751 		le_type_punning_IS_fine = (void*)os_desc;
752 		length = *((uint32_t*)le_type_punning_IS_fine);
753 		if (length > MAX_OS_FD_LENGTH) {
754 			length = MAX_OS_FD_LENGTH;
755 		}
756 
757 		// Read the full feature descriptor
758 		r = libusb_control_transfer(handle, (uint8_t)(LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_VENDOR|os_fd[i].recipient),
759 			bRequest, (uint16_t)(((iface_number)<< 8)|0x00), os_fd[i].index, os_desc, (uint16_t)length, 1000);
760 		if (r < 0) {
761 			perr("   Failed: %s", libusb_strerror((enum libusb_error)r));
762 			return;
763 		} else {
764 			display_buffer_hex(os_desc, (unsigned int)r);
765 		}
766 	}
767 }
768 
print_sublink_speed_attribute(struct libusb_ssplus_sublink_attribute * ss_attr)769 static void print_sublink_speed_attribute(struct libusb_ssplus_sublink_attribute* ss_attr) {
770 	static const char exponent[] = " KMG";
771 	printf("                  id=%u speed=%u%cbs %s %s SuperSpeed%s",
772 		ss_attr->ssid,
773 		ss_attr->mantissa,
774 		(exponent[ss_attr->exponent]),
775 		(ss_attr->type == LIBUSB_SSPLUS_ATTR_TYPE_ASYM)? "Asym" : "Sym",
776 		(ss_attr->direction == LIBUSB_SSPLUS_ATTR_DIR_TX)? "TX" : "RX",
777 		(ss_attr->protocol == LIBUSB_SSPLUS_ATTR_PROT_SSPLUS)? "Plus": "" );
778 }
779 
print_device_cap(struct libusb_bos_dev_capability_descriptor * dev_cap)780 static void print_device_cap(struct libusb_bos_dev_capability_descriptor *dev_cap)
781 {
782 	switch(dev_cap->bDevCapabilityType) {
783 	case LIBUSB_BT_USB_2_0_EXTENSION: {
784 		struct libusb_usb_2_0_extension_descriptor *usb_2_0_ext = NULL;
785 		libusb_get_usb_2_0_extension_descriptor(NULL, dev_cap, &usb_2_0_ext);
786 		if (usb_2_0_ext) {
787 			printf("    USB 2.0 extension:\n");
788 			printf("      attributes             : %02X\n", usb_2_0_ext->bmAttributes);
789 			libusb_free_usb_2_0_extension_descriptor(usb_2_0_ext);
790 		}
791 		break;
792 	}
793 	case LIBUSB_BT_SS_USB_DEVICE_CAPABILITY: {
794 		struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap = NULL;
795 		libusb_get_ss_usb_device_capability_descriptor(NULL, dev_cap, &ss_usb_device_cap);
796 		if (ss_usb_device_cap) {
797 			printf("    USB 3.0 capabilities:\n");
798 			printf("      attributes             : %02X\n", ss_usb_device_cap->bmAttributes);
799 			printf("      supported speeds       : %04X\n", ss_usb_device_cap->wSpeedSupported);
800 			printf("      supported functionality: %02X\n", ss_usb_device_cap->bFunctionalitySupport);
801 			libusb_free_ss_usb_device_capability_descriptor(ss_usb_device_cap);
802 		}
803 		break;
804 	}
805 	case LIBUSB_BT_CONTAINER_ID: {
806 		struct libusb_container_id_descriptor *container_id = NULL;
807 		libusb_get_container_id_descriptor(NULL, dev_cap, &container_id);
808 		if (container_id) {
809 			printf("    Container ID:\n      %s\n", uuid_to_string(container_id->ContainerID));
810 			libusb_free_container_id_descriptor(container_id);
811 		}
812 		break;
813 	}
814 	case LIBUSB_BT_PLATFORM_DESCRIPTOR: {
815 		struct libusb_platform_descriptor *platform_descriptor = NULL;
816 		libusb_get_platform_descriptor(NULL, dev_cap, &platform_descriptor);
817 		if (platform_descriptor) {
818 			printf("    Platform descriptor:\n");
819 			printf("      bLength                : %d\n", platform_descriptor->bLength);
820 			printf("      PlatformCapabilityUUID : %s\n", uuid_to_string(platform_descriptor->PlatformCapabilityUUID));
821 			display_buffer_hex(&platform_descriptor->CapabilityData[0], platform_descriptor->bLength - 20);
822 			printf("\n");
823 			libusb_free_platform_descriptor(platform_descriptor);
824 		}
825 		break;
826 
827 	}
828 	case LIBUSB_BT_SUPERSPEED_PLUS_CAPABILITY: {
829 		struct libusb_ssplus_usb_device_capability_descriptor *ssplus_usb_device_cap = NULL;
830 		libusb_get_ssplus_usb_device_capability_descriptor(NULL, dev_cap, &ssplus_usb_device_cap);
831 		if (ssplus_usb_device_cap) {
832 			printf("    USB 3.1 capabilities:\n");
833 			printf("      num speed IDs: %d\n", ssplus_usb_device_cap->numSublinkSpeedIDs);
834 			printf("      minLaneSpeed: %d\n", ssplus_usb_device_cap->ssid);
835 			printf("      minRXLanes: %d\n", ssplus_usb_device_cap->minRxLaneCount);
836 			printf("      minTXLanes: %d\n", ssplus_usb_device_cap->minTxLaneCount);
837 
838 			printf("      num speed attribute IDs: %d\n", ssplus_usb_device_cap->numSublinkSpeedAttributes);
839 			for(uint8_t i=0 ; i < ssplus_usb_device_cap->numSublinkSpeedAttributes ; i++) {
840 				print_sublink_speed_attribute(&ssplus_usb_device_cap->sublinkSpeedAttributes[i]);
841 				printf("\n");
842 			}
843 			libusb_free_ssplus_usb_device_capability_descriptor(ssplus_usb_device_cap);
844 		}
845 		break;
846 	}
847 	default:
848 		printf("    Unknown BOS device capability %02x:\n", dev_cap->bDevCapabilityType);
849 	}
850 }
851 
test_device(uint16_t vid,uint16_t pid)852 static int test_device(uint16_t vid, uint16_t pid)
853 {
854 	libusb_device_handle *handle;
855 	libusb_device *dev;
856 	uint8_t bus, port_path[8];
857 	struct libusb_config_descriptor *conf_desc;
858 	const struct libusb_endpoint_descriptor *endpoint;
859 	int i, j, k, r;
860 	int iface, nb_ifaces, first_iface = -1;
861 	struct libusb_device_descriptor dev_desc;
862 	const char* const speed_name[] = { "Unknown", "1.5 Mbit/s (USB LowSpeed)", "12 Mbit/s (USB FullSpeed)",
863 		"480 Mbit/s (USB HighSpeed)", "5000 Mbit/s (USB SuperSpeed)", "10000 Mbit/s (USB SuperSpeedPlus)",
864 		"20000 Mbit/s (USB SuperSpeedPlus x2)" };
865 	unsigned char string[128];
866 	uint8_t string_index[3];	// indexes of the string descriptors
867 	uint8_t endpoint_in = 0, endpoint_out = 0;	// default IN and OUT endpoints
868 
869 	printf("Opening device %04X:%04X...\n", vid, pid);
870 	handle = libusb_open_device_with_vid_pid(NULL, vid, pid);
871 
872 	if (handle == NULL) {
873 		perr("  Failed.\n");
874 		return -1;
875 	}
876 
877 	dev = libusb_get_device(handle);
878 	bus = libusb_get_bus_number(dev);
879 	if (extra_info) {
880 		r = libusb_get_port_numbers(dev, port_path, sizeof(port_path));
881 		if (r > 0) {
882 			printf("\nDevice properties:\n");
883 			printf("        bus number: %d\n", bus);
884 			printf("         port path: %d", port_path[0]);
885 			for (i=1; i<r; i++) {
886 				printf("->%d", port_path[i]);
887 			}
888 			printf(" (from root hub)\n");
889 		}
890 		r = libusb_get_device_speed(dev);
891 		if ((r < 0) || ((size_t)r >= ARRAYSIZE(speed_name)))
892 			r = 0;
893 		printf("             speed: %s\n", speed_name[r]);
894 	}
895 
896 	printf("\nReading device descriptor:\n");
897 	CALL_CHECK_CLOSE(libusb_get_device_descriptor(dev, &dev_desc), handle);
898 	printf("            length: %d\n", dev_desc.bLength);
899 	printf("      device class: %d\n", dev_desc.bDeviceClass);
900 	printf("               S/N: %d\n", dev_desc.iSerialNumber);
901 	printf("           VID:PID: %04X:%04X\n", dev_desc.idVendor, dev_desc.idProduct);
902 	printf("         bcdDevice: %04X\n", dev_desc.bcdDevice);
903 	printf("   iMan:iProd:iSer: %d:%d:%d\n", dev_desc.iManufacturer, dev_desc.iProduct, dev_desc.iSerialNumber);
904 	printf("          nb confs: %d\n", dev_desc.bNumConfigurations);
905 	// Copy the string descriptors for easier parsing
906 	string_index[0] = dev_desc.iManufacturer;
907 	string_index[1] = dev_desc.iProduct;
908 	string_index[2] = dev_desc.iSerialNumber;
909 
910 	if (dev_desc.bcdUSB >= 0x0201) {
911 		struct libusb_bos_descriptor *bos_desc;
912 
913 		printf("\nReading BOS descriptor: ");
914 		if (libusb_get_bos_descriptor(handle, &bos_desc) == LIBUSB_SUCCESS) {
915 			printf("%d caps\n", bos_desc->bNumDeviceCaps);
916 			for (i = 0; i < bos_desc->bNumDeviceCaps; i++)
917 				print_device_cap(bos_desc->dev_capability[i]);
918 			libusb_free_bos_descriptor(bos_desc);
919 		} else {
920 			printf("no descriptor\n");
921 		}
922 	}
923 
924 	printf("\nReading first configuration descriptor:\n");
925 	CALL_CHECK_CLOSE(libusb_get_config_descriptor(dev, 0, &conf_desc), handle);
926 	printf("              total length: %d\n", conf_desc->wTotalLength);
927 	printf("         descriptor length: %d\n", conf_desc->bLength);
928 	nb_ifaces = conf_desc->bNumInterfaces;
929 	printf("             nb interfaces: %d\n", nb_ifaces);
930 	if (nb_ifaces > 0)
931 		first_iface = conf_desc->usb_interface[0].altsetting[0].bInterfaceNumber;
932 	for (i=0; i<nb_ifaces; i++) {
933 		printf("              interface[%d]: id = %d\n", i,
934 			conf_desc->usb_interface[i].altsetting[0].bInterfaceNumber);
935 		for (j=0; j<conf_desc->usb_interface[i].num_altsetting; j++) {
936 			printf("interface[%d].altsetting[%d]: num endpoints = %d\n",
937 				i, j, conf_desc->usb_interface[i].altsetting[j].bNumEndpoints);
938 			printf("   Class.SubClass.Protocol: %02X.%02X.%02X\n",
939 				conf_desc->usb_interface[i].altsetting[j].bInterfaceClass,
940 				conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass,
941 				conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol);
942 			if ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceClass == LIBUSB_CLASS_MASS_STORAGE)
943 			  && ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x01)
944 			  || (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x06) )
945 			  && (conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol == 0x50) ) {
946 				// Mass storage devices that can use basic SCSI commands
947 				test_mode = USE_SCSI;
948 			}
949 			for (k=0; k<conf_desc->usb_interface[i].altsetting[j].bNumEndpoints; k++) {
950 				struct libusb_ss_endpoint_companion_descriptor *ep_comp = NULL;
951 				endpoint = &conf_desc->usb_interface[i].altsetting[j].endpoint[k];
952 				printf("       endpoint[%d].address: %02X\n", k, endpoint->bEndpointAddress);
953 				// Use the first interrupt or bulk IN/OUT endpoints as default for testing
954 				if ((endpoint->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) & (LIBUSB_TRANSFER_TYPE_BULK | LIBUSB_TRANSFER_TYPE_INTERRUPT)) {
955 					if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) {
956 						if (!endpoint_in)
957 							endpoint_in = endpoint->bEndpointAddress;
958 					} else {
959 						if (!endpoint_out)
960 							endpoint_out = endpoint->bEndpointAddress;
961 					}
962 				}
963 				printf("           max packet size: %04X\n", endpoint->wMaxPacketSize);
964 				printf("          polling interval: %02X\n", endpoint->bInterval);
965 				libusb_get_ss_endpoint_companion_descriptor(NULL, endpoint, &ep_comp);
966 				if (ep_comp) {
967 					printf("                 max burst: %02X   (USB 3.0)\n", ep_comp->bMaxBurst);
968 					printf("        bytes per interval: %04X (USB 3.0)\n", ep_comp->wBytesPerInterval);
969 					libusb_free_ss_endpoint_companion_descriptor(ep_comp);
970 				}
971 			}
972 		}
973 	}
974 	libusb_free_config_descriptor(conf_desc);
975 
976 	libusb_set_auto_detach_kernel_driver(handle, 1);
977 	for (iface = 0; iface < nb_ifaces; iface++)
978 	{
979 		int ret;
980 
981 		printf("\nKernel driver attached for interface %d: ", iface);
982 		ret = libusb_kernel_driver_active(handle, iface);
983 		if (ret == 0)
984 			printf("none\n");
985 		else if (ret == 1)
986 			printf("yes\n");
987 		else if (ret == LIBUSB_ERROR_NOT_SUPPORTED)
988 			printf("(not supported)\n");
989 		else
990 			perr("\n   Failed (error %d) %s\n", ret,
991 			     libusb_strerror((enum libusb_error) ret));
992 
993 		printf("\nClaiming interface %d...\n", iface);
994 		r = libusb_claim_interface(handle, iface);
995 		if (r != LIBUSB_SUCCESS) {
996 			perr("   Failed (error %d) %s\n", ret,
997 			     libusb_strerror((enum libusb_error) ret));
998 		}
999 	}
1000 
1001 	printf("\nReading string descriptors:\n");
1002 	for (i=0; i<3; i++) {
1003 		if (string_index[i] == 0) {
1004 			continue;
1005 		}
1006 		if (libusb_get_string_descriptor_ascii(handle, string_index[i], string, sizeof(string)) > 0) {
1007 			printf("   String (0x%02X): \"%s\"\n", string_index[i], string);
1008 		}
1009 	}
1010 
1011 	printf("\nReading OS string descriptor:");
1012 	r = libusb_get_string_descriptor(handle, MS_OS_DESC_STRING_INDEX, 0, string, MS_OS_DESC_STRING_LENGTH);
1013 	if (r == MS_OS_DESC_STRING_LENGTH && memcmp(ms_os_desc_string, string, sizeof(ms_os_desc_string)) == 0) {
1014 		// If this is a Microsoft OS String Descriptor,
1015 		// attempt to read the WinUSB extended Feature Descriptors
1016 		printf("\n");
1017 		read_ms_winsub_feature_descriptors(handle, string[MS_OS_DESC_VENDOR_CODE_OFFSET], first_iface);
1018 	} else {
1019 		printf(" no descriptor\n");
1020 	}
1021 
1022 	// Read IADs
1023 	printf("\nReading interface association descriptors (IADs) for first configuration:\n");
1024 	struct libusb_interface_association_descriptor_array *iad_array;
1025 	r = libusb_get_interface_association_descriptors(dev, 0, &iad_array);
1026 	if (r == LIBUSB_SUCCESS) {
1027 		printf("    nb IADs: %d\n", iad_array->length);
1028 		for (i=0; i<iad_array->length;i++) {
1029 			const struct libusb_interface_association_descriptor *iad = &iad_array->iad[i];
1030 			printf("      IAD %d:\n", i);
1031 			printf("            bFirstInterface: %u\n", iad->bFirstInterface);
1032 			printf("            bInterfaceCount: %u\n", iad->bInterfaceCount);
1033 			printf("             bFunctionClass: %02X\n", iad->bFunctionClass);
1034 			printf("          bFunctionSubClass: %02X\n", iad->bFunctionSubClass);
1035 			printf("          bFunctionProtocol: %02X\n", iad->bFunctionProtocol);
1036 			if (iad->iFunction) {
1037 				if (libusb_get_string_descriptor_ascii(handle, iad->iFunction, string, sizeof(string)) > 0)
1038 					printf("                  iFunction: %u (%s)\n", iad->iFunction, string);
1039 				else
1040 					printf("                  iFunction: %u (libusb_get_string_descriptor_ascii failed!)\n", iad->iFunction);
1041 			}
1042 			else
1043 				printf("                  iFunction: 0\n");
1044 		}
1045 		libusb_free_interface_association_descriptors(iad_array);
1046 	}
1047 
1048 	switch(test_mode) {
1049 	case USE_PS3:
1050 		CALL_CHECK_CLOSE(display_ps3_status(handle), handle);
1051 		break;
1052 	case USE_XBOX:
1053 		CALL_CHECK_CLOSE(display_xbox_status(handle), handle);
1054 		CALL_CHECK_CLOSE(set_xbox_actuators(handle, 128, 222), handle);
1055 		msleep(2000);
1056 		CALL_CHECK_CLOSE(set_xbox_actuators(handle, 0, 0), handle);
1057 		break;
1058 	case USE_HID:
1059 		test_hid(handle, endpoint_in);
1060 		break;
1061 	case USE_SCSI:
1062 		CALL_CHECK_CLOSE(test_mass_storage(handle, endpoint_in, endpoint_out), handle);
1063 		break;
1064 	case USE_GENERIC:
1065 		break;
1066 	}
1067 
1068 	printf("\n");
1069 	for (iface = 0; iface<nb_ifaces; iface++) {
1070 		printf("Releasing interface %d...\n", iface);
1071 		libusb_release_interface(handle, iface);
1072 	}
1073 
1074 	printf("Closing device...\n");
1075 	libusb_close(handle);
1076 
1077 	return 0;
1078 }
1079 
main(int argc,char ** argv)1080 int main(int argc, char** argv)
1081 {
1082 	bool show_help = false;
1083 	bool debug_mode = false;
1084 	const struct libusb_version* version;
1085 	int j, r;
1086 	size_t i, arglen;
1087 	unsigned tmp_vid, tmp_pid;
1088 	uint16_t endian_test = 0xBE00;
1089 	char *error_lang = NULL, *old_dbg_str = NULL, str[256];
1090 
1091 	// Default to generic, expecting VID:PID
1092 	VID = 0;
1093 	PID = 0;
1094 	test_mode = USE_GENERIC;
1095 
1096 	if (((uint8_t*)&endian_test)[0] == 0xBE) {
1097 		printf("Despite their natural superiority for end users, big endian\n"
1098 			"CPUs are not supported with this program, sorry.\n");
1099 		return 0;
1100 	}
1101 
1102 	if (argc >= 2) {
1103 		for (j = 1; j<argc; j++) {
1104 			arglen = strlen(argv[j]);
1105 			if ( ((argv[j][0] == '-') || (argv[j][0] == '/'))
1106 			  && (arglen >= 2) ) {
1107 				switch(argv[j][1]) {
1108 				case 'd':
1109 					debug_mode = true;
1110 					break;
1111 				case 'i':
1112 					extra_info = true;
1113 					break;
1114 				case 'w':
1115 					force_device_request = true;
1116 					break;
1117 				case 'b':
1118 					if ((j+1 >= argc) || (argv[j+1][0] == '-') || (argv[j+1][0] == '/')) {
1119 						printf("   Option -b requires a file name\n");
1120 						return 1;
1121 					}
1122 					binary_name = argv[++j];
1123 					binary_dump = true;
1124 					break;
1125 				case 'l':
1126 					if ((j+1 >= argc) || (argv[j+1][0] == '-') || (argv[j+1][0] == '/')) {
1127 						printf("   Option -l requires an ISO 639-1 language parameter\n");
1128 						return 1;
1129 					}
1130 					error_lang = argv[++j];
1131 					break;
1132 				case 'j':
1133 					// OLIMEX ARM-USB-TINY JTAG, 2 channel composite device - 2 interfaces
1134 					if (!VID && !PID) {
1135 						VID = 0x15BA;
1136 						PID = 0x0004;
1137 					}
1138 					break;
1139 				case 'k':
1140 					// Generic 2 GB USB Key (SCSI Transparent/Bulk Only) - 1 interface
1141 					if (!VID && !PID) {
1142 						VID = 0x0204;
1143 						PID = 0x6025;
1144 					}
1145 					break;
1146 				// The following tests will force VID:PID if already provided
1147 				case 'p':
1148 					// Sony PS3 Controller - 1 interface
1149 					VID = 0x054C;
1150 					PID = 0x0268;
1151 					test_mode = USE_PS3;
1152 					break;
1153 				case 's':
1154 					// Microsoft Sidewinder Precision Pro Joystick - 1 HID interface
1155 					VID = 0x045E;
1156 					PID = 0x0008;
1157 					test_mode = USE_HID;
1158 					break;
1159 				case 'x':
1160 					// Microsoft XBox Controller Type S - 1 interface
1161 					VID = 0x045E;
1162 					PID = 0x0289;
1163 					test_mode = USE_XBOX;
1164 					break;
1165 				default:
1166 					show_help = true;
1167 					break;
1168 				}
1169 			} else {
1170 				for (i=0; i<arglen; i++) {
1171 					if (argv[j][i] == ':')
1172 						break;
1173 				}
1174 				if (i != arglen) {
1175 					if (sscanf(argv[j], "%x:%x" , &tmp_vid, &tmp_pid) != 2) {
1176 						printf("   Please specify VID & PID as \"vid:pid\" in hexadecimal format\n");
1177 						return 1;
1178 					}
1179 					VID = (uint16_t)tmp_vid;
1180 					PID = (uint16_t)tmp_pid;
1181 				} else {
1182 					show_help = true;
1183 				}
1184 			}
1185 		}
1186 	}
1187 
1188 	if ((show_help) || (argc == 1) || (argc > 7)) {
1189 		printf("usage: %s [-h] [-d] [-i] [-k] [-b file] [-l lang] [-j] [-x] [-s] [-p] [-w] [vid:pid]\n", argv[0]);
1190 		printf("   -h      : display usage\n");
1191 		printf("   -d      : enable debug output\n");
1192 		printf("   -i      : print topology and speed info\n");
1193 		printf("   -j      : test composite FTDI based JTAG device\n");
1194 		printf("   -k      : test Mass Storage device\n");
1195 		printf("   -b file : dump Mass Storage data to file 'file'\n");
1196 		printf("   -p      : test Sony PS3 SixAxis controller\n");
1197 		printf("   -s      : test Microsoft Sidewinder Precision Pro (HID)\n");
1198 		printf("   -x      : test Microsoft XBox Controller Type S\n");
1199 		printf("   -l lang : language to report errors in (ISO 639-1)\n");
1200 		printf("   -w      : force the use of device requests when querying WCID descriptors\n");
1201 		printf("If only the vid:pid is provided, xusb attempts to run the most appropriate test\n");
1202 		return 0;
1203 	}
1204 
1205 	version = libusb_get_version();
1206 	printf("Using libusb v%d.%d.%d.%d\n\n", version->major, version->minor, version->micro, version->nano);
1207 
1208 	// xusb is commonly used as a debug tool, so it's convenient to have debug output during libusb_init_context().
1209 	if (debug_mode) {
1210 		const struct libusb_init_option options = {.option = LIBUSB_OPTION_LOG_LEVEL, .value = {.ival = LIBUSB_LOG_LEVEL_DEBUG}};
1211 		r = libusb_init_context(/*ctx=*/NULL, /*options=*/&options, /*num_options=*/1);
1212 	} else {
1213 		r = libusb_init_context(/*ctx=*/NULL, /*options=*/NULL, /*num_options=*/0);
1214 	}
1215 
1216 	if (r < 0)
1217 		return r;
1218 
1219 	// If not set externally, and no debug option was given, use info log level
1220 	if ((old_dbg_str == NULL) && (!debug_mode))
1221 		libusb_set_option(NULL, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO);
1222 	if (error_lang != NULL) {
1223 		r = libusb_setlocale(error_lang);
1224 		if (r < 0)
1225 			printf("Invalid or unsupported locale '%s': %s\n", error_lang, libusb_strerror((enum libusb_error)r));
1226 	}
1227 
1228 	test_device(VID, PID);
1229 
1230 	libusb_exit(NULL);
1231 
1232 	if (debug_mode) {
1233 		snprintf(str, sizeof(str), "LIBUSB_DEBUG=%s", (old_dbg_str == NULL)?"":old_dbg_str);
1234 		str[sizeof(str) - 1] = 0;	// Windows may not NUL terminate the string
1235 	}
1236 
1237 	return 0;
1238 }
1239