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