usb 1.7.2-prebuild

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/.github/workflows/prebuild.yml +62 -0
  2. package/.gitmodules +3 -0
  3. package/LICENSE +7 -0
  4. package/Readme.md +339 -0
  5. package/binding.gyp +90 -0
  6. package/libusb/.gitattributes +11 -0
  7. package/libusb/.private/README.txt +5 -0
  8. package/libusb/.private/bd.cmd +89 -0
  9. package/libusb/.private/bm.sh +54 -0
  10. package/libusb/.private/bwince.cmd +57 -0
  11. package/libusb/.private/post-rewrite.sh +28 -0
  12. package/libusb/.private/pre-commit.sh +42 -0
  13. package/libusb/.private/wbs.txt +61 -0
  14. package/libusb/.private/wbs_wince.txt +42 -0
  15. package/libusb/AUTHORS +78 -0
  16. package/libusb/COPYING +504 -0
  17. package/libusb/ChangeLog +211 -0
  18. package/libusb/INSTALL +234 -0
  19. package/libusb/INSTALL_WIN.txt +73 -0
  20. package/libusb/Makefile.am +28 -0
  21. package/libusb/NEWS +2 -0
  22. package/libusb/PORTING +94 -0
  23. package/libusb/README +28 -0
  24. package/libusb/README.git +41 -0
  25. package/libusb/TODO +2 -0
  26. package/libusb/Xcode/common.xcconfig +49 -0
  27. package/libusb/Xcode/debug.xcconfig +29 -0
  28. package/libusb/Xcode/libusb.xcconfig +21 -0
  29. package/libusb/Xcode/libusb.xcodeproj/project.pbxproj +1 -0
  30. package/libusb/Xcode/libusb_debug.xcconfig +21 -0
  31. package/libusb/Xcode/libusb_release.xcconfig +21 -0
  32. package/libusb/Xcode/release.xcconfig +30 -0
  33. package/libusb/android/README +114 -0
  34. package/libusb/android/jni/Android.mk +23 -0
  35. package/libusb/android/jni/Application.mk +24 -0
  36. package/libusb/android/jni/examples.mk +134 -0
  37. package/libusb/android/jni/libusb.mk +54 -0
  38. package/libusb/android/jni/tests.mk +56 -0
  39. package/libusb/autogen.sh +8 -0
  40. package/libusb/bootstrap.sh +19 -0
  41. package/libusb/configure.ac +304 -0
  42. package/libusb/doc/Makefile.am +9 -0
  43. package/libusb/doc/doxygen.cfg.in +1288 -0
  44. package/libusb/doc/libusb.png +0 -0
  45. package/libusb/examples/Makefile.am +19 -0
  46. package/libusb/examples/dpfp.c +506 -0
  47. package/libusb/examples/dpfp_threaded.c +544 -0
  48. package/libusb/examples/ezusb.c +831 -0
  49. package/libusb/examples/ezusb.h +120 -0
  50. package/libusb/examples/fxload.c +287 -0
  51. package/libusb/examples/getopt/getopt.c +1060 -0
  52. package/libusb/examples/getopt/getopt.h +180 -0
  53. package/libusb/examples/getopt/getopt1.c +188 -0
  54. package/libusb/examples/hotplugtest.c +104 -0
  55. package/libusb/examples/listdevs.c +71 -0
  56. package/libusb/examples/sam3u_benchmark.c +193 -0
  57. package/libusb/examples/xusb.c +1129 -0
  58. package/libusb/libusb/Makefile.am +75 -0
  59. package/libusb/libusb/core.c +2342 -0
  60. package/libusb/libusb/descriptor.c +1199 -0
  61. package/libusb/libusb/hotplug.c +327 -0
  62. package/libusb/libusb/hotplug.h +82 -0
  63. package/libusb/libusb/io.c +2631 -0
  64. package/libusb/libusb/libusb-1.0.def +166 -0
  65. package/libusb/libusb/libusb-1.0.rc +61 -0
  66. package/libusb/libusb/libusb.h +1998 -0
  67. package/libusb/libusb/libusbi.h +1040 -0
  68. package/libusb/libusb/os/darwin_usb.c +2009 -0
  69. package/libusb/libusb/os/darwin_usb.h +162 -0
  70. package/libusb/libusb/os/linux_netlink.c +369 -0
  71. package/libusb/libusb/os/linux_udev.c +307 -0
  72. package/libusb/libusb/os/linux_usbfs.c +2695 -0
  73. package/libusb/libusb/os/linux_usbfs.h +192 -0
  74. package/libusb/libusb/os/netbsd_usb.c +738 -0
  75. package/libusb/libusb/os/openbsd_usb.c +832 -0
  76. package/libusb/libusb/os/poll_posix.c +51 -0
  77. package/libusb/libusb/os/poll_posix.h +11 -0
  78. package/libusb/libusb/os/poll_windows.c +796 -0
  79. package/libusb/libusb/os/poll_windows.h +131 -0
  80. package/libusb/libusb/os/threads_posix.c +82 -0
  81. package/libusb/libusb/os/threads_posix.h +50 -0
  82. package/libusb/libusb/os/threads_windows.c +212 -0
  83. package/libusb/libusb/os/threads_windows.h +87 -0
  84. package/libusb/libusb/os/wince_usb.c +1032 -0
  85. package/libusb/libusb/os/wince_usb.h +131 -0
  86. package/libusb/libusb/os/windows_common.h +108 -0
  87. package/libusb/libusb/os/windows_usb.c +5347 -0
  88. package/libusb/libusb/os/windows_usb.h +971 -0
  89. package/libusb/libusb/strerror.c +199 -0
  90. package/libusb/libusb/sync.c +307 -0
  91. package/libusb/libusb/version.h +18 -0
  92. package/libusb/libusb/version_nano.h +1 -0
  93. package/libusb/libusb-1.0.pc.in +11 -0
  94. package/libusb/msvc/config.h +50 -0
  95. package/libusb/msvc/ddk_build.cmd +175 -0
  96. package/libusb/msvc/errno.h +102 -0
  97. package/libusb/msvc/fxload_2010.vcxproj +170 -0
  98. package/libusb/msvc/fxload_2010.vcxproj.filters +25 -0
  99. package/libusb/msvc/fxload_2012.vcxproj +174 -0
  100. package/libusb/msvc/fxload_2012.vcxproj.filters +25 -0
  101. package/libusb/msvc/fxload_2013.vcxproj +174 -0
  102. package/libusb/msvc/fxload_sources +23 -0
  103. package/libusb/msvc/getopt_2005.vcproj +288 -0
  104. package/libusb/msvc/getopt_2010.vcxproj +131 -0
  105. package/libusb/msvc/getopt_2010.vcxproj.filters +26 -0
  106. package/libusb/msvc/getopt_2012.vcxproj +136 -0
  107. package/libusb/msvc/getopt_2012.vcxproj.filters +26 -0
  108. package/libusb/msvc/getopt_2013.vcxproj +136 -0
  109. package/libusb/msvc/getopt_sources +20 -0
  110. package/libusb/msvc/hotplugtest_2010.vcxproj +163 -0
  111. package/libusb/msvc/hotplugtest_2010.vcxproj.filters +14 -0
  112. package/libusb/msvc/hotplugtest_2012.vcxproj +167 -0
  113. package/libusb/msvc/hotplugtest_2012.vcxproj.filters +14 -0
  114. package/libusb/msvc/hotplugtest_2013.vcxproj +167 -0
  115. package/libusb/msvc/hotplugtest_sources +20 -0
  116. package/libusb/msvc/inttypes.h +295 -0
  117. package/libusb/msvc/libusb.dsw +71 -0
  118. package/libusb/msvc/libusb_2005.sln +95 -0
  119. package/libusb/msvc/libusb_2010.sln +94 -0
  120. package/libusb/msvc/libusb_2012.sln +94 -0
  121. package/libusb/msvc/libusb_2013.sln +100 -0
  122. package/libusb/msvc/libusb_2015.sln +100 -0
  123. package/libusb/msvc/libusb_dll.dsp +194 -0
  124. package/libusb/msvc/libusb_dll_2005.vcproj +436 -0
  125. package/libusb/msvc/libusb_dll_2010.vcxproj +170 -0
  126. package/libusb/msvc/libusb_dll_2010.vcxproj.filters +81 -0
  127. package/libusb/msvc/libusb_dll_2012.vcxproj +175 -0
  128. package/libusb/msvc/libusb_dll_2012.vcxproj.filters +84 -0
  129. package/libusb/msvc/libusb_dll_2013.vcxproj +175 -0
  130. package/libusb/msvc/libusb_dll_wince.vcproj +1243 -0
  131. package/libusb/msvc/libusb_sources +38 -0
  132. package/libusb/msvc/libusb_static.dsp +174 -0
  133. package/libusb/msvc/libusb_static_2005.vcproj +362 -0
  134. package/libusb/msvc/libusb_static_2010.vcxproj +156 -0
  135. package/libusb/msvc/libusb_static_2010.vcxproj.filters +74 -0
  136. package/libusb/msvc/libusb_static_2012.vcxproj +160 -0
  137. package/libusb/msvc/libusb_static_2012.vcxproj.filters +74 -0
  138. package/libusb/msvc/libusb_static_2013.vcxproj +160 -0
  139. package/libusb/msvc/libusb_static_wince.vcproj +1185 -0
  140. package/libusb/msvc/libusb_wince.sln +246 -0
  141. package/libusb/msvc/listdevs.dsp +103 -0
  142. package/libusb/msvc/listdevs_2005.vcproj +360 -0
  143. package/libusb/msvc/listdevs_2010.vcxproj +165 -0
  144. package/libusb/msvc/listdevs_2010.vcxproj.filters +14 -0
  145. package/libusb/msvc/listdevs_2012.vcxproj +169 -0
  146. package/libusb/msvc/listdevs_2012.vcxproj.filters +14 -0
  147. package/libusb/msvc/listdevs_2013.vcxproj +169 -0
  148. package/libusb/msvc/listdevs_sources +19 -0
  149. package/libusb/msvc/listdevs_wince.vcproj +1120 -0
  150. package/libusb/msvc/missing.c +80 -0
  151. package/libusb/msvc/missing.h +32 -0
  152. package/libusb/msvc/stdint.h +256 -0
  153. package/libusb/msvc/stress_2005.vcproj +390 -0
  154. package/libusb/msvc/stress_2010.vcxproj +167 -0
  155. package/libusb/msvc/stress_2010.vcxproj.filters +25 -0
  156. package/libusb/msvc/stress_2012.vcxproj +171 -0
  157. package/libusb/msvc/stress_2012.vcxproj.filters +25 -0
  158. package/libusb/msvc/stress_2013.vcxproj +171 -0
  159. package/libusb/msvc/stress_wince.vcproj +1128 -0
  160. package/libusb/msvc/xusb.dsp +102 -0
  161. package/libusb/msvc/xusb_2005.vcproj +344 -0
  162. package/libusb/msvc/xusb_2010.vcxproj +163 -0
  163. package/libusb/msvc/xusb_2010.vcxproj.filters +14 -0
  164. package/libusb/msvc/xusb_2012.vcxproj +167 -0
  165. package/libusb/msvc/xusb_2012.vcxproj.filters +14 -0
  166. package/libusb/msvc/xusb_2013.vcxproj +167 -0
  167. package/libusb/msvc/xusb_sources +20 -0
  168. package/libusb/msvc/xusb_wince.vcproj +1120 -0
  169. package/libusb/tests/Makefile.am +6 -0
  170. package/libusb/tests/libusb_testlib.h +107 -0
  171. package/libusb/tests/stress.c +160 -0
  172. package/libusb/tests/testlib.c +281 -0
  173. package/libusb.gypi +136 -0
  174. package/libusb_config/config.h +1 -0
  175. package/package.json +69 -0
  176. package/src/device.cc +412 -0
  177. package/src/helpers.h +64 -0
  178. package/src/node_usb.cc +319 -0
  179. package/src/node_usb.h +120 -0
  180. package/src/transfer.cc +148 -0
  181. package/src/uv_async_queue.h +33 -0
  182. package/test/usb.coffee +191 -0
  183. package/usb.js +524 -0
