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