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