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