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