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