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