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