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