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