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