ccf7fe4269448a6c7b7e3407e88065539b803dd8
[platform/upstream/libusb.git] / libusb / descriptor.c
1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2 /*
3  * USB descriptor handling functions for libusb
4  * Copyright © 2007 Daniel Drake <dsd@gentoo.org>
5  * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <config.h>
23
24 #include <errno.h>
25 #include <stdint.h>
26 #include <stdlib.h>
27 #include <string.h>
28
29 #include "libusbi.h"
30
31 #define DESC_HEADER_LENGTH              2
32 #define DEVICE_DESC_LENGTH              18
33 #define CONFIG_DESC_LENGTH              9
34 #define INTERFACE_DESC_LENGTH           9
35 #define ENDPOINT_DESC_LENGTH            7
36 #define ENDPOINT_AUDIO_DESC_LENGTH      9
37
38 /** @defgroup libusb_desc USB descriptors
39  * This page details how to examine the various standard USB descriptors
40  * for detected devices
41  */
42
43 /* set host_endian if the w values are already in host endian format,
44  * as opposed to bus endian. */
45 int usbi_parse_descriptor(const unsigned char *source, const char *descriptor,
46         void *dest, int host_endian)
47 {
48         const unsigned char *sp = source;
49         unsigned char *dp = dest;
50         uint16_t w;
51         const char *cp;
52         uint32_t d;
53
54         for (cp = descriptor; *cp; cp++) {
55                 switch (*cp) {
56                         case 'b':       /* 8-bit byte */
57                                 *dp++ = *sp++;
58                                 break;
59                         case 'w':       /* 16-bit word, convert from little endian to CPU */
60                                 dp += ((uintptr_t)dp & 1);      /* Align to word boundary */
61
62                                 if (host_endian) {
63                                         memcpy(dp, sp, 2);
64                                 } else {
65                                         w = (sp[1] << 8) | sp[0];
66                                         *((uint16_t *)dp) = w;
67                                 }
68                                 sp += 2;
69                                 dp += 2;
70                                 break;
71                         case 'd':       /* 32-bit word, convert from little endian to CPU */
72                                 dp += ((uintptr_t)dp & 1);      /* Align to word boundary */
73
74                                 if (host_endian) {
75                                         memcpy(dp, sp, 4);
76                                 } else {
77                                         d = (sp[3] << 24) | (sp[2] << 16) |
78                                                 (sp[1] << 8) | sp[0];
79                                         *((uint32_t *)dp) = d;
80                                 }
81                                 sp += 4;
82                                 dp += 4;
83                                 break;
84                         case 'u':       /* 16 byte UUID */
85                                 memcpy(dp, sp, 16);
86                                 sp += 16;
87                                 dp += 16;
88                                 break;
89                 }
90         }
91
92         return (int) (sp - source);
93 }
94
95 static void clear_endpoint(struct libusb_endpoint_descriptor *endpoint)
96 {
97         if (endpoint->extra)
98                 free((unsigned char *) endpoint->extra);
99 }
100
101 static int parse_endpoint(struct libusb_context *ctx,
102         struct libusb_endpoint_descriptor *endpoint, unsigned char *buffer,
103         int size, int host_endian)
104 {
105         struct usb_descriptor_header header;
106         unsigned char *extra;
107         unsigned char *begin;
108         int parsed = 0;
109         int len;
110
111         if (size < DESC_HEADER_LENGTH) {
112                 usbi_err(ctx, "short endpoint descriptor read %d/%d",
113                          size, DESC_HEADER_LENGTH);
114                 return LIBUSB_ERROR_IO;
115         }
116
117         usbi_parse_descriptor(buffer, "bb", &header, 0);
118         if (header.bDescriptorType != LIBUSB_DT_ENDPOINT) {
119                 usbi_err(ctx, "unexpected descriptor %x (expected %x)",
120                         header.bDescriptorType, LIBUSB_DT_ENDPOINT);
121                 return parsed;
122         }
123         if (header.bLength > size) {
124                 usbi_warn(ctx, "short endpoint descriptor read %d/%d",
125                           size, header.bLength);
126                 return parsed;
127         }
128         if (header.bLength >= ENDPOINT_AUDIO_DESC_LENGTH)
129                 usbi_parse_descriptor(buffer, "bbbbwbbb", endpoint, host_endian);
130         else if (header.bLength >= ENDPOINT_DESC_LENGTH)
131                 usbi_parse_descriptor(buffer, "bbbbwb", endpoint, host_endian);
132         else {
133                 usbi_err(ctx, "invalid endpoint bLength (%d)", header.bLength);
134                 return LIBUSB_ERROR_IO;
135         }
136
137         buffer += header.bLength;
138         size -= header.bLength;
139         parsed += header.bLength;
140
141         /* Skip over the rest of the Class Specific or Vendor Specific */
142         /*  descriptors */
143         begin = buffer;
144         while (size >= DESC_HEADER_LENGTH) {
145                 usbi_parse_descriptor(buffer, "bb", &header, 0);
146                 if (header.bLength < DESC_HEADER_LENGTH) {
147                         usbi_err(ctx, "invalid extra ep desc len (%d)",
148                                  header.bLength);
149                         return LIBUSB_ERROR_IO;
150                 } else if (header.bLength > size) {
151                         usbi_warn(ctx, "short extra ep desc read %d/%d",
152                                   size, header.bLength);
153                         return parsed;
154                 }
155
156                 /* If we find another "proper" descriptor then we're done  */
157                 if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
158                                 (header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
159                                 (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
160                                 (header.bDescriptorType == LIBUSB_DT_DEVICE))
161                         break;
162
163                 usbi_dbg("skipping descriptor %x", header.bDescriptorType);
164                 buffer += header.bLength;
165                 size -= header.bLength;
166                 parsed += header.bLength;
167         }
168
169         /* Copy any unknown descriptors into a storage area for drivers */
170         /*  to later parse */
171         len = (int)(buffer - begin);
172         if (!len) {
173                 endpoint->extra = NULL;
174                 endpoint->extra_length = 0;
175                 return parsed;
176         }
177
178         extra = malloc(len);
179         endpoint->extra = extra;
180         if (!extra) {
181                 endpoint->extra_length = 0;
182                 return LIBUSB_ERROR_NO_MEM;
183         }
184
185         memcpy(extra, begin, len);
186         endpoint->extra_length = len;
187
188         return parsed;
189 }
190
191 static void clear_interface(struct libusb_interface *usb_interface)
192 {
193         int i;
194         int j;
195
196         if (usb_interface->altsetting) {
197                 for (i = 0; i < usb_interface->num_altsetting; i++) {
198                         struct libusb_interface_descriptor *ifp =
199                                 (struct libusb_interface_descriptor *)
200                                 usb_interface->altsetting + i;
201                         if (ifp->extra)
202                                 free((void *) ifp->extra);
203                         if (ifp->endpoint) {
204                                 for (j = 0; j < ifp->bNumEndpoints; j++)
205                                         clear_endpoint((struct libusb_endpoint_descriptor *)
206                                                 ifp->endpoint + j);
207                                 free((void *) ifp->endpoint);
208                         }
209                 }
210                 free((void *) usb_interface->altsetting);
211                 usb_interface->altsetting = NULL;
212         }
213
214 }
215
216 static int parse_interface(libusb_context *ctx,
217         struct libusb_interface *usb_interface, unsigned char *buffer, int size,
218         int host_endian)
219 {
220         int i;
221         int len;
222         int r;
223         int parsed = 0;
224         int interface_number = -1;
225         struct usb_descriptor_header header;
226         struct libusb_interface_descriptor *ifp;
227         unsigned char *begin;
228
229         usb_interface->num_altsetting = 0;
230
231         while (size >= INTERFACE_DESC_LENGTH) {
232                 struct libusb_interface_descriptor *altsetting =
233                         (struct libusb_interface_descriptor *) usb_interface->altsetting;
234                 altsetting = usbi_reallocf(altsetting,
235                         sizeof(struct libusb_interface_descriptor) *
236                         (usb_interface->num_altsetting + 1));
237                 if (!altsetting) {
238                         r = LIBUSB_ERROR_NO_MEM;
239                         goto err;
240                 }
241                 usb_interface->altsetting = altsetting;
242
243                 ifp = altsetting + usb_interface->num_altsetting;
244                 usbi_parse_descriptor(buffer, "bbbbbbbbb", ifp, 0);
245                 if (ifp->bDescriptorType != LIBUSB_DT_INTERFACE) {
246                         usbi_err(ctx, "unexpected descriptor %x (expected %x)",
247                                  ifp->bDescriptorType, LIBUSB_DT_INTERFACE);
248                         return parsed;
249                 }
250                 if (ifp->bLength < INTERFACE_DESC_LENGTH) {
251                         usbi_err(ctx, "invalid interface bLength (%d)",
252                                  ifp->bLength);
253                         r = LIBUSB_ERROR_IO;
254                         goto err;
255                 }
256                 if (ifp->bLength > size) {
257                         usbi_warn(ctx, "short intf descriptor read %d/%d",
258                                  size, ifp->bLength);
259                         return parsed;
260                 }
261                 if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
262                         usbi_err(ctx, "too many endpoints (%d)", ifp->bNumEndpoints);
263                         r = LIBUSB_ERROR_IO;
264                         goto err;
265                 }
266
267                 usb_interface->num_altsetting++;
268                 ifp->extra = NULL;
269                 ifp->extra_length = 0;
270                 ifp->endpoint = NULL;
271
272                 if (interface_number == -1)
273                         interface_number = ifp->bInterfaceNumber;
274
275                 /* Skip over the interface */
276                 buffer += ifp->bLength;
277                 parsed += ifp->bLength;
278                 size -= ifp->bLength;
279
280                 begin = buffer;
281
282                 /* Skip over any interface, class or vendor descriptors */
283                 while (size >= DESC_HEADER_LENGTH) {
284                         usbi_parse_descriptor(buffer, "bb", &header, 0);
285                         if (header.bLength < DESC_HEADER_LENGTH) {
286                                 usbi_err(ctx,
287                                          "invalid extra intf desc len (%d)",
288                                          header.bLength);
289                                 r = LIBUSB_ERROR_IO;
290                                 goto err;
291                         } else if (header.bLength > size) {
292                                 usbi_warn(ctx,
293                                           "short extra intf desc read %d/%d",
294                                           size, header.bLength);
295                                 return parsed;
296                         }
297
298                         /* If we find another "proper" descriptor then we're done */
299                         if ((header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
300                                         (header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
301                                         (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
302                                         (header.bDescriptorType == LIBUSB_DT_DEVICE))
303                                 break;
304
305                         buffer += header.bLength;
306                         parsed += header.bLength;
307                         size -= header.bLength;
308                 }
309
310                 /* Copy any unknown descriptors into a storage area for */
311                 /*  drivers to later parse */
312                 len = (int)(buffer - begin);
313                 if (len) {
314                         ifp->extra = malloc(len);
315                         if (!ifp->extra) {
316                                 r = LIBUSB_ERROR_NO_MEM;
317                                 goto err;
318                         }
319                         memcpy((unsigned char *) ifp->extra, begin, len);
320                         ifp->extra_length = len;
321                 }
322
323                 if (ifp->bNumEndpoints > 0) {
324                         struct libusb_endpoint_descriptor *endpoint;
325                         endpoint = calloc(ifp->bNumEndpoints, sizeof(struct libusb_endpoint_descriptor));
326                         ifp->endpoint = endpoint;
327                         if (!endpoint) {
328                                 r = LIBUSB_ERROR_NO_MEM;
329                                 goto err;
330                         }
331
332                         for (i = 0; i < ifp->bNumEndpoints; i++) {
333                                 r = parse_endpoint(ctx, endpoint + i, buffer, size,
334                                         host_endian);
335                                 if (r < 0)
336                                         goto err;
337                                 if (r == 0) {
338                                         ifp->bNumEndpoints = (uint8_t)i;
339                                         break;;
340                                 }
341
342                                 buffer += r;
343                                 parsed += r;
344                                 size -= r;
345                         }
346                 }
347
348                 /* We check to see if it's an alternate to this one */
349                 ifp = (struct libusb_interface_descriptor *) buffer;
350                 if (size < LIBUSB_DT_INTERFACE_SIZE ||
351                                 ifp->bDescriptorType != LIBUSB_DT_INTERFACE ||
352                                 ifp->bInterfaceNumber != interface_number)
353                         return parsed;
354         }
355
356         return parsed;
357 err:
358         clear_interface(usb_interface);
359         return r;
360 }
361
362 static void clear_configuration(struct libusb_config_descriptor *config)
363 {
364         if (config->interface) {
365                 int i;
366                 for (i = 0; i < config->bNumInterfaces; i++)
367                         clear_interface((struct libusb_interface *)
368                                 config->interface + i);
369                 free((void *) config->interface);
370         }
371         if (config->extra)
372                 free((void *) config->extra);
373 }
374
375 static int parse_configuration(struct libusb_context *ctx,
376         struct libusb_config_descriptor *config, unsigned char *buffer,
377         int size, int host_endian)
378 {
379         int i;
380         int r;
381         struct usb_descriptor_header header;
382         struct libusb_interface *usb_interface;
383
384         if (size < LIBUSB_DT_CONFIG_SIZE) {
385                 usbi_err(ctx, "short config descriptor read %d/%d",
386                          size, LIBUSB_DT_CONFIG_SIZE);
387                 return LIBUSB_ERROR_IO;
388         }
389
390         usbi_parse_descriptor(buffer, "bbwbbbbb", config, host_endian);
391         if (config->bDescriptorType != LIBUSB_DT_CONFIG) {
392                 usbi_err(ctx, "unexpected descriptor %x (expected %x)",
393                          config->bDescriptorType, LIBUSB_DT_CONFIG);
394                 return LIBUSB_ERROR_IO;
395         }
396         if (config->bLength < LIBUSB_DT_CONFIG_SIZE) {
397                 usbi_err(ctx, "invalid config bLength (%d)", config->bLength);
398                 return LIBUSB_ERROR_IO;
399         }
400         if (config->bLength > size) {
401                 usbi_err(ctx, "short config descriptor read %d/%d",
402                          size, config->bLength);
403                 return LIBUSB_ERROR_IO;
404         }
405         if (config->bNumInterfaces > USB_MAXINTERFACES) {
406                 usbi_err(ctx, "too many interfaces (%d)", config->bNumInterfaces);
407                 return LIBUSB_ERROR_IO;
408         }
409
410         usb_interface = calloc(config->bNumInterfaces, sizeof(struct libusb_interface));
411         config->interface = usb_interface;
412         if (!usb_interface)
413                 return LIBUSB_ERROR_NO_MEM;
414
415         buffer += config->bLength;
416         size -= config->bLength;
417
418         config->extra = NULL;
419         config->extra_length = 0;
420
421         for (i = 0; i < config->bNumInterfaces; i++) {
422                 int len;
423                 unsigned char *begin;
424
425                 /* Skip over the rest of the Class Specific or Vendor */
426                 /*  Specific descriptors */
427                 begin = buffer;
428                 while (size >= DESC_HEADER_LENGTH) {
429                         usbi_parse_descriptor(buffer, "bb", &header, 0);
430
431                         if (header.bLength < DESC_HEADER_LENGTH) {
432                                 usbi_err(ctx,
433                                          "invalid extra config desc len (%d)",
434                                          header.bLength);
435                                 r = LIBUSB_ERROR_IO;
436                                 goto err;
437                         } else if (header.bLength > size) {
438                                 usbi_warn(ctx,
439                                           "short extra config desc read %d/%d",
440                                           size, header.bLength);
441                                 config->bNumInterfaces = (uint8_t)i;
442                                 return size;
443                         }
444
445                         /* If we find another "proper" descriptor then we're done */
446                         if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
447                                         (header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
448                                         (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
449                                         (header.bDescriptorType == LIBUSB_DT_DEVICE))
450                                 break;
451
452                         usbi_dbg("skipping descriptor 0x%x", header.bDescriptorType);
453                         buffer += header.bLength;
454                         size -= header.bLength;
455                 }
456
457                 /* Copy any unknown descriptors into a storage area for */
458                 /*  drivers to later parse */
459                 len = (int)(buffer - begin);
460                 if (len) {
461                         /* FIXME: We should realloc and append here */
462                         if (!config->extra_length) {
463                                 config->extra = malloc(len);
464                                 if (!config->extra) {
465                                         r = LIBUSB_ERROR_NO_MEM;
466                                         goto err;
467                                 }
468
469                                 memcpy((unsigned char *) config->extra, begin, len);
470                                 config->extra_length = len;
471                         }
472                 }
473
474                 r = parse_interface(ctx, usb_interface + i, buffer, size, host_endian);
475                 if (r < 0)
476                         goto err;
477                 if (r == 0) {
478                         config->bNumInterfaces = (uint8_t)i;
479                         break;
480                 }
481
482                 buffer += r;
483                 size -= r;
484         }
485
486         return size;
487
488 err:
489         clear_configuration(config);
490         return r;
491 }
492
493 static int raw_desc_to_config(struct libusb_context *ctx,
494         unsigned char *buf, int size, int host_endian,
495         struct libusb_config_descriptor **config)
496 {
497         struct libusb_config_descriptor *_config = malloc(sizeof(*_config));
498         int r;
499         
500         if (!_config)
501                 return LIBUSB_ERROR_NO_MEM;
502
503         r = parse_configuration(ctx, _config, buf, size, host_endian);
504         if (r < 0) {
505                 usbi_err(ctx, "parse_configuration failed with error %d", r);
506                 free(_config);
507                 return r;
508         } else if (r > 0) {
509                 usbi_warn(ctx, "still %d bytes of descriptor data left", r);
510         }
511         
512         *config = _config;
513         return LIBUSB_SUCCESS;
514 }
515
516 int usbi_device_cache_descriptor(libusb_device *dev)
517 {
518         int r, host_endian = 0;
519
520         r = usbi_backend->get_device_descriptor(dev, (unsigned char *) &dev->device_descriptor,
521                                                 &host_endian);
522         if (r < 0)
523                 return r;
524
525         if (!host_endian) {
526                 dev->device_descriptor.bcdUSB = libusb_le16_to_cpu(dev->device_descriptor.bcdUSB);
527                 dev->device_descriptor.idVendor = libusb_le16_to_cpu(dev->device_descriptor.idVendor);
528                 dev->device_descriptor.idProduct = libusb_le16_to_cpu(dev->device_descriptor.idProduct);
529                 dev->device_descriptor.bcdDevice = libusb_le16_to_cpu(dev->device_descriptor.bcdDevice);
530         }
531
532         return LIBUSB_SUCCESS;
533 }
534
535 /** \ingroup libusb_desc
536  * Get the USB device descriptor for a given device.
537  *
538  * This is a non-blocking function; the device descriptor is cached in memory.
539  *
540  * Note since libusb-1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, this
541  * function always succeeds.
542  *
543  * \param dev the device
544  * \param desc output location for the descriptor data
545  * \returns 0 on success or a LIBUSB_ERROR code on failure
546  */
547 int API_EXPORTED libusb_get_device_descriptor(libusb_device *dev,
548         struct libusb_device_descriptor *desc)
549 {
550         usbi_dbg("");
551         memcpy((unsigned char *) desc, (unsigned char *) &dev->device_descriptor,
552                sizeof (dev->device_descriptor));
553         return 0;
554 }
555
556 /** \ingroup libusb_desc
557  * Get the USB configuration descriptor for the currently active configuration.
558  * This is a non-blocking function which does not involve any requests being
559  * sent to the device.
560  *
561  * \param dev a device
562  * \param config output location for the USB configuration descriptor. Only
563  * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
564  * after use.
565  * \returns 0 on success
566  * \returns LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
567  * \returns another LIBUSB_ERROR code on error
568  * \see libusb_get_config_descriptor
569  */
570 int API_EXPORTED libusb_get_active_config_descriptor(libusb_device *dev,
571         struct libusb_config_descriptor **config)
572 {
573         struct libusb_config_descriptor _config;
574         unsigned char tmp[LIBUSB_DT_CONFIG_SIZE];
575         unsigned char *buf = NULL;
576         int host_endian = 0;
577         int r;
578
579         r = usbi_backend->get_active_config_descriptor(dev, tmp,
580                 LIBUSB_DT_CONFIG_SIZE, &host_endian);
581         if (r < 0)
582                 return r;
583         if (r < LIBUSB_DT_CONFIG_SIZE) {
584                 usbi_err(dev->ctx, "short config descriptor read %d/%d",
585                          r, LIBUSB_DT_CONFIG_SIZE);
586                 return LIBUSB_ERROR_IO;
587         }
588
589         usbi_parse_descriptor(tmp, "bbw", &_config, host_endian);
590         buf = malloc(_config.wTotalLength);
591         if (!buf)
592                 return LIBUSB_ERROR_NO_MEM;
593
594         r = usbi_backend->get_active_config_descriptor(dev, buf,
595                 _config.wTotalLength, &host_endian);
596         if (r >= 0)
597                 r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
598
599         free(buf);
600         return r;
601 }
602
603 /** \ingroup libusb_desc
604  * Get a USB configuration descriptor based on its index.
605  * This is a non-blocking function which does not involve any requests being
606  * sent to the device.
607  *
608  * \param dev a device
609  * \param config_index the index of the configuration you wish to retrieve
610  * \param config output location for the USB configuration descriptor. Only
611  * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
612  * after use.
613  * \returns 0 on success
614  * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
615  * \returns another LIBUSB_ERROR code on error
616  * \see libusb_get_active_config_descriptor()
617  * \see libusb_get_config_descriptor_by_value()
618  */
619 int API_EXPORTED libusb_get_config_descriptor(libusb_device *dev,
620         uint8_t config_index, struct libusb_config_descriptor **config)
621 {
622         struct libusb_config_descriptor _config;
623         unsigned char tmp[LIBUSB_DT_CONFIG_SIZE];
624         unsigned char *buf = NULL;
625         int host_endian = 0;
626         int r;
627
628         usbi_dbg("index %d", config_index);
629         if (config_index >= dev->num_configurations)
630                 return LIBUSB_ERROR_NOT_FOUND;
631
632         r = usbi_backend->get_config_descriptor(dev, config_index, tmp,
633                 LIBUSB_DT_CONFIG_SIZE, &host_endian);
634         if (r < 0)
635                 return r;
636         if (r < LIBUSB_DT_CONFIG_SIZE) {
637                 usbi_err(dev->ctx, "short config descriptor read %d/%d",
638                          r, LIBUSB_DT_CONFIG_SIZE);
639                 return LIBUSB_ERROR_IO;
640         }
641
642         usbi_parse_descriptor(tmp, "bbw", &_config, host_endian);
643         buf = malloc(_config.wTotalLength);
644         if (!buf)
645                 return LIBUSB_ERROR_NO_MEM;
646
647         r = usbi_backend->get_config_descriptor(dev, config_index, buf,
648                 _config.wTotalLength, &host_endian);
649         if (r >= 0)
650                 r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
651
652         free(buf);
653         return r;
654 }
655
656 /* iterate through all configurations, returning the index of the configuration
657  * matching a specific bConfigurationValue in the idx output parameter, or -1
658  * if the config was not found.
659  * returns 0 on success or a LIBUSB_ERROR code
660  */
661 int usbi_get_config_index_by_value(struct libusb_device *dev,
662         uint8_t bConfigurationValue, int *idx)
663 {
664         uint8_t i;
665
666         usbi_dbg("value %d", bConfigurationValue);
667         for (i = 0; i < dev->num_configurations; i++) {
668                 unsigned char tmp[6];
669                 int host_endian;
670                 int r = usbi_backend->get_config_descriptor(dev, i, tmp, sizeof(tmp),
671                         &host_endian);
672                 if (r < 0) {
673                         *idx = -1;
674                         return r;
675                 }
676                 if (tmp[5] == bConfigurationValue) {
677                         *idx = i;
678                         return 0;
679                 }
680         }
681
682         *idx = -1;
683         return 0;
684 }
685
686 /** \ingroup libusb_desc
687  * Get a USB configuration descriptor with a specific bConfigurationValue.
688  * This is a non-blocking function which does not involve any requests being
689  * sent to the device.
690  *
691  * \param dev a device
692  * \param bConfigurationValue the bConfigurationValue of the configuration you
693  * wish to retrieve
694  * \param config output location for the USB configuration descriptor. Only
695  * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
696  * after use.
697  * \returns 0 on success
698  * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
699  * \returns another LIBUSB_ERROR code on error
700  * \see libusb_get_active_config_descriptor()
701  * \see libusb_get_config_descriptor()
702  */
703 int API_EXPORTED libusb_get_config_descriptor_by_value(libusb_device *dev,
704         uint8_t bConfigurationValue, struct libusb_config_descriptor **config)
705 {
706         int r, idx, host_endian;
707         unsigned char *buf = NULL;
708
709         if (usbi_backend->get_config_descriptor_by_value) {
710                 r = usbi_backend->get_config_descriptor_by_value(dev,
711                         bConfigurationValue, &buf, &host_endian);
712                 if (r < 0)
713                         return r;
714                 return raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
715         }
716
717         r = usbi_get_config_index_by_value(dev, bConfigurationValue, &idx);
718         if (r < 0)
719                 return r;
720         else if (idx == -1)
721                 return LIBUSB_ERROR_NOT_FOUND;
722         else
723                 return libusb_get_config_descriptor(dev, (uint8_t) idx, config);
724 }
725
726 /** \ingroup libusb_desc
727  * Free a configuration descriptor obtained from
728  * libusb_get_active_config_descriptor() or libusb_get_config_descriptor().
729  * It is safe to call this function with a NULL config parameter, in which
730  * case the function simply returns.
731  *
732  * \param config the configuration descriptor to free
733  */
734 void API_EXPORTED libusb_free_config_descriptor(
735         struct libusb_config_descriptor *config)
736 {
737         if (!config)
738                 return;
739
740         clear_configuration(config);
741         free(config);
742 }
743
744 /** \ingroup libusb_desc
745  * Get an endpoints superspeed endpoint companion descriptor (if any)
746  *
747  * \param ctx the context to operate on, or NULL for the default context
748  * \param endpoint endpoint descriptor from which to get the superspeed
749  * endpoint companion descriptor
750  * \param ep_comp output location for the superspeed endpoint companion
751  * descriptor. Only valid if 0 was returned. Must be freed with
752  * libusb_free_ss_endpoint_companion_descriptor() after use.
753  * \returns 0 on success
754  * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
755  * \returns another LIBUSB_ERROR code on error
756  */
757 int API_EXPORTED libusb_get_ss_endpoint_companion_descriptor(
758         struct libusb_context *ctx,
759         const struct libusb_endpoint_descriptor *endpoint,
760         struct libusb_ss_endpoint_companion_descriptor **ep_comp)
761 {
762         struct usb_descriptor_header header;
763         int size = endpoint->extra_length;
764         const unsigned char *buffer = endpoint->extra;
765
766         *ep_comp = NULL;
767
768         while (size >= DESC_HEADER_LENGTH) {
769                 usbi_parse_descriptor(buffer, "bb", &header, 0);
770                 if (header.bLength < 2 || header.bLength > size) {
771                         usbi_err(ctx, "invalid descriptor length %d",
772                                  header.bLength);
773                         return LIBUSB_ERROR_IO;
774                 }
775                 if (header.bDescriptorType != LIBUSB_DT_SS_ENDPOINT_COMPANION) {
776                         buffer += header.bLength;
777                         size -= header.bLength;
778                         continue;
779                 }
780                 if (header.bLength < LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE) {
781                         usbi_err(ctx, "invalid ss-ep-comp-desc length %d",
782                                  header.bLength);
783                         return LIBUSB_ERROR_IO;
784                 }
785                 *ep_comp = malloc(sizeof(**ep_comp));
786                 if (*ep_comp == NULL)
787                         return LIBUSB_ERROR_NO_MEM;
788                 usbi_parse_descriptor(buffer, "bbbbw", *ep_comp, 0);
789                 return LIBUSB_SUCCESS;
790         }
791         return LIBUSB_ERROR_NOT_FOUND;
792 }
793
794 /** \ingroup libusb_desc
795  * Free a superspeed endpoint companion descriptor obtained from
796  * libusb_get_ss_endpoint_companion_descriptor().
797  * It is safe to call this function with a NULL ep_comp parameter, in which
798  * case the function simply returns.
799  *
800  * \param ep_comp the superspeed endpoint companion descriptor to free
801  */
802 void API_EXPORTED libusb_free_ss_endpoint_companion_descriptor(
803         struct libusb_ss_endpoint_companion_descriptor *ep_comp)
804 {
805         free(ep_comp);
806 }
807
808 static int parse_bos(struct libusb_context *ctx,
809         struct libusb_bos_descriptor **bos,
810         unsigned char *buffer, int size, int host_endian)
811 {
812         struct libusb_bos_descriptor bos_header, *_bos;
813         struct libusb_bos_dev_capability_descriptor dev_cap;
814         int i;
815
816         if (size < LIBUSB_DT_BOS_SIZE) {
817                 usbi_err(ctx, "short bos descriptor read %d/%d",
818                          size, LIBUSB_DT_BOS_SIZE);
819                 return LIBUSB_ERROR_IO;
820         }
821
822         usbi_parse_descriptor(buffer, "bbwb", &bos_header, host_endian);
823         if (bos_header.bDescriptorType != LIBUSB_DT_BOS) {
824                 usbi_err(ctx, "unexpected descriptor %x (expected %x)",
825                          bos_header.bDescriptorType, LIBUSB_DT_BOS);
826                 return LIBUSB_ERROR_IO;
827         }
828         if (bos_header.bLength < LIBUSB_DT_BOS_SIZE) {
829                 usbi_err(ctx, "invalid bos bLength (%d)", bos_header.bLength);
830                 return LIBUSB_ERROR_IO;
831         }
832         if (bos_header.bLength > size) {
833                 usbi_err(ctx, "short bos descriptor read %d/%d",
834                          size, bos_header.bLength);
835                 return LIBUSB_ERROR_IO;
836         }
837
838         _bos = calloc (1,
839                 sizeof(*_bos) + bos_header.bNumDeviceCaps * sizeof(void *));
840         if (!_bos)
841                 return LIBUSB_ERROR_NO_MEM;
842
843         usbi_parse_descriptor(buffer, "bbwb", _bos, host_endian);
844         buffer += bos_header.bLength;
845         size -= bos_header.bLength;
846
847         /* Get the device capability descriptors */
848         for (i = 0; i < bos_header.bNumDeviceCaps; i++) {
849                 if (size < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
850                         usbi_warn(ctx, "short dev-cap descriptor read %d/%d",
851                                   size, LIBUSB_DT_DEVICE_CAPABILITY_SIZE);
852                         break;
853                 }
854                 usbi_parse_descriptor(buffer, "bbb", &dev_cap, host_endian);
855                 if (dev_cap.bDescriptorType != LIBUSB_DT_DEVICE_CAPABILITY) {
856                         usbi_warn(ctx, "unexpected descriptor %x (expected %x)",
857                                   dev_cap.bDescriptorType, LIBUSB_DT_DEVICE_CAPABILITY);
858                         break;
859                 }
860                 if (dev_cap.bLength < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
861                         usbi_err(ctx, "invalid dev-cap bLength (%d)",
862                                  dev_cap.bLength);
863                         libusb_free_bos_descriptor(_bos);
864                         return LIBUSB_ERROR_IO;
865                 }
866                 if (dev_cap.bLength > size) {
867                         usbi_warn(ctx, "short dev-cap descriptor read %d/%d",
868                                   size, dev_cap.bLength);
869                         break;
870                 }
871
872                 _bos->dev_capability[i] = malloc(dev_cap.bLength);
873                 if (!_bos->dev_capability[i]) {
874                         libusb_free_bos_descriptor(_bos);
875                         return LIBUSB_ERROR_NO_MEM;
876                 }
877                 memcpy(_bos->dev_capability[i], buffer, dev_cap.bLength);
878                 buffer += dev_cap.bLength;
879                 size -= dev_cap.bLength;
880         }
881         _bos->bNumDeviceCaps = (uint8_t)i;
882         *bos = _bos;
883
884         return LIBUSB_SUCCESS;
885 }
886
887 /** \ingroup libusb_desc
888  * Get a Binary Object Store (BOS) descriptor
889  * This is a BLOCKING function, which will send requests to the device.
890  *
891  * \param dev_handle the handle of an open libusb device
892  * \param bos output location for the BOS descriptor. Only valid if 0 was returned.
893  * Must be freed with \ref libusb_free_bos_descriptor() after use.
894  * \returns 0 on success
895  * \returns LIBUSB_ERROR_NOT_FOUND if the device doesn't have a BOS descriptor
896  * \returns another LIBUSB_ERROR code on error
897  */
898 int API_EXPORTED libusb_get_bos_descriptor(libusb_device_handle *dev_handle,
899         struct libusb_bos_descriptor **bos)
900 {
901         struct libusb_bos_descriptor _bos;
902         uint8_t bos_header[LIBUSB_DT_BOS_SIZE] = {0};
903         unsigned char *bos_data = NULL;
904         const int host_endian = 0;
905         int r;
906
907         /* Read the BOS. This generates 2 requests on the bus,
908          * one for the header, and one for the full BOS */
909         r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_header,
910                                   LIBUSB_DT_BOS_SIZE);
911         if (r < 0) {
912                 if (r != LIBUSB_ERROR_PIPE)
913                         usbi_err(HANDLE_CTX(dev_handle), "failed to read BOS (%d)", r);
914                 return r;
915         }
916         if (r < LIBUSB_DT_BOS_SIZE) {
917                 usbi_err(HANDLE_CTX(dev_handle), "short BOS read %d/%d",
918                          r, LIBUSB_DT_BOS_SIZE);
919                 return LIBUSB_ERROR_IO;
920         }
921
922         usbi_parse_descriptor(bos_header, "bbwb", &_bos, host_endian);
923         usbi_dbg("found BOS descriptor: size %d bytes, %d capabilities",
924                  _bos.wTotalLength, _bos.bNumDeviceCaps);
925         bos_data = calloc(_bos.wTotalLength, 1);
926         if (bos_data == NULL)
927                 return LIBUSB_ERROR_NO_MEM;
928
929         r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_data,
930                                   _bos.wTotalLength);
931         if (r >= 0)
932                 r = parse_bos(HANDLE_CTX(dev_handle), bos, bos_data, r, host_endian);
933         else
934                 usbi_err(HANDLE_CTX(dev_handle), "failed to read BOS (%d)", r);
935
936         free(bos_data);
937         return r;
938 }
939
940 /** \ingroup libusb_desc
941  * Free a BOS descriptor obtained from libusb_get_bos_descriptor().
942  * It is safe to call this function with a NULL bos parameter, in which
943  * case the function simply returns.
944  *
945  * \param bos the BOS descriptor to free
946  */
947 void API_EXPORTED libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos)
948 {
949         int i;
950
951         if (!bos)
952                 return;
953
954         for (i = 0; i < bos->bNumDeviceCaps; i++)
955                 free(bos->dev_capability[i]);
956         free(bos);
957 }
958
959 /** \ingroup libusb_desc
960  * Get an USB 2.0 Extension descriptor
961  *
962  * \param ctx the context to operate on, or NULL for the default context
963  * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
964  * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION
965  * LIBUSB_BT_USB_2_0_EXTENSION
966  * \param usb_2_0_extension output location for the USB 2.0 Extension
967  * descriptor. Only valid if 0 was returned. Must be freed with
968  * libusb_free_usb_2_0_extension_descriptor() after use.
969  * \returns 0 on success
970  * \returns a LIBUSB_ERROR code on error
971  */
972 int API_EXPORTED libusb_get_usb_2_0_extension_descriptor(
973         struct libusb_context *ctx,
974         struct libusb_bos_dev_capability_descriptor *dev_cap,
975         struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension)
976 {
977         struct libusb_usb_2_0_extension_descriptor *_usb_2_0_extension;
978         const int host_endian = 0;
979
980         if (dev_cap->bDevCapabilityType != LIBUSB_BT_USB_2_0_EXTENSION) {
981                 usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
982                          dev_cap->bDevCapabilityType,
983                          LIBUSB_BT_USB_2_0_EXTENSION);
984                 return LIBUSB_ERROR_INVALID_PARAM;
985         }
986         if (dev_cap->bLength < LIBUSB_BT_USB_2_0_EXTENSION_SIZE) {
987                 usbi_err(ctx, "short dev-cap descriptor read %d/%d",
988                          dev_cap->bLength, LIBUSB_BT_USB_2_0_EXTENSION_SIZE);
989                 return LIBUSB_ERROR_IO;
990         }
991
992         _usb_2_0_extension = malloc(sizeof(*_usb_2_0_extension));
993         if (!_usb_2_0_extension)
994                 return LIBUSB_ERROR_NO_MEM;
995
996         usbi_parse_descriptor((unsigned char *)dev_cap, "bbbd",
997                               _usb_2_0_extension, host_endian);
998
999         *usb_2_0_extension = _usb_2_0_extension;
1000         return LIBUSB_SUCCESS;
1001 }
1002
1003 /** \ingroup libusb_desc
1004  * Free a USB 2.0 Extension descriptor obtained from
1005  * libusb_get_usb_2_0_extension_descriptor().
1006  * It is safe to call this function with a NULL usb_2_0_extension parameter,
1007  * in which case the function simply returns.
1008  *
1009  * \param usb_2_0_extension the USB 2.0 Extension descriptor to free
1010  */
1011 void API_EXPORTED libusb_free_usb_2_0_extension_descriptor(
1012         struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension)
1013 {
1014         free(usb_2_0_extension);
1015 }
1016
1017 /** \ingroup libusb_desc
1018  * Get a SuperSpeed USB Device Capability descriptor
1019  *
1020  * \param ctx the context to operate on, or NULL for the default context
1021  * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
1022  * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
1023  * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
1024  * \param ss_usb_device_cap output location for the SuperSpeed USB Device
1025  * Capability descriptor. Only valid if 0 was returned. Must be freed with
1026  * libusb_free_ss_usb_device_capability_descriptor() after use.
1027  * \returns 0 on success
1028  * \returns a LIBUSB_ERROR code on error
1029  */
1030 int API_EXPORTED libusb_get_ss_usb_device_capability_descriptor(
1031         struct libusb_context *ctx,
1032         struct libusb_bos_dev_capability_descriptor *dev_cap,
1033         struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap)
1034 {
1035         struct libusb_ss_usb_device_capability_descriptor *_ss_usb_device_cap;
1036         const int host_endian = 0;
1037
1038         if (dev_cap->bDevCapabilityType != LIBUSB_BT_SS_USB_DEVICE_CAPABILITY) {
1039                 usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
1040                          dev_cap->bDevCapabilityType,
1041                          LIBUSB_BT_SS_USB_DEVICE_CAPABILITY);
1042                 return LIBUSB_ERROR_INVALID_PARAM;
1043         }
1044         if (dev_cap->bLength < LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) {
1045                 usbi_err(ctx, "short dev-cap descriptor read %d/%d",
1046                          dev_cap->bLength, LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE);
1047                 return LIBUSB_ERROR_IO;
1048         }
1049
1050         _ss_usb_device_cap = malloc(sizeof(*_ss_usb_device_cap));
1051         if (!_ss_usb_device_cap)
1052                 return LIBUSB_ERROR_NO_MEM;
1053
1054         usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbwbbw",
1055                               _ss_usb_device_cap, host_endian);
1056
1057         *ss_usb_device_cap = _ss_usb_device_cap;
1058         return LIBUSB_SUCCESS;
1059 }
1060
1061 /** \ingroup libusb_desc
1062  * Free a SuperSpeed USB Device Capability descriptor obtained from
1063  * libusb_get_ss_usb_device_capability_descriptor().
1064  * It is safe to call this function with a NULL ss_usb_device_cap
1065  * parameter, in which case the function simply returns.
1066  *
1067  * \param ss_usb_device_cap the USB 2.0 Extension descriptor to free
1068  */
1069 void API_EXPORTED libusb_free_ss_usb_device_capability_descriptor(
1070         struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap)
1071 {
1072         free(ss_usb_device_cap);
1073 }
1074
1075 /** \ingroup libusb_desc
1076  * Get a Container ID descriptor
1077  *
1078  * \param ctx the context to operate on, or NULL for the default context
1079  * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
1080  * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID
1081  * LIBUSB_BT_CONTAINER_ID
1082  * \param container_id output location for the Container ID descriptor.
1083  * Only valid if 0 was returned. Must be freed with
1084  * libusb_free_container_id_descriptor() after use.
1085  * \returns 0 on success
1086  * \returns a LIBUSB_ERROR code on error
1087  */
1088 int API_EXPORTED libusb_get_container_id_descriptor(struct libusb_context *ctx,
1089         struct libusb_bos_dev_capability_descriptor *dev_cap,
1090         struct libusb_container_id_descriptor **container_id)
1091 {
1092         struct libusb_container_id_descriptor *_container_id;
1093         const int host_endian = 0;
1094
1095         if (dev_cap->bDevCapabilityType != LIBUSB_BT_CONTAINER_ID) {
1096                 usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
1097                          dev_cap->bDevCapabilityType,
1098                          LIBUSB_BT_CONTAINER_ID);
1099                 return LIBUSB_ERROR_INVALID_PARAM;
1100         }
1101         if (dev_cap->bLength < LIBUSB_BT_CONTAINER_ID_SIZE) {
1102                 usbi_err(ctx, "short dev-cap descriptor read %d/%d",
1103                          dev_cap->bLength, LIBUSB_BT_CONTAINER_ID_SIZE);
1104                 return LIBUSB_ERROR_IO;
1105         }
1106
1107         _container_id = malloc(sizeof(*_container_id));
1108         if (!_container_id)
1109                 return LIBUSB_ERROR_NO_MEM;
1110
1111         usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbu",
1112                               _container_id, host_endian);
1113
1114         *container_id = _container_id;
1115         return LIBUSB_SUCCESS;
1116 }
1117
1118 /** \ingroup libusb_desc
1119  * Free a Container ID descriptor obtained from
1120  * libusb_get_container_id_descriptor().
1121  * It is safe to call this function with a NULL container_id parameter,
1122  * in which case the function simply returns.
1123  *
1124  * \param container_id the USB 2.0 Extension descriptor to free
1125  */
1126 void API_EXPORTED libusb_free_container_id_descriptor(
1127         struct libusb_container_id_descriptor *container_id)
1128 {
1129         free(container_id);
1130 }
1131
1132 /** \ingroup libusb_desc
1133  * Retrieve a string descriptor in C style ASCII.
1134  *
1135  * Wrapper around libusb_get_string_descriptor(). Uses the first language
1136  * supported by the device.
1137  *
1138  * \param dev_handle a device handle
1139  * \param desc_index the index of the descriptor to retrieve
1140  * \param data output buffer for ASCII string descriptor
1141  * \param length size of data buffer
1142  * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
1143  */
1144 int API_EXPORTED libusb_get_string_descriptor_ascii(libusb_device_handle *dev_handle,
1145         uint8_t desc_index, unsigned char *data, int length)
1146 {
1147         unsigned char tbuf[255]; /* Some devices choke on size > 255 */
1148         int r, si, di;
1149         uint16_t langid;
1150
1151         /* Asking for the zero'th index is special - it returns a string
1152          * descriptor that contains all the language IDs supported by the
1153          * device. Typically there aren't many - often only one. Language
1154          * IDs are 16 bit numbers, and they start at the third byte in the
1155          * descriptor. There's also no point in trying to read descriptor 0
1156          * with this function. See USB 2.0 specification section 9.6.7 for
1157          * more information.
1158          */
1159
1160         if (desc_index == 0)
1161                 return LIBUSB_ERROR_INVALID_PARAM;
1162
1163         r = libusb_get_string_descriptor(dev_handle, 0, 0, tbuf, sizeof(tbuf));
1164         if (r < 0)
1165                 return r;
1166
1167         if (r < 4)
1168                 return LIBUSB_ERROR_IO;
1169
1170         langid = tbuf[2] | (tbuf[3] << 8);
1171
1172         r = libusb_get_string_descriptor(dev_handle, desc_index, langid, tbuf,
1173                 sizeof(tbuf));
1174         if (r < 0)
1175                 return r;
1176
1177         if (tbuf[1] != LIBUSB_DT_STRING)
1178                 return LIBUSB_ERROR_IO;
1179
1180         if (tbuf[0] > r)
1181                 return LIBUSB_ERROR_IO;
1182
1183         for (di = 0, si = 2; si < tbuf[0]; si += 2) {
1184                 if (di >= (length - 1))
1185                         break;
1186
1187                 if ((tbuf[si] & 0x80) || (tbuf[si + 1])) /* non-ASCII */
1188                         data[di++] = '?';
1189                 else
1190                         data[di++] = tbuf[si];
1191         }
1192
1193         data[di] = 0;
1194         return di;
1195 }