Coverage Report

Created: 2025-11-14 07:10

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