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