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