core.c 68 KB

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