xref: /freebsd/share/examples/libusb20/control.c (revision d59c7ea2701fe7b73b32eef49a7c712ef38de5a0)
1 /*-
2  * SPDX-License-Identifier: Beerware
3  *
4  * ----------------------------------------------------------------------------
5  * "THE BEER-WARE LICENSE" (Revision 42) (by Poul-Henning Kamp):
6  * <joerg@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
7  * can do whatever you want with this stuff. If we meet some day, and you think
8  * this stuff is worth it, you can buy me a beer in return.        Joerg Wunsch
9  * ----------------------------------------------------------------------------
10  */
11 
12 /*
13  * Simple demo program to illustrate the handling of FreeBSD's
14  * libusb20.
15  */
16 
17 /*
18  * Examples:
19  * Just list all VID:PID pairs
20  * ./control
21  *
22  * Standard device request GET_STATUS, report two bytes of status
23  * (bit 0 in the first byte returned is the "self powered" bit)
24  * ./control -v 0x3eb -p 0x2103 in std dev get_status 0 0 2
25  *
26  * Request input reports through the interrupt pipe from a mouse
27  * device (move the mouse around after issuing the command):
28  * ./control -v 0x093a -p 0x2516 -i 0x81
29  *
30  */
31 
32 
33 #include <capsicum_helpers.h>
34 #include <limits.h>
35 #include <stdbool.h>
36 #include <stdio.h>
37 #include <stdint.h>
38 #include <stdlib.h>
39 #include <sysexits.h>
40 #include <unistd.h>
41 #include <string.h>
42 
43 #include <libusb20.h>
44 #include <libusb20_desc.h>
45 
46 #include <sys/queue.h>
47 
48 #include "util.h"
49 
50 /*
51  * If you want to see the details of the internal datastructures
52  * in the debugger, unifdef the following.
53  */
54 #ifdef DEBUG
55 #  include "/usr/src/lib/libusb/libusb20_int.h"
56 #endif
57 
58 #define BUFLEN 64
59 
60 #define TIMEOUT 5000 		/* 5 s */
61 
62 int intr_ep;		/* endpoints */
63 struct LIBUSB20_CONTROL_SETUP_DECODED setup;
64 
65 uint8_t out_buf[BUFLEN];
66 uint16_t out_len;
67 
68 bool do_request;
69 
70 static void
71 doit(struct libusb20_device *dev)
72 {
73   int rv;
74 
75   if (do_request)
76     printf("doit(): bmRequestType 0x%02x, bRequest 0x%02x, wValue 0x%04x, wIndex 0x%04x, wLength 0x%04x\n",
77 	   setup.bmRequestType,
78 	   setup.bRequest,
79 	   setup.wValue,
80 	   setup.wIndex,
81 	   setup.wLength);
82 
83   /*
84    * Open the device, allocating memory for two possible (bulk or
85    * interrupt) transfers.
86    *
87    * If only control transfers are intended (via
88    * libusb20_dev_request_sync()), transfer_max can be given as 0.
89    */
90   if ((rv = libusb20_dev_open(dev, 1)) != 0)
91     {
92       fprintf(stderr, "libusb20_dev_open: %s\n", libusb20_strerror(rv));
93       return;
94     }
95 
96   /*
97    * If the device has more than one configuration, select the desired
98    * one here.
99    */
100   if ((rv = libusb20_dev_set_config_index(dev, 0)) != 0)
101     {
102       fprintf(stderr, "libusb20_dev_set_config_index: %s\n", libusb20_strerror(rv));
103       return;
104     }
105 
106   uint8_t *data = 0;
107   uint16_t actlen;
108 
109   if ((setup.bmRequestType & 0x80) != 0)
110     {
111       /* this is an IN request, allocate a buffer */
112       data = malloc(setup.wLength);
113       if (data == 0)
114 	{
115 	  fprintf(stderr,
116 		  "Out of memory allocating %u bytes of reply buffer\n",
117 		  setup.wLength);
118 	  return;
119 	}
120     }
121   else
122     data = out_buf;
123 
124   if (do_request)
125     {
126       if ((rv = libusb20_dev_request_sync(dev, &setup, data,
127 					  &actlen,
128 					  TIMEOUT,
129 					  0 /* flags */)) != 0)
130 	{
131 	  fprintf(stderr,
132 		  "libusb20_dev_request_sync: %s\n", libusb20_strerror(rv));
133 	}
134       printf("sent %d bytes\n", actlen);
135       if ((setup.bmRequestType & 0x80) != 0)
136 	{
137 	  print_formatted(data, (uint32_t)setup.wLength);
138 	  free(data);
139 	}
140     }
141 
142   if (intr_ep != 0)
143     {
144       /*
145        * One transfer has been requested in libusb20_dev_open() above;
146        * obtain the corresponding transfer struct pointer.
147        */
148       struct libusb20_transfer *xfr_intr = libusb20_tr_get_pointer(dev, 0);
149 
150       if (xfr_intr == NULL)
151 	{
152 	  fprintf(stderr, "libusb20_tr_get_pointer: %s\n", libusb20_strerror(rv));
153 	  return;
154 	}
155 
156       /*
157        * Open the interrupt transfer.
158        */
159       if ((rv = libusb20_tr_open(xfr_intr, 0, 1, intr_ep)) != 0)
160 	{
161 	  fprintf(stderr, "libusb20_tr_open: %s\n", libusb20_strerror(rv));
162 	  return;
163 	}
164 
165       uint8_t in_buf[BUFLEN];
166       uint32_t rlen;
167 
168       if ((rv = libusb20_tr_bulk_intr_sync(xfr_intr, in_buf, BUFLEN, &rlen, TIMEOUT))
169 	  != 0)
170 	{
171 	  fprintf(stderr, "libusb20_tr_bulk_intr_sync: %s\n", libusb20_strerror(rv));
172 	}
173       printf("received %d bytes\n", rlen);
174       if (rlen > 0)
175 	print_formatted(in_buf, rlen);
176 
177       libusb20_tr_close(xfr_intr);
178     }
179 
180   libusb20_dev_close(dev);
181 }
182 
183 static void
184 usage(void)
185 {
186   fprintf(stderr,
187 	  "Usage ./usb [-i <INTR_EP>] -v <VID> -p <PID> [dir type rcpt req wValue wIndex wLength [<outdata> ...]]\n");
188   exit(EX_USAGE);
189 }
190 
191 static const char *reqnames[] =
192 {
193   "get_status",
194   "clear_feature",
195   "res1",
196   "set_feature",
197   "res2",
198   "set_address",
199   "get_descriptor",
200   "set_descriptor",
201   "get_configuration",
202   "set_configuration",
203   "get_interface",
204   "set_interface",
205   "synch_frame",
206 };
207 
208 static int
209 get_req(const char *reqname)
210 {
211   size_t i;
212   size_t l = strlen(reqname);
213 
214   for (i = 0;
215        i < sizeof reqnames / sizeof reqnames[0];
216        i++)
217     if (strncasecmp(reqname, reqnames[i], l) == 0)
218       return i;
219 
220   return strtoul(reqname, 0, 0);
221 }
222 
223 
224 static int
225 parse_req(int argc, char **argv)
226 {
227   int idx;
228   uint8_t rt = 0;
229 
230   for (idx = 0; argc != 0 && idx <= 6; argc--, idx++)
231     switch (idx)
232       {
233       case 0:
234 	/* dir[ection]: i[n] | o[ut] */
235 	if (*argv[idx] == 'i')
236 	  rt |= 0x80;
237 	else if (*argv[idx] == 'o')
238 	  /* nop */;
239 	else
240 	  {
241 	    fprintf(stderr, "request direction must be \"in\" or \"out\" (got %s)\n",
242 		    argv[idx]);
243 	    return -1;
244 	  }
245 	break;
246 
247       case 1:
248 	/* type: s[tandard] | c[lass] | v[endor] */
249 	if (*argv[idx] == 's')
250 	  /* nop */;
251 	else if (*argv[idx] == 'c')
252 	  rt |= 0x20;
253 	else if (*argv[idx] == 'v')
254 	  rt |= 0x40;
255 	else
256 	  {
257 	    fprintf(stderr,
258 		    "request type must be one of \"standard\", \"class\", or \"vendor\" (got %s)\n",
259 		    argv[idx]);
260 	    return -1;
261 	  }
262 	break;
263 
264       case 2:
265 	/* rcpt: d[evice], i[nterface], e[ndpoint], o[ther] */
266 	if (*argv[idx] == 'd')
267 	  /* nop */;
268 	else if (*argv[idx] == 'i')
269 	  rt |= 1;
270 	else if (*argv[idx] == 'e')
271 	  rt |= 2;
272 	else if (*argv[idx] == 'o')
273 	  rt |= 3;
274 	else
275 	  {
276 	    fprintf(stderr,
277 		    "recipient must be one of \"device\", \"interface\", \"endpoint\", or \"other\" (got %s)\n",
278 		    argv[idx]);
279 	    return -1;
280 	  }
281 	setup.bmRequestType = rt;
282 	break;
283 
284       case 3:
285 	setup.bRequest = get_req(argv[idx]);
286 	break;
287 
288       case 4:
289 	setup.wValue = strtoul(argv[idx], 0, 0);
290 	break;
291 
292       case 5:
293 	setup.wIndex = strtoul(argv[idx], 0, 0);
294 	break;
295 
296       case 6:
297 	setup.wLength = strtoul(argv[idx], 0, 0);
298 	break;
299       }
300 
301   return argc;
302 }
303 
304 
305 int
306 main(int argc, char **argv)
307 {
308   unsigned int vid = UINT_MAX, pid = UINT_MAX; /* impossible VID:PID */
309   int c;
310 
311   /*
312    * Initialize setup struct.  This step is required, and initializes
313    * internal fields in the struct.
314    *
315    * All the "public" fields are named exactly the way as the USB
316    * standard describes them, namely:
317    *
318    *	setup.bmRequestType: bitmask, bit 7 is direction
319    *	                              bits 6/5 is request type
320    *	                                       (standard, class, vendor)
321    *	                              bits 4..0 is recipient
322    *	                                       (device, interface, endpoint,
323    *	                                        other)
324    *	setup.bRequest:      the request itself (see get_req() for standard
325    *	                                         requests, or specific value)
326    *	setup.wValue:        a 16-bit value
327    *	setup.wIndex:        another 16-bit value
328    *	setup.wLength:       length of associated data transfer, direction
329    *	                     depends on bit 7 of bmRequestType
330    */
331   LIBUSB20_INIT(LIBUSB20_CONTROL_SETUP, &setup);
332 
333   while ((c = getopt(argc, argv, "i:p:v:")) != -1)
334     switch (c)
335       {
336       case 'i':
337 	intr_ep = strtol(optarg, NULL, 0);
338 	break;
339 
340       case 'p':
341 	pid = strtol(optarg, NULL, 0);
342 	break;
343 
344       case 'v':
345 	vid = strtol(optarg, NULL, 0);
346 	break;
347 
348       default:
349 	usage();
350 	break;
351       }
352   argc -= optind;
353   argv += optind;
354 
355   if (vid != UINT_MAX || pid != UINT_MAX)
356     {
357       if (intr_ep != 0 && (intr_ep & 0x80) == 0)
358 	{
359 	  fprintf(stderr, "Interrupt endpoint must be of type IN\n");
360 	  usage();
361 	}
362 
363       if (argc > 0)
364 	{
365 	  do_request = true;
366 
367 	  int rv = parse_req(argc, argv);
368 	  if (rv < 0)
369 	    return EX_USAGE;
370 	  argc = rv;
371 
372 	  if (argc > 0)
373 	    {
374 	      for (out_len = 0; argc > 0 && out_len < BUFLEN; out_len++, argc--)
375 		{
376 		  unsigned n = strtoul(argv[out_len], 0, 0);
377 		  if (n > 255)
378 		    fprintf(stderr,
379 			    "Warning: data #%d 0x%0x > 0xff, truncating\n",
380 			    out_len, n);
381 		  out_buf[out_len] = (uint8_t)n;
382 		}
383 	      out_len++;
384 	      if (argc > 0)
385 		fprintf(stderr,
386 			"Data count exceeds maximum of %d, ignoring %d elements\n",
387 			BUFLEN, optind);
388 	    }
389 	}
390     }
391 
392   struct libusb20_backend *be;
393   struct libusb20_device *dev;
394 
395   if ((be = libusb20_be_alloc_default(NULL)) == NULL)
396     {
397       perror("libusb20_be_alloc()");
398       return 1;
399     }
400 
401   if (caph_enter() < 0)
402     {
403       perror("caph_enter()");
404       return 1;
405     }
406 
407   dev = NULL;
408   while ((dev = libusb20_be_device_foreach(be, dev)) != NULL)
409     {
410       struct LIBUSB20_DEVICE_DESC_DECODED *ddp =
411       libusb20_dev_get_device_desc(dev);
412 
413       printf("Found device %s (VID:PID = 0x%04x:0x%04x)\n",
414 	     libusb20_dev_get_desc(dev),
415 	     ddp->idVendor, ddp->idProduct);
416 
417       if (ddp->idVendor == vid && ddp->idProduct == pid)
418 	doit(dev);
419     }
420 
421   libusb20_be_free(be);
422   return 0;
423 }
424