db502808d5ae9e6bd4e75c28eeae29f59eeaf8eb
[libusb-pbatard.git] / examples / xusb.c
1 /*
2  * xusb: Generic USB test program
3  * Copyright (c) 2009-2011 Pete Batard <pbatard@gmail.com>
4  * Based on lsusb, copyright (c) 2007 Daniel Drake <dsd@gentoo.org>
5  * With contributions to Mass Storage test by Alan Stern.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <stdio.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <stdarg.h>
27
28 #include "libusb.h"
29
30 #if defined(_WIN32)
31 #define msleep(msecs) Sleep(msecs)
32 #else
33 #include <unistd.h>
34 #define msleep(msecs) usleep(1000*msecs)
35 #endif
36
37 #if !defined(_MSC_VER) || _MSC_VER<=1200
38 #define sscanf_s sscanf
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
52 // Future versions of libusb will use usb_interface instead of interface
53 // in libusb_config_descriptor => catter for that
54 #define usb_interface interface
55
56 // Global variables
57 bool binary_dump = false;
58 char binary_name[64];
59
60 inline static int perr(char const *format, ...)
61 {
62         va_list args;
63         int r;
64
65         va_start (args, format);
66         r = vfprintf(stderr, format, args);
67         va_end(args);
68
69         return r;
70 }
71
72 #define ERR_EXIT(errcode) do { perr("   %s\n", libusb_strerror((enum libusb_error)errcode)); return -1; } while (0)
73 #define CALL_CHECK(fcall) do { r=fcall; if (r < 0) ERR_EXIT(r); } while (0);
74 #define B(x) (((x)!=0)?1:0)
75 #define be_to_int32(buf) (((buf)[0]<<24)|((buf)[1]<<16)|((buf)[2]<<8)|(buf)[3])
76
77 #define RETRY_MAX                     5
78 #define REQUEST_SENSE_LENGTH          0x12
79 #define INQUIRY_LENGTH                0x24
80 #define READ_CAPACITY_LENGTH          0x08
81
82 // HID Class-Specific Requests values. See section 7.2 of the HID specifications
83 #define HID_GET_REPORT                0x01
84 #define HID_SET_REPORT                0x09
85 #define HID_REPORT_TYPE_INPUT         0x01
86 #define HID_REPORT_TYPE_OUTPUT        0x02
87
88 // Mass Storage Requests values. See section 3 of the Bulk-Only Mass Storage Class specifications
89 #define BOMS_RESET                    0xFF
90 #define BOMS_GET_MAX_LUN              0xFE
91
92 // Section 5.1: Command Block Wrapper (CBW)
93 struct command_block_wrapper {
94         uint8_t dCBWSignature[4];
95         uint32_t dCBWTag;
96         uint32_t dCBWDataTransferLength;
97         uint8_t bmCBWFlags;
98         uint8_t bCBWLUN;
99         uint8_t bCBWCBLength;
100         uint8_t CBWCB[16];
101 };
102
103 // Section 5.2: Command Status Wrapper (CSW)
104 struct command_status_wrapper {
105         uint8_t dCSWSignature[4];
106         uint32_t dCSWTag;
107         uint32_t dCSWDataResidue;
108         uint8_t bCSWStatus;
109 };
110
111 static uint8_t cdb_length[256] = {
112 //       0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
113         06,06,06,06,06,06,06,06,06,06,06,06,06,06,06,06,  //  0
114         06,06,06,06,06,06,06,06,06,06,06,06,06,06,06,06,  //  1
115         10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,  //  2
116         10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,  //  3
117         10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,  //  4
118         10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,  //  5
119         00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  6
120         00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  7
121         16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,  //  8
122         16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,  //  9
123         12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,  //  A
124         12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,  //  B
125         00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  C
126         00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  D
127         00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  E
128         00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,  //  F
129 };
130
131 enum test_type {
132         USE_GENERIC,
133         USE_PS3,
134         USE_XBOX,
135         USE_SCSI,
136 } test_mode;
137 uint16_t VID, PID;
138
139 void display_buffer_hex(unsigned char *buffer, unsigned size)
140 {
141         unsigned i, j, k;
142
143         for (i=0; i<size; i+=16) {
144                 printf("\n  %08x  ", i);
145                 for(j=0,k=0; k<16; j++,k++) {
146                         if (i+j < size) {
147                                 printf("%02x", buffer[i+j]);
148                         } else {
149                                 printf("  ");
150                         }
151                         printf(" ");
152                 }
153                 printf(" ");
154                 for(j=0,k=0; k<16; j++,k++) {
155                         if (i+j < size) {
156                                 if ((buffer[i+j] < 32) || (buffer[i+j] > 126)) {
157                                         printf(".");
158                                 } else {
159                                         printf("%c", buffer[i+j]);
160                                 }
161                         }
162                 }
163         }
164         printf("\n" );
165 }
166
167 // The PS3 Controller is really a HID device that got its HID Report Descriptors
168 // removed by Sony
169 int display_ps3_status(libusb_device_handle *handle)
170 {
171         int r;
172         uint8_t input_report[49];
173         uint8_t master_bt_address[8];
174         uint8_t device_bt_address[18];
175
176         // Get the controller's bluetooth address of its master device
177         CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
178                 HID_GET_REPORT, 0x03f5, 0, master_bt_address, sizeof(master_bt_address), 100));
179         printf("\nMaster's bluetooth address: %02X:%02X:%02X:%02X:%02X:%02X\n", master_bt_address[2], master_bt_address[3],
180                 master_bt_address[4], master_bt_address[5], master_bt_address[6], master_bt_address[7]);
181
182         // Get the controller's bluetooth address
183         CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
184                 HID_GET_REPORT, 0x03f2, 0, device_bt_address, sizeof(device_bt_address), 100));
185         printf("\nMaster's bluetooth address: %02X:%02X:%02X:%02X:%02X:%02X\n", device_bt_address[4], device_bt_address[5],
186                 device_bt_address[6], device_bt_address[7], device_bt_address[8], device_bt_address[9]);
187
188         // Get the status of the controller's buttons via its HID report
189         printf("\nReading PS3 Input Report...\n");
190         CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
191                 HID_GET_REPORT, (HID_REPORT_TYPE_INPUT<<8)|0x01, 0, input_report, sizeof(input_report), 1000));
192         switch(input_report[2]){        /** Direction pad plus start, select, and joystick buttons */
193                 case 0x01:
194                         printf("\tSELECT pressed\n");
195                         break;
196                 case 0x02:
197                         printf("\tLEFT 3 pressed\n");
198                         break;
199                 case 0x04:
200                         printf("\tRIGHT 3 pressed\n");
201                         break;
202                 case 0x08:
203                         printf("\tSTART presed\n");
204                         break;
205                 case 0x10:
206                         printf("\tUP pressed\n");
207                         break;
208                 case 0x20:
209                         printf("\tRIGHT pressed\n");
210                         break;
211                 case 0x40:
212                         printf("\tDOWN pressed\n");
213                         break;
214                 case 0x80:
215                         printf("\tLEFT pressed\n");
216                         break;
217         }
218         switch(input_report[3]){        /** Shapes plus top right and left buttons */
219                 case 0x01:
220                         printf("\tLEFT 2 pressed\n");
221                         break;
222                 case 0x02:
223                         printf("\tRIGHT 2 pressed\n");
224                         break;
225                 case 0x04:
226                         printf("\tLEFT 1 pressed\n");
227                         break;
228                 case 0x08:
229                         printf("\tRIGHT 1 presed\n");
230                         break;
231                 case 0x10:
232                         printf("\tTRIANGLE pressed\n");
233                         break;
234                 case 0x20:
235                         printf("\tCIRCLE pressed\n");
236                         break;
237                 case 0x40:
238                         printf("\tCROSS pressed\n");
239                         break;
240                 case 0x80:
241                         printf("\tSQUARE pressed\n");
242                         break;
243         }
244         printf("\tPS button: %d\n", input_report[4]);
245         printf("\tLeft Analog (X,Y): (%d,%d)\n", input_report[6], input_report[7]);
246         printf("\tRight Analog (X,Y): (%d,%d)\n", input_report[8], input_report[9]);
247         printf("\tL2 Value: %d\tR2 Value: %d\n", input_report[18], input_report[19]);
248         printf("\tL1 Value: %d\tR1 Value: %d\n", input_report[20], input_report[21]);
249         printf("\tRoll (x axis): %d Yaw (y axis): %d Pitch (z axis) %d\n",
250                         //(((input_report[42] + 128) % 256) - 128),
251                         (int8_t)(input_report[42]),
252                         (int8_t)(input_report[44]),
253                         (int8_t)(input_report[46]));
254         printf("\tAcceleration: %d\n\n", (int8_t)(input_report[48]));
255         return 0;
256 }
257 // The XBOX Controller is really a HID device that got its HID Report Descriptors
258 // removed by Microsoft.
259 // Input/Output reports described at http://euc.jp/periphs/xbox-controller.ja.html
260 int display_xbox_status(libusb_device_handle *handle)
261 {
262         int r;
263         uint8_t input_report[20];
264         printf("\nReading XBox Input Report...\n");
265         CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
266                 HID_GET_REPORT, (HID_REPORT_TYPE_INPUT<<8)|0x00, 0, input_report, 20, 1000));
267         printf("   D-pad: %02X\n", input_report[2]&0x0F);
268         printf("   Start:%d, Back:%d, Left Stick Press:%d, Right Stick Press:%d\n", B(input_report[2]&0x10), B(input_report[2]&0x20),
269                 B(input_report[2]&0x40), B(input_report[2]&0x80));
270         // A, B, X, Y, Black, White are pressure sensitive
271         printf("   A:%d, B:%d, X:%d, Y:%d, White:%d, Black:%d\n", input_report[4], input_report[5],
272                 input_report[6], input_report[7], input_report[9], input_report[8]);
273         printf("   Left Trigger: %d, Right Trigger: %d\n", input_report[10], input_report[11]);
274         printf("   Left Analog (X,Y): (%d,%d)\n", (int16_t)((input_report[13]<<8)|input_report[12]),
275                 (int16_t)((input_report[15]<<8)|input_report[14]));
276         printf("   Right Analog (X,Y): (%d,%d)\n", (int16_t)((input_report[17]<<8)|input_report[16]),
277                 (int16_t)((input_report[19]<<8)|input_report[18]));
278         return 0;
279 }
280
281 int set_xbox_actuators(libusb_device_handle *handle, uint8_t left, uint8_t right)
282 {
283         int r;
284         uint8_t output_report[6];
285
286         printf("\nWriting XBox Controller Output Report...\n");
287
288         memset(output_report, 0, sizeof(output_report));
289         output_report[1] = sizeof(output_report);
290         output_report[3] = left;
291         output_report[5] = right;
292
293         CALL_CHECK(libusb_control_transfer(handle, LIBUSB_ENDPOINT_OUT|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
294                 HID_SET_REPORT, (HID_REPORT_TYPE_OUTPUT<<8)|0x00, 0, output_report, 06, 1000));
295         return 0;
296 }
297
298 int send_mass_storage_command(libusb_device_handle *handle, uint8_t endpoint, uint8_t lun,
299         uint8_t *cdb, uint8_t direction, int data_length, uint32_t *ret_tag)
300 {
301         static uint32_t tag = 1;
302         uint8_t cdb_len;
303         int i, r, size;
304         struct command_block_wrapper cbw;
305
306         if (cdb == NULL) {
307                 return -1;
308         }
309
310         if (endpoint & LIBUSB_ENDPOINT_IN) {
311                 perr("send_mass_storage_command: cannot send command on IN endpoint\n");
312                 return -1;
313         }
314
315         cdb_len = cdb_length[cdb[0]];
316         if ((cdb_len == 0) || (cdb_len > sizeof(cbw.CBWCB))) {
317                 perr("send_mass_storage_command: don't know how to handle this command (%02X, length %d)\n",
318                         cdb[0], cdb_len);
319                 return -1;
320         }
321
322         memset(&cbw, 0, sizeof(cbw));
323         cbw.dCBWSignature[0] = 'U';
324         cbw.dCBWSignature[1] = 'S';
325         cbw.dCBWSignature[2] = 'B';
326         cbw.dCBWSignature[3] = 'C';
327         *ret_tag = tag;
328         cbw.dCBWTag = tag++;
329         cbw.dCBWDataTransferLength = data_length;
330         cbw.bmCBWFlags = direction;
331         cbw.bCBWLUN = lun;
332         // Subclass is 1 or 6 => cdb_len
333         cbw.bCBWCBLength = cdb_len;
334         memcpy(cbw.CBWCB, cdb, cdb_len);
335
336         i = 0;
337         do {
338                 // The transfer length must always be exactly 31 bytes.
339                 r = libusb_bulk_transfer(handle, endpoint, (unsigned char*)&cbw, 31, &size, 1000);
340                 if (r == LIBUSB_ERROR_PIPE) {
341                         libusb_clear_halt(handle, endpoint);
342                 }
343                 i++;
344         } while ((r == LIBUSB_ERROR_PIPE) && (i<RETRY_MAX));
345         if (r != LIBUSB_SUCCESS) {
346                 perr("   send_mass_storage_command: %s\n", libusb_strerror(r));
347                 return -1;
348         }
349
350         printf("   sent %d CDB bytes\n", cdb_len);
351         return 0;
352 }
353
354 int get_mass_storage_status(libusb_device_handle *handle, uint8_t endpoint, uint32_t expected_tag)
355 {
356         int i, r, size;
357         struct command_status_wrapper csw;
358
359         // The device is allowed to STALL this transfer. If it does, you have to
360         // clear the stall and try again.
361         i = 0;
362         do {
363                 r = libusb_bulk_transfer(handle, endpoint, (unsigned char*)&csw, 13, &size, 1000);
364                 if (r == LIBUSB_ERROR_PIPE) {
365                         libusb_clear_halt(handle, endpoint);
366                 }
367                 i++;
368         } while ((r == LIBUSB_ERROR_PIPE) && (i<RETRY_MAX));
369         if (r != LIBUSB_SUCCESS) {
370                 perr("   get_mass_storage_status: %s\n", libusb_strerror(r));
371                 return -1;
372         }
373         if (size != 13) {
374                 perr("   get_mass_storage_status: received %d bytes (expected 13)\n", size);
375                 return -1;
376         }
377         if (csw.dCSWTag != expected_tag) {
378                 perr("   get_mass_storage_status: mismatched tags (expected %08X, received %08X)\n",
379                         expected_tag, csw.dCSWTag);
380                 return -1;
381         }
382         // For this test, we ignore the dCSWSignature check for validity...
383         printf("   Mass Storage Status: %02X (%s)\n", csw.bCSWStatus, csw.bCSWStatus?"FAILED":"Success");
384         if (csw.dCSWTag != expected_tag)
385                 return -1;
386         if (csw.bCSWStatus) {
387                 // REQUEST SENSE is appropriate only if bCSWStatus is 1, meaning that the
388                 // command failed somehow.  Larger values (2 in particular) mean that
389                 // the command couldn't be understood.
390                 if (csw.bCSWStatus == 1)
391                         return -2;      // request Get Sense
392                 else
393                         return -1;
394         }
395
396         // In theory we also should check dCSWDataResidue.  But lots of devices
397         // set it wrongly.
398         return 0;
399 }
400
401 void get_sense(libusb_device_handle *handle, uint8_t endpoint_in, uint8_t endpoint_out)
402 {
403         uint8_t cdb[16];        // SCSI Command Descriptor Block
404         uint8_t sense[18];
405         uint32_t expected_tag;
406         int size;
407
408         // Request Sense
409         printf("Request Sense:\n");
410         memset(sense, 0, sizeof(sense));
411         memset(cdb, 0, sizeof(cdb));
412         cdb[0] = 0x03;  // Request Sense
413         cdb[4] = REQUEST_SENSE_LENGTH;
414
415         send_mass_storage_command(handle, endpoint_out, 0, cdb, LIBUSB_ENDPOINT_IN, REQUEST_SENSE_LENGTH, &expected_tag);
416         libusb_bulk_transfer(handle, endpoint_in, (unsigned char*)&sense, REQUEST_SENSE_LENGTH, &size, 1000);
417         printf("   received %d bytes\n", size);
418
419         if ((sense[0] != 0x70) && (sense[0] != 0x71)) {
420                 perr("   ERROR No sense data\n");
421         } else {
422                 perr("   ERROR Sense: %02X %02X %02X\n", sense[2]&0x0F, sense[12], sense[13]);
423         }
424         // Strictly speaking, the get_mass_storage_status() call should come
425         // before these perr() lines.  If the status is nonzero then we must
426         // assume there's no data in the buffer.  For xusb it doesn't matter.
427         get_mass_storage_status(handle, endpoint_in, expected_tag);
428 }
429
430 // Mass Storage device to test bulk transfers (non destructive test)
431 int test_mass_storage(libusb_device_handle *handle, uint8_t endpoint_in, uint8_t endpoint_out)
432 {
433         int r, size;
434         uint8_t lun;
435         uint32_t expected_tag;
436         uint32_t i, max_lba, block_size;
437         double device_size;
438         uint8_t cdb[16];        // SCSI Command Descriptor Block
439         uint8_t buffer[64];
440         char vid[9], pid[9], rev[5];
441         unsigned char *data;
442         FILE *fd;
443
444         printf("Reading Max LUN:\n");
445         r = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE,
446                 BOMS_GET_MAX_LUN, 0, 0, &lun, 1, 1000);
447         // Some devices send a STALL instead of the actual value.
448         // In such cases we should set lun to 0.
449         if (r == 0) {
450                 lun = 0;
451         } else if (r < 0) {
452                 perr("   Failed: %s", libusb_strerror((enum libusb_error)r));
453         }
454         printf("   Max LUN = %d\n", lun);
455
456         // Send Inquiry
457         printf("Sending Inquiry:\n");
458         memset(buffer, 0, sizeof(buffer));
459         memset(cdb, 0, sizeof(cdb));
460         cdb[0] = 0x12;  // Inquiry
461         cdb[4] = INQUIRY_LENGTH;
462
463         send_mass_storage_command(handle, endpoint_out, lun, cdb, LIBUSB_ENDPOINT_IN, INQUIRY_LENGTH, &expected_tag);
464         CALL_CHECK(libusb_bulk_transfer(handle, endpoint_in, (unsigned char*)&buffer, INQUIRY_LENGTH, &size, 1000));
465         printf("   received %d bytes\n", size);
466         // The following strings are not zero terminated
467         for (i=0; i<8; i++) {
468                 vid[i] = buffer[8+i];
469                 pid[i] = buffer[16+i];
470                 rev[i/2] = buffer[32+i/2];      // instead of another loop
471         }
472         vid[8] = 0;
473         pid[8] = 0;
474         rev[4] = 0;
475         printf("   VID:PID:REV \"%8s\":\"%8s\":\"%4s\"\n", vid, pid, rev);
476         if (get_mass_storage_status(handle, endpoint_in, expected_tag) == -2) {
477                 get_sense(handle, endpoint_in, endpoint_out);
478         }
479
480         // Read capacity
481         printf("Reading Capacity:\n");
482         memset(buffer, 0, sizeof(buffer));
483         memset(cdb, 0, sizeof(cdb));
484         cdb[0] = 0x25;  // Read Capacity
485
486         send_mass_storage_command(handle, endpoint_out, lun, cdb, LIBUSB_ENDPOINT_IN, READ_CAPACITY_LENGTH, &expected_tag);
487         CALL_CHECK(libusb_bulk_transfer(handle, endpoint_in, (unsigned char*)&buffer, READ_CAPACITY_LENGTH, &size, 1000));
488         printf("   received %d bytes\n", size);
489         max_lba = be_to_int32(&buffer[0]);
490         block_size = be_to_int32(&buffer[4]);
491         device_size = ((double)(max_lba+1))*block_size/(1024*1024*1024);
492         printf("   Max LBA: %08X, Block Size: %08X (%.2f GB)\n", max_lba, block_size, device_size);
493         if (get_mass_storage_status(handle, endpoint_in, expected_tag) == -2) {
494                 get_sense(handle, endpoint_in, endpoint_out);
495         }
496
497         data = (unsigned char*) calloc(1, block_size);
498         if (data == NULL) {
499                 perr("   unable to allocate data buffer\n");
500                 return -1;
501         }
502
503         // Send Read
504         printf("Attempting to read %d bytes:\n", block_size);
505         memset(cdb, 0, sizeof(cdb));
506
507         cdb[0] = 0x28;  // Read(10)
508         cdb[8] = 0x01;  // 1 block
509
510         send_mass_storage_command(handle, endpoint_out, lun, cdb, LIBUSB_ENDPOINT_IN, block_size, &expected_tag);
511         libusb_bulk_transfer(handle, endpoint_in, data, block_size, &size, 5000);
512         printf("   READ: received %d bytes\n", size);
513         if (get_mass_storage_status(handle, endpoint_in, expected_tag) == -2) {
514                 get_sense(handle, endpoint_in, endpoint_out);
515         } else {
516                 display_buffer_hex(data, size);
517                 if ((binary_dump) && ((fd = fopen(binary_name, "w")) != NULL)) {
518                         if (fwrite(data, 1, (size_t)size, fd) != (unsigned int)size) {
519                                 perr("   unable to write binary data\n");
520                         }
521                         fclose(fd);
522                 }
523         }
524         free(data);
525
526         return 0;
527 }
528
529 // Read the MS WinUSB Feature Descriptors, that are used on Windows 8 for automated driver installation
530 void read_ms_winsub_feature_descriptors(libusb_device_handle *handle, uint8_t bRequest, int iface_number)
531 {
532 #define MAX_OS_FD_LENGTH 256
533         int i, r;
534         uint8_t os_desc[MAX_OS_FD_LENGTH];
535         uint32_t length;
536         void* le_type_punning_IS_fine;
537         struct {
538                 char* desc;
539                 uint8_t recipient;
540                 uint16_t index;
541                 uint16_t header_size;
542         } os_fd[2] = {
543                 {"Extended Compat ID", LIBUSB_RECIPIENT_DEVICE, 0x0004, 0x10},
544                 {"Extended Properties", LIBUSB_RECIPIENT_DEVICE, 0x0005, 0x0A}
545                 // NB: LIBUSB_RECIPIENT_INTERFACE should be used for the Extended Properties.
546                 // However, for Interface requests, the WinUSB DLL forces the low byte of wIndex
547                 // to the interface number, regardless of what you set it to, so we have to
548                 // fallback to Device and hope the firmware answers both equally.
549                 // See http://www.lvr.com/forum/index.php?topic=331
550         };
551
552         if (iface_number < 0) return;
553
554         for (i=0; i<2; i++) {
555                 printf("\nReading %s OS Feature Descriptor (wIndex = 0x%04d):\n", os_fd[i].desc, os_fd[i].index);
556
557                 // Read the header part
558                 r = libusb_control_transfer(handle, (uint8_t)(LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_VENDOR|os_fd[i].recipient),
559                         bRequest, (uint16_t)(((iface_number)<< 8)|0x00), os_fd[i].index, os_desc, os_fd[i].header_size, 1000);
560                 if (r < os_fd[i].header_size) {
561                         perr("   Failed: %s", (r<0)?libusb_strerror((enum libusb_error)r):"header size is too small");
562                         return;
563                 }
564                 le_type_punning_IS_fine = (void*)os_desc;
565                 length = *((uint32_t*)le_type_punning_IS_fine);
566                 if (length > MAX_OS_FD_LENGTH) {
567                         length = MAX_OS_FD_LENGTH;
568                 }
569
570                 // Read the full feature descriptor
571                 r = libusb_control_transfer(handle, (uint8_t)(LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_VENDOR|os_fd[i].recipient),
572                         bRequest, (uint16_t)(((iface_number)<< 8)|0x00), os_fd[i].index, os_desc, (uint16_t)length, 1000);
573                 if (r < 0) {
574                         perr("   Failed: %s", libusb_strerror((enum libusb_error)r));
575                         return;
576                 } else {
577                         display_buffer_hex(os_desc, r);
578                 }
579         }
580 }
581
582 int test_device(uint16_t vid, uint16_t pid)
583 {
584         libusb_device_handle *handle;
585         libusb_device *dev;
586         uint8_t bus, port_path[8];
587         struct libusb_config_descriptor *conf_desc;
588         const struct libusb_endpoint_descriptor *endpoint;
589         int i, j, k, r;
590         int iface, nb_ifaces, first_iface = -1;
591 #if defined(__linux)
592         // Attaching/detaching the kernel driver is only relevant for Linux
593         int iface_detached = -1;
594 #endif
595         struct libusb_device_descriptor dev_desc;
596         char* speed_name[5] = { "Unknown", "1.5 Mbit/s (USB 1.0 LowSpeed)", "12 Mbit/s (USB 1.0 FullSpeed)",
597                 "480 Mbit/s (USB 2.0 HighSpeed)", "5000 Mbit/s (USB 3.0 SuperSpeed)"};
598         char string[128];
599         uint8_t string_index[3];        // indexes of the string descriptors
600         uint8_t endpoint_in = 0, endpoint_out = 0;      // default IN and OUT endpoints
601
602         printf("Opening device...\n");
603         handle = libusb_open_device_with_vid_pid(NULL, vid, pid);
604
605         if (handle == NULL) {
606                 perr("  Failed.\n");
607                 return -1;
608         }
609
610         dev = libusb_get_device(handle);
611         bus = libusb_get_bus_number(dev);
612         r = libusb_get_port_path(NULL, dev, port_path, sizeof(port_path));
613         if (r > 0) {
614                 printf("bus: %d, port path from HCD: %d", bus, port_path[0]);
615                 for (i=1; i<r; i++) {
616                         printf("->%d", port_path[i]);
617                 }
618                 printf("\n");
619         }
620         r = libusb_get_device_speed(dev);
621         if ((r<0) || (r>4)) r=0;
622         printf("speed: %s\n", speed_name[r]);
623
624         printf("\nReading device descriptor:\n");
625         CALL_CHECK(libusb_get_device_descriptor(dev, &dev_desc));
626         printf("            length: %d\n", dev_desc.bLength);
627         printf("      device class: %d\n", dev_desc.bDeviceClass);
628         printf("               S/N: %d\n", dev_desc.iSerialNumber);
629         printf("           VID:PID: %04X:%04X\n", dev_desc.idVendor, dev_desc.idProduct);
630         printf("         bcdDevice: %04X\n", dev_desc.bcdDevice);
631         printf("   iMan:iProd:iSer: %d:%d:%d\n", dev_desc.iManufacturer, dev_desc.iProduct, dev_desc.iSerialNumber);
632         printf("          nb confs: %d\n", dev_desc.bNumConfigurations);
633         // Copy the string descriptors for easier parsing
634         string_index[0] = dev_desc.iManufacturer;
635         string_index[1] = dev_desc.iProduct;
636         string_index[2] = dev_desc.iSerialNumber;
637
638         printf("\nReading configuration descriptors:\n");
639         CALL_CHECK(libusb_get_config_descriptor(dev, 0, &conf_desc));
640         nb_ifaces = conf_desc->bNumInterfaces;
641         printf("             nb interfaces: %d\n", nb_ifaces);
642         if (nb_ifaces > 0)
643                 first_iface = conf_desc->usb_interface[0].altsetting[0].bInterfaceNumber;
644         for (i=0; i<nb_ifaces; i++) {
645                 printf("              interface[%d]: id = %d\n", i,
646                         conf_desc->usb_interface[i].altsetting[0].bInterfaceNumber);
647                 for (j=0; j<conf_desc->usb_interface[i].num_altsetting; j++) {
648                         printf("interface[%d].altsetting[%d]: num endpoints = %d\n",
649                                 i, j, conf_desc->usb_interface[i].altsetting[j].bNumEndpoints);
650                         printf("   Class.SubClass.Protocol: %02X.%02X.%02X\n",
651                                 conf_desc->usb_interface[i].altsetting[j].bInterfaceClass,
652                                 conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass,
653                                 conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol);
654                         if ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceClass == LIBUSB_CLASS_MASS_STORAGE)
655                           && ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x01)
656                           || (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x06) )
657                           && (conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol == 0x50) ) {
658                                 // Mass storage devices that can use basic SCSI commands
659                                 test_mode = USE_SCSI;
660                         }
661                         for (k=0; k<conf_desc->usb_interface[i].altsetting[j].bNumEndpoints; k++) {
662                                 endpoint = &conf_desc->usb_interface[i].altsetting[j].endpoint[k];
663                                 printf("       endpoint[%d].address: %02X\n", k, endpoint->bEndpointAddress);
664                                 // Use the first bulk IN/OUT endpoints found as default for testing
665                                 if ((endpoint->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) == LIBUSB_TRANSFER_TYPE_BULK) {
666                                         if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) {
667                                                 if (!endpoint_in)
668                                                         endpoint_in = endpoint->bEndpointAddress;
669                                         } else {
670                                                 if (!endpoint_out)
671                                                         endpoint_out = endpoint->bEndpointAddress;
672                                         }
673                                 }
674                                 printf("           max packet size: %04X\n", endpoint->wMaxPacketSize);
675                                 printf("          polling interval: %02X\n", endpoint->bInterval);
676                         }
677                 }
678         }
679         libusb_free_config_descriptor(conf_desc);
680
681         for (iface = 0; iface < nb_ifaces; iface++)
682         {
683                 printf("\nClaiming interface %d...\n", iface);
684                 r = libusb_claim_interface(handle, iface);
685 #if defined(__linux)
686                 if ((r != LIBUSB_SUCCESS) && (iface == 0)) {
687                         // Maybe we need to detach the driver
688                         perr("   Failed. Trying to detach driver...\n");
689                         libusb_detach_kernel_driver(handle, iface);
690                         iface_detached = iface;
691                         printf("   Claiming interface again...\n");
692                         r = libusb_claim_interface(handle, iface);
693                 }
694 #endif
695                 if (r != LIBUSB_SUCCESS) {
696                         perr("   Failed.\n");
697                 }
698         }
699
700         printf("\nReading string descriptors:\n");
701         for (i=0; i<3; i++) {
702                 if (string_index[i] == 0) {
703                         continue;
704                 }
705                 if (libusb_get_string_descriptor_ascii(handle, string_index[i], (unsigned char*)string, 128) >= 0) {
706                         printf("   String (0x%02X): \"%s\"\n", string_index[i], string);
707                 }
708         }
709         // Read the OS String Descriptor
710         if (libusb_get_string_descriptor_ascii(handle, 0xEE, (unsigned char*)string, 128) >= 0) {
711                 printf("   String (0x%02X): \"%s\"\n", 0xEE, string);
712                 // If this is a Microsoft OS String Descriptor,
713                 // attempt to read the WinUSB extended Feature Descriptors
714                 if (strncmp(string, "MSFT100", 7) == 0)
715                         read_ms_winsub_feature_descriptors(handle, string[7], first_iface);
716         }
717
718         switch(test_mode) {
719         case USE_PS3:
720                 CALL_CHECK(display_ps3_status(handle));
721                 break;
722         case USE_XBOX:
723                 CALL_CHECK(display_xbox_status(handle));
724                 CALL_CHECK(set_xbox_actuators(handle, 128, 222));
725                 msleep(2000);
726                 CALL_CHECK(set_xbox_actuators(handle, 0, 0));
727                 break;
728         case USE_SCSI:
729                 CALL_CHECK(test_mass_storage(handle, endpoint_in, endpoint_out));
730         default:
731                 break;
732         }
733
734         printf("\n");
735         for (iface = 0; iface<nb_ifaces; iface++) {
736                 printf("Releasing interface %d...\n", iface);
737                 libusb_release_interface(handle, iface);
738         }
739
740 #if defined(__linux)
741         if (iface_detached >= 0) {
742                 printf("Re-attaching kernel driver...\n");
743                 libusb_attach_kernel_driver(handle, iface_detached);
744         }
745 #endif
746
747         printf("Closing device...\n");
748         libusb_close(handle);
749
750         return 0;
751 }
752
753 int main(int argc, char** argv)
754 {
755         bool show_help = false;
756         bool debug_mode = false;
757         const struct libusb_version* version;
758         int j, r;
759         size_t i, arglen;
760         unsigned tmp_vid, tmp_pid;
761         uint16_t endian_test = 0xBE00;
762
763         // Default to generic, expecting VID:PID
764         VID = 0;
765         PID = 0;
766         test_mode = USE_GENERIC;
767
768         if (((uint8_t*)&endian_test)[0] == 0xBE) {
769                 printf("Despite their natural superiority for end users, big endian\n"
770                         "CPUs are not supported with this program, sorry.\n");
771                 return 0;
772         }
773
774         if (argc >= 2) {
775                 for (j = 1; j<argc; j++) {
776                         arglen = strlen(argv[j]);
777                         if ( ((argv[j][0] == '-') || (argv[j][0] == '/'))
778                           && (arglen >= 2) ) {
779                                 switch(argv[j][1]) {
780                                 case 'd':
781                                         debug_mode = true;
782                                         break;
783                                 case 'b':
784                                         strcat(binary_name, "raw.bin");
785                                         if (j+1 < argc) {
786                                                 strncpy(binary_name, argv[j+1], 64);
787                                                 j++;
788                                         }
789                                         binary_dump = true;
790                                         break;
791                                 case 'g':
792                                         break;
793                                 case 'j':
794                                         // OLIMEX ARM-USB-TINY JTAG, 2 channel composite device - 2 interfaces
795                                         if (!VID && !PID) {
796                                                 VID = 0x15BA;
797                                                 PID = 0x0004;
798                                         }
799                                         break;
800                                 case 'k':
801                                         // Generic 2 GB USB Key (SCSI Transparent/Bulk Only) - 1 interface
802                                         if (!VID && !PID) {
803                                                 VID = 0x0204;
804                                                 PID = 0x6025;
805                                         }
806                                         break;
807                                 // The following tests will force VID:PID if already provided
808                                 case 'p':
809                                         // Sony PS3 Controller - 1 interface
810                                         VID = 0x054C;
811                                         PID = 0x0268;
812                                         test_mode = USE_PS3;
813                                         break;
814                                 case 'x':
815                                         // Microsoft XBox Controller Type S - 1 interface
816                                         VID = 0x045E;
817                                         PID = 0x0289;
818                                         test_mode = USE_XBOX;
819                                         break;
820                                 default:
821                                         show_help = true;
822                                         break;
823                                 }
824                         } else {
825                                 for (i=0; i<arglen; i++) {
826                                         if (argv[j][i] == ':')
827                                                 break;
828                                 }
829                                 if (i != arglen) {
830                                         if (sscanf_s(argv[j], "%x:%x" , &tmp_vid, &tmp_pid) != 2) {
831                                                 printf("   Please specify VID & PID as \"vid:pid\" in hexadecimal format\n");
832                                                 return 1;
833                                         }
834                                         VID = (uint16_t)tmp_vid;
835                                         PID = (uint16_t)tmp_pid;
836                                 } else {
837                                         show_help = true;
838                                 }
839                         }
840                 }
841         }
842
843         if ((show_help) || (argc == 1) || (argc > 7)) {
844                 printf("usage: %s [-d] [-b [file]] [-h] [-i] [-j] [-k] [-x] [vid:pid]\n", argv[0]);
845                 printf("   -h: display usage\n");
846                 printf("   -d: enable debug output (if library was compiled with debug enabled)\n");
847                 printf("   -b: dump Mass Storage first block to binary file\n");
848                 printf("   -g: short generic test (default)\n");
849                 printf("   -k: test generic Mass Storage USB device (using WinUSB)\n");
850                 printf("   -j: test FTDI based JTAG device (using WinUSB)\n");
851                 printf("   -p: test Sony PS3 SixAxis controller (using WinUSB)\n");
852                 printf("   -x: test Microsoft XBox Controller Type S (using WinUSB)\n");
853                 return 0;
854         }
855
856         version = libusb_getversion();
857         printf("Using libusb v%d.%d.%d.%d\n\n", version->major, version->minor, version->micro, version->nano);
858         r = libusb_init(NULL);
859         if (r < 0)
860                 return r;
861
862         // Info = 3, Debug = 4
863         libusb_set_debug(NULL, debug_mode?4:3);
864
865         test_device(VID, PID);
866
867         libusb_exit(NULL);
868
869         return 0;
870 }