@@ -0,0 +1,2342 @@
1
+ /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2
+ /*
3
+ * Core functions for libusb
4
+ * Copyright © 2012-2013 Nathan Hjelm <hjelmn@cs.unm.edu>
5
+ * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
6
+ * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ */
22
+
23
+ #include "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)
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://libusb.info" };
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 libusb-1.0 API Reference
76
+ *
77
+ * \section intro Introduction
78
+ *
79
+ * libusb 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://libusb.info">libusb 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.libusb.info">libusb-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 libusb'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 libusb source distribution under
117
+ * the "examples" subdirectory. The libusb homepage includes a list of
118
+ * real-life project examples which use libusb.
119
+ *
120
+ * \section errorhandling Error handling
121
+ *
122
+ * libusb 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
+ * libusb 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, libusb 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
+ * libusb 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 libusb 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 libusb 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
+ * libusb 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
+ * libusb 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
+ * libusb 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. libusb 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 libusb 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
+ * -# libusb 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, libusb
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 libusb, 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 libusb 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, libusb is unable to do this in all situations. After
271
+ * the incomplete packet occurs, "surplus" data may be transferred. For recent
272
+ * versions of libusb, 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
+ * - libusb 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 libusb 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 libusb.
295
+ *
296
+ * libusb is written to allow for these multiple user scenarios. The two
297
+ * "instances" of libusb 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 libusb after one of them calls libusb_exit(), etc.
300
+ *
301
+ * This is made possible through libusb'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 libusb 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 libusb 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 libusb functions require a
321
+ * context pointer in their function definition. Internally, libusb 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 libusb. Initialization
329
+ * must be performed before using any libusb functionality, and similarly you
330
+ * must not call any libusb 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
+ * libusb 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
+ * libusb to open the device using the libusb_open() function. Assuming
404
+ * success, libusb 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. libusb 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, libusb 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
+
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. */
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
+
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. */
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
+
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
+
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. */
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 libusb'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. */
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 = libusb_ref_device(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
+ */
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
+ */
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
+ */
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
+ */
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 LIBUSB_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
+ */
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
+ struct libusb_context *ctx = DEVICE_CTX(dev);
779
+
780
+ if (port_numbers_len <= 0)
781
+ return LIBUSB_ERROR_INVALID_PARAM;
782
+
783
+ // HCDs can be listed as devices with port #0
784
+ while((dev) && (dev->port_number != 0)) {
785
+ if (--i < 0) {
786
+ usbi_warn(ctx, "port numbers array is too small");
787
+ return LIBUSB_ERROR_OVERFLOW;
788
+ }
789
+ port_numbers[i] = dev->port_number;
790
+ dev = dev->parent_dev;
791
+ }
792
+ if (i < port_numbers_len)
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
+ */
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 libusb 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
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
+ */
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
+ */
841
+ int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
842
+ {
843
+ return dev->speed;
844
+ }
845
+
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
+ */
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
+ r = LIBUSB_ERROR_NOT_FOUND;
904
+ goto out;
905
+ }
906
+
907
+ r = ep->wMaxPacketSize;
908
+
909
+ out:
910
+ libusb_free_config_descriptor(config);
911
+ return r;
912
+ }
913
+
914
+ /** \ingroup dev
915
+ * Calculate the maximum packet size which a specific endpoint is capable is
916
+ * sending or receiving in the duration of 1 microframe
917
+ *
918
+ * Only the active configuration is examined. The calculation is based on the
919
+ * wMaxPacketSize field in the endpoint descriptor as described in section
920
+ * 9.6.6 in the USB 2.0 specifications.
921
+ *
922
+ * If acting on an isochronous or interrupt endpoint, this function will
923
+ * multiply the value found in bits 0:10 by the number of transactions per
924
+ * microframe (determined by bits 11:12). Otherwise, this function just
925
+ * returns the numeric value found in bits 0:10.
926
+ *
927
+ * This function is useful for setting up isochronous transfers, for example
928
+ * you might pass the return value from this function to
929
+ * libusb_set_iso_packet_lengths() in order to set the length field of every
930
+ * isochronous packet in a transfer.
931
+ *
932
+ * Since v1.0.3.
933
+ *
934
+ * \param dev a device
935
+ * \param endpoint address of the endpoint in question
936
+ * \returns the maximum packet size which can be sent/received on this endpoint
937
+ * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
938
+ * \returns LIBUSB_ERROR_OTHER on other failure
939
+ */
940
+ int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
941
+ unsigned char endpoint)
942
+ {
943
+ struct libusb_config_descriptor *config;
944
+ const struct libusb_endpoint_descriptor *ep;
945
+ enum libusb_transfer_type ep_type;
946
+ uint16_t val;
947
+ int r;
948
+
949
+ r = libusb_get_active_config_descriptor(dev, &config);
950
+ if (r < 0) {
951
+ usbi_err(DEVICE_CTX(dev),
952
+ "could not retrieve active config descriptor");
953
+ return LIBUSB_ERROR_OTHER;
954
+ }
955
+
956
+ ep = find_endpoint(config, endpoint);
957
+ if (!ep) {
958
+ r = LIBUSB_ERROR_NOT_FOUND;
959
+ goto out;
960
+ }
961
+
962
+ val = ep->wMaxPacketSize;
963
+ ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
964
+
965
+ r = val & 0x07ff;
966
+ if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
967
+ || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
968
+ r *= (1 + ((val >> 11) & 3));
969
+
970
+ out:
971
+ libusb_free_config_descriptor(config);
972
+ return r;
973
+ }
974
+
975
+ /** \ingroup dev
976
+ * Increment the reference count of a device.
977
+ * \param dev the device to reference
978
+ * \returns the same device
979
+ */
980
+ DEFAULT_VISIBILITY
981
+ libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
982
+ {
983
+ usbi_mutex_lock(&dev->lock);
984
+ dev->refcnt++;
985
+ usbi_mutex_unlock(&dev->lock);
986
+ return dev;
987
+ }
988
+
989
+ /** \ingroup dev
990
+ * Decrement the reference count of a device. If the decrement operation
991
+ * causes the reference count to reach zero, the device shall be destroyed.
992
+ * \param dev the device to unreference
993
+ */
994
+ void API_EXPORTED libusb_unref_device(libusb_device *dev)
995
+ {
996
+ int refcnt;
997
+
998
+ if (!dev)
999
+ return;
1000
+
1001
+ usbi_mutex_lock(&dev->lock);
1002
+ refcnt = --dev->refcnt;
1003
+ usbi_mutex_unlock(&dev->lock);
1004
+
1005
+ if (refcnt == 0) {
1006
+ usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
1007
+
1008
+ libusb_unref_device(dev->parent_dev);
1009
+
1010
+ if (usbi_backend->destroy_device)
1011
+ usbi_backend->destroy_device(dev);
1012
+
1013
+ if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1014
+ /* backend does not support hotplug */
1015
+ usbi_disconnect_device(dev);
1016
+ }
1017
+
1018
+ usbi_mutex_destroy(&dev->lock);
1019
+ free(dev);
1020
+ }
1021
+ }
1022
+
1023
+ /*
1024
+ * Interrupt the iteration of the event handling thread, so that it picks
1025
+ * up the new fd.
1026
+ */
1027
+ void usbi_fd_notification(struct libusb_context *ctx)
1028
+ {
1029
+ unsigned char dummy = 1;
1030
+ ssize_t r;
1031
+
1032
+ if (ctx == NULL)
1033
+ return;
1034
+
1035
+ /* record that we are messing with poll fds */
1036
+ usbi_mutex_lock(&ctx->pollfd_modify_lock);
1037
+ ctx->pollfd_modify++;
1038
+ usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1039
+
1040
+ /* write some data on control pipe to interrupt event handlers */
1041
+ r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1042
+ if (r <= 0) {
1043
+ usbi_warn(ctx, "internal signalling write failed");
1044
+ usbi_mutex_lock(&ctx->pollfd_modify_lock);
1045
+ ctx->pollfd_modify--;
1046
+ usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1047
+ return;
1048
+ }
1049
+
1050
+ /* take event handling lock */
1051
+ libusb_lock_events(ctx);
1052
+
1053
+ /* read the dummy data */
1054
+ r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1055
+ if (r <= 0)
1056
+ usbi_warn(ctx, "internal signalling read failed");
1057
+
1058
+ /* we're done with modifying poll fds */
1059
+ usbi_mutex_lock(&ctx->pollfd_modify_lock);
1060
+ ctx->pollfd_modify--;
1061
+ usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1062
+
1063
+ /* Release event handling lock and wake up event waiters */
1064
+ libusb_unlock_events(ctx);
1065
+ }
1066
+
1067
+ /** \ingroup dev
1068
+ * Open a device and obtain a device handle. A handle allows you to perform
1069
+ * I/O on the device in question.
1070
+ *
1071
+ * Internally, this function adds a reference to the device and makes it
1072
+ * available to you through libusb_get_device(). This reference is removed
1073
+ * during libusb_close().
1074
+ *
1075
+ * This is a non-blocking function; no requests are sent over the bus.
1076
+ *
1077
+ * \param dev the device to open
1078
+ * \param handle output location for the returned device handle pointer. Only
1079
+ * populated when the return code is 0.
1080
+ * \returns 0 on success
1081
+ * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
1082
+ * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1083
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1084
+ * \returns another LIBUSB_ERROR code on other failure
1085
+ */
1086
+ int API_EXPORTED libusb_open(libusb_device *dev,
1087
+ libusb_device_handle **handle)
1088
+ {
1089
+ struct libusb_context *ctx = DEVICE_CTX(dev);
1090
+ struct libusb_device_handle *_handle;
1091
+ size_t priv_size = usbi_backend->device_handle_priv_size;
1092
+ int r;
1093
+ usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
1094
+
1095
+ if (!dev->attached) {
1096
+ return LIBUSB_ERROR_NO_DEVICE;
1097
+ }
1098
+
1099
+ _handle = malloc(sizeof(*_handle) + priv_size);
1100
+ if (!_handle)
1101
+ return LIBUSB_ERROR_NO_MEM;
1102
+
1103
+ r = usbi_mutex_init(&_handle->lock, NULL);
1104
+ if (r) {
1105
+ free(_handle);
1106
+ return LIBUSB_ERROR_OTHER;
1107
+ }
1108
+
1109
+ _handle->dev = libusb_ref_device(dev);
1110
+ _handle->auto_detach_kernel_driver = 0;
1111
+ _handle->claimed_interfaces = 0;
1112
+ memset(&_handle->os_priv, 0, priv_size);
1113
+
1114
+ r = usbi_backend->open(_handle);
1115
+ if (r < 0) {
1116
+ usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1117
+ libusb_unref_device(dev);
1118
+ usbi_mutex_destroy(&_handle->lock);
1119
+ free(_handle);
1120
+ return r;
1121
+ }
1122
+
1123
+ usbi_mutex_lock(&ctx->open_devs_lock);
1124
+ list_add(&_handle->list, &ctx->open_devs);
1125
+ usbi_mutex_unlock(&ctx->open_devs_lock);
1126
+ *handle = _handle;
1127
+
1128
+ if (usbi_backend->caps & USBI_CAP_HAS_POLLABLE_DEVICE_FD) {
1129
+ /* At this point, we want to interrupt any existing event handlers so
1130
+ * that they realise the addition of the new device's poll fd. One
1131
+ * example when this is desirable is if the user is running a separate
1132
+ * dedicated libusb events handling thread, which is running with a long
1133
+ * or infinite timeout. We want to interrupt that iteration of the loop,
1134
+ * so that it picks up the new fd, and then continues. */
1135
+ usbi_fd_notification(ctx);
1136
+ }
1137
+
1138
+ return 0;
1139
+ }
1140
+
1141
+ /** \ingroup dev
1142
+ * Convenience function for finding a device with a particular
1143
+ * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1144
+ * for those scenarios where you are using libusb to knock up a quick test
1145
+ * application - it allows you to avoid calling libusb_get_device_list() and
1146
+ * worrying about traversing/freeing the list.
1147
+ *
1148
+ * This function has limitations and is hence not intended for use in real
1149
+ * applications: if multiple devices have the same IDs it will only
1150
+ * give you the first one, etc.
1151
+ *
1152
+ * \param ctx the context to operate on, or NULL for the default context
1153
+ * \param vendor_id the idVendor value to search for
1154
+ * \param product_id the idProduct value to search for
1155
+ * \returns a handle for the first found device, or NULL on error or if the
1156
+ * device could not be found. */
1157
+ DEFAULT_VISIBILITY
1158
+ libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1159
+ libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1160
+ {
1161
+ struct libusb_device **devs;
1162
+ struct libusb_device *found = NULL;
1163
+ struct libusb_device *dev;
1164
+ struct libusb_device_handle *handle = NULL;
1165
+ size_t i = 0;
1166
+ int r;
1167
+
1168
+ if (libusb_get_device_list(ctx, &devs) < 0)
1169
+ return NULL;
1170
+
1171
+ while ((dev = devs[i++]) != NULL) {
1172
+ struct libusb_device_descriptor desc;
1173
+ r = libusb_get_device_descriptor(dev, &desc);
1174
+ if (r < 0)
1175
+ goto out;
1176
+ if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1177
+ found = dev;
1178
+ break;
1179
+ }
1180
+ }
1181
+
1182
+ if (found) {
1183
+ r = libusb_open(found, &handle);
1184
+ if (r < 0)
1185
+ handle = NULL;
1186
+ }
1187
+
1188
+ out:
1189
+ libusb_free_device_list(devs, 1);
1190
+ return handle;
1191
+ }
1192
+
1193
+ static void do_close(struct libusb_context *ctx,
1194
+ struct libusb_device_handle *dev_handle)
1195
+ {
1196
+ struct usbi_transfer *itransfer;
1197
+ struct usbi_transfer *tmp;
1198
+
1199
+ libusb_lock_events(ctx);
1200
+
1201
+ /* remove any transfers in flight that are for this device */
1202
+ usbi_mutex_lock(&ctx->flying_transfers_lock);
1203
+
1204
+ /* safe iteration because transfers may be being deleted */
1205
+ list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
1206
+ struct libusb_transfer *transfer =
1207
+ USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1208
+
1209
+ if (transfer->dev_handle != dev_handle)
1210
+ continue;
1211
+
1212
+ if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1213
+ usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1214
+
1215
+ if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1216
+ usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1217
+ else
1218
+ usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1219
+ }
1220
+
1221
+ /* remove from the list of in-flight transfers and make sure
1222
+ * we don't accidentally use the device handle in the future
1223
+ * (or that such accesses will be easily caught and identified as a crash)
1224
+ */
1225
+ usbi_mutex_lock(&itransfer->lock);
1226
+ list_del(&itransfer->list);
1227
+ transfer->dev_handle = NULL;
1228
+ usbi_mutex_unlock(&itransfer->lock);
1229
+
1230
+ /* it is up to the user to free up the actual transfer struct. this is
1231
+ * just making sure that we don't attempt to process the transfer after
1232
+ * the device handle is invalid
1233
+ */
1234
+ usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
1235
+ transfer, dev_handle);
1236
+ }
1237
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
1238
+
1239
+ libusb_unlock_events(ctx);
1240
+
1241
+ usbi_mutex_lock(&ctx->open_devs_lock);
1242
+ list_del(&dev_handle->list);
1243
+ usbi_mutex_unlock(&ctx->open_devs_lock);
1244
+
1245
+ usbi_backend->close(dev_handle);
1246
+ libusb_unref_device(dev_handle->dev);
1247
+ usbi_mutex_destroy(&dev_handle->lock);
1248
+ free(dev_handle);
1249
+ }
1250
+
1251
+ /** \ingroup dev
1252
+ * Close a device handle. Should be called on all open handles before your
1253
+ * application exits.
1254
+ *
1255
+ * Internally, this function destroys the reference that was added by
1256
+ * libusb_open() on the given device.
1257
+ *
1258
+ * This is a non-blocking function; no requests are sent over the bus.
1259
+ *
1260
+ * \param dev_handle the handle to close
1261
+ */
1262
+ void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1263
+ {
1264
+ struct libusb_context *ctx;
1265
+ unsigned char dummy = 1;
1266
+ ssize_t r;
1267
+
1268
+ if (!dev_handle)
1269
+ return;
1270
+ usbi_dbg("");
1271
+
1272
+ ctx = HANDLE_CTX(dev_handle);
1273
+
1274
+ /* Similarly to libusb_open(), we want to interrupt all event handlers
1275
+ * at this point. More importantly, we want to perform the actual close of
1276
+ * the device while holding the event handling lock (preventing any other
1277
+ * thread from doing event handling) because we will be removing a file
1278
+ * descriptor from the polling loop. */
1279
+
1280
+ /* record that we are messing with poll fds */
1281
+ usbi_mutex_lock(&ctx->pollfd_modify_lock);
1282
+ ctx->pollfd_modify++;
1283
+ usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1284
+
1285
+ /* write some data on control pipe to interrupt event handlers */
1286
+ r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1287
+ if (r <= 0) {
1288
+ usbi_warn(ctx, "internal signalling write failed, closing anyway");
1289
+ do_close(ctx, dev_handle);
1290
+ usbi_mutex_lock(&ctx->pollfd_modify_lock);
1291
+ ctx->pollfd_modify--;
1292
+ usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1293
+ return;
1294
+ }
1295
+
1296
+ /* take event handling lock */
1297
+ libusb_lock_events(ctx);
1298
+
1299
+ /* read the dummy data */
1300
+ r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1301
+ if (r <= 0)
1302
+ usbi_warn(ctx, "internal signalling read failed, closing anyway");
1303
+
1304
+ /* Close the device */
1305
+ do_close(ctx, dev_handle);
1306
+
1307
+ /* we're done with modifying poll fds */
1308
+ usbi_mutex_lock(&ctx->pollfd_modify_lock);
1309
+ ctx->pollfd_modify--;
1310
+ usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1311
+
1312
+ /* Release event handling lock and wake up event waiters */
1313
+ libusb_unlock_events(ctx);
1314
+ }
1315
+
1316
+ /** \ingroup dev
1317
+ * Get the underlying device for a handle. This function does not modify
1318
+ * the reference count of the returned device, so do not feel compelled to
1319
+ * unreference it when you are done.
1320
+ * \param dev_handle a device handle
1321
+ * \returns the underlying device
1322
+ */
1323
+ DEFAULT_VISIBILITY
1324
+ libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1325
+ {
1326
+ return dev_handle->dev;
1327
+ }
1328
+
1329
+ /** \ingroup dev
1330
+ * Determine the bConfigurationValue of the currently active configuration.
1331
+ *
1332
+ * You could formulate your own control request to obtain this information,
1333
+ * but this function has the advantage that it may be able to retrieve the
1334
+ * information from operating system caches (no I/O involved).
1335
+ *
1336
+ * If the OS does not cache this information, then this function will block
1337
+ * while a control transfer is submitted to retrieve the information.
1338
+ *
1339
+ * This function will return a value of 0 in the <tt>config</tt> output
1340
+ * parameter if the device is in unconfigured state.
1341
+ *
1342
+ * \param dev a device handle
1343
+ * \param config output location for the bConfigurationValue of the active
1344
+ * configuration (only valid for return code 0)
1345
+ * \returns 0 on success
1346
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1347
+ * \returns another LIBUSB_ERROR code on other failure
1348
+ */
1349
+ int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
1350
+ int *config)
1351
+ {
1352
+ int r = LIBUSB_ERROR_NOT_SUPPORTED;
1353
+
1354
+ usbi_dbg("");
1355
+ if (usbi_backend->get_configuration)
1356
+ r = usbi_backend->get_configuration(dev, config);
1357
+
1358
+ if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1359
+ uint8_t tmp = 0;
1360
+ usbi_dbg("falling back to control message");
1361
+ r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1362
+ LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1363
+ if (r == 0) {
1364
+ usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1365
+ r = LIBUSB_ERROR_IO;
1366
+ } else if (r == 1) {
1367
+ r = 0;
1368
+ *config = tmp;
1369
+ } else {
1370
+ usbi_dbg("control failed, error %d", r);
1371
+ }
1372
+ }
1373
+
1374
+ if (r == 0)
1375
+ usbi_dbg("active config %d", *config);
1376
+
1377
+ return r;
1378
+ }
1379
+
1380
+ /** \ingroup dev
1381
+ * Set the active configuration for a device.
1382
+ *
1383
+ * The operating system may or may not have already set an active
1384
+ * configuration on the device. It is up to your application to ensure the
1385
+ * correct configuration is selected before you attempt to claim interfaces
1386
+ * and perform other operations.
1387
+ *
1388
+ * If you call this function on a device already configured with the selected
1389
+ * configuration, then this function will act as a lightweight device reset:
1390
+ * it will issue a SET_CONFIGURATION request using the current configuration,
1391
+ * causing most USB-related device state to be reset (altsetting reset to zero,
1392
+ * endpoint halts cleared, toggles reset).
1393
+ *
1394
+ * You cannot change/reset configuration if your application has claimed
1395
+ * interfaces. It is advised to set the desired configuration before claiming
1396
+ * interfaces.
1397
+ *
1398
+ * Alternatively you can call libusb_release_interface() first. Note if you
1399
+ * do things this way you must ensure that auto_detach_kernel_driver for
1400
+ * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1401
+ * release the interface(s).
1402
+ *
1403
+ * You cannot change/reset configuration if other applications or drivers have
1404
+ * claimed interfaces.
1405
+ *
1406
+ * A configuration value of -1 will put the device in unconfigured state.
1407
+ * The USB specifications state that a configuration value of 0 does this,
1408
+ * however buggy devices exist which actually have a configuration 0.
1409
+ *
1410
+ * You should always use this function rather than formulating your own
1411
+ * SET_CONFIGURATION control request. This is because the underlying operating
1412
+ * system needs to know when such changes happen.
1413
+ *
1414
+ * This is a blocking function.
1415
+ *
1416
+ * \param dev a device handle
1417
+ * \param configuration the bConfigurationValue of the configuration you
1418
+ * wish to activate, or -1 if you wish to put the device in unconfigured state
1419
+ * \returns 0 on success
1420
+ * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1421
+ * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1422
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1423
+ * \returns another LIBUSB_ERROR code on other failure
1424
+ * \see libusb_set_auto_detach_kernel_driver()
1425
+ */
1426
+ int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
1427
+ int configuration)
1428
+ {
1429
+ usbi_dbg("configuration %d", configuration);
1430
+ return usbi_backend->set_configuration(dev, configuration);
1431
+ }
1432
+
1433
+ /** \ingroup dev
1434
+ * Claim an interface on a given device handle. You must claim the interface
1435
+ * you wish to use before you can perform I/O on any of its endpoints.
1436
+ *
1437
+ * It is legal to attempt to claim an already-claimed interface, in which
1438
+ * case libusb just returns 0 without doing anything.
1439
+ *
1440
+ * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1441
+ * will be detached if necessary, on failure the detach error is returned.
1442
+ *
1443
+ * Claiming of interfaces is a purely logical operation; it does not cause
1444
+ * any requests to be sent over the bus. Interface claiming is used to
1445
+ * instruct the underlying operating system that your application wishes
1446
+ * to take ownership of the interface.
1447
+ *
1448
+ * This is a non-blocking function.
1449
+ *
1450
+ * \param dev a device handle
1451
+ * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1452
+ * wish to claim
1453
+ * \returns 0 on success
1454
+ * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1455
+ * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1456
+ * interface
1457
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1458
+ * \returns a LIBUSB_ERROR code on other failure
1459
+ * \see libusb_set_auto_detach_kernel_driver()
1460
+ */
1461
+ int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
1462
+ int interface_number)
1463
+ {
1464
+ int r = 0;
1465
+
1466
+ usbi_dbg("interface %d", interface_number);
1467
+ if (interface_number >= USB_MAXINTERFACES)
1468
+ return LIBUSB_ERROR_INVALID_PARAM;
1469
+
1470
+ if (!dev->dev->attached)
1471
+ return LIBUSB_ERROR_NO_DEVICE;
1472
+
1473
+ usbi_mutex_lock(&dev->lock);
1474
+ if (dev->claimed_interfaces & (1 << interface_number))
1475
+ goto out;
1476
+
1477
+ r = usbi_backend->claim_interface(dev, interface_number);
1478
+ if (r == 0)
1479
+ dev->claimed_interfaces |= 1 << interface_number;
1480
+
1481
+ out:
1482
+ usbi_mutex_unlock(&dev->lock);
1483
+ return r;
1484
+ }
1485
+
1486
+ /** \ingroup dev
1487
+ * Release an interface previously claimed with libusb_claim_interface(). You
1488
+ * should release all claimed interfaces before closing a device handle.
1489
+ *
1490
+ * This is a blocking function. A SET_INTERFACE control request will be sent
1491
+ * to the device, resetting interface state to the first alternate setting.
1492
+ *
1493
+ * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1494
+ * driver will be re-attached after releasing the interface.
1495
+ *
1496
+ * \param dev a device handle
1497
+ * \param interface_number the <tt>bInterfaceNumber</tt> of the
1498
+ * previously-claimed interface
1499
+ * \returns 0 on success
1500
+ * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1501
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1502
+ * \returns another LIBUSB_ERROR code on other failure
1503
+ * \see libusb_set_auto_detach_kernel_driver()
1504
+ */
1505
+ int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
1506
+ int interface_number)
1507
+ {
1508
+ int r;
1509
+
1510
+ usbi_dbg("interface %d", interface_number);
1511
+ if (interface_number >= USB_MAXINTERFACES)
1512
+ return LIBUSB_ERROR_INVALID_PARAM;
1513
+
1514
+ usbi_mutex_lock(&dev->lock);
1515
+ if (!(dev->claimed_interfaces & (1 << interface_number))) {
1516
+ r = LIBUSB_ERROR_NOT_FOUND;
1517
+ goto out;
1518
+ }
1519
+
1520
+ r = usbi_backend->release_interface(dev, interface_number);
1521
+ if (r == 0)
1522
+ dev->claimed_interfaces &= ~(1 << interface_number);
1523
+
1524
+ out:
1525
+ usbi_mutex_unlock(&dev->lock);
1526
+ return r;
1527
+ }
1528
+
1529
+ /** \ingroup dev
1530
+ * Activate an alternate setting for an interface. The interface must have
1531
+ * been previously claimed with libusb_claim_interface().
1532
+ *
1533
+ * You should always use this function rather than formulating your own
1534
+ * SET_INTERFACE control request. This is because the underlying operating
1535
+ * system needs to know when such changes happen.
1536
+ *
1537
+ * This is a blocking function.
1538
+ *
1539
+ * \param dev a device handle
1540
+ * \param interface_number the <tt>bInterfaceNumber</tt> of the
1541
+ * previously-claimed interface
1542
+ * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1543
+ * setting to activate
1544
+ * \returns 0 on success
1545
+ * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1546
+ * requested alternate setting does not exist
1547
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1548
+ * \returns another LIBUSB_ERROR code on other failure
1549
+ */
1550
+ int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
1551
+ int interface_number, int alternate_setting)
1552
+ {
1553
+ usbi_dbg("interface %d altsetting %d",
1554
+ interface_number, alternate_setting);
1555
+ if (interface_number >= USB_MAXINTERFACES)
1556
+ return LIBUSB_ERROR_INVALID_PARAM;
1557
+
1558
+ usbi_mutex_lock(&dev->lock);
1559
+ if (!dev->dev->attached) {
1560
+ usbi_mutex_unlock(&dev->lock);
1561
+ return LIBUSB_ERROR_NO_DEVICE;
1562
+ }
1563
+
1564
+ if (!(dev->claimed_interfaces & (1 << interface_number))) {
1565
+ usbi_mutex_unlock(&dev->lock);
1566
+ return LIBUSB_ERROR_NOT_FOUND;
1567
+ }
1568
+ usbi_mutex_unlock(&dev->lock);
1569
+
1570
+ return usbi_backend->set_interface_altsetting(dev, interface_number,
1571
+ alternate_setting);
1572
+ }
1573
+
1574
+ /** \ingroup dev
1575
+ * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1576
+ * are unable to receive or transmit data until the halt condition is stalled.
1577
+ *
1578
+ * You should cancel all pending transfers before attempting to clear the halt
1579
+ * condition.
1580
+ *
1581
+ * This is a blocking function.
1582
+ *
1583
+ * \param dev a device handle
1584
+ * \param endpoint the endpoint to clear halt status
1585
+ * \returns 0 on success
1586
+ * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1587
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1588
+ * \returns another LIBUSB_ERROR code on other failure
1589
+ */
1590
+ int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
1591
+ unsigned char endpoint)
1592
+ {
1593
+ usbi_dbg("endpoint %x", endpoint);
1594
+ if (!dev->dev->attached)
1595
+ return LIBUSB_ERROR_NO_DEVICE;
1596
+
1597
+ return usbi_backend->clear_halt(dev, endpoint);
1598
+ }
1599
+
1600
+ /** \ingroup dev
1601
+ * Perform a USB port reset to reinitialize a device. The system will attempt
1602
+ * to restore the previous configuration and alternate settings after the
1603
+ * reset has completed.
1604
+ *
1605
+ * If the reset fails, the descriptors change, or the previous state cannot be
1606
+ * restored, the device will appear to be disconnected and reconnected. This
1607
+ * means that the device handle is no longer valid (you should close it) and
1608
+ * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1609
+ * when this is the case.
1610
+ *
1611
+ * This is a blocking function which usually incurs a noticeable delay.
1612
+ *
1613
+ * \param dev a handle of the device to reset
1614
+ * \returns 0 on success
1615
+ * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1616
+ * device has been disconnected
1617
+ * \returns another LIBUSB_ERROR code on other failure
1618
+ */
1619
+ int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
1620
+ {
1621
+ usbi_dbg("");
1622
+ if (!dev->dev->attached)
1623
+ return LIBUSB_ERROR_NO_DEVICE;
1624
+
1625
+ return usbi_backend->reset_device(dev);
1626
+ }
1627
+
1628
+ /** \ingroup asyncio
1629
+ * Allocate up to num_streams usb bulk streams on the specified endpoints. This
1630
+ * function takes an array of endpoints rather then a single endpoint because
1631
+ * some protocols require that endpoints are setup with similar stream ids.
1632
+ * All endpoints passed in must belong to the same interface.
1633
+ *
1634
+ * Note this function may return less streams then requested. Also note that the
1635
+ * same number of streams are allocated for each endpoint in the endpoint array.
1636
+ *
1637
+ * Stream id 0 is reserved, and should not be used to communicate with devices.
1638
+ * If libusb_alloc_streams() returns with a value of N, you may use stream ids
1639
+ * 1 to N.
1640
+ *
1641
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1642
+ *
1643
+ * \param dev a device handle
1644
+ * \param num_streams number of streams to try to allocate
1645
+ * \param endpoints array of endpoints to allocate streams on
1646
+ * \param num_endpoints length of the endpoints array
1647
+ * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
1648
+ */
1649
+ int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev,
1650
+ uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1651
+ {
1652
+ usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
1653
+
1654
+ if (!dev->dev->attached)
1655
+ return LIBUSB_ERROR_NO_DEVICE;
1656
+
1657
+ if (usbi_backend->alloc_streams)
1658
+ return usbi_backend->alloc_streams(dev, num_streams, endpoints,
1659
+ num_endpoints);
1660
+ else
1661
+ return LIBUSB_ERROR_NOT_SUPPORTED;
1662
+ }
1663
+
1664
+ /** \ingroup asyncio
1665
+ * Free usb bulk streams allocated with libusb_alloc_streams().
1666
+ *
1667
+ * Note streams are automatically free-ed when releasing an interface.
1668
+ *
1669
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1670
+ *
1671
+ * \param dev a device handle
1672
+ * \param endpoints array of endpoints to free streams on
1673
+ * \param num_endpoints length of the endpoints array
1674
+ * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1675
+ */
1676
+ int API_EXPORTED libusb_free_streams(libusb_device_handle *dev,
1677
+ unsigned char *endpoints, int num_endpoints)
1678
+ {
1679
+ usbi_dbg("eps %d", num_endpoints);
1680
+
1681
+ if (!dev->dev->attached)
1682
+ return LIBUSB_ERROR_NO_DEVICE;
1683
+
1684
+ if (usbi_backend->free_streams)
1685
+ return usbi_backend->free_streams(dev, endpoints,
1686
+ num_endpoints);
1687
+ else
1688
+ return LIBUSB_ERROR_NOT_SUPPORTED;
1689
+ }
1690
+
1691
+ /** \ingroup dev
1692
+ * Determine if a kernel driver is active on an interface. If a kernel driver
1693
+ * is active, you cannot claim the interface, and libusb will be unable to
1694
+ * perform I/O.
1695
+ *
1696
+ * This functionality is not available on Windows.
1697
+ *
1698
+ * \param dev a device handle
1699
+ * \param interface_number the interface to check
1700
+ * \returns 0 if no kernel driver is active
1701
+ * \returns 1 if a kernel driver is active
1702
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1703
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1704
+ * is not available
1705
+ * \returns another LIBUSB_ERROR code on other failure
1706
+ * \see libusb_detach_kernel_driver()
1707
+ */
1708
+ int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
1709
+ int interface_number)
1710
+ {
1711
+ usbi_dbg("interface %d", interface_number);
1712
+
1713
+ if (!dev->dev->attached)
1714
+ return LIBUSB_ERROR_NO_DEVICE;
1715
+
1716
+ if (usbi_backend->kernel_driver_active)
1717
+ return usbi_backend->kernel_driver_active(dev, interface_number);
1718
+ else
1719
+ return LIBUSB_ERROR_NOT_SUPPORTED;
1720
+ }
1721
+
1722
+ /** \ingroup dev
1723
+ * Detach a kernel driver from an interface. If successful, you will then be
1724
+ * able to claim the interface and perform I/O.
1725
+ *
1726
+ * This functionality is not available on Darwin or Windows.
1727
+ *
1728
+ * Note that libusb itself also talks to the device through a special kernel
1729
+ * driver, if this driver is already attached to the device, this call will
1730
+ * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1731
+ *
1732
+ * \param dev a device handle
1733
+ * \param interface_number the interface to detach the driver from
1734
+ * \returns 0 on success
1735
+ * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1736
+ * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1737
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1738
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1739
+ * is not available
1740
+ * \returns another LIBUSB_ERROR code on other failure
1741
+ * \see libusb_kernel_driver_active()
1742
+ */
1743
+ int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
1744
+ int interface_number)
1745
+ {
1746
+ usbi_dbg("interface %d", interface_number);
1747
+
1748
+ if (!dev->dev->attached)
1749
+ return LIBUSB_ERROR_NO_DEVICE;
1750
+
1751
+ if (usbi_backend->detach_kernel_driver)
1752
+ return usbi_backend->detach_kernel_driver(dev, interface_number);
1753
+ else
1754
+ return LIBUSB_ERROR_NOT_SUPPORTED;
1755
+ }
1756
+
1757
+ /** \ingroup dev
1758
+ * Re-attach an interface's kernel driver, which was previously detached
1759
+ * using libusb_detach_kernel_driver(). This call is only effective on
1760
+ * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1761
+ *
1762
+ * This functionality is not available on Darwin or Windows.
1763
+ *
1764
+ * \param dev a device handle
1765
+ * \param interface_number the interface to attach the driver from
1766
+ * \returns 0 on success
1767
+ * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1768
+ * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1769
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1770
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1771
+ * is not available
1772
+ * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1773
+ * interface is claimed by a program or driver
1774
+ * \returns another LIBUSB_ERROR code on other failure
1775
+ * \see libusb_kernel_driver_active()
1776
+ */
1777
+ int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
1778
+ int interface_number)
1779
+ {
1780
+ usbi_dbg("interface %d", interface_number);
1781
+
1782
+ if (!dev->dev->attached)
1783
+ return LIBUSB_ERROR_NO_DEVICE;
1784
+
1785
+ if (usbi_backend->attach_kernel_driver)
1786
+ return usbi_backend->attach_kernel_driver(dev, interface_number);
1787
+ else
1788
+ return LIBUSB_ERROR_NOT_SUPPORTED;
1789
+ }
1790
+
1791
+ /** \ingroup dev
1792
+ * Enable/disable libusb's automatic kernel driver detachment. When this is
1793
+ * enabled libusb will automatically detach the kernel driver on an interface
1794
+ * when claiming the interface, and attach it when releasing the interface.
1795
+ *
1796
+ * Automatic kernel driver detachment is disabled on newly opened device
1797
+ * handles by default.
1798
+ *
1799
+ * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
1800
+ * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
1801
+ * continue as if this function was never called.
1802
+ *
1803
+ * \param dev a device handle
1804
+ * \param enable whether to enable or disable auto kernel driver detachment
1805
+ *
1806
+ * \returns LIBUSB_SUCCESS on success
1807
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1808
+ * is not available
1809
+ * \see libusb_claim_interface()
1810
+ * \see libusb_release_interface()
1811
+ * \see libusb_set_configuration()
1812
+ */
1813
+ int API_EXPORTED libusb_set_auto_detach_kernel_driver(
1814
+ libusb_device_handle *dev, int enable)
1815
+ {
1816
+ if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
1817
+ return LIBUSB_ERROR_NOT_SUPPORTED;
1818
+
1819
+ dev->auto_detach_kernel_driver = enable;
1820
+ return LIBUSB_SUCCESS;
1821
+ }
1822
+
1823
+ /** \ingroup lib
1824
+ * Set log message verbosity.
1825
+ *
1826
+ * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
1827
+ * printed. If you choose to increase the message verbosity level, ensure
1828
+ * that your application does not close the stdout/stderr file descriptors.
1829
+ *
1830
+ * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative
1831
+ * with its message logging and most of the time, will only log messages that
1832
+ * explain error conditions and other oddities. This will help you debug
1833
+ * your software.
1834
+ *
1835
+ * If the LIBUSB_DEBUG environment variable was set when libusb was
1836
+ * initialized, this function does nothing: the message verbosity is fixed
1837
+ * to the value in the environment variable.
1838
+ *
1839
+ * If libusb was compiled without any message logging, this function does
1840
+ * nothing: you'll never get any messages.
1841
+ *
1842
+ * If libusb was compiled with verbose debug message logging, this function
1843
+ * does nothing: you'll always get messages from all levels.
1844
+ *
1845
+ * \param ctx the context to operate on, or NULL for the default context
1846
+ * \param level debug level to set
1847
+ */
1848
+ void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
1849
+ {
1850
+ USBI_GET_CONTEXT(ctx);
1851
+ if (!ctx->debug_fixed)
1852
+ ctx->debug = level;
1853
+ }
1854
+
1855
+ /** \ingroup lib
1856
+ * Initialize libusb. This function must be called before calling any other
1857
+ * libusb function.
1858
+ *
1859
+ * If you do not provide an output location for a context pointer, a default
1860
+ * context will be created. If there was already a default context, it will
1861
+ * be reused (and nothing will be initialized/reinitialized).
1862
+ *
1863
+ * \param context Optional output location for context pointer.
1864
+ * Only valid on return code 0.
1865
+ * \returns 0 on success, or a LIBUSB_ERROR code on failure
1866
+ * \see contexts
1867
+ */
1868
+ int API_EXPORTED libusb_init(libusb_context **context)
1869
+ {
1870
+ struct libusb_device *dev, *next;
1871
+ char *dbg = getenv("LIBUSB_DEBUG");
1872
+ struct libusb_context *ctx;
1873
+ static int first_init = 1;
1874
+ int r = 0;
1875
+
1876
+ usbi_mutex_static_lock(&default_context_lock);
1877
+
1878
+ if (!timestamp_origin.tv_sec) {
1879
+ usbi_gettimeofday(&timestamp_origin, NULL);
1880
+ }
1881
+
1882
+ if (!context && usbi_default_context) {
1883
+ usbi_dbg("reusing default context");
1884
+ default_context_refcnt++;
1885
+ usbi_mutex_static_unlock(&default_context_lock);
1886
+ return 0;
1887
+ }
1888
+
1889
+ ctx = calloc(1, sizeof(*ctx));
1890
+ if (!ctx) {
1891
+ r = LIBUSB_ERROR_NO_MEM;
1892
+ goto err_unlock;
1893
+ }
1894
+
1895
+ #ifdef ENABLE_DEBUG_LOGGING
1896
+ ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
1897
+ #endif
1898
+
1899
+ if (dbg) {
1900
+ ctx->debug = atoi(dbg);
1901
+ if (ctx->debug)
1902
+ ctx->debug_fixed = 1;
1903
+ }
1904
+
1905
+ /* default context should be initialized before calling usbi_dbg */
1906
+ if (!usbi_default_context) {
1907
+ usbi_default_context = ctx;
1908
+ default_context_refcnt++;
1909
+ usbi_dbg("created default context");
1910
+ }
1911
+
1912
+ usbi_dbg("libusb v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
1913
+ libusb_version_internal.micro, libusb_version_internal.nano);
1914
+
1915
+ usbi_mutex_init(&ctx->usb_devs_lock, NULL);
1916
+ usbi_mutex_init(&ctx->open_devs_lock, NULL);
1917
+ usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
1918
+ list_init(&ctx->usb_devs);
1919
+ list_init(&ctx->open_devs);
1920
+ list_init(&ctx->hotplug_cbs);
1921
+
1922
+ usbi_mutex_static_lock(&active_contexts_lock);
1923
+ if (first_init) {
1924
+ first_init = 0;
1925
+ list_init (&active_contexts_list);
1926
+ }
1927
+ list_add (&ctx->list, &active_contexts_list);
1928
+ usbi_mutex_static_unlock(&active_contexts_lock);
1929
+
1930
+ if (usbi_backend->init) {
1931
+ r = usbi_backend->init(ctx);
1932
+ if (r)
1933
+ goto err_free_ctx;
1934
+ }
1935
+
1936
+ r = usbi_io_init(ctx);
1937
+ if (r < 0)
1938
+ goto err_backend_exit;
1939
+
1940
+ usbi_mutex_static_unlock(&default_context_lock);
1941
+
1942
+ if (context)
1943
+ *context = ctx;
1944
+
1945
+ return 0;
1946
+
1947
+ err_backend_exit:
1948
+ if (usbi_backend->exit)
1949
+ usbi_backend->exit();
1950
+ err_free_ctx:
1951
+ if (ctx == usbi_default_context) {
1952
+ usbi_default_context = NULL;
1953
+ default_context_refcnt--;
1954
+ }
1955
+
1956
+ usbi_mutex_static_lock(&active_contexts_lock);
1957
+ list_del (&ctx->list);
1958
+ usbi_mutex_static_unlock(&active_contexts_lock);
1959
+
1960
+ usbi_mutex_lock(&ctx->usb_devs_lock);
1961
+ list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
1962
+ list_del(&dev->list);
1963
+ libusb_unref_device(dev);
1964
+ }
1965
+ usbi_mutex_unlock(&ctx->usb_devs_lock);
1966
+
1967
+ usbi_mutex_destroy(&ctx->open_devs_lock);
1968
+ usbi_mutex_destroy(&ctx->usb_devs_lock);
1969
+ usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
1970
+
1971
+ free(ctx);
1972
+ err_unlock:
1973
+ usbi_mutex_static_unlock(&default_context_lock);
1974
+ return r;
1975
+ }
1976
+
1977
+ /** \ingroup lib
1978
+ * Deinitialize libusb. Should be called after closing all open devices and
1979
+ * before your application terminates.
1980
+ * \param ctx the context to deinitialize, or NULL for the default context
1981
+ */
1982
+ void API_EXPORTED libusb_exit(struct libusb_context *ctx)
1983
+ {
1984
+ struct libusb_device *dev, *next;
1985
+ struct timeval tv = { 0, 0 };
1986
+
1987
+ usbi_dbg("");
1988
+ USBI_GET_CONTEXT(ctx);
1989
+
1990
+ /* if working with default context, only actually do the deinitialization
1991
+ * if we're the last user */
1992
+ usbi_mutex_static_lock(&default_context_lock);
1993
+ if (ctx == usbi_default_context) {
1994
+ if (--default_context_refcnt > 0) {
1995
+ usbi_dbg("not destroying default context");
1996
+ usbi_mutex_static_unlock(&default_context_lock);
1997
+ return;
1998
+ }
1999
+ usbi_dbg("destroying default context");
2000
+ }
2001
+ usbi_mutex_static_unlock(&default_context_lock);
2002
+
2003
+ usbi_mutex_static_lock(&active_contexts_lock);
2004
+ list_del (&ctx->list);
2005
+ usbi_mutex_static_unlock(&active_contexts_lock);
2006
+
2007
+ if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
2008
+ usbi_hotplug_deregister_all(ctx);
2009
+
2010
+ /*
2011
+ * Ensure any pending unplug events are read from the hotplug
2012
+ * pipe. The usb_device-s hold in the events are no longer part
2013
+ * of usb_devs, but the events still hold a reference!
2014
+ *
2015
+ * Note we don't do this if the application has left devices
2016
+ * open (which implies a buggy app) to avoid packet completion
2017
+ * handlers running when the app does not expect them to run.
2018
+ */
2019
+ if (list_empty(&ctx->open_devs))
2020
+ libusb_handle_events_timeout(ctx, &tv);
2021
+
2022
+ usbi_mutex_lock(&ctx->usb_devs_lock);
2023
+ list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
2024
+ list_del(&dev->list);
2025
+ libusb_unref_device(dev);
2026
+ }
2027
+ usbi_mutex_unlock(&ctx->usb_devs_lock);
2028
+ }
2029
+
2030
+ /* a few sanity checks. don't bother with locking because unless
2031
+ * there is an application bug, nobody will be accessing these. */
2032
+ if (!list_empty(&ctx->usb_devs))
2033
+ usbi_warn(ctx, "some libusb_devices were leaked");
2034
+ if (!list_empty(&ctx->open_devs))
2035
+ usbi_warn(ctx, "application left some devices open");
2036
+
2037
+ usbi_io_exit(ctx);
2038
+ if (usbi_backend->exit)
2039
+ usbi_backend->exit();
2040
+
2041
+ usbi_mutex_destroy(&ctx->open_devs_lock);
2042
+ usbi_mutex_destroy(&ctx->usb_devs_lock);
2043
+ usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2044
+
2045
+ if (ctx == usbi_default_context) {
2046
+ usbi_default_context = NULL;
2047
+ }
2048
+
2049
+ free(ctx);
2050
+ }
2051
+
2052
+ /** \ingroup misc
2053
+ * Check at runtime if the loaded library has a given capability.
2054
+ * This call should be performed after \ref libusb_init(), to ensure the
2055
+ * backend has updated its capability set.
2056
+ *
2057
+ * \param capability the \ref libusb_capability to check for
2058
+ * \returns nonzero if the running library has the capability, 0 otherwise
2059
+ */
2060
+ int API_EXPORTED libusb_has_capability(uint32_t capability)
2061
+ {
2062
+ switch (capability) {
2063
+ case LIBUSB_CAP_HAS_CAPABILITY:
2064
+ return 1;
2065
+ case LIBUSB_CAP_HAS_HOTPLUG:
2066
+ return !(usbi_backend->get_device_list);
2067
+ case LIBUSB_CAP_HAS_HID_ACCESS:
2068
+ return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
2069
+ case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2070
+ return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
2071
+ }
2072
+ return 0;
2073
+ }
2074
+
2075
+ /* this is defined in libusbi.h if needed */
2076
+ #ifdef LIBUSB_GETTIMEOFDAY_WIN32
2077
+ /*
2078
+ * gettimeofday
2079
+ * Implementation according to:
2080
+ * The Open Group Base Specifications Issue 6
2081
+ * IEEE Std 1003.1, 2004 Edition
2082
+ */
2083
+
2084
+ /*
2085
+ * THIS SOFTWARE IS NOT COPYRIGHTED
2086
+ *
2087
+ * This source code is offered for use in the public domain. You may
2088
+ * use, modify or distribute it freely.
2089
+ *
2090
+ * This code is distributed in the hope that it will be useful but
2091
+ * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
2092
+ * DISCLAIMED. This includes but is not limited to warranties of
2093
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2094
+ *
2095
+ * Contributed by:
2096
+ * Danny Smith <dannysmith@users.sourceforge.net>
2097
+ */
2098
+
2099
+ /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
2100
+ #define _W32_FT_OFFSET (116444736000000000)
2101
+
2102
+ int usbi_gettimeofday(struct timeval *tp, void *tzp)
2103
+ {
2104
+ union {
2105
+ unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
2106
+ FILETIME ft;
2107
+ } _now;
2108
+ UNUSED(tzp);
2109
+
2110
+ if(tp) {
2111
+ #if defined(OS_WINCE)
2112
+ SYSTEMTIME st;
2113
+ GetSystemTime(&st);
2114
+ SystemTimeToFileTime(&st, &_now.ft);
2115
+ #else
2116
+ GetSystemTimeAsFileTime (&_now.ft);
2117
+ #endif
2118
+ tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
2119
+ tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
2120
+ }
2121
+ /* Always return 0 as per Open Group Base Specifications Issue 6.
2122
+ Do not set errno on error. */
2123
+ return 0;
2124
+ }
2125
+ #endif
2126
+
2127
+ static void usbi_log_str(struct libusb_context *ctx,
2128
+ enum libusb_log_level level, const char * str)
2129
+ {
2130
+ #if defined(USE_SYSTEM_LOGGING_FACILITY)
2131
+ #if defined(OS_WINDOWS) || defined(OS_WINCE)
2132
+ /* Windows CE only supports the Unicode version of OutputDebugString. */
2133
+ WCHAR wbuf[USBI_MAX_LOG_LEN];
2134
+ MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
2135
+ OutputDebugStringW(wbuf);
2136
+ #elif defined(__ANDROID__)
2137
+ int priority = ANDROID_LOG_UNKNOWN;
2138
+ switch (level) {
2139
+ case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2140
+ case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2141
+ case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2142
+ case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2143
+ }
2144
+ __android_log_write(priority, "libusb", str);
2145
+ #elif defined(HAVE_SYSLOG_FUNC)
2146
+ int syslog_level = LOG_INFO;
2147
+ switch (level) {
2148
+ case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2149
+ case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2150
+ case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2151
+ case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2152
+ }
2153
+ syslog(syslog_level, "%s", str);
2154
+ #else /* All of gcc, Clang, XCode seem to use #warning */
2155
+ #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2156
+ fputs(str, stderr);
2157
+ #endif
2158
+ #else
2159
+ fputs(str, stderr);
2160
+ #endif /* USE_SYSTEM_LOGGING_FACILITY */
2161
+ UNUSED(ctx);
2162
+ UNUSED(level);
2163
+ }
2164
+
2165
+ void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
2166
+ const char *function, const char *format, va_list args)
2167
+ {
2168
+ const char *prefix = "";
2169
+ char buf[USBI_MAX_LOG_LEN];
2170
+ struct timeval now;
2171
+ int global_debug, header_len, text_len;
2172
+ static int has_debug_header_been_displayed = 0;
2173
+
2174
+ #ifdef ENABLE_DEBUG_LOGGING
2175
+ global_debug = 1;
2176
+ UNUSED(ctx);
2177
+ #else
2178
+ int ctx_level = 0;
2179
+
2180
+ USBI_GET_CONTEXT(ctx);
2181
+ if (ctx) {
2182
+ ctx_level = ctx->debug;
2183
+ } else {
2184
+ char *dbg = getenv("LIBUSB_DEBUG");
2185
+ if (dbg)
2186
+ ctx_level = atoi(dbg);
2187
+ }
2188
+ global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
2189
+ if (!ctx_level)
2190
+ return;
2191
+ if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
2192
+ return;
2193
+ if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
2194
+ return;
2195
+ if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
2196
+ return;
2197
+ #endif
2198
+
2199
+ usbi_gettimeofday(&now, NULL);
2200
+ if ((global_debug) && (!has_debug_header_been_displayed)) {
2201
+ has_debug_header_been_displayed = 1;
2202
+ usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>\n");
2203
+ usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------\n");
2204
+ }
2205
+ if (now.tv_usec < timestamp_origin.tv_usec) {
2206
+ now.tv_sec--;
2207
+ now.tv_usec += 1000000;
2208
+ }
2209
+ now.tv_sec -= timestamp_origin.tv_sec;
2210
+ now.tv_usec -= timestamp_origin.tv_usec;
2211
+
2212
+ switch (level) {
2213
+ case LIBUSB_LOG_LEVEL_INFO:
2214
+ prefix = "info";
2215
+ break;
2216
+ case LIBUSB_LOG_LEVEL_WARNING:
2217
+ prefix = "warning";
2218
+ break;
2219
+ case LIBUSB_LOG_LEVEL_ERROR:
2220
+ prefix = "error";
2221
+ break;
2222
+ case LIBUSB_LOG_LEVEL_DEBUG:
2223
+ prefix = "debug";
2224
+ break;
2225
+ case LIBUSB_LOG_LEVEL_NONE:
2226
+ return;
2227
+ default:
2228
+ prefix = "unknown";
2229
+ break;
2230
+ }
2231
+
2232
+ if (global_debug) {
2233
+ header_len = snprintf(buf, sizeof(buf),
2234
+ "[%2d.%06d] [%08x] libusb: %s [%s] ",
2235
+ (int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
2236
+ } else {
2237
+ header_len = snprintf(buf, sizeof(buf),
2238
+ "libusb: %s [%s] ", prefix, function);
2239
+ }
2240
+
2241
+ if (header_len < 0 || header_len >= sizeof(buf)) {
2242
+ /* Somehow snprintf failed to write to the buffer,
2243
+ * remove the header so something useful is output. */
2244
+ header_len = 0;
2245
+ }
2246
+ /* Make sure buffer is NUL terminated */
2247
+ buf[header_len] = '\0';
2248
+ text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
2249
+ format, args);
2250
+ if (text_len < 0 || text_len + header_len >= sizeof(buf)) {
2251
+ /* Truncated log output. On some platforms a -1 return value means
2252
+ * that the output was truncated. */
2253
+ text_len = sizeof(buf) - header_len;
2254
+ }
2255
+ if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
2256
+ /* Need to truncate the text slightly to fit on the terminator. */
2257
+ text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
2258
+ }
2259
+ strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2260
+
2261
+ usbi_log_str(ctx, level, buf);
2262
+ }
2263
+
2264
+ void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2265
+ const char *function, const char *format, ...)
2266
+ {
2267
+ va_list args;
2268
+
2269
+ va_start (args, format);
2270
+ usbi_log_v(ctx, level, function, format, args);
2271
+ va_end (args);
2272
+ }
2273
+
2274
+ /** \ingroup misc
2275
+ * Returns a constant NULL-terminated string with the ASCII name of a libusb
2276
+ * error or transfer status code. The caller must not free() the returned
2277
+ * string.
2278
+ *
2279
+ * \param error_code The \ref libusb_error or libusb_transfer_status code to
2280
+ * return the name of.
2281
+ * \returns The error name, or the string **UNKNOWN** if the value of
2282
+ * error_code is not a known error / status code.
2283
+ */
2284
+ DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
2285
+ {
2286
+ switch (error_code) {
2287
+ case LIBUSB_ERROR_IO:
2288
+ return "LIBUSB_ERROR_IO";
2289
+ case LIBUSB_ERROR_INVALID_PARAM:
2290
+ return "LIBUSB_ERROR_INVALID_PARAM";
2291
+ case LIBUSB_ERROR_ACCESS:
2292
+ return "LIBUSB_ERROR_ACCESS";
2293
+ case LIBUSB_ERROR_NO_DEVICE:
2294
+ return "LIBUSB_ERROR_NO_DEVICE";
2295
+ case LIBUSB_ERROR_NOT_FOUND:
2296
+ return "LIBUSB_ERROR_NOT_FOUND";
2297
+ case LIBUSB_ERROR_BUSY:
2298
+ return "LIBUSB_ERROR_BUSY";
2299
+ case LIBUSB_ERROR_TIMEOUT:
2300
+ return "LIBUSB_ERROR_TIMEOUT";
2301
+ case LIBUSB_ERROR_OVERFLOW:
2302
+ return "LIBUSB_ERROR_OVERFLOW";
2303
+ case LIBUSB_ERROR_PIPE:
2304
+ return "LIBUSB_ERROR_PIPE";
2305
+ case LIBUSB_ERROR_INTERRUPTED:
2306
+ return "LIBUSB_ERROR_INTERRUPTED";
2307
+ case LIBUSB_ERROR_NO_MEM:
2308
+ return "LIBUSB_ERROR_NO_MEM";
2309
+ case LIBUSB_ERROR_NOT_SUPPORTED:
2310
+ return "LIBUSB_ERROR_NOT_SUPPORTED";
2311
+ case LIBUSB_ERROR_OTHER:
2312
+ return "LIBUSB_ERROR_OTHER";
2313
+
2314
+ case LIBUSB_TRANSFER_ERROR:
2315
+ return "LIBUSB_TRANSFER_ERROR";
2316
+ case LIBUSB_TRANSFER_TIMED_OUT:
2317
+ return "LIBUSB_TRANSFER_TIMED_OUT";
2318
+ case LIBUSB_TRANSFER_CANCELLED:
2319
+ return "LIBUSB_TRANSFER_CANCELLED";
2320
+ case LIBUSB_TRANSFER_STALL:
2321
+ return "LIBUSB_TRANSFER_STALL";
2322
+ case LIBUSB_TRANSFER_NO_DEVICE:
2323
+ return "LIBUSB_TRANSFER_NO_DEVICE";
2324
+ case LIBUSB_TRANSFER_OVERFLOW:
2325
+ return "LIBUSB_TRANSFER_OVERFLOW";
2326
+
2327
+ case 0:
2328
+ return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2329
+ default:
2330
+ return "**UNKNOWN**";
2331
+ }
2332
+ }
2333
+
2334
+ /** \ingroup misc
2335
+ * Returns a pointer to const struct libusb_version with the version
2336
+ * (major, minor, micro, nano and rc) of the running library.
2337
+ */
2338
+ DEFAULT_VISIBILITY
2339
+ const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
2340
+ {
2341
+ return &libusb_version_internal;
2342
+ }