libusb: Fix usb_devs_lock mutex use after free in libusb_init error path
[platform/upstream/libusb.git] / libusb / core.c
1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2 /*
3  * Core functions for libusbx
4  * Copyright © 2012-2013 Nathan Hjelm <hjelmn@cs.unm.edu>
5  * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
6  * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #ifdef HAVE_SYS_TIME_H
34 #include <sys/time.h>
35 #endif
36 #ifdef HAVE_SYSLOG_H
37 #include <syslog.h>
38 #endif
39
40 #ifdef __ANDROID__
41 #include <android/log.h>
42 #endif
43
44 #include "libusbi.h"
45 #include "hotplug.h"
46
47 #if defined(OS_LINUX)
48 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
49 #elif defined(OS_DARWIN)
50 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
51 #elif defined(OS_OPENBSD)
52 const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
53 #elif defined(OS_WINDOWS)
54 const struct usbi_os_backend * const usbi_backend = &windows_backend;
55 #elif defined(OS_WINCE)
56 const struct usbi_os_backend * const usbi_backend = &wince_backend;
57 #else
58 #error "Unsupported OS"
59 #endif
60
61 struct libusb_context *usbi_default_context = NULL;
62 static const struct libusb_version libusb_version_internal =
63         { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
64           LIBUSB_RC, "http://libusbx.org" };
65 static int default_context_refcnt = 0;
66 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
67 static struct timeval timestamp_origin = { 0, 0 };
68
69 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
70 struct list_head active_contexts_list;
71
72 /**
73  * \mainpage libusbx-1.0 API Reference
74  *
75  * \section intro Introduction
76  *
77  * libusbx is an open source library that allows you to communicate with USB
78  * devices from userspace. For more info, see the
79  * <a href="http://libusbx.org">libusbx homepage</a>.
80  *
81  * This documentation is aimed at application developers wishing to
82  * communicate with USB peripherals from their own software. After reviewing
83  * this documentation, feedback and questions can be sent to the
84  * <a href="http://mailing-list.libusbx.org">libusbx-devel mailing list</a>.
85  *
86  * This documentation assumes knowledge of how to operate USB devices from
87  * a software standpoint (descriptors, configurations, interfaces, endpoints,
88  * control/bulk/interrupt/isochronous transfers, etc). Full information
89  * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
90  * Specification</a> which is available for free download. You can probably
91  * find less verbose introductions by searching the web.
92  *
93  * \section features Library features
94  *
95  * - All transfer types supported (control/bulk/interrupt/isochronous)
96  * - 2 transfer interfaces:
97  *    -# Synchronous (simple)
98  *    -# Asynchronous (more complicated, but more powerful)
99  * - Thread safe (although the asynchronous interface means that you
100  *   usually won't need to thread)
101  * - Lightweight with lean API
102  * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
103  * - Hotplug support (on some platforms). See \ref hotplug.
104  *
105  * \section gettingstarted Getting Started
106  *
107  * To begin reading the API documentation, start with the Modules page which
108  * links to the different categories of libusbx's functionality.
109  *
110  * One decision you will have to make is whether to use the synchronous
111  * or the asynchronous data transfer interface. The \ref io documentation
112  * provides some insight into this topic.
113  *
114  * Some example programs can be found in the libusbx source distribution under
115  * the "examples" subdirectory. The libusbx homepage includes a list of
116  * real-life project examples which use libusbx.
117  *
118  * \section errorhandling Error handling
119  *
120  * libusbx functions typically return 0 on success or a negative error code
121  * on failure. These negative error codes relate to LIBUSB_ERROR constants
122  * which are listed on the \ref misc "miscellaneous" documentation page.
123  *
124  * \section msglog Debug message logging
125  *
126  * libusbx uses stderr for all logging. By default, logging is set to NONE,
127  * which means that no output will be produced. However, unless the library
128  * has been compiled with logging disabled, then any application calls to
129  * libusb_set_debug(), or the setting of the environmental variable
130  * LIBUSB_DEBUG outside of the application, can result in logging being
131  * produced. Your application should therefore not close stderr, but instead
132  * direct it to the null device if its output is undesireable.
133  *
134  * The libusb_set_debug() function can be used to enable logging of certain
135  * messages. Under standard configuration, libusbx doesn't really log much
136  * so you are advised to use this function to enable all error/warning/
137  * informational messages. It will help debug problems with your software.
138  *
139  * The logged messages are unstructured. There is no one-to-one correspondence
140  * between messages being logged and success or failure return codes from
141  * libusbx functions. There is no format to the messages, so you should not
142  * try to capture or parse them. They are not and will not be localized.
143  * These messages are not intended to being passed to your application user;
144  * instead, you should interpret the error codes returned from libusbx functions
145  * and provide appropriate notification to the user. The messages are simply
146  * there to aid you as a programmer, and if you're confused because you're
147  * getting a strange error code from a libusbx function, enabling message
148  * logging may give you a suitable explanation.
149  *
150  * The LIBUSB_DEBUG environment variable can be used to enable message logging
151  * at run-time. This environment variable should be set to a log level number,
152  * which is interpreted the same as the libusb_set_debug() parameter. When this
153  * environment variable is set, the message logging verbosity level is fixed
154  * and libusb_set_debug() effectively does nothing.
155  *
156  * libusbx can be compiled without any logging functions, useful for embedded
157  * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
158  * variable have no effects.
159  *
160  * libusbx can also be compiled with verbose debugging messages always. When
161  * the library is compiled in this way, all messages of all verbosities are
162  * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
163  * have no effects.
164  *
165  * \section remarks Other remarks
166  *
167  * libusbx does have imperfections. The \ref caveats "caveats" page attempts
168  * to document these.
169  */
170
171 /**
172  * \page caveats Caveats
173  *
174  * \section devresets Device resets
175  *
176  * The libusb_reset_device() function allows you to reset a device. If your
177  * program has to call such a function, it should obviously be aware that
178  * the reset will cause device state to change (e.g. register values may be
179  * reset).
180  *
181  * The problem is that any other program could reset the device your program
182  * is working with, at any time. libusbx does not offer a mechanism to inform
183  * you when this has happened, so if someone else resets your device it will
184  * not be clear to your own program why the device state has changed.
185  *
186  * Ultimately, this is a limitation of writing drivers in userspace.
187  * Separation from the USB stack in the underlying kernel makes it difficult
188  * for the operating system to deliver such notifications to your program.
189  * The Linux kernel USB stack allows such reset notifications to be delivered
190  * to in-kernel USB drivers, but it is not clear how such notifications could
191  * be delivered to second-class drivers that live in userspace.
192  *
193  * \section blockonly Blocking-only functionality
194  *
195  * The functionality listed below is only available through synchronous,
196  * blocking functions. There are no asynchronous/non-blocking alternatives,
197  * and no clear ways of implementing these.
198  *
199  * - Configuration activation (libusb_set_configuration())
200  * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
201  * - Releasing of interfaces (libusb_release_interface())
202  * - Clearing of halt/stall condition (libusb_clear_halt())
203  * - Device resets (libusb_reset_device())
204  *
205  * \section configsel Configuration selection and handling
206  *
207  * When libusbx presents a device handle to an application, there is a chance
208  * that the corresponding device may be in unconfigured state. For devices
209  * with multiple configurations, there is also a chance that the configuration
210  * currently selected is not the one that the application wants to use.
211  *
212  * The obvious solution is to add a call to libusb_set_configuration() early
213  * on during your device initialization routines, but there are caveats to
214  * be aware of:
215  * -# If the device is already in the desired configuration, calling
216  *    libusb_set_configuration() using the same configuration value will cause
217  *    a lightweight device reset. This may not be desirable behaviour.
218  * -# libusbx will be unable to change configuration if the device is in
219  *    another configuration and other programs or drivers have claimed
220  *    interfaces under that configuration.
221  * -# In the case where the desired configuration is already active, libusbx
222  *    may not even be able to perform a lightweight device reset. For example,
223  *    take my USB keyboard with fingerprint reader: I'm interested in driving
224  *    the fingerprint reader interface through libusbx, but the kernel's
225  *    USB-HID driver will almost always have claimed the keyboard interface.
226  *    Because the kernel has claimed an interface, it is not even possible to
227  *    perform the lightweight device reset, so libusb_set_configuration() will
228  *    fail. (Luckily the device in question only has a single configuration.)
229  *
230  * One solution to some of the above problems is to consider the currently
231  * active configuration. If the configuration we want is already active, then
232  * we don't have to select any configuration:
233 \code
234 cfg = libusb_get_configuration(dev);
235 if (cfg != desired)
236         libusb_set_configuration(dev, desired);
237 \endcode
238  *
239  * This is probably suitable for most scenarios, but is inherently racy:
240  * another application or driver may change the selected configuration
241  * <em>after</em> the libusb_get_configuration() call.
242  *
243  * Even in cases where libusb_set_configuration() succeeds, consider that other
244  * applications or drivers may change configuration after your application
245  * calls libusb_set_configuration().
246  *
247  * One possible way to lock your device into a specific configuration is as
248  * follows:
249  * -# Set the desired configuration (or use the logic above to realise that
250  *    it is already in the desired configuration)
251  * -# Claim the interface that you wish to use
252  * -# Check that the currently active configuration is the one that you want
253  *    to use.
254  *
255  * The above method works because once an interface is claimed, no application
256  * or driver is able to select another configuration.
257  *
258  * \section earlycomp Early transfer completion
259  *
260  * NOTE: This section is currently Linux-centric. I am not sure if any of these
261  * considerations apply to Darwin or other platforms.
262  *
263  * When a transfer completes early (i.e. when less data is received/sent in
264  * any one packet than the transfer buffer allows for) then libusbx is designed
265  * to terminate the transfer immediately, not transferring or receiving any
266  * more data unless other transfers have been queued by the user.
267  *
268  * On legacy platforms, libusbx is unable to do this in all situations. After
269  * the incomplete packet occurs, "surplus" data may be transferred. For recent
270  * versions of libusbx, this information is kept (the data length of the
271  * transfer is updated) and, for device-to-host transfers, any surplus data was
272  * added to the buffer. Still, this is not a nice solution because it loses the
273  * information about the end of the short packet, and the user probably wanted
274  * that surplus data to arrive in the next logical transfer.
275  *
276  *
277  * \section zlp Zero length packets
278  *
279  * - libusbx is able to send a packet of zero length to an endpoint simply by
280  * submitting a transfer of zero length.
281  * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
282  * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
283  */
284
285 /**
286  * \page contexts Contexts
287  *
288  * It is possible that libusbx may be used simultaneously from two independent
289  * libraries linked into the same executable. For example, if your application
290  * has a plugin-like system which allows the user to dynamically load a range
291  * of modules into your program, it is feasible that two independently
292  * developed modules may both use libusbx.
293  *
294  * libusbx is written to allow for these multiple user scenarios. The two
295  * "instances" of libusbx will not interfere: libusb_set_debug() calls
296  * from one user will not affect the same settings for other users, other
297  * users can continue using libusbx after one of them calls libusb_exit(), etc.
298  *
299  * This is made possible through libusbx's <em>context</em> concept. When you
300  * call libusb_init(), you are (optionally) given a context. You can then pass
301  * this context pointer back into future libusbx functions.
302  *
303  * In order to keep things simple for more simplistic applications, it is
304  * legal to pass NULL to all functions requiring a context pointer (as long as
305  * you're sure no other code will attempt to use libusbx from the same process).
306  * When you pass NULL, the default context will be used. The default context
307  * is created the first time a process calls libusb_init() when no other
308  * context is alive. Contexts are destroyed during libusb_exit().
309  *
310  * The default context is reference-counted and can be shared. That means that
311  * if libusb_init(NULL) is called twice within the same process, the two
312  * users end up sharing the same context. The deinitialization and freeing of
313  * the default context will only happen when the last user calls libusb_exit().
314  * In other words, the default context is created and initialized when its
315  * reference count goes from 0 to 1, and is deinitialized and destroyed when
316  * its reference count goes from 1 to 0.
317  *
318  * You may be wondering why only a subset of libusbx functions require a
319  * context pointer in their function definition. Internally, libusbx stores
320  * context pointers in other objects (e.g. libusb_device instances) and hence
321  * can infer the context from those objects.
322  */
323
324 /**
325  * @defgroup lib Library initialization/deinitialization
326  * This page details how to initialize and deinitialize libusbx. Initialization
327  * must be performed before using any libusbx functionality, and similarly you
328  * must not call any libusbx functions after deinitialization.
329  */
330
331 /**
332  * @defgroup dev Device handling and enumeration
333  * The functionality documented below is designed to help with the following
334  * operations:
335  * - Enumerating the USB devices currently attached to the system
336  * - Choosing a device to operate from your software
337  * - Opening and closing the chosen device
338  *
339  * \section nutshell In a nutshell...
340  *
341  * The description below really makes things sound more complicated than they
342  * actually are. The following sequence of function calls will be suitable
343  * for almost all scenarios and does not require you to have such a deep
344  * understanding of the resource management issues:
345  * \code
346 // discover devices
347 libusb_device **list;
348 libusb_device *found = NULL;
349 ssize_t cnt = libusb_get_device_list(NULL, &list);
350 ssize_t i = 0;
351 int err = 0;
352 if (cnt < 0)
353         error();
354
355 for (i = 0; i < cnt; i++) {
356         libusb_device *device = list[i];
357         if (is_interesting(device)) {
358                 found = device;
359                 break;
360         }
361 }
362
363 if (found) {
364         libusb_device_handle *handle;
365
366         err = libusb_open(found, &handle);
367         if (err)
368                 error();
369         // etc
370 }
371
372 libusb_free_device_list(list, 1);
373 \endcode
374  *
375  * The two important points:
376  * - You asked libusb_free_device_list() to unreference the devices (2nd
377  *   parameter)
378  * - You opened the device before freeing the list and unreferencing the
379  *   devices
380  *
381  * If you ended up with a handle, you can now proceed to perform I/O on the
382  * device.
383  *
384  * \section devshandles Devices and device handles
385  * libusbx has a concept of a USB device, represented by the
386  * \ref libusb_device opaque type. A device represents a USB device that
387  * is currently or was previously connected to the system. Using a reference
388  * to a device, you can determine certain information about the device (e.g.
389  * you can read the descriptor data).
390  *
391  * The libusb_get_device_list() function can be used to obtain a list of
392  * devices currently connected to the system. This is known as device
393  * discovery.
394  *
395  * Just because you have a reference to a device does not mean it is
396  * necessarily usable. The device may have been unplugged, you may not have
397  * permission to operate such device, or another program or driver may be
398  * using the device.
399  *
400  * When you've found a device that you'd like to operate, you must ask
401  * libusbx to open the device using the libusb_open() function. Assuming
402  * success, libusbx then returns you a <em>device handle</em>
403  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
404  * operate on the handle rather than the original device pointer.
405  *
406  * \section devref Device discovery and reference counting
407  *
408  * Device discovery (i.e. calling libusb_get_device_list()) returns a
409  * freshly-allocated list of devices. The list itself must be freed when
410  * you are done with it. libusbx also needs to know when it is OK to free
411  * the contents of the list - the devices themselves.
412  *
413  * To handle these issues, libusbx provides you with two separate items:
414  * - A function to free the list itself
415  * - A reference counting system for the devices inside
416  *
417  * New devices presented by the libusb_get_device_list() function all have a
418  * reference count of 1. You can increase and decrease reference count using
419  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
420  * its reference count reaches 0.
421  *
422  * With the above information in mind, the process of opening a device can
423  * be viewed as follows:
424  * -# Discover devices using libusb_get_device_list().
425  * -# Choose the device that you want to operate, and call libusb_open().
426  * -# Unref all devices in the discovered device list.
427  * -# Free the discovered device list.
428  *
429  * The order is important - you must not unreference the device before
430  * attempting to open it, because unreferencing it may destroy the device.
431  *
432  * For convenience, the libusb_free_device_list() function includes a
433  * parameter to optionally unreference all the devices in the list before
434  * freeing the list itself. This combines steps 3 and 4 above.
435  *
436  * As an implementation detail, libusb_open() actually adds a reference to
437  * the device in question. This is because the device remains available
438  * through the handle via libusb_get_device(). The reference is deleted during
439  * libusb_close().
440  */
441
442 /** @defgroup misc Miscellaneous */
443
444 /* we traverse usbfs without knowing how many devices we are going to find.
445  * so we create this discovered_devs model which is similar to a linked-list
446  * which grows when required. it can be freed once discovery has completed,
447  * eliminating the need for a list node in the libusb_device structure
448  * itself. */
449 #define DISCOVERED_DEVICES_SIZE_STEP 8
450
451 static struct discovered_devs *discovered_devs_alloc(void)
452 {
453         struct discovered_devs *ret =
454                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
455
456         if (ret) {
457                 ret->len = 0;
458                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
459         }
460         return ret;
461 }
462
463 /* append a device to the discovered devices collection. may realloc itself,
464  * returning new discdevs. returns NULL on realloc failure. */
465 struct discovered_devs *discovered_devs_append(
466         struct discovered_devs *discdevs, struct libusb_device *dev)
467 {
468         size_t len = discdevs->len;
469         size_t capacity;
470
471         /* if there is space, just append the device */
472         if (len < discdevs->capacity) {
473                 discdevs->devices[len] = libusb_ref_device(dev);
474                 discdevs->len++;
475                 return discdevs;
476         }
477
478         /* exceeded capacity, need to grow */
479         usbi_dbg("need to increase capacity");
480         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
481         discdevs = usbi_reallocf(discdevs,
482                 sizeof(*discdevs) + (sizeof(void *) * capacity));
483         if (discdevs) {
484                 discdevs->capacity = capacity;
485                 discdevs->devices[len] = libusb_ref_device(dev);
486                 discdevs->len++;
487         }
488
489         return discdevs;
490 }
491
492 static void discovered_devs_free(struct discovered_devs *discdevs)
493 {
494         size_t i;
495
496         for (i = 0; i < discdevs->len; i++)
497                 libusb_unref_device(discdevs->devices[i]);
498
499         free(discdevs);
500 }
501
502 /* Allocate a new device with a specific session ID. The returned device has
503  * a reference count of 1. */
504 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
505         unsigned long session_id)
506 {
507         size_t priv_size = usbi_backend->device_priv_size;
508         struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
509         int r;
510
511         if (!dev)
512                 return NULL;
513
514         r = usbi_mutex_init(&dev->lock, NULL);
515         if (r) {
516                 free(dev);
517                 return NULL;
518         }
519
520         dev->ctx = ctx;
521         dev->refcnt = 1;
522         dev->session_data = session_id;
523         dev->speed = LIBUSB_SPEED_UNKNOWN;
524
525         if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
526                 usbi_connect_device (dev);
527         }
528
529         return dev;
530 }
531
532 void usbi_connect_device(struct libusb_device *dev)
533 {
534         libusb_hotplug_message message;
535         ssize_t ret;
536
537         memset(&message, 0, sizeof(message));
538         message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED;
539         message.device = dev;
540         dev->attached = 1;
541
542         usbi_mutex_lock(&dev->ctx->usb_devs_lock);
543         list_add(&dev->list, &dev->ctx->usb_devs);
544         usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
545
546         /* Signal that an event has occurred for this device if we support hotplug AND
547          * the hotplug pipe is ready. This prevents an event from getting raised during
548          * initial enumeration. */
549         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_pipe[1] > 0) {
550                 ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
551                 if (sizeof (message) != ret) {
552                         usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
553                 }
554         }
555 }
556
557 void usbi_disconnect_device(struct libusb_device *dev)
558 {
559         libusb_hotplug_message message;
560         struct libusb_context *ctx = dev->ctx;
561         ssize_t ret;
562
563         memset(&message, 0, sizeof(message));
564         message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT;
565         message.device = dev;
566         usbi_mutex_lock(&dev->lock);
567         dev->attached = 0;
568         usbi_mutex_unlock(&dev->lock);
569
570         /* Signal that an event has occurred for this device if we support hotplug AND
571          * the hotplug pipe is ready. This prevents an event from getting raised during
572          * initial enumeration. libusb_handle_events will take care of dereferencing the
573          * device. */
574         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_pipe[1] > 0) {
575                 ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
576                 if (sizeof(message) != ret) {
577                         usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
578                 }
579         }
580
581         usbi_mutex_lock(&ctx->usb_devs_lock);
582         list_del(&dev->list);
583         usbi_mutex_unlock(&ctx->usb_devs_lock);
584 }
585
586 /* Perform some final sanity checks on a newly discovered device. If this
587  * function fails (negative return code), the device should not be added
588  * to the discovered device list. */
589 int usbi_sanitize_device(struct libusb_device *dev)
590 {
591         int r;
592         uint8_t num_configurations;
593
594         r = usbi_device_cache_descriptor(dev);
595         if (r < 0)
596                 return r;
597
598         num_configurations = dev->device_descriptor.bNumConfigurations;
599         if (num_configurations > USB_MAXCONFIG) {
600                 usbi_err(DEVICE_CTX(dev), "too many configurations");
601                 return LIBUSB_ERROR_IO;
602         } else if (0 == num_configurations)
603                 usbi_dbg("zero configurations, maybe an unauthorized device");
604
605         dev->num_configurations = num_configurations;
606         return 0;
607 }
608
609 /* Examine libusbx's internal list of known devices, looking for one with
610  * a specific session ID. Returns the matching device if it was found, and
611  * NULL otherwise. */
612 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
613         unsigned long session_id)
614 {
615         struct libusb_device *dev;
616         struct libusb_device *ret = NULL;
617
618         usbi_mutex_lock(&ctx->usb_devs_lock);
619         list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
620                 if (dev->session_data == session_id) {
621                         ret = dev;
622                         break;
623                 }
624         usbi_mutex_unlock(&ctx->usb_devs_lock);
625
626         return ret;
627 }
628
629 /** @ingroup dev
630  * Returns a list of USB devices currently attached to the system. This is
631  * your entry point into finding a USB device to operate.
632  *
633  * You are expected to unreference all the devices when you are done with
634  * them, and then free the list with libusb_free_device_list(). Note that
635  * libusb_free_device_list() can unref all the devices for you. Be careful
636  * not to unreference a device you are about to open until after you have
637  * opened it.
638  *
639  * This return value of this function indicates the number of devices in
640  * the resultant list. The list is actually one element larger, as it is
641  * NULL-terminated.
642  *
643  * \param ctx the context to operate on, or NULL for the default context
644  * \param list output location for a list of devices. Must be later freed with
645  * libusb_free_device_list().
646  * \returns the number of devices in the outputted list, or any
647  * \ref libusb_error according to errors encountered by the backend.
648  */
649 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
650         libusb_device ***list)
651 {
652         struct discovered_devs *discdevs = discovered_devs_alloc();
653         struct libusb_device **ret;
654         int r = 0;
655         ssize_t i, len;
656         USBI_GET_CONTEXT(ctx);
657         usbi_dbg("");
658
659         if (!discdevs)
660                 return LIBUSB_ERROR_NO_MEM;
661
662         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
663                 /* backend provides hotplug support */
664                 struct libusb_device *dev;
665
666                 if (usbi_backend->hotplug_poll)
667                         usbi_backend->hotplug_poll();
668
669                 usbi_mutex_lock(&ctx->usb_devs_lock);
670                 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
671                         discdevs = discovered_devs_append(discdevs, dev);
672
673                         if (!discdevs) {
674                                 r = LIBUSB_ERROR_NO_MEM;
675                                 break;
676                         }
677                 }
678                 usbi_mutex_unlock(&ctx->usb_devs_lock);
679         } else {
680                 /* backend does not provide hotplug support */
681                 r = usbi_backend->get_device_list(ctx, &discdevs);
682         }
683
684         if (r < 0) {
685                 len = r;
686                 goto out;
687         }
688
689         /* convert discovered_devs into a list */
690         len = discdevs->len;
691         ret = calloc(len + 1, sizeof(struct libusb_device *));
692         if (!ret) {
693                 len = LIBUSB_ERROR_NO_MEM;
694                 goto out;
695         }
696
697         ret[len] = NULL;
698         for (i = 0; i < len; i++) {
699                 struct libusb_device *dev = discdevs->devices[i];
700                 ret[i] = libusb_ref_device(dev);
701         }
702         *list = ret;
703
704 out:
705         discovered_devs_free(discdevs);
706         return len;
707 }
708
709 /** \ingroup dev
710  * Frees a list of devices previously discovered using
711  * libusb_get_device_list(). If the unref_devices parameter is set, the
712  * reference count of each device in the list is decremented by 1.
713  * \param list the list to free
714  * \param unref_devices whether to unref the devices in the list
715  */
716 void API_EXPORTED libusb_free_device_list(libusb_device **list,
717         int unref_devices)
718 {
719         if (!list)
720                 return;
721
722         if (unref_devices) {
723                 int i = 0;
724                 struct libusb_device *dev;
725
726                 while ((dev = list[i++]) != NULL)
727                         libusb_unref_device(dev);
728         }
729         free(list);
730 }
731
732 /** \ingroup dev
733  * Get the number of the bus that a device is connected to.
734  * \param dev a device
735  * \returns the bus number
736  */
737 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
738 {
739         return dev->bus_number;
740 }
741
742 /** \ingroup dev
743  * Get the number of the port that a device is connected to.
744  * Unless the OS does something funky, or you are hot-plugging USB extension cards,
745  * the port number returned by this call is usually guaranteed to be uniquely tied
746  * to a physical port, meaning that different devices plugged on the same physical
747  * port should return the same port number.
748  *
749  * But outside of this, there is no guarantee that the port number returned by this
750  * call will remain the same, or even match the order in which ports have been
751  * numbered by the HUB/HCD manufacturer.
752  *
753  * \param dev a device
754  * \returns the port number (0 if not available)
755  */
756 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
757 {
758         return dev->port_number;
759 }
760
761 /** \ingroup dev
762  * Get the list of all port numbers from root for the specified device
763  *
764  * Since version 1.0.16, \ref LIBUSBX_API_VERSION >= 0x01000102
765  * \param dev a device
766  * \param port_numbers the array that should contain the port numbers
767  * \param port_numbers_len the maximum length of the array. As per the USB 3.0
768  * specs, the current maximum limit for the depth is 7.
769  * \returns the number of elements filled
770  * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
771  */
772 int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
773         uint8_t* port_numbers, int port_numbers_len)
774 {
775         int i = port_numbers_len;
776
777         while(dev) {
778                 // HCDs can be listed as devices and would have port #0
779                 // TODO: see how the other backends want to implement HCDs as parents
780                 if (dev->port_number == 0)
781                         break;
782                 i--;
783                 if (i < 0) {
784                         usbi_warn(DEVICE_CTX(dev),
785                                 "port numbers array too small");
786                         return LIBUSB_ERROR_OVERFLOW;
787                 }
788                 port_numbers[i] = dev->port_number;
789                 dev = dev->parent_dev;
790         }
791         memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
792         return port_numbers_len - i;
793 }
794
795 /** \ingroup dev
796  * Deprecated please use libusb_get_port_numbers instead.
797  */
798 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
799         uint8_t* port_numbers, uint8_t port_numbers_len)
800 {
801         UNUSED(ctx);
802
803         return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
804 }
805
806 /** \ingroup dev
807  * Get the the parent from the specified device.
808  * \param dev a device
809  * \returns the device parent or NULL if not available
810  * You should issue a \ref libusb_get_device_list() before calling this
811  * function and make sure that you only access the parent before issuing
812  * \ref libusb_free_device_list(). The reason is that libusbx currently does
813  * not maintain a permanent list of device instances, and therefore can
814  * only guarantee that parents are fully instantiated within a 
815  * libusb_get_device_list() - libusb_free_device_list() block.
816  */
817 DEFAULT_VISIBILITY
818 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
819 {
820         return dev->parent_dev;
821 }
822
823 /** \ingroup dev
824  * Get the address of the device on the bus it is connected to.
825  * \param dev a device
826  * \returns the device address
827  */
828 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
829 {
830         return dev->device_address;
831 }
832
833 /** \ingroup dev
834  * Get the negotiated connection speed for a device.
835  * \param dev a device
836  * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
837  * the OS doesn't know or doesn't support returning the negotiated speed.
838  */
839 int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
840 {
841         return dev->speed;
842 }
843
844 static const struct libusb_endpoint_descriptor *find_endpoint(
845         struct libusb_config_descriptor *config, unsigned char endpoint)
846 {
847         int iface_idx;
848         for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
849                 const struct libusb_interface *iface = &config->interface[iface_idx];
850                 int altsetting_idx;
851
852                 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
853                                 altsetting_idx++) {
854                         const struct libusb_interface_descriptor *altsetting
855                                 = &iface->altsetting[altsetting_idx];
856                         int ep_idx;
857
858                         for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
859                                 const struct libusb_endpoint_descriptor *ep =
860                                         &altsetting->endpoint[ep_idx];
861                                 if (ep->bEndpointAddress == endpoint)
862                                         return ep;
863                         }
864                 }
865         }
866         return NULL;
867 }
868
869 /** \ingroup dev
870  * Convenience function to retrieve the wMaxPacketSize value for a particular
871  * endpoint in the active device configuration.
872  *
873  * This function was originally intended to be of assistance when setting up
874  * isochronous transfers, but a design mistake resulted in this function
875  * instead. It simply returns the wMaxPacketSize value without considering
876  * its contents. If you're dealing with isochronous transfers, you probably
877  * want libusb_get_max_iso_packet_size() instead.
878  *
879  * \param dev a device
880  * \param endpoint address of the endpoint in question
881  * \returns the wMaxPacketSize value
882  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
883  * \returns LIBUSB_ERROR_OTHER on other failure
884  */
885 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
886         unsigned char endpoint)
887 {
888         struct libusb_config_descriptor *config;
889         const struct libusb_endpoint_descriptor *ep;
890         int r;
891
892         r = libusb_get_active_config_descriptor(dev, &config);
893         if (r < 0) {
894                 usbi_err(DEVICE_CTX(dev),
895                         "could not retrieve active config descriptor");
896                 return LIBUSB_ERROR_OTHER;
897         }
898
899         ep = find_endpoint(config, endpoint);
900         if (!ep)
901                 return LIBUSB_ERROR_NOT_FOUND;
902
903         r = ep->wMaxPacketSize;
904         libusb_free_config_descriptor(config);
905         return r;
906 }
907
908 /** \ingroup dev
909  * Calculate the maximum packet size which a specific endpoint is capable is
910  * sending or receiving in the duration of 1 microframe
911  *
912  * Only the active configuration is examined. The calculation is based on the
913  * wMaxPacketSize field in the endpoint descriptor as described in section
914  * 9.6.6 in the USB 2.0 specifications.
915  *
916  * If acting on an isochronous or interrupt endpoint, this function will
917  * multiply the value found in bits 0:10 by the number of transactions per
918  * microframe (determined by bits 11:12). Otherwise, this function just
919  * returns the numeric value found in bits 0:10.
920  *
921  * This function is useful for setting up isochronous transfers, for example
922  * you might pass the return value from this function to
923  * libusb_set_iso_packet_lengths() in order to set the length field of every
924  * isochronous packet in a transfer.
925  *
926  * Since v1.0.3.
927  *
928  * \param dev a device
929  * \param endpoint address of the endpoint in question
930  * \returns the maximum packet size which can be sent/received on this endpoint
931  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
932  * \returns LIBUSB_ERROR_OTHER on other failure
933  */
934 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
935         unsigned char endpoint)
936 {
937         struct libusb_config_descriptor *config;
938         const struct libusb_endpoint_descriptor *ep;
939         enum libusb_transfer_type ep_type;
940         uint16_t val;
941         int r;
942
943         r = libusb_get_active_config_descriptor(dev, &config);
944         if (r < 0) {
945                 usbi_err(DEVICE_CTX(dev),
946                         "could not retrieve active config descriptor");
947                 return LIBUSB_ERROR_OTHER;
948         }
949
950         ep = find_endpoint(config, endpoint);
951         if (!ep)
952                 return LIBUSB_ERROR_NOT_FOUND;
953
954         val = ep->wMaxPacketSize;
955         ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
956         libusb_free_config_descriptor(config);
957
958         r = val & 0x07ff;
959         if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
960                         || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
961                 r *= (1 + ((val >> 11) & 3));
962         return r;
963 }
964
965 /** \ingroup dev
966  * Increment the reference count of a device.
967  * \param dev the device to reference
968  * \returns the same device
969  */
970 DEFAULT_VISIBILITY
971 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
972 {
973         usbi_mutex_lock(&dev->lock);
974         dev->refcnt++;
975         usbi_mutex_unlock(&dev->lock);
976         return dev;
977 }
978
979 /** \ingroup dev
980  * Decrement the reference count of a device. If the decrement operation
981  * causes the reference count to reach zero, the device shall be destroyed.
982  * \param dev the device to unreference
983  */
984 void API_EXPORTED libusb_unref_device(libusb_device *dev)
985 {
986         int refcnt;
987
988         if (!dev)
989                 return;
990
991         usbi_mutex_lock(&dev->lock);
992         refcnt = --dev->refcnt;
993         usbi_mutex_unlock(&dev->lock);
994
995         if (refcnt == 0) {
996                 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
997
998                 libusb_unref_device(dev->parent_dev);
999
1000                 if (usbi_backend->destroy_device)
1001                         usbi_backend->destroy_device(dev);
1002
1003                 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1004                         /* backend does not support hotplug */
1005                         usbi_disconnect_device(dev);
1006                 }
1007
1008                 usbi_mutex_destroy(&dev->lock);
1009                 free(dev);
1010         }
1011 }
1012
1013 /*
1014  * Interrupt the iteration of the event handling thread, so that it picks
1015  * up the new fd.
1016  */
1017 void usbi_fd_notification(struct libusb_context *ctx)
1018 {
1019         unsigned char dummy = 1;
1020         ssize_t r;
1021
1022         if (ctx == NULL)
1023                 return;
1024
1025         /* record that we are messing with poll fds */
1026         usbi_mutex_lock(&ctx->pollfd_modify_lock);
1027         ctx->pollfd_modify++;
1028         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1029
1030         /* write some data on control pipe to interrupt event handlers */
1031         r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1032         if (r <= 0) {
1033                 usbi_warn(ctx, "internal signalling write failed");
1034                 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1035                 ctx->pollfd_modify--;
1036                 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1037                 return;
1038         }
1039
1040         /* take event handling lock */
1041         libusb_lock_events(ctx);
1042
1043         /* read the dummy data */
1044         r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1045         if (r <= 0)
1046                 usbi_warn(ctx, "internal signalling read failed");
1047
1048         /* we're done with modifying poll fds */
1049         usbi_mutex_lock(&ctx->pollfd_modify_lock);
1050         ctx->pollfd_modify--;
1051         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1052
1053         /* Release event handling lock and wake up event waiters */
1054         libusb_unlock_events(ctx);
1055 }
1056
1057 /** \ingroup dev
1058  * Open a device and obtain a device handle. A handle allows you to perform
1059  * I/O on the device in question.
1060  *
1061  * Internally, this function adds a reference to the device and makes it
1062  * available to you through libusb_get_device(). This reference is removed
1063  * during libusb_close().
1064  *
1065  * This is a non-blocking function; no requests are sent over the bus.
1066  *
1067  * \param dev the device to open
1068  * \param handle output location for the returned device handle pointer. Only
1069  * populated when the return code is 0.
1070  * \returns 0 on success
1071  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
1072  * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1073  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1074  * \returns another LIBUSB_ERROR code on other failure
1075  */
1076 int API_EXPORTED libusb_open(libusb_device *dev,
1077         libusb_device_handle **handle)
1078 {
1079         struct libusb_context *ctx = DEVICE_CTX(dev);
1080         struct libusb_device_handle *_handle;
1081         size_t priv_size = usbi_backend->device_handle_priv_size;
1082         int r;
1083         usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
1084
1085         if (!dev->attached) {
1086                 return LIBUSB_ERROR_NO_DEVICE;
1087         }
1088
1089         _handle = malloc(sizeof(*_handle) + priv_size);
1090         if (!_handle)
1091                 return LIBUSB_ERROR_NO_MEM;
1092
1093         r = usbi_mutex_init(&_handle->lock, NULL);
1094         if (r) {
1095                 free(_handle);
1096                 return LIBUSB_ERROR_OTHER;
1097         }
1098
1099         _handle->dev = libusb_ref_device(dev);
1100         _handle->auto_detach_kernel_driver = 0;
1101         _handle->claimed_interfaces = 0;
1102         memset(&_handle->os_priv, 0, priv_size);
1103
1104         r = usbi_backend->open(_handle);
1105         if (r < 0) {
1106                 usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1107                 libusb_unref_device(dev);
1108                 usbi_mutex_destroy(&_handle->lock);
1109                 free(_handle);
1110                 return r;
1111         }
1112
1113         usbi_mutex_lock(&ctx->open_devs_lock);
1114         list_add(&_handle->list, &ctx->open_devs);
1115         usbi_mutex_unlock(&ctx->open_devs_lock);
1116         *handle = _handle;
1117
1118         /* At this point, we want to interrupt any existing event handlers so
1119          * that they realise the addition of the new device's poll fd. One
1120          * example when this is desirable is if the user is running a separate
1121          * dedicated libusbx events handling thread, which is running with a long
1122          * or infinite timeout. We want to interrupt that iteration of the loop,
1123          * so that it picks up the new fd, and then continues. */
1124         usbi_fd_notification(ctx);
1125
1126         return 0;
1127 }
1128
1129 /** \ingroup dev
1130  * Convenience function for finding a device with a particular
1131  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1132  * for those scenarios where you are using libusbx to knock up a quick test
1133  * application - it allows you to avoid calling libusb_get_device_list() and
1134  * worrying about traversing/freeing the list.
1135  *
1136  * This function has limitations and is hence not intended for use in real
1137  * applications: if multiple devices have the same IDs it will only
1138  * give you the first one, etc.
1139  *
1140  * \param ctx the context to operate on, or NULL for the default context
1141  * \param vendor_id the idVendor value to search for
1142  * \param product_id the idProduct value to search for
1143  * \returns a handle for the first found device, or NULL on error or if the
1144  * device could not be found. */
1145 DEFAULT_VISIBILITY
1146 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1147         libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1148 {
1149         struct libusb_device **devs;
1150         struct libusb_device *found = NULL;
1151         struct libusb_device *dev;
1152         struct libusb_device_handle *handle = NULL;
1153         size_t i = 0;
1154         int r;
1155
1156         if (libusb_get_device_list(ctx, &devs) < 0)
1157                 return NULL;
1158
1159         while ((dev = devs[i++]) != NULL) {
1160                 struct libusb_device_descriptor desc;
1161                 r = libusb_get_device_descriptor(dev, &desc);
1162                 if (r < 0)
1163                         goto out;
1164                 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1165                         found = dev;
1166                         break;
1167                 }
1168         }
1169
1170         if (found) {
1171                 r = libusb_open(found, &handle);
1172                 if (r < 0)
1173                         handle = NULL;
1174         }
1175
1176 out:
1177         libusb_free_device_list(devs, 1);
1178         return handle;
1179 }
1180
1181 static void do_close(struct libusb_context *ctx,
1182         struct libusb_device_handle *dev_handle)
1183 {
1184         struct usbi_transfer *itransfer;
1185         struct usbi_transfer *tmp;
1186
1187         libusb_lock_events(ctx);
1188
1189         /* remove any transfers in flight that are for this device */
1190         usbi_mutex_lock(&ctx->flying_transfers_lock);
1191
1192         /* safe iteration because transfers may be being deleted */
1193         list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1194                 struct libusb_transfer *transfer =
1195                         USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1196
1197                 if (transfer->dev_handle != dev_handle)
1198                         continue;
1199
1200                 if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1201                         usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1202
1203                         if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1204                                 usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1205                         else
1206                                 usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1207                 }
1208
1209                 /* remove from the list of in-flight transfers and make sure
1210                  * we don't accidentally use the device handle in the future
1211                  * (or that such accesses will be easily caught and identified as a crash)
1212                  */
1213                 usbi_mutex_lock(&itransfer->lock);
1214                 list_del(&itransfer->list);
1215                 transfer->dev_handle = NULL;
1216                 usbi_mutex_unlock(&itransfer->lock);
1217
1218                 /* it is up to the user to free up the actual transfer struct.  this is
1219                  * just making sure that we don't attempt to process the transfer after
1220                  * the device handle is invalid
1221                  */
1222                 usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1223                          transfer, dev_handle);
1224         }
1225         usbi_mutex_unlock(&ctx->flying_transfers_lock);
1226
1227         libusb_unlock_events(ctx);
1228
1229         usbi_mutex_lock(&ctx->open_devs_lock);
1230         list_del(&dev_handle->list);
1231         usbi_mutex_unlock(&ctx->open_devs_lock);
1232
1233         usbi_backend->close(dev_handle);
1234         libusb_unref_device(dev_handle->dev);
1235         usbi_mutex_destroy(&dev_handle->lock);
1236         free(dev_handle);
1237 }
1238
1239 /** \ingroup dev
1240  * Close a device handle. Should be called on all open handles before your
1241  * application exits.
1242  *
1243  * Internally, this function destroys the reference that was added by
1244  * libusb_open() on the given device.
1245  *
1246  * This is a non-blocking function; no requests are sent over the bus.
1247  *
1248  * \param dev_handle the handle to close
1249  */
1250 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1251 {
1252         struct libusb_context *ctx;
1253         unsigned char dummy = 1;
1254         ssize_t r;
1255
1256         if (!dev_handle)
1257                 return;
1258         usbi_dbg("");
1259
1260         ctx = HANDLE_CTX(dev_handle);
1261
1262         /* Similarly to libusb_open(), we want to interrupt all event handlers
1263          * at this point. More importantly, we want to perform the actual close of
1264          * the device while holding the event handling lock (preventing any other
1265          * thread from doing event handling) because we will be removing a file
1266          * descriptor from the polling loop. */
1267
1268         /* record that we are messing with poll fds */
1269         usbi_mutex_lock(&ctx->pollfd_modify_lock);
1270         ctx->pollfd_modify++;
1271         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1272
1273         /* write some data on control pipe to interrupt event handlers */
1274         r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1275         if (r <= 0) {
1276                 usbi_warn(ctx, "internal signalling write failed, closing anyway");
1277                 do_close(ctx, dev_handle);
1278                 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1279                 ctx->pollfd_modify--;
1280                 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1281                 return;
1282         }
1283
1284         /* take event handling lock */
1285         libusb_lock_events(ctx);
1286
1287         /* read the dummy data */
1288         r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1289         if (r <= 0)
1290                 usbi_warn(ctx, "internal signalling read failed, closing anyway");
1291
1292         /* Close the device */
1293         do_close(ctx, dev_handle);
1294
1295         /* we're done with modifying poll fds */
1296         usbi_mutex_lock(&ctx->pollfd_modify_lock);
1297         ctx->pollfd_modify--;
1298         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1299
1300         /* Release event handling lock and wake up event waiters */
1301         libusb_unlock_events(ctx);
1302 }
1303
1304 /** \ingroup dev
1305  * Get the underlying device for a handle. This function does not modify
1306  * the reference count of the returned device, so do not feel compelled to
1307  * unreference it when you are done.
1308  * \param dev_handle a device handle
1309  * \returns the underlying device
1310  */
1311 DEFAULT_VISIBILITY
1312 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1313 {
1314         return dev_handle->dev;
1315 }
1316
1317 /** \ingroup dev
1318  * Determine the bConfigurationValue of the currently active configuration.
1319  *
1320  * You could formulate your own control request to obtain this information,
1321  * but this function has the advantage that it may be able to retrieve the
1322  * information from operating system caches (no I/O involved).
1323  *
1324  * If the OS does not cache this information, then this function will block
1325  * while a control transfer is submitted to retrieve the information.
1326  *
1327  * This function will return a value of 0 in the <tt>config</tt> output
1328  * parameter if the device is in unconfigured state.
1329  *
1330  * \param dev a device handle
1331  * \param config output location for the bConfigurationValue of the active
1332  * configuration (only valid for return code 0)
1333  * \returns 0 on success
1334  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1335  * \returns another LIBUSB_ERROR code on other failure
1336  */
1337 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
1338         int *config)
1339 {
1340         int r = LIBUSB_ERROR_NOT_SUPPORTED;
1341
1342         usbi_dbg("");
1343         if (usbi_backend->get_configuration)
1344                 r = usbi_backend->get_configuration(dev, config);
1345
1346         if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1347                 uint8_t tmp = 0;
1348                 usbi_dbg("falling back to control message");
1349                 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1350                         LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1351                 if (r == 0) {
1352                         usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1353                         r = LIBUSB_ERROR_IO;
1354                 } else if (r == 1) {
1355                         r = 0;
1356                         *config = tmp;
1357                 } else {
1358                         usbi_dbg("control failed, error %d", r);
1359                 }
1360         }
1361
1362         if (r == 0)
1363                 usbi_dbg("active config %d", *config);
1364
1365         return r;
1366 }
1367
1368 /** \ingroup dev
1369  * Set the active configuration for a device.
1370  *
1371  * The operating system may or may not have already set an active
1372  * configuration on the device. It is up to your application to ensure the
1373  * correct configuration is selected before you attempt to claim interfaces
1374  * and perform other operations.
1375  *
1376  * If you call this function on a device already configured with the selected
1377  * configuration, then this function will act as a lightweight device reset:
1378  * it will issue a SET_CONFIGURATION request using the current configuration,
1379  * causing most USB-related device state to be reset (altsetting reset to zero,
1380  * endpoint halts cleared, toggles reset).
1381  *
1382  * You cannot change/reset configuration if your application has claimed
1383  * interfaces. It is advised to set the desired configuration before claiming
1384  * interfaces.
1385  *
1386  * Alternatively you can call libusb_release_interface() first. Note if you
1387  * do things this way you must ensure that auto_detach_kernel_driver for
1388  * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1389  * release the interface(s).
1390  *
1391  * You cannot change/reset configuration if other applications or drivers have
1392  * claimed interfaces.
1393  *
1394  * A configuration value of -1 will put the device in unconfigured state.
1395  * The USB specifications state that a configuration value of 0 does this,
1396  * however buggy devices exist which actually have a configuration 0.
1397  *
1398  * You should always use this function rather than formulating your own
1399  * SET_CONFIGURATION control request. This is because the underlying operating
1400  * system needs to know when such changes happen.
1401  *
1402  * This is a blocking function.
1403  *
1404  * \param dev a device handle
1405  * \param configuration the bConfigurationValue of the configuration you
1406  * wish to activate, or -1 if you wish to put the device in unconfigured state
1407  * \returns 0 on success
1408  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1409  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1410  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1411  * \returns another LIBUSB_ERROR code on other failure
1412  * \see libusb_set_auto_detach_kernel_driver()
1413  */
1414 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
1415         int configuration)
1416 {
1417         usbi_dbg("configuration %d", configuration);
1418         return usbi_backend->set_configuration(dev, configuration);
1419 }
1420
1421 /** \ingroup dev
1422  * Claim an interface on a given device handle. You must claim the interface
1423  * you wish to use before you can perform I/O on any of its endpoints.
1424  *
1425  * It is legal to attempt to claim an already-claimed interface, in which
1426  * case libusbx just returns 0 without doing anything.
1427  *
1428  * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1429  * will be detached if necessary, on failure the detach error is returned.
1430  *
1431  * Claiming of interfaces is a purely logical operation; it does not cause
1432  * any requests to be sent over the bus. Interface claiming is used to
1433  * instruct the underlying operating system that your application wishes
1434  * to take ownership of the interface.
1435  *
1436  * This is a non-blocking function.
1437  *
1438  * \param dev a device handle
1439  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1440  * wish to claim
1441  * \returns 0 on success
1442  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1443  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1444  * interface
1445  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1446  * \returns a LIBUSB_ERROR code on other failure
1447  * \see libusb_set_auto_detach_kernel_driver()
1448  */
1449 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
1450         int interface_number)
1451 {
1452         int r = 0;
1453
1454         usbi_dbg("interface %d", interface_number);
1455         if (interface_number >= USB_MAXINTERFACES)
1456                 return LIBUSB_ERROR_INVALID_PARAM;
1457
1458         if (!dev->dev->attached)
1459                 return LIBUSB_ERROR_NO_DEVICE;
1460
1461         usbi_mutex_lock(&dev->lock);
1462         if (dev->claimed_interfaces & (1 << interface_number))
1463                 goto out;
1464
1465         r = usbi_backend->claim_interface(dev, interface_number);
1466         if (r == 0)
1467                 dev->claimed_interfaces |= 1 << interface_number;
1468
1469 out:
1470         usbi_mutex_unlock(&dev->lock);
1471         return r;
1472 }
1473
1474 /** \ingroup dev
1475  * Release an interface previously claimed with libusb_claim_interface(). You
1476  * should release all claimed interfaces before closing a device handle.
1477  *
1478  * This is a blocking function. A SET_INTERFACE control request will be sent
1479  * to the device, resetting interface state to the first alternate setting.
1480  *
1481  * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1482  * driver will be re-attached after releasing the interface.
1483  *
1484  * \param dev a device handle
1485  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1486  * previously-claimed interface
1487  * \returns 0 on success
1488  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1489  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1490  * \returns another LIBUSB_ERROR code on other failure
1491  * \see libusb_set_auto_detach_kernel_driver()
1492  */
1493 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
1494         int interface_number)
1495 {
1496         int r;
1497
1498         usbi_dbg("interface %d", interface_number);
1499         if (interface_number >= USB_MAXINTERFACES)
1500                 return LIBUSB_ERROR_INVALID_PARAM;
1501
1502         usbi_mutex_lock(&dev->lock);
1503         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1504                 r = LIBUSB_ERROR_NOT_FOUND;
1505                 goto out;
1506         }
1507
1508         r = usbi_backend->release_interface(dev, interface_number);
1509         if (r == 0)
1510                 dev->claimed_interfaces &= ~(1 << interface_number);
1511
1512 out:
1513         usbi_mutex_unlock(&dev->lock);
1514         return r;
1515 }
1516
1517 /** \ingroup dev
1518  * Activate an alternate setting for an interface. The interface must have
1519  * been previously claimed with libusb_claim_interface().
1520  *
1521  * You should always use this function rather than formulating your own
1522  * SET_INTERFACE control request. This is because the underlying operating
1523  * system needs to know when such changes happen.
1524  *
1525  * This is a blocking function.
1526  *
1527  * \param dev a device handle
1528  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1529  * previously-claimed interface
1530  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1531  * setting to activate
1532  * \returns 0 on success
1533  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1534  * requested alternate setting does not exist
1535  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1536  * \returns another LIBUSB_ERROR code on other failure
1537  */
1538 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
1539         int interface_number, int alternate_setting)
1540 {
1541         usbi_dbg("interface %d altsetting %d",
1542                 interface_number, alternate_setting);
1543         if (interface_number >= USB_MAXINTERFACES)
1544                 return LIBUSB_ERROR_INVALID_PARAM;
1545
1546         usbi_mutex_lock(&dev->lock);
1547         if (!dev->dev->attached) {
1548                 usbi_mutex_unlock(&dev->lock);
1549                 return LIBUSB_ERROR_NO_DEVICE;
1550         }
1551
1552         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1553                 usbi_mutex_unlock(&dev->lock);
1554                 return LIBUSB_ERROR_NOT_FOUND;
1555         }
1556         usbi_mutex_unlock(&dev->lock);
1557
1558         return usbi_backend->set_interface_altsetting(dev, interface_number,
1559                 alternate_setting);
1560 }
1561
1562 /** \ingroup dev
1563  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1564  * are unable to receive or transmit data until the halt condition is stalled.
1565  *
1566  * You should cancel all pending transfers before attempting to clear the halt
1567  * condition.
1568  *
1569  * This is a blocking function.
1570  *
1571  * \param dev a device handle
1572  * \param endpoint the endpoint to clear halt status
1573  * \returns 0 on success
1574  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1575  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1576  * \returns another LIBUSB_ERROR code on other failure
1577  */
1578 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
1579         unsigned char endpoint)
1580 {
1581         usbi_dbg("endpoint %x", endpoint);
1582         if (!dev->dev->attached)
1583                 return LIBUSB_ERROR_NO_DEVICE;
1584
1585         return usbi_backend->clear_halt(dev, endpoint);
1586 }
1587
1588 /** \ingroup dev
1589  * Perform a USB port reset to reinitialize a device. The system will attempt
1590  * to restore the previous configuration and alternate settings after the
1591  * reset has completed.
1592  *
1593  * If the reset fails, the descriptors change, or the previous state cannot be
1594  * restored, the device will appear to be disconnected and reconnected. This
1595  * means that the device handle is no longer valid (you should close it) and
1596  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1597  * when this is the case.
1598  *
1599  * This is a blocking function which usually incurs a noticeable delay.
1600  *
1601  * \param dev a handle of the device to reset
1602  * \returns 0 on success
1603  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1604  * device has been disconnected
1605  * \returns another LIBUSB_ERROR code on other failure
1606  */
1607 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
1608 {
1609         usbi_dbg("");
1610         if (!dev->dev->attached)
1611                 return LIBUSB_ERROR_NO_DEVICE;
1612
1613         return usbi_backend->reset_device(dev);
1614 }
1615
1616 /** \ingroup dev
1617  * Determine if a kernel driver is active on an interface. If a kernel driver
1618  * is active, you cannot claim the interface, and libusbx will be unable to
1619  * perform I/O.
1620  *
1621  * This functionality is not available on Windows.
1622  *
1623  * \param dev a device handle
1624  * \param interface_number the interface to check
1625  * \returns 0 if no kernel driver is active
1626  * \returns 1 if a kernel driver is active
1627  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1628  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1629  * is not available
1630  * \returns another LIBUSB_ERROR code on other failure
1631  * \see libusb_detach_kernel_driver()
1632  */
1633 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
1634         int interface_number)
1635 {
1636         usbi_dbg("interface %d", interface_number);
1637
1638         if (!dev->dev->attached)
1639                 return LIBUSB_ERROR_NO_DEVICE;
1640
1641         if (usbi_backend->kernel_driver_active)
1642                 return usbi_backend->kernel_driver_active(dev, interface_number);
1643         else
1644                 return LIBUSB_ERROR_NOT_SUPPORTED;
1645 }
1646
1647 /** \ingroup dev
1648  * Detach a kernel driver from an interface. If successful, you will then be
1649  * able to claim the interface and perform I/O.
1650  *
1651  * This functionality is not available on Darwin or Windows.
1652  *
1653  * Note that libusbx itself also talks to the device through a special kernel
1654  * driver, if this driver is already attached to the device, this call will
1655  * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1656  *
1657  * \param dev a device handle
1658  * \param interface_number the interface to detach the driver from
1659  * \returns 0 on success
1660  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1661  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1662  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1663  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1664  * is not available
1665  * \returns another LIBUSB_ERROR code on other failure
1666  * \see libusb_kernel_driver_active()
1667  */
1668 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
1669         int interface_number)
1670 {
1671         usbi_dbg("interface %d", interface_number);
1672
1673         if (!dev->dev->attached)
1674                 return LIBUSB_ERROR_NO_DEVICE;
1675
1676         if (usbi_backend->detach_kernel_driver)
1677                 return usbi_backend->detach_kernel_driver(dev, interface_number);
1678         else
1679                 return LIBUSB_ERROR_NOT_SUPPORTED;
1680 }
1681
1682 /** \ingroup dev
1683  * Re-attach an interface's kernel driver, which was previously detached
1684  * using libusb_detach_kernel_driver(). This call is only effective on
1685  * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1686  *
1687  * This functionality is not available on Darwin or Windows.
1688  *
1689  * \param dev a device handle
1690  * \param interface_number the interface to attach the driver from
1691  * \returns 0 on success
1692  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1693  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1694  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1695  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1696  * is not available
1697  * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1698  * interface is claimed by a program or driver
1699  * \returns another LIBUSB_ERROR code on other failure
1700  * \see libusb_kernel_driver_active()
1701  */
1702 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
1703         int interface_number)
1704 {
1705         usbi_dbg("interface %d", interface_number);
1706
1707         if (!dev->dev->attached)
1708                 return LIBUSB_ERROR_NO_DEVICE;
1709
1710         if (usbi_backend->attach_kernel_driver)
1711                 return usbi_backend->attach_kernel_driver(dev, interface_number);
1712         else
1713                 return LIBUSB_ERROR_NOT_SUPPORTED;
1714 }
1715
1716 /** \ingroup dev
1717  * Enable/disable libusbx's automatic kernel driver detachment. When this is
1718  * enabled libusbx will automatically detach the kernel driver on an interface
1719  * when claiming the interface, and attach it when releasing the interface.
1720  *
1721  * Automatic kernel driver detachment is disabled on newly opened device
1722  * handles by default.
1723  *
1724  * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
1725  * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusbx will
1726  * continue as if this function was never called.
1727  *
1728  * \param dev a device handle
1729  * \param enable whether to enable or disable auto kernel driver detachment
1730  *
1731  * \returns LIBUSB_SUCCESS on success
1732  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1733  * is not available
1734  * \see libusb_claim_interface()
1735  * \see libusb_release_interface()
1736  * \see libusb_set_configuration()
1737  */
1738 int API_EXPORTED libusb_set_auto_detach_kernel_driver(
1739         libusb_device_handle *dev, int enable)
1740 {
1741         if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
1742                 return LIBUSB_ERROR_NOT_SUPPORTED;
1743
1744         dev->auto_detach_kernel_driver = enable;
1745         return LIBUSB_SUCCESS;
1746 }
1747
1748 /** \ingroup lib
1749  * Set log message verbosity.
1750  *
1751  * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
1752  * printed. If you choose to increase the message verbosity level, ensure
1753  * that your application does not close the stdout/stderr file descriptors.
1754  *
1755  * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusbx is conservative
1756  * with its message logging and most of the time, will only log messages that
1757  * explain error conditions and other oddities. This will help you debug
1758  * your software.
1759  *
1760  * If the LIBUSB_DEBUG environment variable was set when libusbx was
1761  * initialized, this function does nothing: the message verbosity is fixed
1762  * to the value in the environment variable.
1763  *
1764  * If libusbx was compiled without any message logging, this function does
1765  * nothing: you'll never get any messages.
1766  *
1767  * If libusbx was compiled with verbose debug message logging, this function
1768  * does nothing: you'll always get messages from all levels.
1769  *
1770  * \param ctx the context to operate on, or NULL for the default context
1771  * \param level debug level to set
1772  */
1773 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
1774 {
1775         USBI_GET_CONTEXT(ctx);
1776         if (!ctx->debug_fixed)
1777                 ctx->debug = level;
1778 }
1779
1780 /** \ingroup lib
1781  * Initialize libusb. This function must be called before calling any other
1782  * libusbx function.
1783  *
1784  * If you do not provide an output location for a context pointer, a default
1785  * context will be created. If there was already a default context, it will
1786  * be reused (and nothing will be initialized/reinitialized).
1787  *
1788  * \param context Optional output location for context pointer.
1789  * Only valid on return code 0.
1790  * \returns 0 on success, or a LIBUSB_ERROR code on failure
1791  * \see contexts
1792  */
1793 int API_EXPORTED libusb_init(libusb_context **context)
1794 {
1795         struct libusb_device *dev, *next;
1796         char *dbg = getenv("LIBUSB_DEBUG");
1797         struct libusb_context *ctx;
1798         static int first_init = 1;
1799         int r = 0;
1800
1801         usbi_mutex_static_lock(&default_context_lock);
1802
1803         if (!timestamp_origin.tv_sec) {
1804                 usbi_gettimeofday(&timestamp_origin, NULL);
1805         }
1806
1807         if (!context && usbi_default_context) {
1808                 usbi_dbg("reusing default context");
1809                 default_context_refcnt++;
1810                 usbi_mutex_static_unlock(&default_context_lock);
1811                 return 0;
1812         }
1813
1814         ctx = calloc(1, sizeof(*ctx));
1815         if (!ctx) {
1816                 r = LIBUSB_ERROR_NO_MEM;
1817                 goto err_unlock;
1818         }
1819
1820 #ifdef ENABLE_DEBUG_LOGGING
1821         ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
1822 #endif
1823
1824         if (dbg) {
1825                 ctx->debug = atoi(dbg);
1826                 if (ctx->debug)
1827                         ctx->debug_fixed = 1;
1828         }
1829
1830         /* default context should be initialized before calling usbi_dbg */
1831         if (!usbi_default_context) {
1832                 usbi_default_context = ctx;
1833                 default_context_refcnt++;
1834                 usbi_dbg("created default context");
1835         }
1836
1837         usbi_dbg("libusbx v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
1838                 libusb_version_internal.micro, libusb_version_internal.nano);
1839
1840         usbi_mutex_init(&ctx->usb_devs_lock, NULL);
1841         usbi_mutex_init(&ctx->open_devs_lock, NULL);
1842         usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
1843         list_init(&ctx->usb_devs);
1844         list_init(&ctx->open_devs);
1845         list_init(&ctx->hotplug_cbs);
1846
1847         usbi_mutex_static_lock(&active_contexts_lock);
1848         if (first_init) {
1849                 first_init = 0;
1850                 list_init (&active_contexts_list);
1851         }
1852         list_add (&ctx->list, &active_contexts_list);
1853         usbi_mutex_static_unlock(&active_contexts_lock);
1854
1855         if (usbi_backend->init) {
1856                 r = usbi_backend->init(ctx);
1857                 if (r)
1858                         goto err_free_ctx;
1859         }
1860
1861         r = usbi_io_init(ctx);
1862         if (r < 0)
1863                 goto err_backend_exit;
1864
1865         usbi_mutex_static_unlock(&default_context_lock);
1866
1867         if (context)
1868                 *context = ctx;
1869
1870         return 0;
1871
1872 err_backend_exit:
1873         if (usbi_backend->exit)
1874                 usbi_backend->exit();
1875 err_free_ctx:
1876         if (ctx == usbi_default_context)
1877                 usbi_default_context = NULL;
1878
1879         usbi_mutex_static_lock(&active_contexts_lock);
1880         list_del (&ctx->list);
1881         usbi_mutex_static_unlock(&active_contexts_lock);
1882
1883         usbi_mutex_lock(&ctx->usb_devs_lock);
1884         list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
1885                 list_del(&dev->list);
1886                 libusb_unref_device(dev);
1887         }
1888         usbi_mutex_unlock(&ctx->usb_devs_lock);
1889
1890         usbi_mutex_destroy(&ctx->open_devs_lock);
1891         usbi_mutex_destroy(&ctx->usb_devs_lock);
1892         usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
1893
1894         free(ctx);
1895 err_unlock:
1896         usbi_mutex_static_unlock(&default_context_lock);
1897         return r;
1898 }
1899
1900 /** \ingroup lib
1901  * Deinitialize libusb. Should be called after closing all open devices and
1902  * before your application terminates.
1903  * \param ctx the context to deinitialize, or NULL for the default context
1904  */
1905 void API_EXPORTED libusb_exit(struct libusb_context *ctx)
1906 {
1907         struct libusb_device *dev, *next;
1908
1909         usbi_dbg("");
1910         USBI_GET_CONTEXT(ctx);
1911
1912         /* if working with default context, only actually do the deinitialization
1913          * if we're the last user */
1914         usbi_mutex_static_lock(&default_context_lock);
1915         if (ctx == usbi_default_context) {
1916                 if (--default_context_refcnt > 0) {
1917                         usbi_dbg("not destroying default context");
1918                         usbi_mutex_static_unlock(&default_context_lock);
1919                         return;
1920                 }
1921                 usbi_dbg("destroying default context");
1922                 usbi_default_context = NULL;
1923         }
1924         usbi_mutex_static_unlock(&default_context_lock);
1925
1926         usbi_mutex_static_lock(&active_contexts_lock);
1927         list_del (&ctx->list);
1928         usbi_mutex_static_unlock(&active_contexts_lock);
1929
1930         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1931                 usbi_hotplug_deregister_all(ctx);
1932                 usbi_mutex_lock(&ctx->usb_devs_lock);
1933                 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
1934                         list_del(&dev->list);
1935                         libusb_unref_device(dev);
1936                 }
1937                 usbi_mutex_unlock(&ctx->usb_devs_lock);
1938         }
1939
1940         /* a few sanity checks. don't bother with locking because unless
1941          * there is an application bug, nobody will be accessing these. */
1942         if (!list_empty(&ctx->usb_devs))
1943                 usbi_warn(ctx, "some libusb_devices were leaked");
1944         if (!list_empty(&ctx->open_devs))
1945                 usbi_warn(ctx, "application left some devices open");
1946
1947         usbi_io_exit(ctx);
1948         if (usbi_backend->exit)
1949                 usbi_backend->exit();
1950
1951         usbi_mutex_destroy(&ctx->open_devs_lock);
1952         usbi_mutex_destroy(&ctx->usb_devs_lock);
1953         usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
1954         free(ctx);
1955 }
1956
1957 /** \ingroup misc
1958  * Check at runtime if the loaded library has a given capability.
1959  * This call should be performed after \ref libusb_init(), to ensure the
1960  * backend has updated its capability set.
1961  *
1962  * \param capability the \ref libusb_capability to check for
1963  * \returns nonzero if the running library has the capability, 0 otherwise
1964  */
1965 int API_EXPORTED libusb_has_capability(uint32_t capability)
1966 {
1967         switch (capability) {
1968         case LIBUSB_CAP_HAS_CAPABILITY:
1969                 return 1;
1970         case LIBUSB_CAP_HAS_HOTPLUG:
1971                 return !(usbi_backend->get_device_list);
1972         case LIBUSB_CAP_HAS_HID_ACCESS:
1973                 return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
1974         case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
1975                 return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
1976         }
1977         return 0;
1978 }
1979
1980 /* this is defined in libusbi.h if needed */
1981 #ifdef LIBUSB_GETTIMEOFDAY_WIN32
1982 /*
1983  * gettimeofday
1984  * Implementation according to:
1985  * The Open Group Base Specifications Issue 6
1986  * IEEE Std 1003.1, 2004 Edition
1987  */
1988
1989 /*
1990  *  THIS SOFTWARE IS NOT COPYRIGHTED
1991  *
1992  *  This source code is offered for use in the public domain. You may
1993  *  use, modify or distribute it freely.
1994  *
1995  *  This code is distributed in the hope that it will be useful but
1996  *  WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
1997  *  DISCLAIMED. This includes but is not limited to warranties of
1998  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1999  *
2000  *  Contributed by:
2001  *  Danny Smith <dannysmith@users.sourceforge.net>
2002  */
2003
2004 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
2005 #define _W32_FT_OFFSET (116444736000000000)
2006
2007 int usbi_gettimeofday(struct timeval *tp, void *tzp)
2008 {
2009         union {
2010                 unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
2011                 FILETIME ft;
2012         } _now;
2013         UNUSED(tzp);
2014
2015         if(tp) {
2016 #if defined(OS_WINCE)
2017                 SYSTEMTIME st;
2018                 GetSystemTime(&st);
2019                 SystemTimeToFileTime(&st, &_now.ft);
2020 #else
2021                 GetSystemTimeAsFileTime (&_now.ft);
2022 #endif
2023                 tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
2024                 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
2025         }
2026         /* Always return 0 as per Open Group Base Specifications Issue 6.
2027            Do not set errno on error.  */
2028         return 0;
2029 }
2030 #endif
2031
2032 static void usbi_log_str(struct libusb_context *ctx,
2033         enum libusb_log_level level, const char * str)
2034 {
2035 #if defined(USE_SYSTEM_LOGGING_FACILITY)
2036 #if defined(OS_WINDOWS) || defined(OS_WINCE)
2037         /* Windows CE only supports the Unicode version of OutputDebugString. */
2038         WCHAR wbuf[USBI_MAX_LOG_LEN];
2039         MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
2040         OutputDebugStringW(wbuf);
2041 #elif defined(__ANDROID__)
2042         int priority = ANDROID_LOG_UNKNOWN;
2043         switch (level) {
2044         case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2045         case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2046         case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2047         case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2048         }
2049         __android_log_write(priority, "libusb", str);
2050 #elif defined(HAVE_SYSLOG_FUNC)
2051         int syslog_level = LOG_INFO;
2052         switch (level) {
2053         case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2054         case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2055         case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2056         case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2057         }
2058         syslog(syslog_level, "%s", str);
2059 #else /* All of gcc, Clang, XCode seem to use #warning */
2060 #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2061         fputs(str, stderr);
2062 #endif
2063 #else
2064         fputs(str, stderr);
2065 #endif /* USE_SYSTEM_LOGGING_FACILITY */
2066         UNUSED(ctx);
2067         UNUSED(level);
2068 }
2069
2070 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
2071         const char *function, const char *format, va_list args)
2072 {
2073         const char *prefix = "";
2074         char buf[USBI_MAX_LOG_LEN];
2075         struct timeval now;
2076         int global_debug, header_len, text_len;
2077         static int has_debug_header_been_displayed = 0;
2078
2079 #ifdef ENABLE_DEBUG_LOGGING
2080         global_debug = 1;
2081         UNUSED(ctx);
2082 #else
2083         USBI_GET_CONTEXT(ctx);
2084         if (ctx == NULL)
2085                 return;
2086         global_debug = (ctx->debug == LIBUSB_LOG_LEVEL_DEBUG);
2087         if (!ctx->debug)
2088                 return;
2089         if (level == LIBUSB_LOG_LEVEL_WARNING && ctx->debug < LIBUSB_LOG_LEVEL_WARNING)
2090                 return;
2091         if (level == LIBUSB_LOG_LEVEL_INFO && ctx->debug < LIBUSB_LOG_LEVEL_INFO)
2092                 return;
2093         if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx->debug < LIBUSB_LOG_LEVEL_DEBUG)
2094                 return;
2095 #endif
2096
2097         usbi_gettimeofday(&now, NULL);
2098         if ((global_debug) && (!has_debug_header_been_displayed)) {
2099                 has_debug_header_been_displayed = 1;
2100                 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>\n");
2101                 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------\n");
2102         }
2103         if (now.tv_usec < timestamp_origin.tv_usec) {
2104                 now.tv_sec--;
2105                 now.tv_usec += 1000000;
2106         }
2107         now.tv_sec -= timestamp_origin.tv_sec;
2108         now.tv_usec -= timestamp_origin.tv_usec;
2109
2110         switch (level) {
2111         case LIBUSB_LOG_LEVEL_INFO:
2112                 prefix = "info";
2113                 break;
2114         case LIBUSB_LOG_LEVEL_WARNING:
2115                 prefix = "warning";
2116                 break;
2117         case LIBUSB_LOG_LEVEL_ERROR:
2118                 prefix = "error";
2119                 break;
2120         case LIBUSB_LOG_LEVEL_DEBUG:
2121                 prefix = "debug";
2122                 break;
2123         case LIBUSB_LOG_LEVEL_NONE:
2124                 return;
2125         default:
2126                 prefix = "unknown";
2127                 break;
2128         }
2129
2130         if (global_debug) {
2131                 header_len = snprintf(buf, sizeof(buf),
2132                         "[%2d.%06d] [%08x] libusbx: %s [%s] ",
2133                         (int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
2134         } else {
2135                 header_len = snprintf(buf, sizeof(buf),
2136                         "libusbx: %s [%s] ", prefix, function);
2137         }
2138
2139         if (header_len < 0 || header_len >= sizeof(buf)) {
2140                 /* Somehow snprintf failed to write to the buffer,
2141                  * remove the header so something useful is output. */
2142                 header_len = 0;
2143         }
2144         /* Make sure buffer is NUL terminated */
2145         buf[header_len] = '\0';
2146         text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
2147                 format, args);
2148         if (text_len < 0 || text_len + header_len >= sizeof(buf)) {
2149                 /* Truncated log output. On some platforms a -1 return value means
2150                  * that the output was truncated. */
2151                 text_len = sizeof(buf) - header_len;
2152         }
2153         if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
2154                 /* Need to truncate the text slightly to fit on the terminator. */
2155                 text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
2156         }
2157         strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2158
2159         usbi_log_str(ctx, level, buf);
2160 }
2161
2162 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2163         const char *function, const char *format, ...)
2164 {
2165         va_list args;
2166
2167         va_start (args, format);
2168         usbi_log_v(ctx, level, function, format, args);
2169         va_end (args);
2170 }
2171
2172 /** \ingroup misc
2173  * Returns a constant NULL-terminated string with the ASCII name of a libusbx
2174  * error or transfer status code. The caller must not free() the returned
2175  * string.
2176  *
2177  * \param error_code The \ref libusb_error or libusb_transfer_status code to
2178  * return the name of.
2179  * \returns The error name, or the string **UNKNOWN** if the value of
2180  * error_code is not a known error / status code.
2181  */
2182 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
2183 {
2184         switch (error_code) {
2185         case LIBUSB_ERROR_IO:
2186                 return "LIBUSB_ERROR_IO";
2187         case LIBUSB_ERROR_INVALID_PARAM:
2188                 return "LIBUSB_ERROR_INVALID_PARAM";
2189         case LIBUSB_ERROR_ACCESS:
2190                 return "LIBUSB_ERROR_ACCESS";
2191         case LIBUSB_ERROR_NO_DEVICE:
2192                 return "LIBUSB_ERROR_NO_DEVICE";
2193         case LIBUSB_ERROR_NOT_FOUND:
2194                 return "LIBUSB_ERROR_NOT_FOUND";
2195         case LIBUSB_ERROR_BUSY:
2196                 return "LIBUSB_ERROR_BUSY";
2197         case LIBUSB_ERROR_TIMEOUT:
2198                 return "LIBUSB_ERROR_TIMEOUT";
2199         case LIBUSB_ERROR_OVERFLOW:
2200                 return "LIBUSB_ERROR_OVERFLOW";
2201         case LIBUSB_ERROR_PIPE:
2202                 return "LIBUSB_ERROR_PIPE";
2203         case LIBUSB_ERROR_INTERRUPTED:
2204                 return "LIBUSB_ERROR_INTERRUPTED";
2205         case LIBUSB_ERROR_NO_MEM:
2206                 return "LIBUSB_ERROR_NO_MEM";
2207         case LIBUSB_ERROR_NOT_SUPPORTED:
2208                 return "LIBUSB_ERROR_NOT_SUPPORTED";
2209         case LIBUSB_ERROR_OTHER:
2210                 return "LIBUSB_ERROR_OTHER";
2211
2212         case LIBUSB_TRANSFER_ERROR:
2213                 return "LIBUSB_TRANSFER_ERROR";
2214         case LIBUSB_TRANSFER_TIMED_OUT:
2215                 return "LIBUSB_TRANSFER_TIMED_OUT";
2216         case LIBUSB_TRANSFER_CANCELLED:
2217                 return "LIBUSB_TRANSFER_CANCELLED";
2218         case LIBUSB_TRANSFER_STALL:
2219                 return "LIBUSB_TRANSFER_STALL";
2220         case LIBUSB_TRANSFER_NO_DEVICE:
2221                 return "LIBUSB_TRANSFER_NO_DEVICE";
2222         case LIBUSB_TRANSFER_OVERFLOW:
2223                 return "LIBUSB_TRANSFER_OVERFLOW";
2224
2225         case 0:
2226                 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2227         default:
2228                 return "**UNKNOWN**";
2229         }
2230 }
2231
2232 /** \ingroup misc
2233  * Returns a pointer to const struct libusb_version with the version
2234  * (major, minor, micro, nano and rc) of the running library.
2235  */
2236 DEFAULT_VISIBILITY
2237 const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
2238 {
2239         return &libusb_version_internal;
2240 }