Refine configuration selection again
[platform/upstream/libusb.git] / libusb / core.c
1 /*
2  * Core functions for libusb
3  * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org>
4  * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <config.h>
22
23 #include <errno.h>
24 #include <poll.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30
31 #include "libusb.h"
32 #include "libusbi.h"
33
34 static int usbi_debug = 0;
35 static int debug_fixed = 0;
36
37 #ifdef OS_LINUX
38 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
39 #else
40 #error "Unsupported OS"
41 #endif
42
43 static struct list_head usb_devs;
44 static pthread_mutex_t usb_devs_lock = PTHREAD_MUTEX_INITIALIZER;
45
46 /* A list of open handles. Backends are free to traverse this if required. */
47 struct list_head usbi_open_devs;
48 pthread_mutex_t usbi_open_devs_lock = PTHREAD_MUTEX_INITIALIZER;
49
50 /**
51  * \mainpage libusb-1.0 API Reference
52  *
53  * \section intro Introduction
54  *
55  * libusb is an open source library that allows you to communicate with USB
56  * devices from userspace. For more info, see the
57  * <a href="http://libusb.sourceforge.net">libusb homepage</a>.
58  *
59  * This documentation is aimed at application developers wishing to
60  * communicate with USB peripherals from their own software. After reviewing
61  * this documentation, feedback and questions can be sent to the
62  * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing
63  * list</a>.
64  *
65  * This documentation assumes knowledge of how to operate USB devices from
66  * a software standpoint (descriptors, configurations, interfaces, endpoints,
67  * control/bulk/interrupt/isochronous transfers, etc). Full information
68  * can be found in the <a href="http://www.usb.org/developers/docs/">USB 2.0
69  * Specification</a> which is available for free download. You can probably
70  * find less verbose introductions by searching the web.
71  *
72  * \section features Library features
73  *
74  * - All transfer types supported (control/bulk/interrupt/isochronous)
75  * - 2 transfer interfaces:
76  *    -# Synchronous (simple)
77  *    -# Asynchronous (more complicated, but more powerful)
78  * - Thread safe (although the asynchronous interface means that you
79  *   usually won't need to thread)
80  * - Lightweight with lean API
81  * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
82  *
83  * \section gettingstarted Getting Started
84  *
85  * To begin reading the API documentation, start with the Modules page which
86  * links to the different categories of libusb's functionality.
87  *
88  * One decision you will have to make is whether to use the synchronous
89  * or the asynchronous data transfer interface. The \ref io documentation
90  * provides some insight into this topic.
91  *
92  * Some example programs can be found in the libusb source distribution under
93  * the "examples" subdirectory. The libusb homepage includes a list of
94  * real-life project examples which use libusb.
95  *
96  * \section errorhandling Error handling
97  *
98  * libusb functions typically return 0 on success or a negative error code
99  * on failure. These negative error codes relate to LIBUSB_ERROR constants
100  * which are listed on the \ref misc "miscellaneous" documentation page.
101  *
102  * \section msglog Debug message logging
103  *
104  * libusb does not log any messages by default. Your application is therefore
105  * free to close stdout/stderr and those descriptors may be reused without
106  * worry.
107  *
108  * The libusb_set_debug() function can be used to enable stdout/stderr logging
109  * of certain messages. Under standard configuration, libusb doesn't really
110  * log much at all, so you are advised to use this function to enable all
111  * error/warning/informational messages. It will help you debug problems with
112  * your software.
113  *
114  * The LIBUSB_DEBUG environment variable can be used to enable message logging
115  * at run-time. This environment variable should be set to a number, which is
116  * interpreted the same as the libusb_set_debug() parameter. When this
117  * environment variable is set, the message logging verbosity level is fixed
118  * and libusb_set_debug() effectively does nothing.
119  *
120  * libusb can be compiled without any logging functions, useful for embedded
121  * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
122  * variable have no effects.
123  *
124  * libusb can also be compiled with verbose debugging messages. When the
125  * library is compiled in this way, all messages of all verbosities are always
126  * logged.  libusb_set_debug() and the LIBUSB_DEBUG environment variable have
127  * no effects.
128  *
129  * \section remarks Other remarks
130  *
131  * libusb does have imperfections. The \ref caveats "caveats" page attempts
132  * to document these.
133  */
134
135 /**
136  * \page caveats Caveats
137  *
138  * \section devresets Device resets
139  *
140  * The libusb_reset_device() function allows you to reset a device. If your
141  * program has to call such a function, it should obviously be aware that
142  * the reset will cause device state to change (e.g. register values may be
143  * reset).
144  *
145  * The problem is that any other program could reset the device your program
146  * is working with, at any time. libusb does not offer a mechanism to inform
147  * you when this has happened, so if someone else resets your device it will
148  * not be clear to your own program why the device state has changed.
149  *
150  * Ultimately, this is a limitation of writing drivers in userspace.
151  * Separation from the USB stack in the underlying kernel makes it difficult
152  * for the operating system to deliver such notifications to your program.
153  * The Linux kernel USB stack allows such reset notifications to be delivered
154  * to in-kernel USB drivers, but it is not clear how such notifications could
155  * be delivered to second-class drivers that live in userspace.
156  *
157  * \section blockonly Blocking-only functionality
158  *
159  * The functionality listed below is only available through synchronous,
160  * blocking functions. There are no asynchronous/non-blocking alternatives,
161  * and no clear ways of implementing these.
162  *
163  * - Configuration activation (libusb_set_configuration())
164  * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
165  * - Releasing of interfaces (libusb_release_interface())
166  * - Clearing of halt/stall condition (libusb_clear_halt())
167  * - Device resets (libusb_reset_device())
168  *
169  * \section nohotplug No hotplugging
170  *
171  * libusb-1.0 lacks functionality for providing notifications of when devices
172  * are added or removed. This functionality is planned to be implemented
173  * for libusb-1.1.
174  *
175  * That said, there is basic disconnection handling for open device handles:
176  *  - If there are ongoing transfers, libusb's handle_events loop will detect
177  *    disconnections and complete ongoing transfers with the
178  *    LIBUSB_TRANSFER_NO_DEVICE status code.
179  *  - Many functions such as libusb_set_configuration() return the special
180  *    LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected.
181  *
182  * \section configsel Configuration selection and handling
183  *
184  * When libusb presents a device handle to an application, there is a chance
185  * that the corresponding device may be in unconfigured state. For devices
186  * with multiple configurations, there is also a chance that the configuration
187  * currently selected is not the one that the application wants to use.
188  *
189  * The obvious solution is to add a call to libusb_set_configuration() early
190  * on during your device initialization routines, but there are caveats to
191  * be aware of:
192  * -# If the device is already in the desired configuration, calling
193  *    libusb_set_configuration() using the same configuration value will cause
194  *    a lightweight device reset. This may not be desirable behaviour.
195  * -# libusb will be unable to change configuration if the device is in
196  *    another configuration and other programs or drivers have claimed
197  *    interfaces under that configuration.
198  * -# In the case where the desired configuration is already active, libusb
199  *    may not even be able to perform a lightweight device reset. For example,
200  *    take my USB keyboard with fingerprint reader: I'm interested in driving
201  *    the fingerprint reader interface through libusb, but the kernel's
202  *    USB-HID driver will almost always have claimed the keyboard interface.
203  *    Because the kernel has claimed an interface, it is not even possible to
204  *    perform the lightweight device reset, so libusb_set_configuration() will
205  *    fail. (Luckily the device in question only has a single configuration.)
206  *
207  * One solution to some of the above problems is to consider the currently
208  * active configuration. If the configuration we want is already active, then
209  * we don't have to select any configuration:
210 \code
211 cfg = libusb_get_configuration(dev);
212 if (cfg != desired)
213         libusb_set_configuration(dev, desired);
214 \endcode
215  *
216  * This is probably suitable for most scenarios, but is inherently racy:
217  * another application or driver may change the selected configuration
218  * <em>after</em> the libusb_get_configuration() call.
219  *
220  * Even in cases where libusb_set_configuration() succeeds, consider that other
221  * applications or drivers may change configuration after your application
222  * calls libusb_set_configuration().
223  *
224  * One possible way to lock your device into a specific configuration is as
225  * follows:
226  * -# Set the desired configuration (or use the logic above to realise that
227  *    it is already in the desired configuration)
228  * -# Claim the interface that you wish to use
229  * -# Check that the currently active configuration is the one that you want
230  *    to use.
231  *
232  * The above method works because once an interface is claimed, no application
233  * or driver is able to select another configuration.
234  */
235
236 /**
237  * @defgroup lib Library initialization/deinitialization
238  * This page details how to initialize and deinitialize libusb. Initialization
239  * must be performed before using any libusb functionality, and similarly you
240  * must not call any libusb functions after deinitialization.
241  */
242
243 /**
244  * @defgroup dev Device handling and enumeration
245  * The functionality documented below is designed to help with the following
246  * operations:
247  * - Enumerating the USB devices currently attached to the system
248  * - Choosing a device to operate from your software
249  * - Opening and closing the chosen device
250  *
251  * \section nutshell In a nutshell...
252  *
253  * The description below really makes things sound more complicated than they
254  * actually are. The following sequence of function calls will be suitable
255  * for almost all scenarios and does not require you to have such a deep
256  * understanding of the resource management issues:
257  * \code
258 // discover devices
259 libusb_device **list;
260 libusb_device *found = NULL;
261 size_t cnt = libusb_get_device_list(&list);
262 size_t i = 0;
263 int err = 0;
264 if (cnt < 0)
265         error();
266
267 for (i = 0; i < cnt; i++) {
268         libusb_device *device = list[i];
269         if (is_interesting(device)) {
270                 found = device;
271                 break;
272         }
273 }
274
275 if (found) {
276         libusb_device_handle *handle;
277
278         err = libusb_open(found, &handle);
279         if (err)
280                 error();
281         // etc
282 }
283
284 libusb_free_device_list(list, 1);
285 \endcode
286  *
287  * The two important points:
288  * - You asked libusb_free_device_list() to unreference the devices (2nd
289  *   parameter)
290  * - You opened the device before freeing the list and unreferencing the
291  *   devices
292  *
293  * If you ended up with a handle, you can now proceed to perform I/O on the
294  * device.
295  *
296  * \section devshandles Devices and device handles
297  * libusb has a concept of a USB device, represented by the
298  * \ref libusb_device opaque type. A device represents a USB device that
299  * is currently or was previously connected to the system. Using a reference
300  * to a device, you can determine certain information about the device (e.g.
301  * you can read the descriptor data).
302  *
303  * The libusb_get_device_list() function can be used to obtain a list of
304  * devices currently connected to the system. This is known as device
305  * discovery.
306  *
307  * Just because you have a reference to a device does not mean it is
308  * necessarily usable. The device may have been unplugged, you may not have
309  * permission to operate such device, or another program or driver may be
310  * using the device.
311  *
312  * When you've found a device that you'd like to operate, you must ask
313  * libusb to open the device using the libusb_open() function. Assuming
314  * success, libusb then returns you a <em>device handle</em>
315  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
316  * operate on the handle rather than the original device pointer.
317  *
318  * \section devref Device discovery and reference counting
319  *
320  * Device discovery (i.e. calling libusb_get_device_list()) returns a
321  * freshly-allocated list of devices. The list itself must be freed when
322  * you are done with it. libusb also needs to know when it is OK to free
323  * the contents of the list - the devices themselves.
324  *
325  * To handle these issues, libusb provides you with two separate items:
326  * - A function to free the list itself
327  * - A reference counting system for the devices inside
328  *
329  * New devices presented by the libusb_get_device_list() function all have a
330  * reference count of 1. You can increase and decrease reference count using
331  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
332  * it's reference count reaches 0.
333  *
334  * With the above information in mind, the process of opening a device can
335  * be viewed as follows:
336  * -# Discover devices using libusb_get_device_list().
337  * -# Choose the device that you want to operate, and call libusb_open().
338  * -# Unref all devices in the discovered device list.
339  * -# Free the discovered device list.
340  *
341  * The order is important - you must not unreference the device before
342  * attempting to open it, because unreferencing it may destroy the device.
343  *
344  * For convenience, the libusb_free_device_list() function includes a
345  * parameter to optionally unreference all the devices in the list before
346  * freeing the list itself. This combines steps 3 and 4 above.
347  *
348  * As an implementation detail, libusb_open() actually adds a reference to
349  * the device in question. This is because the device remains available
350  * through the handle via libusb_get_device(). The reference is deleted during
351  * libusb_close().
352  */
353
354 /** @defgroup misc Miscellaneous */
355
356 /* we traverse usbfs without knowing how many devices we are going to find.
357  * so we create this discovered_devs model which is similar to a linked-list
358  * which grows when required. it can be freed once discovery has completed,
359  * eliminating the need for a list node in the libusb_device structure
360  * itself. */
361 #define DISCOVERED_DEVICES_SIZE_STEP 8
362
363 static struct discovered_devs *discovered_devs_alloc(void)
364 {
365         struct discovered_devs *ret =
366                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
367
368         if (ret) {
369                 ret->len = 0;
370                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
371         }
372         return ret;
373 }
374
375 /* append a device to the discovered devices collection. may realloc itself,
376  * returning new discdevs. returns NULL on realloc failure. */
377 struct discovered_devs *discovered_devs_append(
378         struct discovered_devs *discdevs, struct libusb_device *dev)
379 {
380         size_t len = discdevs->len;
381         size_t capacity;
382
383         /* if there is space, just append the device */
384         if (len < discdevs->capacity) {
385                 discdevs->devices[len] = libusb_ref_device(dev);
386                 discdevs->len++;
387                 return discdevs;
388         }
389
390         /* exceeded capacity, need to grow */
391         usbi_dbg("need to increase capacity");
392         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
393         discdevs = realloc(discdevs,
394                 sizeof(*discdevs) + (sizeof(void *) * capacity));
395         if (discdevs) {
396                 discdevs->capacity = capacity;
397                 discdevs->devices[len] = libusb_ref_device(dev);
398                 discdevs->len++;
399         }
400
401         return discdevs;
402 }
403
404 static void discovered_devs_free(struct discovered_devs *discdevs)
405 {
406         size_t i;
407
408         for (i = 0; i < discdevs->len; i++)
409                 libusb_unref_device(discdevs->devices[i]);
410
411         free(discdevs);
412 }
413
414 /* Allocate a new device with a specific session ID. The returned device has
415  * a reference count of 1. */
416 struct libusb_device *usbi_alloc_device(unsigned long session_id)
417 {
418         size_t priv_size = usbi_backend->device_priv_size;
419         struct libusb_device *dev = malloc(sizeof(*dev) + priv_size);
420         int r;
421
422         if (!dev)
423                 return NULL;
424
425         r = pthread_mutex_init(&dev->lock, NULL);
426         if (r)
427                 return NULL;
428
429         dev->refcnt = 1;
430         dev->session_data = session_id;
431         memset(&dev->os_priv, 0, priv_size);
432
433         pthread_mutex_lock(&usb_devs_lock);
434         list_add(&dev->list, &usb_devs);
435         pthread_mutex_unlock(&usb_devs_lock);
436         return dev;
437 }
438
439 /* Perform some final sanity checks on a newly discovered device. If this
440  * function fails (negative return code), the device should not be added
441  * to the discovered device list. */
442 int usbi_sanitize_device(struct libusb_device *dev)
443 {
444         int r;
445         unsigned char raw_desc[DEVICE_DESC_LENGTH];
446         uint8_t num_configurations;
447         int host_endian;
448
449         r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian);
450         if (r < 0)
451                 return r;
452
453         num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1];
454         if (num_configurations > USB_MAXCONFIG) {
455                 usbi_err("too many configurations");
456                 return LIBUSB_ERROR_IO;
457         } else if (num_configurations < 1) {
458                 usbi_dbg("no configurations?");
459                 return LIBUSB_ERROR_IO;
460         }
461
462         dev->num_configurations = num_configurations;
463         return 0;
464 }
465
466 /* Examine libusb's internal list of known devices, looking for one with
467  * a specific session ID. Returns the matching device if it was found, and
468  * NULL otherwise. */
469 struct libusb_device *usbi_get_device_by_session_id(unsigned long session_id)
470 {
471         struct libusb_device *dev;
472         struct libusb_device *ret = NULL;
473
474         pthread_mutex_lock(&usb_devs_lock);
475         list_for_each_entry(dev, &usb_devs, list)
476                 if (dev->session_data == session_id) {
477                         ret = dev;
478                         break;
479                 }
480         pthread_mutex_unlock(&usb_devs_lock);
481
482         return ret;
483 }
484
485 /** @ingroup dev
486  * Returns a list of USB devices currently attached to the system. This is
487  * your entry point into finding a USB device to operate.
488  *
489  * You are expected to unreference all the devices when you are done with
490  * them, and then free the list with libusb_free_device_list(). Note that
491  * libusb_free_device_list() can unref all the devices for you. Be careful
492  * not to unreference a device you are about to open until after you have
493  * opened it.
494  *
495  * This return value of this function indicates the number of devices in
496  * the resultant list. The list is actually one element larger, as it is
497  * NULL-terminated.
498  *
499  * \param list output location for a list of devices. Must be later freed with
500  * libusb_free_device_list().
501  * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM
502  * on memory allocation failure.
503  */
504 API_EXPORTED ssize_t libusb_get_device_list(libusb_device ***list)
505 {
506         struct discovered_devs *discdevs = discovered_devs_alloc();
507         struct libusb_device **ret;
508         int r = 0;
509         size_t i;
510         ssize_t len;
511         usbi_dbg("");
512
513         if (!discdevs)
514                 return LIBUSB_ERROR_NO_MEM;
515
516         r = usbi_backend->get_device_list(&discdevs);
517         if (r < 0) {
518                 len = r;
519                 goto out;
520         }
521
522         /* convert discovered_devs into a list */
523         len = discdevs->len;
524         ret = malloc(sizeof(void *) * (len + 1));
525         if (!ret) {
526                 len = LIBUSB_ERROR_NO_MEM;
527                 goto out;
528         }
529
530         ret[len] = NULL;
531         for (i = 0; i < len; i++) {
532                 struct libusb_device *dev = discdevs->devices[i];
533                 ret[i] = libusb_ref_device(dev);
534         }
535         *list = ret;
536
537 out:
538         discovered_devs_free(discdevs);
539         return len;
540 }
541
542 /** \ingroup dev
543  * Frees a list of devices previously discovered using
544  * libusb_get_device_list(). If the unref_devices parameter is set, the
545  * reference count of each device in the list is decremented by 1.
546  * \param list the list to free
547  * \param unref_devices whether to unref the devices in the list
548  */
549 API_EXPORTED void libusb_free_device_list(libusb_device **list,
550         int unref_devices)
551 {
552         if (!list)
553                 return;
554
555         if (unref_devices) {
556                 int i = 0;
557                 struct libusb_device *dev;
558
559                 while ((dev = list[i++]) != NULL)
560                         libusb_unref_device(dev);
561         }
562         free(list);
563 }
564
565 /** \ingroup dev
566  * Get the number of the bus that a device is connected to.
567  * \param dev a device
568  * \returns the bus number
569  */
570 API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev)
571 {
572         return dev->bus_number;
573 }
574
575 /** \ingroup dev
576  * Get the address of the device on the bus it is connected to.
577  * \param dev a device
578  * \returns the device address
579  */
580 API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev)
581 {
582         return dev->device_address;
583 }
584
585 /** \ingroup dev
586  * Convenience function to retrieve the wMaxPacketSize value for a particular
587  * endpoint in the active device configuration. This is useful for setting up
588  * isochronous transfers.
589  *
590  * \param dev a device
591  * \param endpoint address of the endpoint in question
592  * \returns the wMaxPacketSize value
593  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
594  * \returns LIBUSB_ERROR_OTHER on other failure
595  */
596 API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev,
597         unsigned char endpoint)
598 {
599         int iface_idx;
600         struct libusb_config_descriptor *config;
601         int r;
602         
603         r = libusb_get_active_config_descriptor(dev, &config);
604         if (r < 0) {
605                 usbi_err("could not retrieve active config descriptor");
606                 return LIBUSB_ERROR_OTHER;
607         }
608
609         r = LIBUSB_ERROR_NOT_FOUND;
610         for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
611                 const struct libusb_interface *iface = &config->interface[iface_idx];
612                 int altsetting_idx;
613
614                 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
615                                 altsetting_idx++) {
616                         const struct libusb_interface_descriptor *altsetting
617                                 = &iface->altsetting[altsetting_idx];
618                         int ep_idx;
619
620                         for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
621                                 const struct libusb_endpoint_descriptor *ep =
622                                         &altsetting->endpoint[ep_idx];
623                                 if (ep->bEndpointAddress == endpoint) {
624                                         r = ep->wMaxPacketSize;
625                                         goto out;
626                                 }
627                         }
628                 }
629         }
630
631 out:
632         libusb_free_config_descriptor(config);
633         return r;
634 }
635
636 /** \ingroup dev
637  * Increment the reference count of a device.
638  * \param dev the device to reference
639  * \returns the same device
640  */
641 API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev)
642 {
643         pthread_mutex_lock(&dev->lock);
644         dev->refcnt++;
645         pthread_mutex_unlock(&dev->lock);
646         return dev;
647 }
648
649 /** \ingroup dev
650  * Decrement the reference count of a device. If the decrement operation
651  * causes the reference count to reach zero, the device shall be destroyed.
652  * \param dev the device to unreference
653  */
654 API_EXPORTED void libusb_unref_device(libusb_device *dev)
655 {
656         int refcnt;
657
658         if (!dev)
659                 return;
660
661         pthread_mutex_lock(&dev->lock);
662         refcnt = --dev->refcnt;
663         pthread_mutex_unlock(&dev->lock);
664
665         if (refcnt == 0) {
666                 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
667
668                 if (usbi_backend->destroy_device)
669                         usbi_backend->destroy_device(dev);
670
671                 pthread_mutex_lock(&usb_devs_lock);
672                 list_del(&dev->list);
673                 pthread_mutex_unlock(&usb_devs_lock);
674
675                 free(dev);
676         }
677 }
678
679 /** \ingroup dev
680  * Open a device and obtain a device handle. A handle allows you to perform
681  * I/O on the device in question.
682  *
683  * Internally, this function adds a reference to the device and makes it
684  * available to you through libusb_get_device(). This reference is removed
685  * during libusb_close().
686  *
687  * This is a non-blocking function; no requests are sent over the bus.
688  *
689  * \param dev the device to open
690  * \param handle output location for the returned device handle pointer. Only
691  * populated when the return code is 0.
692  * \returns 0 on success
693  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
694  * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
695  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
696  * \returns another LIBUSB_ERROR code on other failure
697  */
698 API_EXPORTED int libusb_open(libusb_device *dev, libusb_device_handle **handle)
699 {
700         struct libusb_device_handle *_handle;
701         size_t priv_size = usbi_backend->device_handle_priv_size;
702         int r;
703         usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
704
705         _handle = malloc(sizeof(*_handle) + priv_size);
706         if (!_handle)
707                 return LIBUSB_ERROR_NO_MEM;
708
709         r = pthread_mutex_init(&_handle->lock, NULL);
710         if (r)
711                 return LIBUSB_ERROR_OTHER;
712
713         _handle->dev = libusb_ref_device(dev);
714         _handle->claimed_interfaces = 0;
715         memset(&_handle->os_priv, 0, priv_size);
716
717         r = usbi_backend->open(_handle);
718         if (r < 0) {
719                 libusb_unref_device(dev);
720                 free(_handle);
721                 return r;
722         }
723
724         pthread_mutex_lock(&usbi_open_devs_lock);
725         list_add(&_handle->list, &usbi_open_devs);
726         pthread_mutex_unlock(&usbi_open_devs_lock);
727         *handle = _handle;
728         return 0;
729 }
730
731 /** \ingroup dev
732  * Convenience function for finding a device with a particular
733  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
734  * for those scenarios where you are using libusb to knock up a quick test
735  * application - it allows you to avoid calling libusb_get_device_list() and
736  * worrying about traversing/freeing the list.
737  *
738  * This function has limitations and is hence not intended for use in real
739  * applications: if multiple devices have the same IDs it will only
740  * give you the first one, etc.
741  *
742  * \param vendor_id the idVendor value to search for
743  * \param product_id the idProduct value to search for
744  * \returns a handle for the first found device, or NULL on error or if the
745  * device could not be found. */
746 API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid(
747         uint16_t vendor_id, uint16_t product_id)
748 {
749         struct libusb_device **devs;
750         struct libusb_device *found = NULL;
751         struct libusb_device *dev;
752         struct libusb_device_handle *handle = NULL;
753         size_t i = 0;
754         int r;
755
756         if (libusb_get_device_list(&devs) < 0)
757                 return NULL;
758
759         while ((dev = devs[i++]) != NULL) {
760                 struct libusb_device_descriptor desc;
761                 r = libusb_get_device_descriptor(dev, &desc);
762                 if (r < 0)
763                         goto out;
764                 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
765                         found = dev;
766                         break;
767                 }
768         }
769
770         if (found) {
771                 r = libusb_open(found, &handle);
772                 if (r < 0)
773                         handle = NULL;
774         }
775
776 out:
777         libusb_free_device_list(devs, 1);
778         return handle;
779 }
780
781 static void do_close(struct libusb_device_handle *dev_handle)
782 {
783         usbi_backend->close(dev_handle);
784         libusb_unref_device(dev_handle->dev);
785 }
786
787 /** \ingroup dev
788  * Close a device handle. Should be called on all open handles before your
789  * application exits.
790  *
791  * Internally, this function destroys the reference that was added by
792  * libusb_open() on the given device.
793  *
794  * This is a non-blocking function; no requests are sent over the bus.
795  *
796  * \param dev_handle the handle to close
797  */
798 API_EXPORTED void libusb_close(libusb_device_handle *dev_handle)
799 {
800         if (!dev_handle)
801                 return;
802         usbi_dbg("");
803
804         pthread_mutex_lock(&usbi_open_devs_lock);
805         list_del(&dev_handle->list);
806         pthread_mutex_unlock(&usbi_open_devs_lock);
807
808         do_close(dev_handle);
809         free(dev_handle);
810 }
811
812 /** \ingroup dev
813  * Get the underlying device for a handle. This function does not modify
814  * the reference count of the returned device, so do not feel compelled to
815  * unreference it when you are done.
816  * \param dev_handle a device handle
817  * \returns the underlying device
818  */
819 API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle)
820 {
821         return dev_handle->dev;
822 }
823
824 /** \ingroup dev
825  * Determine the bConfigurationValue of the currently active configuration.
826  *
827  * You could formulate your own control request to obtain this information,
828  * but this function has the advantage that it may be able to retrieve the
829  * information from operating system caches (no I/O involved).
830  *
831  * If the OS does not cache this information, then this function will block
832  * while a control transfer is submitted to retrieve the information.
833  *
834  * This function will return a value of 0 in the <tt>config</tt> output
835  * parameter if the device is in unconfigured state.
836  *
837  * \param dev a device handle
838  * \param config output location for the bConfigurationValue of the active
839  * configuration (only valid for return code 0)
840  * \returns 0 on success
841  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
842  * \returns another LIBUSB_ERROR code on other failure
843  */
844 API_EXPORTED int libusb_get_configuration(libusb_device_handle *dev,
845         int *config)
846 {
847         int r = LIBUSB_ERROR_NOT_SUPPORTED;
848
849         usbi_dbg("");
850         if (usbi_backend->get_configuration)
851                 r = usbi_backend->get_configuration(dev, config);
852
853         if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
854                 uint8_t tmp = 0;
855                 usbi_dbg("falling back to control message");
856                 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
857                         LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
858                 if (r == 0) {
859                         usbi_err("zero bytes returned in ctrl transfer?");
860                         r = LIBUSB_ERROR_IO;
861                 } else if (r == 1) {
862                         r = 0;
863                         *config = tmp;
864                 } else {
865                         usbi_dbg("control failed, error %d", r);
866                 }
867         }
868
869         if (r == 0)
870                 usbi_dbg("active config %d", *config);
871
872         return r;
873 }
874
875 /** \ingroup dev
876  * Set the active configuration for a device.
877  *
878  * The operating system may or may not have already set an active
879  * configuration on the device. It is up to your application to ensure the
880  * correct configuration is selected before you attempt to claim interfaces
881  * and perform other operations.
882  * 
883  * If you call this function on a device already configured with the selected
884  * configuration, then this function will act as a lightweight device reset:
885  * it will issue a SET_CONFIGURATION request using the current configuration,
886  * causing most USB-related device state to be reset (altsetting reset to zero,
887  * endpoint halts cleared, toggles reset).
888  *
889  * You cannot change/reset configuration if your application has claimed
890  * interfaces - you should free them with libusb_release_interface() first.
891  * You cannot change/reset configuration if other applications or drivers have
892  * claimed interfaces.
893  *
894  * A configuration value of -1 will put the device in unconfigured state.
895  * The USB specifications state that a configuration value of 0 does this,
896  * however buggy devices exist which actually have a configuration 0.
897  *
898  * You should always use this function rather than formulating your own
899  * SET_CONFIGURATION control request. This is because the underlying operating
900  * system needs to know when such changes happen.
901  *
902  * This is a blocking function.
903  *
904  * \param dev a device handle
905  * \param configuration the bConfigurationValue of the configuration you
906  * wish to activate, or -1 if you wish to put the device in unconfigured state
907  * \returns 0 on success
908  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
909  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
910  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
911  * \returns another LIBUSB_ERROR code on other failure
912  */
913 API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev,
914         int configuration)
915 {
916         usbi_dbg("configuration %d", configuration);
917         return usbi_backend->set_configuration(dev, configuration);
918 }
919
920 /** \ingroup dev
921  * Claim an interface on a given device handle. You must claim the interface
922  * you wish to use before you can perform I/O on any of its endpoints.
923  *
924  * It is legal to attempt to claim an already-claimed interface, in which
925  * case libusb just returns 0 without doing anything.
926  *
927  * Claiming of interfaces is a purely logical operation; it does not cause
928  * any requests to be sent over the bus. Interface claiming is used to
929  * instruct the underlying operating system that your application wishes
930  * to take ownership of the interface.
931  *
932  * This is a non-blocking function.
933  *
934  * \param dev a device handle
935  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
936  * wish to claim
937  * \returns 0 on success
938  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
939  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
940  * interface
941  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
942  * \returns a LIBUSB_ERROR code on other failure
943  */
944 API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev,
945         int interface_number)
946 {
947         int r = 0;
948
949         usbi_dbg("interface %d", interface_number);
950         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
951                 return LIBUSB_ERROR_INVALID_PARAM;
952
953         pthread_mutex_lock(&dev->lock);
954         if (dev->claimed_interfaces & (1 << interface_number))
955                 goto out;
956
957         r = usbi_backend->claim_interface(dev, interface_number);
958         if (r == 0)
959                 dev->claimed_interfaces |= 1 << interface_number;
960
961 out:
962         pthread_mutex_unlock(&dev->lock);
963         return r;
964 }
965
966 /** \ingroup dev
967  * Release an interface previously claimed with libusb_claim_interface(). You
968  * should release all claimed interfaces before closing a device handle.
969  *
970  * This is a blocking function. A SET_INTERFACE control request will be sent
971  * to the device, resetting interface state to the first alternate setting.
972  *
973  * \param dev a device handle
974  * \param interface_number the <tt>bInterfaceNumber</tt> of the
975  * previously-claimed interface
976  * \returns 0 on success
977  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
978  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
979  * \returns another LIBUSB_ERROR code on other failure
980  */
981 API_EXPORTED int libusb_release_interface(libusb_device_handle *dev,
982         int interface_number)
983 {
984         int r;
985
986         usbi_dbg("interface %d", interface_number);
987         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
988                 return LIBUSB_ERROR_INVALID_PARAM;
989
990         pthread_mutex_lock(&dev->lock);
991         if (!(dev->claimed_interfaces & (1 << interface_number))) {
992                 r = LIBUSB_ERROR_NOT_FOUND;
993                 goto out;
994         }
995
996         r = usbi_backend->release_interface(dev, interface_number);
997         if (r == 0)
998                 dev->claimed_interfaces &= ~(1 << interface_number);
999
1000 out:
1001         pthread_mutex_unlock(&dev->lock);
1002         return r;
1003 }
1004
1005 /** \ingroup dev
1006  * Activate an alternate setting for an interface. The interface must have
1007  * been previously claimed with libusb_claim_interface().
1008  *
1009  * You should always use this function rather than formulating your own
1010  * SET_INTERFACE control request. This is because the underlying operating
1011  * system needs to know when such changes happen.
1012  *
1013  * This is a blocking function.
1014  *
1015  * \param dev a device handle
1016  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1017  * previously-claimed interface
1018  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1019  * setting to activate
1020  * \returns 0 on success
1021  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1022  * requested alternate setting does not exist
1023  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1024  * \returns another LIBUSB_ERROR code on other failure
1025  */
1026 API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev,
1027         int interface_number, int alternate_setting)
1028 {
1029         usbi_dbg("interface %d altsetting %d", interface_number, alternate_setting);
1030         if (interface_number >= sizeof(dev->claimed_interfaces) * 8)
1031                 return LIBUSB_ERROR_INVALID_PARAM;
1032
1033         pthread_mutex_lock(&dev->lock);
1034         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1035                 pthread_mutex_unlock(&dev->lock);       
1036                 return LIBUSB_ERROR_NOT_FOUND;
1037         }
1038         pthread_mutex_unlock(&dev->lock);
1039
1040         return usbi_backend->set_interface_altsetting(dev, interface_number,
1041                 alternate_setting);
1042 }
1043
1044 /** \ingroup dev
1045  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1046  * are unable to receive or transmit data until the halt condition is stalled.
1047  *
1048  * You should cancel all pending transfers before attempting to clear the halt
1049  * condition.
1050  *
1051  * This is a blocking function.
1052  *
1053  * \param dev a device handle
1054  * \param endpoint the endpoint to clear halt status
1055  * \returns 0 on success
1056  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1057  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1058  * \returns another LIBUSB_ERROR code on other failure
1059  */
1060 API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev,
1061         unsigned char endpoint)
1062 {
1063         usbi_dbg("endpoint %x", endpoint);
1064         return usbi_backend->clear_halt(dev, endpoint);
1065 }
1066
1067 /** \ingroup dev
1068  * Perform a USB port reset to reinitialize a device. The system will attempt
1069  * to restore the previous configuration and alternate settings after the
1070  * reset has completed.
1071  *
1072  * If the reset fails, the descriptors change, or the previous state cannot be
1073  * restored, the device will appear to be disconnected and reconnected. This
1074  * means that the device handle is no longer valid (you should close it) and
1075  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1076  * when this is the case.
1077  *
1078  * This is a blocking function which usually incurs a noticeable delay.
1079  *
1080  * \param dev a handle of the device to reset
1081  * \returns 0 on success
1082  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1083  * device has been disconnected
1084  * \returns another LIBUSB_ERROR code on other failure
1085  */
1086 API_EXPORTED int libusb_reset_device(libusb_device_handle *dev)
1087 {
1088         usbi_dbg("");
1089         return usbi_backend->reset_device(dev);
1090 }
1091
1092 /** \ingroup dev
1093  * Determine if a kernel driver is active on an interface. If a kernel driver
1094  * is active, you cannot claim the interface, and libusb will be unable to
1095  * perform I/O.
1096  *
1097  * \param dev a device handle
1098  * \param interface the interface to check
1099  * \returns 0 if no kernel driver is active
1100  * \returns 1 if a kernel driver is active
1101  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1102  * \returns another LIBUSB_ERROR code on other failure
1103  * \see libusb_detach_kernel_driver()
1104  */
1105 API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev,
1106         int interface)
1107 {
1108         usbi_dbg("interface %d", interface);
1109         if (usbi_backend->kernel_driver_active)
1110                 return usbi_backend->kernel_driver_active(dev, interface);
1111         else
1112                 return LIBUSB_ERROR_NOT_SUPPORTED;
1113 }
1114
1115 /** \ingroup dev
1116  * Detach a kernel driver from an interface. If successful, you will then be
1117  * able to claim the interface and perform I/O.
1118  *
1119  * \param dev a device handle
1120  * \param interface the interface to detach the driver from
1121  * \returns 0 on success
1122  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1123  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1124  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1125  * \returns another LIBUSB_ERROR code on other failure
1126  * \see libusb_kernel_driver_active()
1127  */
1128 API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev,
1129         int interface)
1130 {
1131         usbi_dbg("interface %d", interface);
1132         if (usbi_backend->detach_kernel_driver)
1133                 return usbi_backend->detach_kernel_driver(dev, interface);
1134         else
1135                 return LIBUSB_ERROR_NOT_SUPPORTED;
1136 }
1137
1138 /** \ingroup lib
1139  * Set message verbosity.
1140  *  - Level 0: no messages ever printed by the library (default)
1141  *  - Level 1: error messages are printed to stderr
1142  *  - Level 2: warning and error messages are printed to stderr
1143  *  - Level 3: informational messages are printed to stdout, warning and error
1144  *    messages are printed to stderr
1145  *
1146  * The default level is 0, which means no messages are ever printed. If you
1147  * choose to increase the message verbosity level, ensure that your
1148  * application does not close the stdout/stderr file descriptors.
1149  *
1150  * You are advised to set level 3. libusb is conservative with it's message
1151  * logging and most of the time, will only log messages that explain error
1152  * conditions and other oddities. This will help you debug your software.
1153  *
1154  * If the LIBUSB_DEBUG environment variable was set when libusb was
1155  * initialized, this function does nothing: the message verbosity is fixed
1156  * to the value in the environment variable.
1157  *
1158  * If libusb was compiled without any message logging, this function does
1159  * nothing: you'll never get any messages.
1160  *
1161  * If libusb was compiled with verbose debug message logging, this function
1162  * does nothing: you'll always get messages from all levels.
1163  *
1164  * \param level debug level to set
1165  */
1166 API_EXPORTED void libusb_set_debug(int level)
1167 {
1168         if (!debug_fixed)
1169                 usbi_debug = level;
1170 }
1171
1172 /** \ingroup lib
1173  * Initialize libusb. This function must be called before calling any other
1174  * libusb function.
1175  * \returns 0 on success, or a LIBUSB_ERROR code on failure
1176  */
1177 API_EXPORTED int libusb_init(void)
1178 {
1179         char *dbg = getenv("LIBUSB_DEBUG");
1180         if (dbg) {
1181                 usbi_debug = atoi(dbg);
1182                 if (usbi_debug)
1183                         debug_fixed = 1;
1184         }
1185
1186         usbi_dbg("");
1187         if (usbi_backend->init) {
1188                 int r = usbi_backend->init();
1189                 if (r)
1190                         return r;
1191         }
1192
1193         list_init(&usb_devs);
1194         list_init(&usbi_open_devs);
1195         usbi_io_init();
1196         return 0;
1197 }
1198
1199 /** \ingroup lib
1200  * Deinitialize libusb. Should be called after closing all open devices and
1201  * before your application terminates.
1202  */
1203 API_EXPORTED void libusb_exit(void)
1204 {
1205         usbi_dbg("");
1206
1207         pthread_mutex_lock(&usbi_open_devs_lock);
1208         if (!list_empty(&usbi_open_devs)) {
1209                 struct libusb_device_handle *devh;
1210                 struct libusb_device_handle *tmp;
1211
1212                 usbi_dbg("naughty app left some devices open!");
1213                 list_for_each_entry_safe(devh, tmp, &usbi_open_devs, list) {
1214                         list_del(&devh->list);
1215                         do_close(devh);
1216                         free(devh);
1217                 }
1218         }
1219         pthread_mutex_unlock(&usbi_open_devs_lock);
1220
1221         if (usbi_backend->exit)
1222                 usbi_backend->exit();
1223 }
1224
1225 void usbi_log(enum usbi_log_level level, const char *function,
1226         const char *format, ...)
1227 {
1228         va_list args;
1229         FILE *stream = stdout;
1230         const char *prefix;
1231
1232 #ifndef ENABLE_DEBUG_LOGGING
1233         if (!usbi_debug)
1234                 return;
1235         if (level == LOG_LEVEL_WARNING && usbi_debug < 2)
1236                 return;
1237         if (level == LOG_LEVEL_INFO && usbi_debug < 3)
1238                 return;
1239 #endif
1240
1241         switch (level) {
1242         case LOG_LEVEL_INFO:
1243                 prefix = "info";
1244                 break;
1245         case LOG_LEVEL_WARNING:
1246                 stream = stderr;
1247                 prefix = "warning";
1248                 break;
1249         case LOG_LEVEL_ERROR:
1250                 stream = stderr;
1251                 prefix = "error";
1252                 break;
1253         case LOG_LEVEL_DEBUG:
1254                 stream = stderr;
1255                 prefix = "debug";
1256                 break;
1257         default:
1258                 stream = stderr;
1259                 prefix = "unknown";
1260                 break;
1261         }
1262
1263         fprintf(stream, "libusb:%s [%s] ", prefix, function);
1264
1265         va_start (args, format);
1266         vfprintf(stream, format, args);
1267         va_end (args);
1268
1269         fprintf(stream, "\n");
1270 }
1271