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