subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

usbhid.c (19551B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2016 Jef Driesen
      5  *
      6  * This library is free software; you can redistribute it and/or
      7  * modify it under the terms of the GNU Lesser General Public
      8  * License as published by the Free Software Foundation; either
      9  * version 2.1 of the License, or (at your option) any later version.
     10  *
     11  * This library is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14  * Lesser General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU Lesser General Public
     17  * License along with this library; if not, write to the Free Software
     18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     19  * MA 02110-1301 USA
     20  */
     21 
     22 #ifdef HAVE_CONFIG_H
     23 #include "config.h"
     24 #endif
     25 
     26 #include <stdlib.h>
     27 #include <string.h>
     28 #ifdef HAVE_PTHREAD_H
     29 #include <pthread.h>
     30 #endif
     31 #ifdef _WIN32
     32 #define WIN32_LEAN_AND_MEAN
     33 #define NOGDI
     34 #include <windows.h>
     35 #endif
     36 
     37 #if defined(HAVE_HIDAPI)
     38 #define USE_HIDAPI
     39 #define USBHID
     40 #elif defined(HAVE_LIBUSB) && !defined(__APPLE__)
     41 #define USE_LIBUSB
     42 #define USBHID
     43 #endif
     44 
     45 #if defined(USE_LIBUSB)
     46 #ifdef _WIN32
     47 #define WIN32_LEAN_AND_MEAN
     48 #define NOGDI
     49 #endif
     50 #include <libusb.h>
     51 #elif defined(USE_HIDAPI)
     52 #include <hidapi.h>
     53 #endif
     54 
     55 #include <libdivecomputer/usbhid.h>
     56 
     57 #include "common-private.h"
     58 #include "context-private.h"
     59 #include "iostream-private.h"
     60 #include "iterator-private.h"
     61 #include "platform.h"
     62 
     63 #ifdef _WIN32
     64 typedef LONG dc_mutex_t;
     65 #define DC_MUTEX_INIT 0
     66 #else
     67 typedef pthread_mutex_t dc_mutex_t;
     68 #define DC_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER
     69 #endif
     70 
     71 #define ISINSTANCE(device) dc_iostream_isinstance((device), &dc_usbhid_vtable)
     72 
     73 typedef struct dc_usbhid_session_t {
     74 	size_t refcount;
     75 #if defined(USE_LIBUSB)
     76 	libusb_context *handle;
     77 #endif
     78 } dc_usbhid_session_t;
     79 
     80 struct dc_usbhid_device_t {
     81 	unsigned short vid, pid;
     82 	dc_usbhid_session_t *session;
     83 #if defined(USE_LIBUSB)
     84 	struct libusb_device *handle;
     85 	int interface;
     86 	unsigned char endpoint_in;
     87 	unsigned char endpoint_out;
     88 	unsigned short packetsize;
     89 #elif defined(USE_HIDAPI)
     90 	char *path;
     91 #endif
     92 };
     93 
     94 #ifdef USBHID
     95 static dc_status_t dc_usbhid_iterator_next (dc_iterator_t *iterator, void *item);
     96 static dc_status_t dc_usbhid_iterator_free (dc_iterator_t *iterator);
     97 
     98 static dc_status_t dc_usbhid_set_timeout (dc_iostream_t *iostream, int timeout);
     99 static dc_status_t dc_usbhid_poll (dc_iostream_t *iostream, int timeout);
    100 static dc_status_t dc_usbhid_read (dc_iostream_t *iostream, void *data, size_t size, size_t *actual);
    101 static dc_status_t dc_usbhid_write (dc_iostream_t *iostream, const void *data, size_t size, size_t *actual);
    102 static dc_status_t dc_usbhid_ioctl (dc_iostream_t *iostream, unsigned int request, void *data, size_t size);
    103 static dc_status_t dc_usbhid_close (dc_iostream_t *iostream);
    104 
    105 typedef struct dc_usbhid_iterator_t {
    106 	dc_iterator_t base;
    107 	dc_descriptor_t *descriptor;
    108 	dc_usbhid_session_t *session;
    109 #if defined(USE_LIBUSB)
    110 	struct libusb_device **devices;
    111 	size_t count;
    112 	size_t current;
    113 #elif defined(USE_HIDAPI)
    114 	struct hid_device_info *devices, *current;
    115 #endif
    116 } dc_usbhid_iterator_t;
    117 
    118 typedef struct dc_usbhid_t {
    119 	/* Base class. */
    120 	dc_iostream_t base;
    121 	/* Internal state. */
    122 	dc_usbhid_session_t *session;
    123 #if defined(USE_LIBUSB)
    124 	libusb_device_handle *handle;
    125 	int interface;
    126 	unsigned char endpoint_in;
    127 	unsigned char endpoint_out;
    128 	unsigned short packetsize;
    129 	unsigned int timeout;
    130 #elif defined(USE_HIDAPI)
    131 	hid_device *handle;
    132 	int timeout;
    133 #endif
    134 } dc_usbhid_t;
    135 
    136 static const dc_iterator_vtable_t dc_usbhid_iterator_vtable = {
    137 	sizeof(dc_usbhid_iterator_t),
    138 	dc_usbhid_iterator_next,
    139 	dc_usbhid_iterator_free,
    140 };
    141 
    142 static const dc_iostream_vtable_t dc_usbhid_vtable = {
    143 	sizeof(dc_usbhid_t),
    144 	dc_usbhid_set_timeout, /* set_timeout */
    145 	NULL, /* set_break */
    146 	NULL, /* set_dtr */
    147 	NULL, /* set_rts */
    148 	NULL, /* get_lines */
    149 	NULL, /* get_available */
    150 	NULL, /* configure */
    151 	dc_usbhid_poll, /* poll */
    152 	dc_usbhid_read, /* read */
    153 	dc_usbhid_write, /* write */
    154 	dc_usbhid_ioctl, /* ioctl */
    155 	NULL, /* flush */
    156 	NULL, /* purge */
    157 	NULL, /* sleep */
    158 	dc_usbhid_close, /* close */
    159 };
    160 
    161 #ifdef USE_HIDAPI
    162 static dc_mutex_t g_usbhid_mutex = DC_MUTEX_INIT;
    163 static dc_usbhid_session_t *g_usbhid_session = NULL;
    164 #endif
    165 
    166 #if defined(USE_LIBUSB)
    167 static dc_status_t
    168 syserror(int errcode)
    169 {
    170 	switch (errcode) {
    171 	case LIBUSB_ERROR_INVALID_PARAM:
    172 		return DC_STATUS_INVALIDARGS;
    173 	case LIBUSB_ERROR_NO_MEM:
    174 		return DC_STATUS_NOMEMORY;
    175 	case LIBUSB_ERROR_NO_DEVICE:
    176 	case LIBUSB_ERROR_NOT_FOUND:
    177 		return DC_STATUS_NODEVICE;
    178 	case LIBUSB_ERROR_ACCESS:
    179 	case LIBUSB_ERROR_BUSY:
    180 		return DC_STATUS_NOACCESS;
    181 	case LIBUSB_ERROR_TIMEOUT:
    182 		return DC_STATUS_TIMEOUT;
    183 	default:
    184 		return DC_STATUS_IO;
    185 	}
    186 }
    187 #endif
    188 
    189 #ifdef USE_HIDAPI
    190 static void
    191 dc_mutex_lock (dc_mutex_t *mutex)
    192 {
    193 #ifdef _WIN32
    194 	while (InterlockedCompareExchange (mutex, 1, 0) == 1) {
    195 		SleepEx (0, TRUE);
    196 	}
    197 #else
    198 	pthread_mutex_lock (mutex);
    199 #endif
    200 }
    201 
    202 static void
    203 dc_mutex_unlock (dc_mutex_t *mutex)
    204 {
    205 #ifdef _WIN32
    206 	InterlockedExchange (mutex, 0);
    207 #else
    208 	pthread_mutex_unlock (mutex);
    209 #endif
    210 }
    211 #endif
    212 
    213 static dc_status_t
    214 dc_usbhid_session_new (dc_usbhid_session_t **out, dc_context_t *context)
    215 {
    216 	dc_status_t status = DC_STATUS_SUCCESS;
    217 	dc_usbhid_session_t *session = NULL;
    218 
    219 	if (out == NULL)
    220 		return DC_STATUS_INVALIDARGS;
    221 
    222 #ifdef USE_HIDAPI
    223 	dc_mutex_lock (&g_usbhid_mutex);
    224 
    225 	if (g_usbhid_session) {
    226 		g_usbhid_session->refcount++;
    227 		*out = g_usbhid_session;
    228 		dc_mutex_unlock (&g_usbhid_mutex);
    229 		return DC_STATUS_SUCCESS;
    230 	}
    231 #endif
    232 
    233 	session = (dc_usbhid_session_t *) malloc (sizeof(dc_usbhid_session_t));
    234 	if (session == NULL) {
    235 		ERROR (context, "Failed to allocate memory.");
    236 		status = DC_STATUS_NOMEMORY;
    237 		goto error_unlock;
    238 	}
    239 
    240 	session->refcount = 1;
    241 
    242 #if defined(USE_LIBUSB)
    243 #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x0100010A)
    244 	int rc = libusb_init_context (&session->handle, NULL, 0);
    245 #else
    246 	int rc = libusb_init (&session->handle);
    247 #endif
    248 	if (rc != LIBUSB_SUCCESS) {
    249 		ERROR (context, "Failed to initialize usb support (%s).",
    250 			libusb_error_name (rc));
    251 		status = syserror (rc);
    252 		goto error_free;
    253 	}
    254 #elif defined(USE_HIDAPI)
    255 	int rc = hid_init();
    256 	if (rc < 0) {
    257 		ERROR (context, "Failed to initialize usb support.");
    258 		status = DC_STATUS_IO;
    259 		goto error_free;
    260 	}
    261 
    262 	g_usbhid_session = session;
    263 
    264 	dc_mutex_unlock (&g_usbhid_mutex);
    265 #endif
    266 
    267 	*out = session;
    268 
    269 	return status;
    270 
    271 error_free:
    272 	free (session);
    273 error_unlock:
    274 #ifdef USE_HIDAPI
    275 	dc_mutex_unlock (&g_usbhid_mutex);
    276 #endif
    277 	return status;
    278 }
    279 
    280 static dc_usbhid_session_t *
    281 dc_usbhid_session_ref (dc_usbhid_session_t *session)
    282 {
    283 	if (session == NULL)
    284 		return NULL;
    285 
    286 #ifdef USE_HIDAPI
    287 	dc_mutex_lock (&g_usbhid_mutex);
    288 #endif
    289 
    290 	session->refcount++;
    291 
    292 #ifdef USE_HIDAPI
    293 	dc_mutex_unlock (&g_usbhid_mutex);
    294 #endif
    295 
    296 	return session;
    297 }
    298 
    299 static dc_status_t
    300 dc_usbhid_session_unref (dc_usbhid_session_t *session)
    301 {
    302 	if (session == NULL)
    303 		return DC_STATUS_SUCCESS;
    304 
    305 #ifdef USE_HIDAPI
    306 	dc_mutex_lock (&g_usbhid_mutex);
    307 #endif
    308 
    309 	if (--session->refcount == 0) {
    310 #if defined(USE_LIBUSB)
    311 		libusb_exit (session->handle);
    312 #elif defined(USE_HIDAPI)
    313 		hid_exit ();
    314 		g_usbhid_session = NULL;
    315 #endif
    316 		free (session);
    317 	}
    318 
    319 #ifdef USE_HIDAPI
    320 	dc_mutex_unlock (&g_usbhid_mutex);
    321 #endif
    322 
    323 	return DC_STATUS_SUCCESS;
    324 }
    325 #endif
    326 
    327 unsigned int
    328 dc_usbhid_device_get_vid (dc_usbhid_device_t *device)
    329 {
    330 	if (device == NULL)
    331 		return 0;
    332 
    333 	return device->vid;
    334 }
    335 
    336 unsigned int
    337 dc_usbhid_device_get_pid (dc_usbhid_device_t *device)
    338 {
    339 	if (device == NULL)
    340 		return 0;
    341 
    342 	return device->pid;
    343 }
    344 
    345 void
    346 dc_usbhid_device_free(dc_usbhid_device_t *device)
    347 {
    348 	if (device == NULL)
    349 		return;
    350 
    351 #ifdef USBHID
    352 #if defined(USE_LIBUSB)
    353 	libusb_unref_device (device->handle);
    354 #elif defined(USE_HIDAPI)
    355 	free (device->path);
    356 #endif
    357 	dc_usbhid_session_unref (device->session);
    358 #endif
    359 	free (device);
    360 }
    361 
    362 dc_status_t
    363 dc_usbhid_iterator_new (dc_iterator_t **out, dc_context_t *context, dc_descriptor_t *descriptor)
    364 {
    365 #ifdef USBHID
    366 	dc_status_t status = DC_STATUS_SUCCESS;
    367 	dc_usbhid_iterator_t *iterator = NULL;
    368 
    369 	if (out == NULL)
    370 		return DC_STATUS_INVALIDARGS;
    371 
    372 	iterator = (dc_usbhid_iterator_t *) dc_iterator_allocate (context, &dc_usbhid_iterator_vtable);
    373 	if (iterator == NULL) {
    374 		ERROR (context, "Failed to allocate memory.");
    375 		return DC_STATUS_NOMEMORY;
    376 	}
    377 
    378 	// Initialize the usb library.
    379 	status = dc_usbhid_session_new (&iterator->session, context);
    380 	if (status != DC_STATUS_SUCCESS) {
    381 		goto error_free;
    382 	}
    383 
    384 #if defined(USE_LIBUSB)
    385 	// Enumerate the USB devices.
    386 	struct libusb_device **devices = NULL;
    387 	ssize_t ndevices = libusb_get_device_list (iterator->session->handle, &devices);
    388 	if (ndevices < 0) {
    389 		ERROR (context, "Failed to enumerate the usb devices (%s).",
    390 			libusb_error_name (ndevices));
    391 		status = syserror (ndevices);
    392 		goto error_session_unref;
    393 	}
    394 
    395 	iterator->devices = devices;
    396 	iterator->count = ndevices;
    397 	iterator->current = 0;
    398 #elif defined(USE_HIDAPI)
    399 	struct hid_device_info *devices = hid_enumerate(0x0, 0x0);
    400 	if (devices == NULL) {
    401 		status = DC_STATUS_IO;
    402 		goto error_session_unref;
    403 	}
    404 
    405 	iterator->devices = devices;
    406 	iterator->current = devices;
    407 #endif
    408 	iterator->descriptor = descriptor;
    409 
    410 	*out = (dc_iterator_t *) iterator;
    411 
    412 	return DC_STATUS_SUCCESS;
    413 
    414 error_session_unref:
    415 	dc_usbhid_session_unref (iterator->session);
    416 error_free:
    417 	dc_iterator_deallocate ((dc_iterator_t *) iterator);
    418 	return status;
    419 #else
    420 	return DC_STATUS_UNSUPPORTED;
    421 #endif
    422 }
    423 
    424 #ifdef USBHID
    425 static dc_status_t
    426 dc_usbhid_iterator_next (dc_iterator_t *abstract, void *out)
    427 {
    428 	dc_usbhid_iterator_t *iterator = (dc_usbhid_iterator_t *) abstract;
    429 	dc_usbhid_device_t *device = NULL;
    430 
    431 #if defined(USE_LIBUSB)
    432 	while (iterator->current < iterator->count) {
    433 		struct libusb_device *current = iterator->devices[iterator->current++];
    434 
    435 		// Get the device descriptor.
    436 		struct libusb_device_descriptor dev;
    437 		int rc = libusb_get_device_descriptor (current, &dev);
    438 		if (rc < 0) {
    439 			ERROR (abstract->context, "Failed to get the device descriptor (%s).",
    440 				libusb_error_name (rc));
    441 			return syserror (rc);
    442 		}
    443 
    444 		dc_usbhid_desc_t usb = {dev.idVendor, dev.idProduct};
    445 		if (!dc_descriptor_filter (iterator->descriptor, DC_TRANSPORT_USBHID, &usb)) {
    446 			continue;
    447 		}
    448 
    449 		// Get the active configuration descriptor.
    450 		struct libusb_config_descriptor *config = NULL;
    451 		rc = libusb_get_active_config_descriptor (current, &config);
    452 		if (rc != LIBUSB_SUCCESS) {
    453 			ERROR (abstract->context, "Failed to get the configuration descriptor (%s).",
    454 				libusb_error_name (rc));
    455 			return syserror (rc);
    456 		}
    457 
    458 		// Find the first HID interface.
    459 		const struct libusb_interface_descriptor *interface = NULL;
    460 		for (unsigned int i = 0; i < config->bNumInterfaces; i++) {
    461 			const struct libusb_interface *iface = &config->interface[i];
    462 			for (int j = 0; j < iface->num_altsetting; j++) {
    463 				const struct libusb_interface_descriptor *desc = &iface->altsetting[j];
    464 				if (desc->bInterfaceClass == LIBUSB_CLASS_HID && interface == NULL) {
    465 					interface = desc;
    466 				}
    467 			}
    468 		}
    469 
    470 		if (interface == NULL) {
    471 			libusb_free_config_descriptor (config);
    472 			continue;
    473 		}
    474 
    475 		// Find the first input and output interrupt endpoints.
    476 		const struct libusb_endpoint_descriptor *ep_in = NULL, *ep_out = NULL;
    477 		for (unsigned int i = 0; i < interface->bNumEndpoints; i++) {
    478 			const struct libusb_endpoint_descriptor *desc = &interface->endpoint[i];
    479 
    480 			unsigned int type = desc->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK;
    481 			unsigned int direction = desc->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK;
    482 
    483 			if (type != LIBUSB_TRANSFER_TYPE_INTERRUPT) {
    484 				continue;
    485 			}
    486 
    487 			if (direction == LIBUSB_ENDPOINT_IN && ep_in == NULL) {
    488 				ep_in = desc;
    489 			}
    490 
    491 			if (direction == LIBUSB_ENDPOINT_OUT && ep_out == NULL) {
    492 				ep_out = desc;
    493 			}
    494 		}
    495 
    496 		if (ep_in == NULL || ep_out == NULL) {
    497 			libusb_free_config_descriptor (config);
    498 			continue;
    499 		}
    500 
    501 		device = (dc_usbhid_device_t *) malloc (sizeof(dc_usbhid_device_t));
    502 		if (device == NULL) {
    503 			ERROR (abstract->context, "Failed to allocate memory.");
    504 			libusb_free_config_descriptor (config);
    505 			return DC_STATUS_NOMEMORY;
    506 		}
    507 
    508 		device->session = dc_usbhid_session_ref (iterator->session);
    509 		device->vid = dev.idVendor;
    510 		device->pid = dev.idProduct;
    511 		device->handle = libusb_ref_device (current);
    512 		device->interface = interface->bInterfaceNumber;
    513 		device->endpoint_in = ep_in->bEndpointAddress;
    514 		device->endpoint_out = ep_out->bEndpointAddress;
    515 		device->packetsize = ep_in->wMaxPacketSize;
    516 
    517 		*(dc_usbhid_device_t **) out = device;
    518 
    519 		libusb_free_config_descriptor (config);
    520 
    521 		return DC_STATUS_SUCCESS;
    522 	}
    523 #elif defined(USE_HIDAPI)
    524 	while (iterator->current) {
    525 		struct hid_device_info *current = iterator->current;
    526 		iterator->current = current->next;
    527 
    528 		dc_usbhid_desc_t usb = {current->vendor_id, current->product_id};
    529 		if (!dc_descriptor_filter (iterator->descriptor, DC_TRANSPORT_USBHID, &usb)) {
    530 			continue;
    531 		}
    532 
    533 		device = (dc_usbhid_device_t *) malloc (sizeof(dc_usbhid_device_t));
    534 		if (device == NULL) {
    535 			ERROR (abstract->context, "Failed to allocate memory.");
    536 			return DC_STATUS_NOMEMORY;
    537 		}
    538 
    539 		device->session = dc_usbhid_session_ref (iterator->session);
    540 		device->vid = current->vendor_id;
    541 		device->pid = current->product_id;
    542 		device->path = strdup (current->path);
    543 
    544 		*(dc_usbhid_device_t **) out = device;
    545 
    546 		return DC_STATUS_SUCCESS;
    547 	}
    548 #endif
    549 
    550 	return DC_STATUS_DONE;
    551 }
    552 
    553 static dc_status_t
    554 dc_usbhid_iterator_free (dc_iterator_t *abstract)
    555 {
    556 	dc_usbhid_iterator_t *iterator = (dc_usbhid_iterator_t *) abstract;
    557 
    558 #if defined(USE_LIBUSB)
    559 	libusb_free_device_list (iterator->devices, 1);
    560 #elif defined(USE_HIDAPI)
    561 	hid_free_enumeration (iterator->devices);
    562 #endif
    563 	dc_usbhid_session_unref (iterator->session);
    564 
    565 	return DC_STATUS_SUCCESS;
    566 }
    567 #endif
    568 
    569 dc_status_t
    570 dc_usbhid_open (dc_iostream_t **out, dc_context_t *context, dc_usbhid_device_t *device)
    571 {
    572 #ifdef USBHID
    573 	dc_status_t status = DC_STATUS_SUCCESS;
    574 	dc_usbhid_t *usbhid = NULL;
    575 
    576 	if (out == NULL || device == NULL)
    577 		return DC_STATUS_INVALIDARGS;
    578 
    579 	INFO (context, "Open: vid=%04x, pid=%04x", device->vid, device->pid);
    580 
    581 	// Allocate memory.
    582 	usbhid = (dc_usbhid_t *) dc_iostream_allocate (context, &dc_usbhid_vtable, DC_TRANSPORT_USBHID);
    583 	if (usbhid == NULL) {
    584 		ERROR (context, "Out of memory.");
    585 		return DC_STATUS_NOMEMORY;
    586 	}
    587 
    588 	// Initialize the usb library.
    589 	usbhid->session = dc_usbhid_session_ref (device->session);
    590 	if (usbhid->session == NULL) {
    591 		goto error_free;
    592 	}
    593 
    594 #if defined(USE_LIBUSB)
    595 	INFO (context, "Open: interface=%u, endpoints=%02x,%02x",
    596 		device->interface, device->endpoint_in, device->endpoint_out);
    597 
    598 	// Open the USB device.
    599 	int rc = libusb_open (device->handle, &usbhid->handle);
    600 	if (rc != LIBUSB_SUCCESS) {
    601 		ERROR (context, "Failed to open the usb device (%s).",
    602 			libusb_error_name (rc));
    603 		status = syserror (rc);
    604 		goto error_session_unref;
    605 	}
    606 
    607 #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000102)
    608 	libusb_set_auto_detach_kernel_driver (usbhid->handle, 1);
    609 #endif
    610 
    611 	// Claim the HID interface.
    612 	rc = libusb_claim_interface (usbhid->handle, device->interface);
    613 	if (rc != LIBUSB_SUCCESS) {
    614 		ERROR (context, "Failed to claim the usb interface (%s).",
    615 			libusb_error_name (rc));
    616 		status = syserror (rc);
    617 		goto error_usb_close;
    618 	}
    619 
    620 	usbhid->interface = device->interface;
    621 	usbhid->endpoint_in = device->endpoint_in;
    622 	usbhid->endpoint_out = device->endpoint_out;
    623 	usbhid->packetsize = device->packetsize;
    624 	usbhid->timeout = 0;
    625 
    626 #elif defined(USE_HIDAPI)
    627 	INFO (context, "Open: path=%s", device->path);
    628 
    629 	// Open the USB device.
    630 	usbhid->handle = hid_open_path (device->path);
    631 	if (usbhid->handle == NULL) {
    632 		ERROR (context, "Failed to open the usb device.");
    633 		status = DC_STATUS_IO;
    634 		goto error_session_unref;
    635 	}
    636 
    637 	usbhid->timeout = -1;
    638 #endif
    639 
    640 	*out = (dc_iostream_t *) usbhid;
    641 
    642 	return DC_STATUS_SUCCESS;
    643 
    644 #if defined(USE_LIBUSB)
    645 error_usb_close:
    646 	libusb_close (usbhid->handle);
    647 #endif
    648 error_session_unref:
    649 	dc_usbhid_session_unref (usbhid->session);
    650 error_free:
    651 	dc_iostream_deallocate ((dc_iostream_t *) usbhid);
    652 	return status;
    653 #else
    654 	return DC_STATUS_UNSUPPORTED;
    655 #endif
    656 }
    657 
    658 #ifdef USBHID
    659 static dc_status_t
    660 dc_usbhid_close (dc_iostream_t *abstract)
    661 {
    662 	dc_status_t status = DC_STATUS_SUCCESS;
    663 	dc_usbhid_t *usbhid = (dc_usbhid_t *) abstract;
    664 
    665 #if defined(USE_LIBUSB)
    666 	libusb_release_interface (usbhid->handle, usbhid->interface);
    667 	libusb_close (usbhid->handle);
    668 #elif defined(USE_HIDAPI)
    669 	hid_close(usbhid->handle);
    670 #endif
    671 	dc_usbhid_session_unref (usbhid->session);
    672 
    673 	return status;
    674 }
    675 
    676 static dc_status_t
    677 dc_usbhid_set_timeout (dc_iostream_t *abstract, int timeout)
    678 {
    679 	dc_usbhid_t *usbhid = (dc_usbhid_t *) abstract;
    680 
    681 #if defined(USE_LIBUSB)
    682 	if (timeout < 0) {
    683 		usbhid->timeout = 0;
    684 	} else if (timeout == 0) {
    685 		return DC_STATUS_UNSUPPORTED;
    686 	} else {
    687 		usbhid->timeout = timeout;
    688 	}
    689 #elif defined(USE_HIDAPI)
    690 	if (timeout < 0) {
    691 		usbhid->timeout = -1;
    692 	} else {
    693 		usbhid->timeout = timeout;
    694 	}
    695 #endif
    696 
    697 	return DC_STATUS_SUCCESS;
    698 }
    699 
    700 static dc_status_t
    701 dc_usbhid_poll (dc_iostream_t *abstract, int timeout)
    702 {
    703 	return DC_STATUS_UNSUPPORTED;
    704 }
    705 
    706 static dc_status_t
    707 dc_usbhid_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual)
    708 {
    709 	dc_status_t status = DC_STATUS_SUCCESS;
    710 	dc_usbhid_t *usbhid = (dc_usbhid_t *) abstract;
    711 	int nbytes = 0;
    712 
    713 #if defined(USE_LIBUSB)
    714 	if (size > usbhid->packetsize) {
    715 		size = usbhid->packetsize;
    716 	}
    717 
    718 	int rc = libusb_interrupt_transfer (usbhid->handle, usbhid->endpoint_in, data, size, &nbytes, usbhid->timeout);
    719 	if (rc != LIBUSB_SUCCESS || nbytes < 0) {
    720 		ERROR (abstract->context, "Usb read interrupt transfer failed (%s).",
    721 			libusb_error_name (rc));
    722 		status = syserror (rc);
    723 		if (nbytes < 0)
    724 			nbytes = 0;
    725 		goto out;
    726 	}
    727 #elif defined(USE_HIDAPI)
    728 	nbytes = hid_read_timeout(usbhid->handle, data, size, usbhid->timeout);
    729 	if (nbytes < 0) {
    730 		ERROR (abstract->context, "Usb read interrupt transfer failed.");
    731 		status = DC_STATUS_IO;
    732 		nbytes = 0;
    733 		goto out;
    734 	}
    735 #endif
    736 
    737 out:
    738 	if (actual)
    739 		*actual = nbytes;
    740 
    741 	return status;
    742 }
    743 
    744 static dc_status_t
    745 dc_usbhid_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual)
    746 {
    747 	dc_status_t status = DC_STATUS_SUCCESS;
    748 	dc_usbhid_t *usbhid = (dc_usbhid_t *) abstract;
    749 	int nbytes = 0;
    750 
    751 	if (size == 0) {
    752 		goto out;
    753 	}
    754 
    755 #if defined(USE_LIBUSB)
    756 	const unsigned char *buffer = (const unsigned char *) data;
    757 	size_t length = size;
    758 
    759 	// Skip a report id of zero.
    760 	unsigned char report = buffer[0];
    761 	if (report == 0) {
    762 		buffer++;
    763 		length--;
    764 	}
    765 
    766 	int rc = libusb_interrupt_transfer (usbhid->handle, usbhid->endpoint_out, (void *) buffer, length, &nbytes, 0);
    767 	if (rc != LIBUSB_SUCCESS || nbytes < 0) {
    768 		ERROR (abstract->context, "Usb write interrupt transfer failed (%s).",
    769 			libusb_error_name (rc));
    770 		status = syserror (rc);
    771 		if (nbytes < 0)
    772 			nbytes = 0;
    773 		goto out;
    774 	}
    775 
    776 	if (report == 0) {
    777 		nbytes++;
    778 	}
    779 #elif defined(USE_HIDAPI)
    780 	nbytes = hid_write(usbhid->handle, data, size);
    781 	if (nbytes < 0) {
    782 		ERROR (abstract->context, "Usb write interrupt transfer failed.");
    783 		status = DC_STATUS_IO;
    784 		nbytes = 0;
    785 		goto out;
    786 	}
    787 #endif
    788 
    789 out:
    790 #ifdef _WIN32
    791 	if ((size_t) nbytes > size) {
    792 		WARNING (abstract->context, "Number of bytes exceeds the buffer size (" DC_PRINTF_SIZE " > " DC_PRINTF_SIZE ")!", nbytes, size);
    793 		nbytes = size;
    794 	}
    795 #endif
    796 
    797 	if (actual)
    798 		*actual = nbytes;
    799 
    800 	return status;
    801 }
    802 
    803 static dc_status_t
    804 dc_usbhid_ioctl (dc_iostream_t *abstract, unsigned int request, void *data, size_t size)
    805 {
    806 	return DC_STATUS_UNSUPPORTED;
    807 }
    808 #endif