libusb 1.0.20-rc3
[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 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         size_t tmp;
226         struct usb_descriptor_header header;
227         struct libusb_interface_descriptor *ifp;
228         unsigned char *begin;
229
230         usb_interface->num_altsetting = 0;
231
232         while (size >= INTERFACE_DESC_LENGTH) {
233                 struct libusb_interface_descriptor *altsetting =
234                         (struct libusb_interface_descriptor *) usb_interface->altsetting;
235                 altsetting = usbi_reallocf(altsetting,
236                         sizeof(struct libusb_interface_descriptor) *
237                         (usb_interface->num_altsetting + 1));
238                 if (!altsetting) {
239                         r = LIBUSB_ERROR_NO_MEM;
240                         goto err;
241                 }
242                 usb_interface->altsetting = altsetting;
243
244                 ifp = altsetting + usb_interface->num_altsetting;
245                 usbi_parse_descriptor(buffer, "bbbbbbbbb", ifp, 0);
246                 if (ifp->bDescriptorType != LIBUSB_DT_INTERFACE) {
247                         usbi_err(ctx, "unexpected descriptor %x (expected %x)",
248                                  ifp->bDescriptorType, LIBUSB_DT_INTERFACE);
249                         return parsed;
250                 }
251                 if (ifp->bLength < INTERFACE_DESC_LENGTH) {
252                         usbi_err(ctx, "invalid interface bLength (%d)",
253                                  ifp->bLength);
254                         r = LIBUSB_ERROR_IO;
255                         goto err;
256                 }
257                 if (ifp->bLength > size) {
258                         usbi_warn(ctx, "short intf descriptor read %d/%d",
259                                  size, ifp->bLength);
260                         return parsed;
261                 }
262                 if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
263                         usbi_err(ctx, "too many endpoints (%d)", ifp->bNumEndpoints);
264                         r = LIBUSB_ERROR_IO;
265                         goto err;
266                 }
267
268                 usb_interface->num_altsetting++;
269                 ifp->extra = NULL;
270                 ifp->extra_length = 0;
271                 ifp->endpoint = NULL;
272
273                 if (interface_number == -1)
274                         interface_number = ifp->bInterfaceNumber;
275
276                 /* Skip over the interface */
277                 buffer += ifp->bLength;
278                 parsed += ifp->bLength;
279                 size -= ifp->bLength;
280
281                 begin = buffer;
282
283                 /* Skip over any interface, class or vendor descriptors */
284                 while (size >= DESC_HEADER_LENGTH) {
285                         usbi_parse_descriptor(buffer, "bb", &header, 0);
286                         if (header.bLength < DESC_HEADER_LENGTH) {
287                                 usbi_err(ctx,
288                                          "invalid extra intf desc len (%d)",
289                                          header.bLength);
290                                 r = LIBUSB_ERROR_IO;
291                                 goto err;
292                         } else if (header.bLength > size) {
293                                 usbi_warn(ctx,
294                                           "short extra intf desc read %d/%d",
295                                           size, header.bLength);
296                                 return parsed;
297                         }
298
299                         /* If we find another "proper" descriptor then we're done */
300                         if ((header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
301                                         (header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
302                                         (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
303                                         (header.bDescriptorType == LIBUSB_DT_DEVICE))
304                                 break;
305
306                         buffer += header.bLength;
307                         parsed += header.bLength;
308                         size -= header.bLength;
309                 }
310
311                 /* Copy any unknown descriptors into a storage area for */
312                 /*  drivers to later parse */
313                 len = (int)(buffer - begin);
314                 if (len) {
315                         ifp->extra = malloc(len);
316                         if (!ifp->extra) {
317                                 r = LIBUSB_ERROR_NO_MEM;
318                                 goto err;
319                         }
320                         memcpy((unsigned char *) ifp->extra, begin, len);
321                         ifp->extra_length = len;
322                 }
323
324                 if (ifp->bNumEndpoints > 0) {
325                         struct libusb_endpoint_descriptor *endpoint;
326                         tmp = ifp->bNumEndpoints * sizeof(struct libusb_endpoint_descriptor);
327                         endpoint = malloc(tmp);
328                         ifp->endpoint = endpoint;
329                         if (!endpoint) {
330                                 r = LIBUSB_ERROR_NO_MEM;
331                                 goto err;
332                         }
333
334                         memset(endpoint, 0, tmp);
335                         for (i = 0; i < ifp->bNumEndpoints; i++) {
336                                 r = parse_endpoint(ctx, endpoint + i, buffer, size,
337                                         host_endian);
338                                 if (r < 0)
339                                         goto err;
340                                 if (r == 0) {
341                                         ifp->bNumEndpoints = (uint8_t)i;
342                                         break;;
343                                 }
344
345                                 buffer += r;
346                                 parsed += r;
347                                 size -= r;
348                         }
349                 }
350
351                 /* We check to see if it's an alternate to this one */
352                 ifp = (struct libusb_interface_descriptor *) buffer;
353                 if (size < LIBUSB_DT_INTERFACE_SIZE ||
354                                 ifp->bDescriptorType != LIBUSB_DT_INTERFACE ||
355                                 ifp->bInterfaceNumber != interface_number)
356                         return parsed;
357         }
358
359         return parsed;
360 err:
361         clear_interface(usb_interface);
362         return r;
363 }
364
365 static void clear_configuration(struct libusb_config_descriptor *config)
366 {
367         if (config->interface) {
368                 int i;
369                 for (i = 0; i < config->bNumInterfaces; i++)
370                         clear_interface((struct libusb_interface *)
371                                 config->interface + i);
372                 free((void *) config->interface);
373         }
374         if (config->extra)
375                 free((void *) config->extra);
376 }
377
378 static int parse_configuration(struct libusb_context *ctx,
379         struct libusb_config_descriptor *config, unsigned char *buffer,
380         int size, int host_endian)
381 {
382         int i;
383         int r;
384         size_t tmp;
385         struct usb_descriptor_header header;
386         struct libusb_interface *usb_interface;
387
388         if (size < LIBUSB_DT_CONFIG_SIZE) {
389                 usbi_err(ctx, "short config descriptor read %d/%d",
390                          size, LIBUSB_DT_CONFIG_SIZE);
391                 return LIBUSB_ERROR_IO;
392         }
393
394         usbi_parse_descriptor(buffer, "bbwbbbbb", config, host_endian);
395         if (config->bDescriptorType != LIBUSB_DT_CONFIG) {
396                 usbi_err(ctx, "unexpected descriptor %x (expected %x)",
397                          config->bDescriptorType, LIBUSB_DT_CONFIG);
398                 return LIBUSB_ERROR_IO;
399         }
400         if (config->bLength < LIBUSB_DT_CONFIG_SIZE) {
401                 usbi_err(ctx, "invalid config bLength (%d)", config->bLength);
402                 return LIBUSB_ERROR_IO;
403         }
404         if (config->bLength > size) {
405                 usbi_err(ctx, "short config descriptor read %d/%d",
406                          size, config->bLength);
407                 return LIBUSB_ERROR_IO;
408         }
409         if (config->bNumInterfaces > USB_MAXINTERFACES) {
410                 usbi_err(ctx, "too many interfaces (%d)", config->bNumInterfaces);
411                 return LIBUSB_ERROR_IO;
412         }
413
414         tmp = config->bNumInterfaces * sizeof(struct libusb_interface);
415         usb_interface = malloc(tmp);
416         config->interface = usb_interface;
417         if (!config->interface)
418                 return LIBUSB_ERROR_NO_MEM;
419
420         memset(usb_interface, 0, tmp);
421         buffer += config->bLength;
422         size -= config->bLength;
423
424         config->extra = NULL;
425         config->extra_length = 0;
426
427         for (i = 0; i < config->bNumInterfaces; i++) {
428                 int len;
429                 unsigned char *begin;
430
431                 /* Skip over the rest of the Class Specific or Vendor */
432                 /*  Specific descriptors */
433                 begin = buffer;
434                 while (size >= DESC_HEADER_LENGTH) {
435                         usbi_parse_descriptor(buffer, "bb", &header, 0);
436
437                         if (header.bLength < DESC_HEADER_LENGTH) {
438                                 usbi_err(ctx,
439                                          "invalid extra config desc len (%d)",
440                                          header.bLength);
441                                 r = LIBUSB_ERROR_IO;
442                                 goto err;
443                         } else if (header.bLength > size) {
444                                 usbi_warn(ctx,
445                                           "short extra config desc read %d/%d",
446                                           size, header.bLength);
447                                 config->bNumInterfaces = (uint8_t)i;
448                                 return size;
449                         }
450
451                         /* If we find another "proper" descriptor then we're done */
452                         if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
453                                         (header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
454                                         (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
455                                         (header.bDescriptorType == LIBUSB_DT_DEVICE))
456                                 break;
457
458                         usbi_dbg("skipping descriptor 0x%x", header.bDescriptorType);
459                         buffer += header.bLength;
460                         size -= header.bLength;
461                 }
462
463                 /* Copy any unknown descriptors into a storage area for */
464                 /*  drivers to later parse */
465                 len = (int)(buffer - begin);
466                 if (len) {
467                         /* FIXME: We should realloc and append here */
468                         if (!config->extra_length) {
469                                 config->extra = malloc(len);
470                                 if (!config->extra) {
471                                         r = LIBUSB_ERROR_NO_MEM;
472                                         goto err;
473                                 }
474
475                                 memcpy((unsigned char *) config->extra, begin, len);
476                                 config->extra_length = len;
477                         }
478                 }
479
480                 r = parse_interface(ctx, usb_interface + i, buffer, size, host_endian);
481                 if (r < 0)
482                         goto err;
483                 if (r == 0) {
484                         config->bNumInterfaces = (uint8_t)i;
485                         break;
486                 }
487
488                 buffer += r;
489                 size -= r;
490         }
491
492         return size;
493
494 err:
495         clear_configuration(config);
496         return r;
497 }
498
499 static int raw_desc_to_config(struct libusb_context *ctx,
500         unsigned char *buf, int size, int host_endian,
501         struct libusb_config_descriptor **config)
502 {
503         struct libusb_config_descriptor *_config = malloc(sizeof(*_config));
504         int r;
505         
506         if (!_config)
507                 return LIBUSB_ERROR_NO_MEM;
508
509         r = parse_configuration(ctx, _config, buf, size, host_endian);
510         if (r < 0) {
511                 usbi_err(ctx, "parse_configuration failed with error %d", r);
512                 free(_config);
513                 return r;
514         } else if (r > 0) {
515                 usbi_warn(ctx, "still %d bytes of descriptor data left", r);
516         }
517         
518         *config = _config;
519         return LIBUSB_SUCCESS;
520 }
521
522 int usbi_device_cache_descriptor(libusb_device *dev)
523 {
524         int r, host_endian = 0;
525
526         r = usbi_backend->get_device_descriptor(dev, (unsigned char *) &dev->device_descriptor,
527                                                 &host_endian);
528         if (r < 0)
529                 return r;
530
531         if (!host_endian) {
532                 dev->device_descriptor.bcdUSB = libusb_le16_to_cpu(dev->device_descriptor.bcdUSB);
533                 dev->device_descriptor.idVendor = libusb_le16_to_cpu(dev->device_descriptor.idVendor);
534                 dev->device_descriptor.idProduct = libusb_le16_to_cpu(dev->device_descriptor.idProduct);
535                 dev->device_descriptor.bcdDevice = libusb_le16_to_cpu(dev->device_descriptor.bcdDevice);
536         }
537
538         return LIBUSB_SUCCESS;
539 }
540
541 /** \ingroup desc
542  * Get the USB device descriptor for a given device.
543  *
544  * This is a non-blocking function; the device descriptor is cached in memory.
545  *
546  * Note since libusb-1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, this
547  * function always succeeds.
548  *
549  * \param dev the device
550  * \param desc output location for the descriptor data
551  * \returns 0 on success or a LIBUSB_ERROR code on failure
552  */
553 int API_EXPORTED libusb_get_device_descriptor(libusb_device *dev,
554         struct libusb_device_descriptor *desc)
555 {
556         usbi_dbg("");
557         memcpy((unsigned char *) desc, (unsigned char *) &dev->device_descriptor,
558                sizeof (dev->device_descriptor));
559         return 0;
560 }
561
562 /** \ingroup desc
563  * Get the USB configuration descriptor for the currently active configuration.
564  * This is a non-blocking function which does not involve any requests being
565  * sent to the device.
566  *
567  * \param dev a device
568  * \param config output location for the USB configuration descriptor. Only
569  * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
570  * after use.
571  * \returns 0 on success
572  * \returns LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
573  * \returns another LIBUSB_ERROR code on error
574  * \see libusb_get_config_descriptor
575  */
576 int API_EXPORTED libusb_get_active_config_descriptor(libusb_device *dev,
577         struct libusb_config_descriptor **config)
578 {
579         struct libusb_config_descriptor _config;
580         unsigned char tmp[LIBUSB_DT_CONFIG_SIZE];
581         unsigned char *buf = NULL;
582         int host_endian = 0;
583         int r;
584
585         r = usbi_backend->get_active_config_descriptor(dev, tmp,
586                 LIBUSB_DT_CONFIG_SIZE, &host_endian);
587         if (r < 0)
588                 return r;
589         if (r < LIBUSB_DT_CONFIG_SIZE) {
590                 usbi_err(dev->ctx, "short config descriptor read %d/%d",
591                          r, LIBUSB_DT_CONFIG_SIZE);
592                 return LIBUSB_ERROR_IO;
593         }
594
595         usbi_parse_descriptor(tmp, "bbw", &_config, host_endian);
596         buf = malloc(_config.wTotalLength);
597         if (!buf)
598                 return LIBUSB_ERROR_NO_MEM;
599
600         r = usbi_backend->get_active_config_descriptor(dev, buf,
601                 _config.wTotalLength, &host_endian);
602         if (r >= 0)
603                 r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
604
605         free(buf);
606         return r;
607 }
608
609 /** \ingroup desc
610  * Get a USB configuration descriptor based on its index.
611  * This is a non-blocking function which does not involve any requests being
612  * sent to the device.
613  *
614  * \param dev a device
615  * \param config_index the index of the configuration you wish to retrieve
616  * \param config output location for the USB configuration descriptor. Only
617  * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
618  * after use.
619  * \returns 0 on success
620  * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
621  * \returns another LIBUSB_ERROR code on error
622  * \see libusb_get_active_config_descriptor()
623  * \see libusb_get_config_descriptor_by_value()
624  */
625 int API_EXPORTED libusb_get_config_descriptor(libusb_device *dev,
626         uint8_t config_index, struct libusb_config_descriptor **config)
627 {
628         struct libusb_config_descriptor _config;
629         unsigned char tmp[LIBUSB_DT_CONFIG_SIZE];
630         unsigned char *buf = NULL;
631         int host_endian = 0;
632         int r;
633
634         usbi_dbg("index %d", config_index);
635         if (config_index >= dev->num_configurations)
636                 return LIBUSB_ERROR_NOT_FOUND;
637
638         r = usbi_backend->get_config_descriptor(dev, config_index, tmp,
639                 LIBUSB_DT_CONFIG_SIZE, &host_endian);
640         if (r < 0)
641                 return r;
642         if (r < LIBUSB_DT_CONFIG_SIZE) {
643                 usbi_err(dev->ctx, "short config descriptor read %d/%d",
644                          r, LIBUSB_DT_CONFIG_SIZE);
645                 return LIBUSB_ERROR_IO;
646         }
647
648         usbi_parse_descriptor(tmp, "bbw", &_config, host_endian);
649         buf = malloc(_config.wTotalLength);
650         if (!buf)
651                 return LIBUSB_ERROR_NO_MEM;
652
653         r = usbi_backend->get_config_descriptor(dev, config_index, buf,
654                 _config.wTotalLength, &host_endian);
655         if (r >= 0)
656                 r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
657
658         free(buf);
659         return r;
660 }
661
662 /* iterate through all configurations, returning the index of the configuration
663  * matching a specific bConfigurationValue in the idx output parameter, or -1
664  * if the config was not found.
665  * returns 0 on success or a LIBUSB_ERROR code
666  */
667 int usbi_get_config_index_by_value(struct libusb_device *dev,
668         uint8_t bConfigurationValue, int *idx)
669 {
670         uint8_t i;
671
672         usbi_dbg("value %d", bConfigurationValue);
673         for (i = 0; i < dev->num_configurations; i++) {
674                 unsigned char tmp[6];
675                 int host_endian;
676                 int r = usbi_backend->get_config_descriptor(dev, i, tmp, sizeof(tmp),
677                         &host_endian);
678                 if (r < 0) {
679                         *idx = -1;
680                         return r;
681                 }
682                 if (tmp[5] == bConfigurationValue) {
683                         *idx = i;
684                         return 0;
685                 }
686         }
687
688         *idx = -1;
689         return 0;
690 }
691
692 /** \ingroup desc
693  * Get a USB configuration descriptor with a specific bConfigurationValue.
694  * This is a non-blocking function which does not involve any requests being
695  * sent to the device.
696  *
697  * \param dev a device
698  * \param bConfigurationValue the bConfigurationValue of the configuration you
699  * wish to retrieve
700  * \param config output location for the USB configuration descriptor. Only
701  * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
702  * after use.
703  * \returns 0 on success
704  * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
705  * \returns another LIBUSB_ERROR code on error
706  * \see libusb_get_active_config_descriptor()
707  * \see libusb_get_config_descriptor()
708  */
709 int API_EXPORTED libusb_get_config_descriptor_by_value(libusb_device *dev,
710         uint8_t bConfigurationValue, struct libusb_config_descriptor **config)
711 {
712         int r, idx, host_endian;
713         unsigned char *buf = NULL;
714
715         if (usbi_backend->get_config_descriptor_by_value) {
716                 r = usbi_backend->get_config_descriptor_by_value(dev,
717                         bConfigurationValue, &buf, &host_endian);
718                 if (r < 0)
719                         return r;
720                 return raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
721         }
722
723         r = usbi_get_config_index_by_value(dev, bConfigurationValue, &idx);
724         if (r < 0)
725                 return r;
726         else if (idx == -1)
727                 return LIBUSB_ERROR_NOT_FOUND;
728         else
729                 return libusb_get_config_descriptor(dev, (uint8_t) idx, config);
730 }
731
732 /** \ingroup desc
733  * Free a configuration descriptor obtained from
734  * libusb_get_active_config_descriptor() or libusb_get_config_descriptor().
735  * It is safe to call this function with a NULL config parameter, in which
736  * case the function simply returns.
737  *
738  * \param config the configuration descriptor to free
739  */
740 void API_EXPORTED libusb_free_config_descriptor(
741         struct libusb_config_descriptor *config)
742 {
743         if (!config)
744                 return;
745
746         clear_configuration(config);
747         free(config);
748 }
749
750 /** \ingroup desc
751  * Get an endpoints superspeed endpoint companion descriptor (if any)
752  *
753  * \param ctx the context to operate on, or NULL for the default context
754  * \param endpoint endpoint descriptor from which to get the superspeed
755  * endpoint companion descriptor
756  * \param ep_comp output location for the superspeed endpoint companion
757  * descriptor. Only valid if 0 was returned. Must be freed with
758  * libusb_free_ss_endpoint_companion_descriptor() after use.
759  * \returns 0 on success
760  * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
761  * \returns another LIBUSB_ERROR code on error
762  */
763 int API_EXPORTED libusb_get_ss_endpoint_companion_descriptor(
764         struct libusb_context *ctx,
765         const struct libusb_endpoint_descriptor *endpoint,
766         struct libusb_ss_endpoint_companion_descriptor **ep_comp)
767 {
768         struct usb_descriptor_header header;
769         int size = endpoint->extra_length;
770         const unsigned char *buffer = endpoint->extra;
771
772         *ep_comp = NULL;
773
774         while (size >= DESC_HEADER_LENGTH) {
775                 usbi_parse_descriptor(buffer, "bb", &header, 0);
776                 if (header.bLength < 2 || header.bLength > size) {
777                         usbi_err(ctx, "invalid descriptor length %d",
778                                  header.bLength);
779                         return LIBUSB_ERROR_IO;
780                 }
781                 if (header.bDescriptorType != LIBUSB_DT_SS_ENDPOINT_COMPANION) {
782                         buffer += header.bLength;
783                         size -= header.bLength;
784                         continue;
785                 }
786                 if (header.bLength < LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE) {
787                         usbi_err(ctx, "invalid ss-ep-comp-desc length %d",
788                                  header.bLength);
789                         return LIBUSB_ERROR_IO;
790                 }
791                 *ep_comp = malloc(sizeof(**ep_comp));
792                 if (*ep_comp == NULL)
793                         return LIBUSB_ERROR_NO_MEM;
794                 usbi_parse_descriptor(buffer, "bbbbw", *ep_comp, 0);
795                 return LIBUSB_SUCCESS;
796         }
797         return LIBUSB_ERROR_NOT_FOUND;
798 }
799
800 /** \ingroup desc
801  * Free a superspeed endpoint companion descriptor obtained from
802  * libusb_get_ss_endpoint_companion_descriptor().
803  * It is safe to call this function with a NULL ep_comp parameter, in which
804  * case the function simply returns.
805  *
806  * \param ep_comp the superspeed endpoint companion descriptor to free
807  */
808 void API_EXPORTED libusb_free_ss_endpoint_companion_descriptor(
809         struct libusb_ss_endpoint_companion_descriptor *ep_comp)
810 {
811         free(ep_comp);
812 }
813
814 static int parse_bos(struct libusb_context *ctx,
815         struct libusb_bos_descriptor **bos,
816         unsigned char *buffer, int size, int host_endian)
817 {
818         struct libusb_bos_descriptor bos_header, *_bos;
819         struct libusb_bos_dev_capability_descriptor dev_cap;
820         int i;
821
822         if (size < LIBUSB_DT_BOS_SIZE) {
823                 usbi_err(ctx, "short bos descriptor read %d/%d",
824                          size, LIBUSB_DT_BOS_SIZE);
825                 return LIBUSB_ERROR_IO;
826         }
827
828         usbi_parse_descriptor(buffer, "bbwb", &bos_header, host_endian);
829         if (bos_header.bDescriptorType != LIBUSB_DT_BOS) {
830                 usbi_err(ctx, "unexpected descriptor %x (expected %x)",
831                          bos_header.bDescriptorType, LIBUSB_DT_BOS);
832                 return LIBUSB_ERROR_IO;
833         }
834         if (bos_header.bLength < LIBUSB_DT_BOS_SIZE) {
835                 usbi_err(ctx, "invalid bos bLength (%d)", bos_header.bLength);
836                 return LIBUSB_ERROR_IO;
837         }
838         if (bos_header.bLength > size) {
839                 usbi_err(ctx, "short bos descriptor read %d/%d",
840                          size, bos_header.bLength);
841                 return LIBUSB_ERROR_IO;
842         }
843
844         _bos = calloc (1,
845                 sizeof(*_bos) + bos_header.bNumDeviceCaps * sizeof(void *));
846         if (!_bos)
847                 return LIBUSB_ERROR_NO_MEM;
848
849         usbi_parse_descriptor(buffer, "bbwb", _bos, host_endian);
850         buffer += bos_header.bLength;
851         size -= bos_header.bLength;
852
853         /* Get the device capability descriptors */
854         for (i = 0; i < bos_header.bNumDeviceCaps; i++) {
855                 if (size < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
856                         usbi_warn(ctx, "short dev-cap descriptor read %d/%d",
857                                   size, LIBUSB_DT_DEVICE_CAPABILITY_SIZE);
858                         break;
859                 }
860                 usbi_parse_descriptor(buffer, "bbb", &dev_cap, host_endian);
861                 if (dev_cap.bDescriptorType != LIBUSB_DT_DEVICE_CAPABILITY) {
862                         usbi_warn(ctx, "unexpected descriptor %x (expected %x)",
863                                   dev_cap.bDescriptorType, LIBUSB_DT_DEVICE_CAPABILITY);
864                         break;
865                 }
866                 if (dev_cap.bLength < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
867                         usbi_err(ctx, "invalid dev-cap bLength (%d)",
868                                  dev_cap.bLength);
869                         libusb_free_bos_descriptor(_bos);
870                         return LIBUSB_ERROR_IO;
871                 }
872                 if (dev_cap.bLength > size) {
873                         usbi_warn(ctx, "short dev-cap descriptor read %d/%d",
874                                   size, dev_cap.bLength);
875                         break;
876                 }
877
878                 _bos->dev_capability[i] = malloc(dev_cap.bLength);
879                 if (!_bos->dev_capability[i]) {
880                         libusb_free_bos_descriptor(_bos);
881                         return LIBUSB_ERROR_NO_MEM;
882                 }
883                 memcpy(_bos->dev_capability[i], buffer, dev_cap.bLength);
884                 buffer += dev_cap.bLength;
885                 size -= dev_cap.bLength;
886         }
887         _bos->bNumDeviceCaps = (uint8_t)i;
888         *bos = _bos;
889
890         return LIBUSB_SUCCESS;
891 }
892
893 /** \ingroup desc
894  * Get a Binary Object Store (BOS) descriptor
895  * This is a BLOCKING function, which will send requests to the device.
896  *
897  * \param handle the handle of an open libusb device
898  * \param bos output location for the BOS descriptor. Only valid if 0 was returned.
899  * Must be freed with \ref libusb_free_bos_descriptor() after use.
900  * \returns 0 on success
901  * \returns LIBUSB_ERROR_NOT_FOUND if the device doesn't have a BOS descriptor
902  * \returns another LIBUSB_ERROR code on error
903  */
904 int API_EXPORTED libusb_get_bos_descriptor(libusb_device_handle *handle,
905         struct libusb_bos_descriptor **bos)
906 {
907         struct libusb_bos_descriptor _bos;
908         uint8_t bos_header[LIBUSB_DT_BOS_SIZE] = {0};
909         unsigned char *bos_data = NULL;
910         const int host_endian = 0;
911         int r;
912
913         /* Read the BOS. This generates 2 requests on the bus,
914          * one for the header, and one for the full BOS */
915         r = libusb_get_descriptor(handle, LIBUSB_DT_BOS, 0, bos_header,
916                                   LIBUSB_DT_BOS_SIZE);
917         if (r < 0) {
918                 if (r != LIBUSB_ERROR_PIPE)
919                         usbi_err(handle->dev->ctx, "failed to read BOS (%d)", r);
920                 return r;
921         }
922         if (r < LIBUSB_DT_BOS_SIZE) {
923                 usbi_err(handle->dev->ctx, "short BOS read %d/%d",
924                          r, LIBUSB_DT_BOS_SIZE);
925                 return LIBUSB_ERROR_IO;
926         }
927
928         usbi_parse_descriptor(bos_header, "bbwb", &_bos, host_endian);
929         usbi_dbg("found BOS descriptor: size %d bytes, %d capabilities",
930                  _bos.wTotalLength, _bos.bNumDeviceCaps);
931         bos_data = calloc(_bos.wTotalLength, 1);
932         if (bos_data == NULL)
933                 return LIBUSB_ERROR_NO_MEM;
934
935         r = libusb_get_descriptor(handle, LIBUSB_DT_BOS, 0, bos_data,
936                                   _bos.wTotalLength);
937         if (r >= 0)
938                 r = parse_bos(handle->dev->ctx, bos, bos_data, r, host_endian);
939         else
940                 usbi_err(handle->dev->ctx, "failed to read BOS (%d)", r);
941
942         free(bos_data);
943         return r;
944 }
945
946 /** \ingroup desc
947  * Free a BOS descriptor obtained from libusb_get_bos_descriptor().
948  * It is safe to call this function with a NULL bos parameter, in which
949  * case the function simply returns.
950  *
951  * \param bos the BOS descriptor to free
952  */
953 void API_EXPORTED libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos)
954 {
955         int i;
956
957         if (!bos)
958                 return;
959
960         for (i = 0; i < bos->bNumDeviceCaps; i++)
961                 free(bos->dev_capability[i]);
962         free(bos);
963 }
964
965 /** \ingroup desc
966  * Get an USB 2.0 Extension descriptor
967  *
968  * \param ctx the context to operate on, or NULL for the default context
969  * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
970  * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION
971  * LIBUSB_BT_USB_2_0_EXTENSION
972  * \param usb_2_0_extension output location for the USB 2.0 Extension
973  * descriptor. Only valid if 0 was returned. Must be freed with
974  * libusb_free_usb_2_0_extension_descriptor() after use.
975  * \returns 0 on success
976  * \returns a LIBUSB_ERROR code on error
977  */
978 int API_EXPORTED libusb_get_usb_2_0_extension_descriptor(
979         struct libusb_context *ctx,
980         struct libusb_bos_dev_capability_descriptor *dev_cap,
981         struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension)
982 {
983         struct libusb_usb_2_0_extension_descriptor *_usb_2_0_extension;
984         const int host_endian = 0;
985
986         if (dev_cap->bDevCapabilityType != LIBUSB_BT_USB_2_0_EXTENSION) {
987                 usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
988                          dev_cap->bDevCapabilityType,
989                          LIBUSB_BT_USB_2_0_EXTENSION);
990                 return LIBUSB_ERROR_INVALID_PARAM;
991         }
992         if (dev_cap->bLength < LIBUSB_BT_USB_2_0_EXTENSION_SIZE) {
993                 usbi_err(ctx, "short dev-cap descriptor read %d/%d",
994                          dev_cap->bLength, LIBUSB_BT_USB_2_0_EXTENSION_SIZE);
995                 return LIBUSB_ERROR_IO;
996         }
997
998         _usb_2_0_extension = malloc(sizeof(*_usb_2_0_extension));
999         if (!_usb_2_0_extension)
1000                 return LIBUSB_ERROR_NO_MEM;
1001
1002         usbi_parse_descriptor((unsigned char *)dev_cap, "bbbd",
1003                               _usb_2_0_extension, host_endian);
1004
1005         *usb_2_0_extension = _usb_2_0_extension;
1006         return LIBUSB_SUCCESS;
1007 }
1008
1009 /** \ingroup desc
1010  * Free a USB 2.0 Extension descriptor obtained from
1011  * libusb_get_usb_2_0_extension_descriptor().
1012  * It is safe to call this function with a NULL usb_2_0_extension parameter,
1013  * in which case the function simply returns.
1014  *
1015  * \param usb_2_0_extension the USB 2.0 Extension descriptor to free
1016  */
1017 void API_EXPORTED libusb_free_usb_2_0_extension_descriptor(
1018         struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension)
1019 {
1020         free(usb_2_0_extension);
1021 }
1022
1023 /** \ingroup desc
1024  * Get a SuperSpeed USB Device Capability descriptor
1025  *
1026  * \param ctx the context to operate on, or NULL for the default context
1027  * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
1028  * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
1029  * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
1030  * \param ss_usb_device_cap output location for the SuperSpeed USB Device
1031  * Capability descriptor. Only valid if 0 was returned. Must be freed with
1032  * libusb_free_ss_usb_device_capability_descriptor() after use.
1033  * \returns 0 on success
1034  * \returns a LIBUSB_ERROR code on error
1035  */
1036 int API_EXPORTED libusb_get_ss_usb_device_capability_descriptor(
1037         struct libusb_context *ctx,
1038         struct libusb_bos_dev_capability_descriptor *dev_cap,
1039         struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap)
1040 {
1041         struct libusb_ss_usb_device_capability_descriptor *_ss_usb_device_cap;
1042         const int host_endian = 0;
1043
1044         if (dev_cap->bDevCapabilityType != LIBUSB_BT_SS_USB_DEVICE_CAPABILITY) {
1045                 usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
1046                          dev_cap->bDevCapabilityType,
1047                          LIBUSB_BT_SS_USB_DEVICE_CAPABILITY);
1048                 return LIBUSB_ERROR_INVALID_PARAM;
1049         }
1050         if (dev_cap->bLength < LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) {
1051                 usbi_err(ctx, "short dev-cap descriptor read %d/%d",
1052                          dev_cap->bLength, LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE);
1053                 return LIBUSB_ERROR_IO;
1054         }
1055
1056         _ss_usb_device_cap = malloc(sizeof(*_ss_usb_device_cap));
1057         if (!_ss_usb_device_cap)
1058                 return LIBUSB_ERROR_NO_MEM;
1059
1060         usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbwbbw",
1061                               _ss_usb_device_cap, host_endian);
1062
1063         *ss_usb_device_cap = _ss_usb_device_cap;
1064         return LIBUSB_SUCCESS;
1065 }
1066
1067 /** \ingroup desc
1068  * Free a SuperSpeed USB Device Capability descriptor obtained from
1069  * libusb_get_ss_usb_device_capability_descriptor().
1070  * It is safe to call this function with a NULL ss_usb_device_cap
1071  * parameter, in which case the function simply returns.
1072  *
1073  * \param ss_usb_device_cap the USB 2.0 Extension descriptor to free
1074  */
1075 void API_EXPORTED libusb_free_ss_usb_device_capability_descriptor(
1076         struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap)
1077 {
1078         free(ss_usb_device_cap);
1079 }
1080
1081 /** \ingroup desc
1082  * Get a Container ID descriptor
1083  *
1084  * \param ctx the context to operate on, or NULL for the default context
1085  * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
1086  * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID
1087  * LIBUSB_BT_CONTAINER_ID
1088  * \param container_id output location for the Container ID descriptor.
1089  * Only valid if 0 was returned. Must be freed with
1090  * libusb_free_container_id_descriptor() after use.
1091  * \returns 0 on success
1092  * \returns a LIBUSB_ERROR code on error
1093  */
1094 int API_EXPORTED libusb_get_container_id_descriptor(struct libusb_context *ctx,
1095         struct libusb_bos_dev_capability_descriptor *dev_cap,
1096         struct libusb_container_id_descriptor **container_id)
1097 {
1098         struct libusb_container_id_descriptor *_container_id;
1099         const int host_endian = 0;
1100
1101         if (dev_cap->bDevCapabilityType != LIBUSB_BT_CONTAINER_ID) {
1102                 usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
1103                          dev_cap->bDevCapabilityType,
1104                          LIBUSB_BT_CONTAINER_ID);
1105                 return LIBUSB_ERROR_INVALID_PARAM;
1106         }
1107         if (dev_cap->bLength < LIBUSB_BT_CONTAINER_ID_SIZE) {
1108                 usbi_err(ctx, "short dev-cap descriptor read %d/%d",
1109                          dev_cap->bLength, LIBUSB_BT_CONTAINER_ID_SIZE);
1110                 return LIBUSB_ERROR_IO;
1111         }
1112
1113         _container_id = malloc(sizeof(*_container_id));
1114         if (!_container_id)
1115                 return LIBUSB_ERROR_NO_MEM;
1116
1117         usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbu",
1118                               _container_id, host_endian);
1119
1120         *container_id = _container_id;
1121         return LIBUSB_SUCCESS;
1122 }
1123
1124 /** \ingroup desc
1125  * Free a Container ID descriptor obtained from
1126  * libusb_get_container_id_descriptor().
1127  * It is safe to call this function with a NULL container_id parameter,
1128  * in which case the function simply returns.
1129  *
1130  * \param container_id the USB 2.0 Extension descriptor to free
1131  */
1132 void API_EXPORTED libusb_free_container_id_descriptor(
1133         struct libusb_container_id_descriptor *container_id)
1134 {
1135         free(container_id);
1136 }
1137
1138 /** \ingroup desc
1139  * Retrieve a string descriptor in C style ASCII.
1140  *
1141  * Wrapper around libusb_get_string_descriptor(). Uses the first language
1142  * supported by the device.
1143  *
1144  * \param dev a device handle
1145  * \param desc_index the index of the descriptor to retrieve
1146  * \param data output buffer for ASCII string descriptor
1147  * \param length size of data buffer
1148  * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
1149  */
1150 int API_EXPORTED libusb_get_string_descriptor_ascii(libusb_device_handle *dev,
1151         uint8_t desc_index, unsigned char *data, int length)
1152 {
1153         unsigned char tbuf[255]; /* Some devices choke on size > 255 */
1154         int r, si, di;
1155         uint16_t langid;
1156
1157         /* Asking for the zero'th index is special - it returns a string
1158          * descriptor that contains all the language IDs supported by the
1159          * device. Typically there aren't many - often only one. Language
1160          * IDs are 16 bit numbers, and they start at the third byte in the
1161          * descriptor. There's also no point in trying to read descriptor 0
1162          * with this function. See USB 2.0 specification section 9.6.7 for
1163          * more information.
1164          */
1165
1166         if (desc_index == 0)
1167                 return LIBUSB_ERROR_INVALID_PARAM;
1168
1169         r = libusb_get_string_descriptor(dev, 0, 0, tbuf, sizeof(tbuf));
1170         if (r < 0)
1171                 return r;
1172
1173         if (r < 4)
1174                 return LIBUSB_ERROR_IO;
1175
1176         langid = tbuf[2] | (tbuf[3] << 8);
1177
1178         r = libusb_get_string_descriptor(dev, desc_index, langid, tbuf,
1179                 sizeof(tbuf));
1180         if (r < 0)
1181                 return r;
1182
1183         if (tbuf[1] != LIBUSB_DT_STRING)
1184                 return LIBUSB_ERROR_IO;
1185
1186         if (tbuf[0] > r)
1187                 return LIBUSB_ERROR_IO;
1188
1189         for (di = 0, si = 2; si < tbuf[0]; si += 2) {
1190                 if (di >= (length - 1))
1191                         break;
1192
1193                 if ((tbuf[si] & 0x80) || (tbuf[si + 1])) /* non-ASCII */
1194                         data[di++] = '?';
1195                 else
1196                         data[di++] = tbuf[si];
1197         }
1198
1199         data[di] = 0;
1200         return di;
1201 }