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