1 /*******************************************************
2  HIDAPI - Multi-Platform library for
3  communication with HID devices.
4 
5  Alan Ott
6  Signal 11 Software
7 
8  8/22/2009
9  Linux Version - 6/2/2009
10 
11  Copyright 2009, All Rights Reserved.
12 
13  At the discretion of the user of this library,
14  this software may be licensed under the terms of the
15  GNU General Public License v3, a BSD-Style license, or the
16  original HIDAPI license as outlined in the LICENSE.txt,
17  LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
18  files located at the root of the source distribution.
19  These files may also be found in the public source
20  code repository located at:
21         https://github.com/libusb/hidapi .
22 ********************************************************/
23 #include "../../SDL_internal.h"
24 
25 #ifndef _GNU_SOURCE
26 #define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */
27 #endif
28 
29 /* C */
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <locale.h>
34 #include <errno.h>
35 
36 /* Unix */
37 #include <unistd.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/ioctl.h>
41 #include <sys/utsname.h>
42 #include <fcntl.h>
43 #include <poll.h>
44 
45 /* Linux */
46 #include <linux/hidraw.h>
47 #include <linux/version.h>
48 #include <linux/input.h>
49 #include <libudev.h>
50 
51 #include "../hidapi/hidapi.h"
52 
53 #ifdef NAMESPACE
54 namespace NAMESPACE
55 {
56 #endif
57 
58 /* Definitions from linux/hidraw.h. Since these are new, some distros
59    may not have header files which contain them. */
60 #ifndef HIDIOCSFEATURE
61 #define HIDIOCSFEATURE(len)    _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len)
62 #endif
63 #ifndef HIDIOCGFEATURE
64 #define HIDIOCGFEATURE(len)    _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len)
65 #endif
66 
67 /* USB HID device property names */
68 const char *device_string_names[] = {
69 	"manufacturer",
70 	"product",
71 	"serial",
72 };
73 
74 /* Symbolic names for the properties above */
75 enum device_string_id {
76 	DEVICE_STRING_MANUFACTURER,
77 	DEVICE_STRING_PRODUCT,
78 	DEVICE_STRING_SERIAL,
79 
80 	DEVICE_STRING_COUNT,
81 };
82 
83 struct hid_device_ {
84 	int device_handle;
85 	int blocking;
86 	int uses_numbered_reports;
87 	int needs_ble_hack;
88 };
89 
90 
91 static __u32 kernel_version = 0;
92 
detect_kernel_version(void)93 static __u32 detect_kernel_version(void)
94 {
95 	struct utsname name;
96 	int major, minor, release;
97 	int ret;
98 
99 	uname(&name);
100 	ret = sscanf(name.release, "%d.%d.%d", &major, &minor, &release);
101 	if (ret == 3) {
102 		return KERNEL_VERSION(major, minor, release);
103 	}
104 
105 	ret = sscanf(name.release, "%d.%d", &major, &minor);
106 	if (ret == 2) {
107 		return KERNEL_VERSION(major, minor, 0);
108 	}
109 
110 	printf("Couldn't determine kernel version from version string \"%s\"\n", name.release);
111 	return 0;
112 }
113 
new_hid_device(void)114 static hid_device *new_hid_device(void)
115 {
116 	hid_device *dev = (hid_device *)calloc(1, sizeof(hid_device));
117 	dev->device_handle = -1;
118 	dev->blocking = 1;
119 	dev->uses_numbered_reports = 0;
120 	dev->needs_ble_hack = 0;
121 
122 	return dev;
123 }
124 
125 
126 /* The caller must free the returned string with free(). */
utf8_to_wchar_t(const char * utf8)127 static wchar_t *utf8_to_wchar_t(const char *utf8)
128 {
129 	wchar_t *ret = NULL;
130 
131 	if (utf8) {
132 		size_t wlen = mbstowcs(NULL, utf8, 0);
133 		if ((size_t) -1 == wlen) {
134 			return wcsdup(L"");
135 		}
136 		ret = (wchar_t *)calloc(wlen+1, sizeof(wchar_t));
137 		mbstowcs(ret, utf8, wlen+1);
138 		ret[wlen] = 0x0000;
139 	}
140 
141 	return ret;
142 }
143 
144 /* Get an attribute value from a udev_device and return it as a whar_t
145    string. The returned string must be freed with free() when done.*/
copy_udev_string(struct udev_device * dev,const char * udev_name)146 static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name)
147 {
148 	return utf8_to_wchar_t(udev_device_get_sysattr_value(dev, udev_name));
149 }
150 
151 /* uses_numbered_reports() returns 1 if report_descriptor describes a device
152    which contains numbered reports. */
uses_numbered_reports(__u8 * report_descriptor,__u32 size)153 static int uses_numbered_reports(__u8 *report_descriptor, __u32 size) {
154 	unsigned int i = 0;
155 	int size_code;
156 	int data_len, key_size;
157 
158 	while (i < size) {
159 		int key = report_descriptor[i];
160 
161 		/* Check for the Report ID key */
162 		if (key == 0x85/*Report ID*/) {
163 			/* This device has a Report ID, which means it uses
164 			   numbered reports. */
165 			return 1;
166 		}
167 
168 		//printf("key: %02hhx\n", key);
169 
170 		if ((key & 0xf0) == 0xf0) {
171 			/* This is a Long Item. The next byte contains the
172 			   length of the data section (value) for this key.
173 			   See the HID specification, version 1.11, section
174 			   6.2.2.3, titled "Long Items." */
175 			if (i+1 < size)
176 				data_len = report_descriptor[i+1];
177 			else
178 				data_len = 0; /* malformed report */
179 			key_size = 3;
180 		}
181 		else {
182 			/* This is a Short Item. The bottom two bits of the
183 			   key contain the size code for the data section
184 			   (value) for this key.  Refer to the HID
185 			   specification, version 1.11, section 6.2.2.2,
186 			   titled "Short Items." */
187 			size_code = key & 0x3;
188 			switch (size_code) {
189 			case 0:
190 			case 1:
191 			case 2:
192 				data_len = size_code;
193 				break;
194 			case 3:
195 				data_len = 4;
196 				break;
197 			default:
198 				/* Can't ever happen since size_code is & 0x3 */
199 				data_len = 0;
200 				break;
201 			};
202 			key_size = 1;
203 		}
204 
205 		/* Skip over this key and it's associated data */
206 		i += data_len + key_size;
207 	}
208 
209 	/* Didn't find a Report ID key. Device doesn't use numbered reports. */
210 	return 0;
211 }
212 
213 /*
214  * The caller is responsible for free()ing the (newly-allocated) character
215  * strings pointed to by serial_number_utf8 and product_name_utf8 after use.
216  */
217 static int
parse_uevent_info(const char * uevent,unsigned * bus_type,unsigned short * vendor_id,unsigned short * product_id,char ** serial_number_utf8,char ** product_name_utf8)218 parse_uevent_info(const char *uevent, unsigned *bus_type,
219 	unsigned short *vendor_id, unsigned short *product_id,
220 	char **serial_number_utf8, char **product_name_utf8)
221 {
222 	char *tmp = strdup(uevent);
223 	char *saveptr = NULL;
224 	char *line;
225 	char *key;
226 	char *value;
227 
228 	int found_id = 0;
229 	int found_serial = 0;
230 	int found_name = 0;
231 
232 	line = strtok_r(tmp, "\n", &saveptr);
233 	while (line != NULL) {
234 		/* line: "KEY=value" */
235 		key = line;
236 		value = strchr(line, '=');
237 		if (!value) {
238 			goto next_line;
239 		}
240 		*value = '\0';
241 		value++;
242 
243 		if (strcmp(key, "HID_ID") == 0) {
244 			/**
245 			 *        type vendor   product
246 			 * HID_ID=0003:000005AC:00008242
247 			 **/
248 			int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id);
249 			if (ret == 3) {
250 				found_id = 1;
251 			}
252 		} else if (strcmp(key, "HID_NAME") == 0) {
253 			/* The caller has to free the product name */
254 			*product_name_utf8 = strdup(value);
255 			found_name = 1;
256 		} else if (strcmp(key, "HID_UNIQ") == 0) {
257 			/* The caller has to free the serial number */
258 			*serial_number_utf8 = strdup(value);
259 			found_serial = 1;
260 		}
261 
262 next_line:
263 		line = strtok_r(NULL, "\n", &saveptr);
264 	}
265 
266 	free(tmp);
267 	return (found_id && found_name && found_serial);
268 }
269 
is_BLE(hid_device * dev)270 static int is_BLE(hid_device *dev)
271 {
272 	struct udev *udev;
273 	struct udev_device *udev_dev, *hid_dev;
274 	struct stat s;
275 	int ret;
276 
277 	/* Create the udev object */
278 	udev = udev_new();
279 	if (!udev) {
280 		printf("Can't create udev\n");
281 		return -1;
282 	}
283 
284 	/* Get the dev_t (major/minor numbers) from the file handle. */
285 	if (fstat(dev->device_handle, &s) < 0) {
286 		udev_unref(udev);
287 		return -1;
288 	}
289 
290 	/* Open a udev device from the dev_t. 'c' means character device. */
291 	ret = 0;
292 	udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev);
293 	if (udev_dev) {
294 		hid_dev = udev_device_get_parent_with_subsystem_devtype(
295 			udev_dev,
296 			"hid",
297 			NULL);
298 		if (hid_dev) {
299 			unsigned short dev_vid = 0;
300 			unsigned short dev_pid = 0;
301 			unsigned bus_type = 0;
302 			char *serial_number_utf8 = NULL;
303 			char *product_name_utf8 = NULL;
304 
305 			parse_uevent_info(
306 			           udev_device_get_sysattr_value(hid_dev, "uevent"),
307 			           &bus_type,
308 			           &dev_vid,
309 			           &dev_pid,
310 			           &serial_number_utf8,
311 			           &product_name_utf8);
312 			free(serial_number_utf8);
313 			free(product_name_utf8);
314 
315 			if (bus_type == BUS_BLUETOOTH) {
316 				/* Right now the Steam Controller is the only BLE device that we send feature reports to */
317 				if (dev_vid == 0x28de /* Valve */) {
318 					ret = 1;
319 				}
320 			}
321 
322 			/* hid_dev doesn't need to be (and can't be) unref'd.
323 			   I'm not sure why, but it'll throw double-free() errors. */
324 		}
325 		udev_device_unref(udev_dev);
326 	}
327 
328 	udev_unref(udev);
329 
330 	return ret;
331 }
332 
get_device_string(hid_device * dev,enum device_string_id key,wchar_t * string,size_t maxlen)333 static int get_device_string(hid_device *dev, enum device_string_id key, wchar_t *string, size_t maxlen)
334 {
335 	struct udev *udev;
336 	struct udev_device *udev_dev, *parent, *hid_dev;
337 	struct stat s;
338 	int ret = -1;
339 	char *serial_number_utf8 = NULL;
340 	char *product_name_utf8 = NULL;
341 	char *tmp;
342 
343 	/* Create the udev object */
344 	udev = udev_new();
345 	if (!udev) {
346 		printf("Can't create udev\n");
347 		return -1;
348 	}
349 
350 	/* Get the dev_t (major/minor numbers) from the file handle. */
351 	ret = fstat(dev->device_handle, &s);
352 	if (-1 == ret) {
353 		udev_unref(udev);
354 		return ret;
355 	}
356 	/* Open a udev device from the dev_t. 'c' means character device. */
357 	udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev);
358 	if (udev_dev) {
359 		hid_dev = udev_device_get_parent_with_subsystem_devtype(
360 			udev_dev,
361 			"hid",
362 			NULL);
363 		if (hid_dev) {
364 			unsigned short dev_vid;
365 			unsigned short dev_pid;
366 			unsigned bus_type;
367 			size_t retm;
368 
369 			ret = parse_uevent_info(
370 			           udev_device_get_sysattr_value(hid_dev, "uevent"),
371 			           &bus_type,
372 			           &dev_vid,
373 			           &dev_pid,
374 			           &serial_number_utf8,
375 			           &product_name_utf8);
376 
377 			if (bus_type == BUS_BLUETOOTH) {
378 				switch (key) {
379 					case DEVICE_STRING_MANUFACTURER:
380 						wcsncpy(string, L"", maxlen);
381 						ret = 0;
382 						break;
383 					case DEVICE_STRING_PRODUCT:
384 						retm = mbstowcs(string, product_name_utf8, maxlen);
385 						ret = (retm == (size_t)-1)? -1: 0;
386 						break;
387 					case DEVICE_STRING_SERIAL:
388 						/* Bluetooth serial numbers are often the bluetooth device address
389 						   and we want that with the colons stripped out, which is the correct
390 						   serial number for PS4 controllers
391 						 */
392 						while ((tmp = strchr(serial_number_utf8, ':')) != NULL) {
393 							memmove(tmp, tmp+1, strlen(tmp));
394 						}
395 						retm = mbstowcs(string, serial_number_utf8, maxlen);
396 						ret = (retm == (size_t)-1)? -1: 0;
397 						break;
398 					case DEVICE_STRING_COUNT:
399 					default:
400 						ret = -1;
401 						break;
402 				}
403 			}
404 			else {
405 				/* This is a USB device. Find its parent USB Device node. */
406 				parent = udev_device_get_parent_with_subsystem_devtype(
407 					   udev_dev,
408 					   "usb",
409 					   "usb_device");
410 				if (parent) {
411 					const char *str;
412 					const char *key_str = NULL;
413 
414 					if (key >= 0 && key < DEVICE_STRING_COUNT) {
415 						key_str = device_string_names[key];
416 					} else {
417 						ret = -1;
418 						goto end;
419 					}
420 
421 					str = udev_device_get_sysattr_value(parent, key_str);
422 					if (str) {
423 						/* Convert the string from UTF-8 to wchar_t */
424 						retm = mbstowcs(string, str, maxlen);
425 						ret = (retm == (size_t)-1)? -1: 0;
426 						goto end;
427 					}
428 				}
429 			}
430 		}
431 	}
432 
433 end:
434 	free(serial_number_utf8);
435 	free(product_name_utf8);
436 
437 	udev_device_unref(udev_dev);
438 	/* parent and hid_dev don't need to be (and can't be) unref'd.
439 	   I'm not sure why, but they'll throw double-free() errors. */
440 	udev_unref(udev);
441 
442 	return ret;
443 }
444 
hid_init(void)445 int HID_API_EXPORT hid_init(void)
446 {
447 	const char *locale;
448 
449 	/* Set the locale if it's not set. */
450 	locale = setlocale(LC_CTYPE, NULL);
451 	if (!locale)
452 		setlocale(LC_CTYPE, "");
453 
454 	kernel_version = detect_kernel_version();
455 
456 	return 0;
457 }
458 
hid_exit(void)459 int HID_API_EXPORT hid_exit(void)
460 {
461 	/* Nothing to do for this in the Linux/hidraw implementation. */
462 	return 0;
463 }
464 
465 
hid_enumerate(unsigned short vendor_id,unsigned short product_id)466 struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
467 {
468 	struct udev *udev;
469 	struct udev_enumerate *enumerate;
470 	struct udev_list_entry *devices, *dev_list_entry;
471 
472 	struct hid_device_info *root = NULL; /* return object */
473 	struct hid_device_info *cur_dev = NULL;
474 	struct hid_device_info *prev_dev = NULL; /* previous device */
475 
476 	hid_init();
477 
478 	/* Create the udev object */
479 	udev = udev_new();
480 	if (!udev) {
481 		printf("Can't create udev\n");
482 		return NULL;
483 	}
484 
485 	/* Create a list of the devices in the 'hidraw' subsystem. */
486 	enumerate = udev_enumerate_new(udev);
487 	udev_enumerate_add_match_subsystem(enumerate, "hidraw");
488 	udev_enumerate_scan_devices(enumerate);
489 	devices = udev_enumerate_get_list_entry(enumerate);
490 	/* For each item, see if it matches the vid/pid, and if so
491 	   create a udev_device record for it */
492 	udev_list_entry_foreach(dev_list_entry, devices) {
493 		const char *sysfs_path;
494 		const char *dev_path;
495 		const char *str;
496 		struct udev_device *raw_dev; /* The device's hidraw udev node. */
497 		struct udev_device *hid_dev; /* The device's HID udev node. */
498 		struct udev_device *usb_dev; /* The device's USB udev node. */
499 		struct udev_device *intf_dev; /* The device's interface (in the USB sense). */
500 		unsigned short dev_vid;
501 		unsigned short dev_pid;
502 		char *serial_number_utf8 = NULL;
503 		char *product_name_utf8 = NULL;
504 		unsigned bus_type;
505 		int result;
506 
507 		/* Get the filename of the /sys entry for the device
508 		   and create a udev_device object (dev) representing it */
509 		sysfs_path = udev_list_entry_get_name(dev_list_entry);
510 		raw_dev = udev_device_new_from_syspath(udev, sysfs_path);
511 		dev_path = udev_device_get_devnode(raw_dev);
512 
513 		hid_dev = udev_device_get_parent_with_subsystem_devtype(
514 			raw_dev,
515 			"hid",
516 			NULL);
517 
518 		if (!hid_dev) {
519 			/* Unable to find parent hid device. */
520 			goto next;
521 		}
522 
523 		result = parse_uevent_info(
524 			udev_device_get_sysattr_value(hid_dev, "uevent"),
525 			&bus_type,
526 			&dev_vid,
527 			&dev_pid,
528 			&serial_number_utf8,
529 			&product_name_utf8);
530 
531 		if (!result) {
532 			/* parse_uevent_info() failed for at least one field. */
533 			goto next;
534 		}
535 
536 		if (bus_type != BUS_USB && bus_type != BUS_BLUETOOTH) {
537 			/* We only know how to handle USB and BT devices. */
538 			goto next;
539 		}
540 
541 		if (access(dev_path, R_OK|W_OK) != 0) {
542 			/* We can't open this device, ignore it */
543 			goto next;
544 		}
545 
546 		/* Check the VID/PID against the arguments */
547 		if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
548 		    (product_id == 0x0 || product_id == dev_pid)) {
549 			struct hid_device_info *tmp;
550 
551 			/* VID/PID match. Create the record. */
552 			tmp = (struct hid_device_info *)calloc(1, sizeof(struct hid_device_info));
553 			if (cur_dev) {
554 				cur_dev->next = tmp;
555 			}
556 			else {
557 				root = tmp;
558 			}
559 			prev_dev = cur_dev;
560 			cur_dev = tmp;
561 
562 			/* Fill out the record */
563 			cur_dev->next = NULL;
564 			cur_dev->path = dev_path? strdup(dev_path): NULL;
565 
566 			/* VID/PID */
567 			cur_dev->vendor_id = dev_vid;
568 			cur_dev->product_id = dev_pid;
569 
570 			/* Serial Number */
571 			cur_dev->serial_number = utf8_to_wchar_t(serial_number_utf8);
572 
573 			/* Release Number */
574 			cur_dev->release_number = 0x0;
575 
576 			/* Interface Number */
577 			cur_dev->interface_number = -1;
578 
579 			switch (bus_type) {
580 				case BUS_USB:
581 					/* The device pointed to by raw_dev contains information about
582 					   the hidraw device. In order to get information about the
583 					   USB device, get the parent device with the
584 					   subsystem/devtype pair of "usb"/"usb_device". This will
585 					   be several levels up the tree, but the function will find
586 					   it. */
587 					usb_dev = udev_device_get_parent_with_subsystem_devtype(
588 							raw_dev,
589 							"usb",
590 							"usb_device");
591 
592 					if (!usb_dev) {
593 						/* Free this device */
594 						free(cur_dev->serial_number);
595 						free(cur_dev->path);
596 						free(cur_dev);
597 
598 						/* Take it off the device list. */
599 						if (prev_dev) {
600 							prev_dev->next = NULL;
601 							cur_dev = prev_dev;
602 						}
603 						else {
604 							cur_dev = root = NULL;
605 						}
606 
607 						goto next;
608 					}
609 
610 					/* Manufacturer and Product strings */
611 					cur_dev->manufacturer_string = copy_udev_string(usb_dev, device_string_names[DEVICE_STRING_MANUFACTURER]);
612 					cur_dev->product_string = copy_udev_string(usb_dev, device_string_names[DEVICE_STRING_PRODUCT]);
613 
614 					/* Release Number */
615 					str = udev_device_get_sysattr_value(usb_dev, "bcdDevice");
616 					cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0;
617 
618 					/* Get a handle to the interface's udev node. */
619 					intf_dev = udev_device_get_parent_with_subsystem_devtype(
620 							raw_dev,
621 							"usb",
622 							"usb_interface");
623 					if (intf_dev) {
624 						str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber");
625 						cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1;
626 					}
627 
628 					break;
629 
630 				case BUS_BLUETOOTH:
631 					/* Manufacturer and Product strings */
632 					cur_dev->manufacturer_string = wcsdup(L"");
633 					cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
634 
635 					break;
636 
637 				default:
638 					/* Unknown device type - this should never happen, as we
639 					 * check for USB and Bluetooth devices above */
640 					break;
641 			}
642 		}
643 
644 	next:
645 		free(serial_number_utf8);
646 		free(product_name_utf8);
647 		udev_device_unref(raw_dev);
648 		/* hid_dev, usb_dev and intf_dev don't need to be (and can't be)
649 		   unref()d.  It will cause a double-free() error.  I'm not
650 		   sure why.  */
651 	}
652 	/* Free the enumerator and udev objects. */
653 	udev_enumerate_unref(enumerate);
654 	udev_unref(udev);
655 
656 	return root;
657 }
658 
hid_free_enumeration(struct hid_device_info * devs)659 void  HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
660 {
661 	struct hid_device_info *d = devs;
662 	while (d) {
663 		struct hid_device_info *next = d->next;
664 		free(d->path);
665 		free(d->serial_number);
666 		free(d->manufacturer_string);
667 		free(d->product_string);
668 		free(d);
669 		d = next;
670 	}
671 }
672 
hid_open(unsigned short vendor_id,unsigned short product_id,const wchar_t * serial_number)673 hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
674 {
675 	struct hid_device_info *devs, *cur_dev;
676 	const char *path_to_open = NULL;
677 	hid_device *handle = NULL;
678 
679 	devs = hid_enumerate(vendor_id, product_id);
680 	cur_dev = devs;
681 	while (cur_dev) {
682 		if (cur_dev->vendor_id == vendor_id &&
683 		    cur_dev->product_id == product_id) {
684 			if (serial_number) {
685 				if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
686 					path_to_open = cur_dev->path;
687 					break;
688 				}
689 			}
690 			else {
691 				path_to_open = cur_dev->path;
692 				break;
693 			}
694 		}
695 		cur_dev = cur_dev->next;
696 	}
697 
698 	if (path_to_open) {
699 		/* Open the device */
700 		handle = hid_open_path(path_to_open, 0);
701 	}
702 
703 	hid_free_enumeration(devs);
704 
705 	return handle;
706 }
707 
hid_open_path(const char * path,int bExclusive)708 hid_device * HID_API_EXPORT hid_open_path(const char *path, int bExclusive)
709 {
710 	hid_device *dev = NULL;
711 
712 	hid_init();
713 
714 	dev = new_hid_device();
715 
716 	/* OPEN HERE */
717 	dev->device_handle = open(path, O_RDWR | O_CLOEXEC);
718 
719 	/* If we have a good handle, return it. */
720 	if (dev->device_handle >= 0) {
721 
722 		/* Get the report descriptor */
723 		int res, desc_size = 0;
724 		struct hidraw_report_descriptor rpt_desc;
725 
726 		memset(&rpt_desc, 0x0, sizeof(rpt_desc));
727 
728 		/* Get Report Descriptor Size */
729 		res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size);
730 		if (res < 0)
731 			perror("HIDIOCGRDESCSIZE");
732 
733 
734 		/* Get Report Descriptor */
735 		rpt_desc.size = desc_size;
736 		res = ioctl(dev->device_handle, HIDIOCGRDESC, &rpt_desc);
737 		if (res < 0) {
738 			perror("HIDIOCGRDESC");
739 		} else {
740 			/* Determine if this device uses numbered reports. */
741 			dev->uses_numbered_reports =
742 				uses_numbered_reports(rpt_desc.value,
743 				                      rpt_desc.size);
744 		}
745 
746 		dev->needs_ble_hack = (is_BLE(dev) == 1);
747 
748 		return dev;
749 	}
750 	else {
751 		/* Unable to open any devices. */
752 		free(dev);
753 		return NULL;
754 	}
755 }
756 
757 
hid_write(hid_device * dev,const unsigned char * data,size_t length)758 int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
759 {
760 	int bytes_written;
761 
762 	bytes_written = write(dev->device_handle, data, length);
763 
764 	return bytes_written;
765 }
766 
767 
hid_read_timeout(hid_device * dev,unsigned char * data,size_t length,int milliseconds)768 int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
769 {
770 	int bytes_read;
771 
772 	if (milliseconds >= 0) {
773 		/* Milliseconds is either 0 (non-blocking) or > 0 (contains
774 		   a valid timeout). In both cases we want to call poll()
775 		   and wait for data to arrive.  Don't rely on non-blocking
776 		   operation (O_NONBLOCK) since some kernels don't seem to
777 		   properly report device disconnection through read() when
778 		   in non-blocking mode.  */
779 		int ret;
780 		struct pollfd fds;
781 
782 		fds.fd = dev->device_handle;
783 		fds.events = POLLIN;
784 		fds.revents = 0;
785 		ret = poll(&fds, 1, milliseconds);
786 		if (ret == -1 || ret == 0) {
787 			/* Error or timeout */
788 			return ret;
789 		}
790 		else {
791 			/* Check for errors on the file descriptor. This will
792 			   indicate a device disconnection. */
793 			if (fds.revents & (POLLERR | POLLHUP | POLLNVAL))
794 				return -1;
795 		}
796 	}
797 
798 	bytes_read = read(dev->device_handle, data, length);
799 	if (bytes_read < 0 && (errno == EAGAIN || errno == EINPROGRESS))
800 		bytes_read = 0;
801 
802 	if (bytes_read >= 0 &&
803 	    kernel_version != 0 &&
804 	    kernel_version < KERNEL_VERSION(2,6,34) &&
805 	    dev->uses_numbered_reports) {
806 		/* Work around a kernel bug. Chop off the first byte. */
807 		memmove(data, data+1, bytes_read);
808 		bytes_read--;
809 	}
810 
811 	return bytes_read;
812 }
813 
hid_read(hid_device * dev,unsigned char * data,size_t length)814 int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
815 {
816 	return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
817 }
818 
hid_set_nonblocking(hid_device * dev,int nonblock)819 int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
820 {
821 	/* Do all non-blocking in userspace using poll(), since it looks
822 	   like there's a bug in the kernel in some versions where
823 	   read() will not return -1 on disconnection of the USB device */
824 
825 	dev->blocking = !nonblock;
826 	return 0; /* Success */
827 }
828 
hid_send_feature_report(hid_device * dev,const unsigned char * data,size_t length)829 int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
830 {
831 	static const int MAX_RETRIES = 50;
832 	int retry;
833 	int res;
834 
835 	for (retry = 0; retry < MAX_RETRIES; ++retry) {
836 		res = ioctl(dev->device_handle, HIDIOCSFEATURE(length), data);
837 		if (res < 0 && errno == EPIPE) {
838 			/* Try again... */
839 			continue;
840 		}
841 
842 		if (res < 0)
843 			perror("ioctl (SFEATURE)");
844 		break;
845 	}
846 	return res;
847 }
848 
hid_get_feature_report(hid_device * dev,unsigned char * data,size_t length)849 int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
850 {
851 	int res;
852 	unsigned char report = data[0];
853 
854 	res = ioctl(dev->device_handle, HIDIOCGFEATURE(length), data);
855 	if (res < 0)
856 		perror("ioctl (GFEATURE)");
857 	else if (dev->needs_ble_hack) {
858 		/* Versions of BlueZ before 5.56 don't include the report in the data,
859 		 * and versions of BlueZ >= 5.56 include 2 copies of the report.
860 		 * We'll fix it so that there is a single copy of the report in both cases
861 		 */
862 		if (data[0] == report && data[1] == report) {
863 			memmove(&data[0], &data[1], res);
864 		} else if (data[0] != report) {
865 			memmove(&data[1], &data[0], res);
866 			data[0] = report;
867 			++res;
868 		}
869 	}
870 	return res;
871 }
872 
873 
hid_close(hid_device * dev)874 void HID_API_EXPORT hid_close(hid_device *dev)
875 {
876 	if (!dev)
877 		return;
878 	close(dev->device_handle);
879 	free(dev);
880 }
881 
882 
hid_get_manufacturer_string(hid_device * dev,wchar_t * string,size_t maxlen)883 int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
884 {
885 	return get_device_string(dev, DEVICE_STRING_MANUFACTURER, string, maxlen);
886 }
887 
hid_get_product_string(hid_device * dev,wchar_t * string,size_t maxlen)888 int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
889 {
890 	return get_device_string(dev, DEVICE_STRING_PRODUCT, string, maxlen);
891 }
892 
hid_get_serial_number_string(hid_device * dev,wchar_t * string,size_t maxlen)893 int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
894 {
895 	return get_device_string(dev, DEVICE_STRING_SERIAL, string, maxlen);
896 }
897 
hid_get_indexed_string(hid_device * dev,int string_index,wchar_t * string,size_t maxlen)898 int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
899 {
900 	(void)dev;
901 	(void)string_index;
902 	(void)string;
903 	(void)maxlen;
904 	return -1;
905 }
906 
907 
hid_error(hid_device * dev)908 HID_API_EXPORT const wchar_t * HID_API_CALL  hid_error(hid_device *dev)
909 {
910 	return NULL;
911 }
912 
913 #ifdef NAMESPACE
914 }
915 #endif
916