Debian Codegraph @

3rdparty/hidapi/linux/hid.c

raw symbols SCIP
1 /*******************************************************
2 HIDAPI - Multi-Platform library for
3 communication with HID devices.
4
5 Alan Ott
6 Signal 11 Software
7
8 libusb/hidapi Team
9
10 Copyright 2022, All Rights Reserved.
11
12 At the discretion of the user of this library,
13 this software may be licensed under the terms of the
14 GNU General Public License v3, a BSD-Style license, or the
15 original HIDAPI license as outlined in the LICENSE.txt,
16 LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
17 files located at the root of the source distribution.
18 These files may also be found in the public source
19 code repository located at:
20 https://github.com/libusb/hidapi .
21 ********************************************************/
22
23 /* C */
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <locale.h>
28 #include <errno.h>
29
30 /* Unix */
31 #include <unistd.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/ioctl.h>
35 #include <sys/utsname.h>
36 #include <fcntl.h>
37 #include <poll.h>
38
39 /* Linux */
40 #include <linux/hidraw.h>
41 #include <linux/version.h>
42 #include <linux/input.h>
43 #include <libudev.h>
44
45 #include "hidapi.h"
46
47 #ifdef HIDAPI_ALLOW_BUILD_WORKAROUND_KERNEL_2_6_39
48 /* This definitions first appeared in Linux Kernel 2.6.39 in linux/hidraw.h.
49 hidapi doesn't support kernels older than that,
50 so we don't define macros below explicitly, to fail builds on old kernels.
51 For those who really need this as a workaround (e.g. to be able to build on old build machines),
52 can workaround by defining the macro above.
53 */
54 #ifndef HIDIOCSFEATURE
55 #define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len)
56 #endif
57 #ifndef HIDIOCGFEATURE
58 #define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len)
59 #endif
60
61 #endif
62
63
64 // HIDIOCGINPUT and HIDIOCSOUTPUT are not defined in Linux kernel headers < 5.11.
65 // These definitions are from hidraw.h in Linux >= 5.11.
66 // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f43d3870cafa2a0f3854c1819c8385733db8f9ae
67 #ifndef HIDIOCGINPUT
68 #define HIDIOCGINPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0A, len)
69 #endif
70 #ifndef HIDIOCSOUTPUT
71 #define HIDIOCSOUTPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0B, len)
72 #endif
73
74 struct hid_device_ {
75 int device_handle;
76 int blocking;
77 wchar_t *last_error_str;
78 wchar_t *last_read_error_str;
79 struct hid_device_info* device_info;
80 };
81
82 static struct hid_api_version api_version = {
83 .major = HID_API_VERSION_MAJOR,
84 .minor = HID_API_VERSION_MINOR,
85 .patch = HID_API_VERSION_PATCH
86 };
87
88 static wchar_t *last_global_error_str = NULL;
89
90
91 static hid_device *new_hid_device(void)
92 {
93 hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
94 if (dev == NULL) {
95 return NULL;
96 }
97
98 dev->device_handle = -1;
99 dev->blocking = 1;
100 dev->last_error_str = NULL;
101 dev->last_read_error_str = NULL;
102 dev->device_info = NULL;
103
104 return dev;
105 }
106
107
108 /* The caller must free the returned string with free(). */
109 static wchar_t *utf8_to_wchar_t(const char *utf8)
110 {
111 wchar_t *ret = NULL;
112
113 if (utf8) {
114 size_t wlen = mbstowcs(NULL, utf8, 0);
115 if ((size_t) -1 == wlen) {
116 return wcsdup(L"");
117 }
118 ret = (wchar_t*) calloc(wlen+1, sizeof(wchar_t));
119 if (ret == NULL) {
120 /* as much as we can do at this point */
121 return NULL;
122 }
123 mbstowcs(ret, utf8, wlen+1);
124 ret[wlen] = 0x0000;
125 }
126
127 return ret;
128 }
129
130
131 /* Makes a copy of the given error message (and decoded according to the
132 * currently locale) into the wide string pointer pointed by error_str.
133 * The last stored error string is freed.
134 * Use register_error_str(NULL) to free the error message completely. */
135 static void register_error_str(wchar_t **error_str, const char *msg)
136 {
137 free(*error_str);
138 *error_str = utf8_to_wchar_t(msg);
139 }
140
141 /* Semilar to register_error_str, but allows passing a format string with va_list args into this function. */
142 static void register_error_str_vformat(wchar_t **error_str, const char *format, va_list args)
143 {
144 char msg[256];
145 vsnprintf(msg, sizeof(msg), format, args);
146
147 register_error_str(error_str, msg);
148 }
149
150 /* Set the last global error to be reported by hid_error(NULL).
151 * The given error message will be copied (and decoded according to the
152 * currently locale, so do not pass in string constants).
153 * The last stored global error message is freed.
154 * Use register_global_error(NULL) to indicate "no error". */
155 static void register_global_error(const char *msg)
156 {
157 register_error_str(&last_global_error_str, msg);
158 }
159
160 /* Similar to register_global_error, but allows passing a format string into this function. */
161 static void register_global_error_format(const char *format, ...)
162 {
163 va_list args;
164 va_start(args, format);
165 register_error_str_vformat(&last_global_error_str, format, args);
166 va_end(args);
167 }
168
169 /* Set the last error for a device to be reported by hid_error(dev).
170 * The given error message will be copied (and decoded according to the
171 * currently locale, so do not pass in string constants).
172 * The last stored device error message is freed.
173 * Use register_device_error(dev, NULL) to indicate "no error". */
174 static void register_device_error(hid_device *dev, const char *msg)
175 {
176 register_error_str(&dev->last_error_str, msg);
177 }
178
179 /* Similar to register_device_error, but you can pass a format string into this function. */
180 static void register_device_error_format(hid_device *dev, const char *format, ...)
181 {
182 va_list args;
183 va_start(args, format);
184 register_error_str_vformat(&dev->last_error_str, format, args);
185 va_end(args);
186 }
187
188 /* Get an attribute value from a udev_device and return it as a whar_t
189 string. The returned string must be freed with free() when done.*/
190 static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name)
191 {
192 return utf8_to_wchar_t(udev_device_get_sysattr_value(dev, udev_name));
193 }
194
195 /*
196 * Gets the size of the HID item at the given position
197 * Returns 1 if successful, 0 if an invalid key
198 * Sets data_len and key_size when successful
199 */
200 static int get_hid_item_size(const __u8 *report_descriptor, __u32 size, unsigned int pos, int *data_len, int *key_size)
201 {
202 int key = report_descriptor[pos];
203 int size_code;
204
205 /*
206 * This is a Long Item. The next byte contains the
207 * length of the data section (value) for this key.
208 * See the HID specification, version 1.11, section
209 * 6.2.2.3, titled "Long Items."
210 */
211 if ((key & 0xf0) == 0xf0) {
212 if (pos + 1 < size)
213 {
214 *data_len = report_descriptor[pos + 1];
215 *key_size = 3;
216 return 1;
217 }
218 *data_len = 0; /* malformed report */
219 *key_size = 0;
220 }
221
222 /*
223 * This is a Short Item. The bottom two bits of the
224 * key contain the size code for the data section
225 * (value) for this key. Refer to the HID
226 * specification, version 1.11, section 6.2.2.2,
227 * titled "Short Items."
228 */
229 size_code = key & 0x3;
230 switch (size_code) {
231 case 0:
232 case 1:
233 case 2:
234 *data_len = size_code;
235 *key_size = 1;
236 return 1;
237 case 3:
238 *data_len = 4;
239 *key_size = 1;
240 return 1;
241 default:
242 /* Can't ever happen since size_code is & 0x3 */
243 *data_len = 0;
244 *key_size = 0;
245 break;
246 };
247
248 /* malformed report */
249 return 0;
250 }
251
252 /*
253 * Get bytes from a HID Report Descriptor.
254 * Only call with a num_bytes of 0, 1, 2, or 4.
255 */
256 static __u32 get_hid_report_bytes(const __u8 *rpt, size_t len, size_t num_bytes, size_t cur)
257 {
258 /* Return if there aren't enough bytes. */
259 if (cur + num_bytes >= len)
260 return 0;
261
262 if (num_bytes == 0)
263 return 0;
264 else if (num_bytes == 1)
265 return rpt[cur + 1];
266 else if (num_bytes == 2)
267 return (rpt[cur + 2] * 256 + rpt[cur + 1]);
268 else if (num_bytes == 4)
269 return (
270 rpt[cur + 4] * 0x01000000 +
271 rpt[cur + 3] * 0x00010000 +
272 rpt[cur + 2] * 0x00000100 +
273 rpt[cur + 1] * 0x00000001
274 );
275 else
276 return 0;
277 }
278
279 /*
280 * Iterates until the end of a Collection.
281 * Assumes that *pos is exactly at the beginning of a Collection.
282 * Skips all nested Collection, i.e. iterates until the end of current level Collection.
283 *
284 * The return value is non-0 when an end of current Collection is found,
285 * 0 when error is occured (broken Descriptor, end of a Collection is found before its begin,
286 * or no Collection is found at all).
287 */
288 static int hid_iterate_over_collection(const __u8 *report_descriptor, __u32 size, unsigned int *pos, int *data_len, int *key_size)
289 {
290 int collection_level = 0;
291
292 while (*pos < size) {
293 int key = report_descriptor[*pos];
294 int key_cmd = key & 0xfc;
295
296 /* Determine data_len and key_size */
297 if (!get_hid_item_size(report_descriptor, size, *pos, data_len, key_size))
298 return 0; /* malformed report */
299
300 switch (key_cmd) {
301 case 0xa0: /* Collection 6.2.2.4 (Main) */
302 collection_level++;
303 break;
304 case 0xc0: /* End Collection 6.2.2.4 (Main) */
305 collection_level--;
306 break;
307 }
308
309 if (collection_level < 0) {
310 /* Broken descriptor or someone is using this function wrong,
311 * i.e. should be called exactly at the collection start */
312 return 0;
313 }
314
315 if (collection_level == 0) {
316 /* Found it!
317 * Also possible when called not at the collection start, but should not happen if used correctly */
318 return 1;
319 }
320
321 *pos += *data_len + *key_size;
322 }
323
324 return 0; /* Did not find the end of a Collection */
325 }
326
327 struct hid_usage_iterator {
328 unsigned int pos;
329 int usage_page_found;
330 unsigned short usage_page;
331 };
332
333 /*
334 * Retrieves the device's Usage Page and Usage from the report descriptor.
335 * The algorithm returns the current Usage Page/Usage pair whenever a new
336 * Collection is found and a Usage Local Item is currently in scope.
337 * Usage Local Items are consumed by each Main Item (See. 6.2.2.8).
338 * The algorithm should give similar results as Apple's:
339 * https://developer.apple.com/documentation/iokit/kiohiddeviceusagepairskey?language=objc
340 * Physical Collections are also matched (macOS does the same).
341 *
342 * This function can be called repeatedly until it returns non-0
343 * Usage is found. pos is the starting point (initially 0) and will be updated
344 * to the next search position.
345 *
346 * The return value is 0 when a pair is found.
347 * 1 when finished processing descriptor.
348 * -1 on a malformed report.
349 */
350 static int get_next_hid_usage(const __u8 *report_descriptor, __u32 size, struct hid_usage_iterator *ctx, unsigned short *usage_page, unsigned short *usage)
351 {
352 int data_len, key_size;
353 int initial = ctx->pos == 0; /* Used to handle case where no top-level application collection is defined */
354
355 int usage_found = 0;
356
357 while (ctx->pos < size) {
358 int key = report_descriptor[ctx->pos];
359 int key_cmd = key & 0xfc;
360
361 /* Determine data_len and key_size */
362 if (!get_hid_item_size(report_descriptor, size, ctx->pos, &data_len, &key_size))
363 return -1; /* malformed report */
364
365 switch (key_cmd) {
366 case 0x4: /* Usage Page 6.2.2.7 (Global) */
367 ctx->usage_page = get_hid_report_bytes(report_descriptor, size, data_len, ctx->pos);
368 ctx->usage_page_found = 1;
369 break;
370
371 case 0x8: /* Usage 6.2.2.8 (Local) */
372 if (data_len == 4) { /* Usages 5.5 / Usage Page 6.2.2.7 */
373 ctx->usage_page = get_hid_report_bytes(report_descriptor, size, 2, ctx->pos + 2);
374 ctx->usage_page_found = 1;
375 *usage = get_hid_report_bytes(report_descriptor, size, 2, ctx->pos);
376 usage_found = 1;
377 }
378 else {
379 *usage = get_hid_report_bytes(report_descriptor, size, data_len, ctx->pos);
380 usage_found = 1;
381 }
382 break;
383
384 case 0xa0: /* Collection 6.2.2.4 (Main) */
385 if (!hid_iterate_over_collection(report_descriptor, size, &ctx->pos, &data_len, &key_size)) {
386 return -1;
387 }
388
389 /* A pair is valid - to be reported when Collection is found */
390 if (usage_found && ctx->usage_page_found) {
391 *usage_page = ctx->usage_page;
392 return 0;
393 }
394
395 break;
396 }
397
398 /* Skip over this key and its associated data */
399 ctx->pos += data_len + key_size;
400 }
401
402 /* If no top-level application collection is found and usage page/usage pair is found, pair is valid
403 https://docs.microsoft.com/en-us/windows-hardware/drivers/hid/top-level-collections */
404 if (initial && usage_found && ctx->usage_page_found) {
405 *usage_page = ctx->usage_page;
406 return 0; /* success */
407 }
408
409 return 1; /* finished processing */
410 }
411
412 /*
413 * Retrieves the hidraw report descriptor from a file.
414 * When using this form, <sysfs_path>/device/report_descriptor, elevated privileges are not required.
415 */
416 static int get_hid_report_descriptor(const char *rpt_path, struct hidraw_report_descriptor *rpt_desc)
417 {
418 int rpt_handle;
419 ssize_t res;
420
421 rpt_handle = open(rpt_path, O_RDONLY | O_CLOEXEC);
422 if (rpt_handle < 0) {
423 register_global_error_format("open failed (%s): %s", rpt_path, strerror(errno));
424 return -1;
425 }
426
427 /*
428 * Read in the Report Descriptor
429 * The sysfs file has a maximum size of 4096 (which is the same as HID_MAX_DESCRIPTOR_SIZE) so we should always
430 * be ok when reading the descriptor.
431 * In practice if the HID descriptor is any larger I suspect many other things will break.
432 */
433 memset(rpt_desc, 0x0, sizeof(*rpt_desc));
434 res = read(rpt_handle, rpt_desc->value, HID_MAX_DESCRIPTOR_SIZE);
435 if (res < 0) {
436 register_global_error_format("read failed (%s): %s", rpt_path, strerror(errno));
437 }
438 rpt_desc->size = (__u32) res;
439
440 close(rpt_handle);
441 return (int) res;
442 }
443
444 /* return size of the descriptor, or -1 on failure */
445 static int get_hid_report_descriptor_from_sysfs(const char *sysfs_path, struct hidraw_report_descriptor *rpt_desc)
446 {
447 int res = -1;
448 /* Construct <sysfs_path>/device/report_descriptor */
449 size_t rpt_path_len = strlen(sysfs_path) + 25 + 1;
450 char* rpt_path = (char*) calloc(1, rpt_path_len);
451 if (!rpt_path)
452 return -1;
453 snprintf(rpt_path, rpt_path_len, "%s/device/report_descriptor", sysfs_path);
454
455 res = get_hid_report_descriptor(rpt_path, rpt_desc);
456 free(rpt_path);
457
458 return res;
459 }
460
461 /* return non-zero if successfully parsed */
462 static int parse_hid_vid_pid_from_uevent(const char *uevent, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id)
463 {
464 char tmp[1024];
465 size_t uevent_len = strlen(uevent);
466 if (uevent_len > sizeof(tmp) - 1)
467 uevent_len = sizeof(tmp) - 1;
468 memcpy(tmp, uevent, uevent_len);
469 tmp[uevent_len] = '\0';
470
471 char *saveptr = NULL;
472 char *line;
473 char *key;
474 char *value;
475
476 line = strtok_r(tmp, "\n", &saveptr);
477 while (line != NULL) {
478 /* line: "KEY=value" */
479 key = line;
480 value = strchr(line, '=');
481 if (!value) {
482 goto next_line;
483 }
484 *value = '\0';
485 value++;
486
487 if (strcmp(key, "HID_ID") == 0) {
488 /**
489 * type vendor product
490 * HID_ID=0003:000005AC:00008242
491 **/
492 int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id);
493 if (ret == 3) {
494 return 1;
495 }
496 }
497
498 next_line:
499 line = strtok_r(NULL, "\n", &saveptr);
500 }
501
502 register_global_error("Couldn't find/parse HID_ID");
503 return 0;
504 }
505
506 /* return non-zero if successfully parsed */
507 static int parse_hid_vid_pid_from_uevent_path(const char *uevent_path, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id)
508 {
509 int handle;
510 ssize_t res;
511
512 handle = open(uevent_path, O_RDONLY | O_CLOEXEC);
513 if (handle < 0) {
514 register_global_error_format("open failed (%s): %s", uevent_path, strerror(errno));
515 return 0;
516 }
517
518 char buf[1024];
519 res = read(handle, buf, sizeof(buf) - 1); /* -1 for '\0' at the end */
520 close(handle);
521
522 if (res < 0) {
523 register_global_error_format("read failed (%s): %s", uevent_path, strerror(errno));
524 return 0;
525 }
526
527 buf[res] = '\0';
528 return parse_hid_vid_pid_from_uevent(buf, bus_type, vendor_id, product_id);
529 }
530
531 /* return non-zero if successfully read/parsed */
532 static int parse_hid_vid_pid_from_sysfs(const char *sysfs_path, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id)
533 {
534 int res = 0;
535 /* Construct <sysfs_path>/device/uevent */
536 size_t uevent_path_len = strlen(sysfs_path) + 14 + 1;
537 char* uevent_path = (char*) calloc(1, uevent_path_len);
538 snprintf(uevent_path, uevent_path_len, "%s/device/uevent", sysfs_path);
539
540 res = parse_hid_vid_pid_from_uevent_path(uevent_path, bus_type, vendor_id, product_id);
541 free(uevent_path);
542
543 return res;
544 }
545
546 static int get_hid_report_descriptor_from_hidraw(hid_device *dev, struct hidraw_report_descriptor *rpt_desc)
547 {
548 int desc_size = 0;
549
550 /* Get Report Descriptor Size */
551 int res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size);
552 if (res < 0) {
553 register_device_error_format(dev, "ioctl(GRDESCSIZE): %s", strerror(errno));
554 return res;
555 }
556
557 /* Get Report Descriptor */
558 memset(rpt_desc, 0x0, sizeof(*rpt_desc));
559 rpt_desc->size = desc_size;
560 res = ioctl(dev->device_handle, HIDIOCGRDESC, rpt_desc);
561 if (res < 0) {
562 register_device_error_format(dev, "ioctl(GRDESC): %s", strerror(errno));
563 }
564
565 return res;
566 }
567
568 /*
569 * The caller is responsible for free()ing the (newly-allocated) character
570 * strings pointed to by serial_number_utf8 and product_name_utf8 after use.
571 */
572 static int parse_uevent_info(const char *uevent, unsigned *bus_type,
573 unsigned short *vendor_id, unsigned short *product_id,
574 char **serial_number_utf8, char **product_name_utf8)
575 {
576 char tmp[1024];
577
578 if (!uevent) {
579 return 0;
580 }
581
582 size_t uevent_len = strlen(uevent);
583 if (uevent_len > sizeof(tmp) - 1)
584 uevent_len = sizeof(tmp) - 1;
585 memcpy(tmp, uevent, uevent_len);
586 tmp[uevent_len] = '\0';
587
588 char *saveptr = NULL;
589 char *line;
590 char *key;
591 char *value;
592
593 int found_id = 0;
594 int found_serial = 0;
595 int found_name = 0;
596
597 line = strtok_r(tmp, "\n", &saveptr);
598 while (line != NULL) {
599 /* line: "KEY=value" */
600 key = line;
601 value = strchr(line, '=');
602 if (!value) {
603 goto next_line;
604 }
605 *value = '\0';
606 value++;
607
608 if (strcmp(key, "HID_ID") == 0) {
609 /**
610 * type vendor product
611 * HID_ID=0003:000005AC:00008242
612 **/
613 int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id);
614 if (ret == 3) {
615 found_id = 1;
616 }
617 } else if (strcmp(key, "HID_NAME") == 0) {
618 /* The caller has to free the product name */
619 *product_name_utf8 = strdup(value);
620 found_name = 1;
621 } else if (strcmp(key, "HID_UNIQ") == 0) {
622 /* The caller has to free the serial number */
623 *serial_number_utf8 = strdup(value);
624 found_serial = 1;
625 }
626
627 next_line:
628 line = strtok_r(NULL, "\n", &saveptr);
629 }
630
631 return (found_id && found_name && found_serial);
632 }
633
634
635 static struct hid_device_info * create_device_info_for_device(struct udev_device *raw_dev)
636 {
637 struct hid_device_info *root = NULL;
638 struct hid_device_info *cur_dev = NULL;
639
640 const char *sysfs_path;
641 const char *dev_path;
642 const char *str;
643 struct udev_device *hid_dev; /* The device's HID udev node. */
644 struct udev_device *usb_dev; /* The device's USB udev node. */
645 struct udev_device *intf_dev; /* The device's interface (in the USB sense). */
646 unsigned short dev_vid;
647 unsigned short dev_pid;
648 char *serial_number_utf8 = NULL;
649 char *product_name_utf8 = NULL;
650 unsigned bus_type;
651 int result;
652 struct hidraw_report_descriptor report_desc;
653
654 sysfs_path = udev_device_get_syspath(raw_dev);
655 dev_path = udev_device_get_devnode(raw_dev);
656
657 hid_dev = udev_device_get_parent_with_subsystem_devtype(
658 raw_dev,
659 "hid",
660 NULL);
661
662 if (!hid_dev) {
663 /* Unable to find parent hid device. */
664 goto end;
665 }
666
667 result = parse_uevent_info(
668 udev_device_get_sysattr_value(hid_dev, "uevent"),
669 &bus_type,
670 &dev_vid,
671 &dev_pid,
672 &serial_number_utf8,
673 &product_name_utf8);
674
675 if (!result) {
676 /* parse_uevent_info() failed for at least one field. */
677 goto end;
678 }
679
680 /* Filter out unhandled devices right away */
681 switch (bus_type) {
682 case BUS_BLUETOOTH:
683 case BUS_I2C:
684 case BUS_USB:
685 case BUS_SPI:
686 case BUS_VIRTUAL:
687 break;
688
689 default:
690 goto end;
691 }
692
693 /* Create the record. */
694 root = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
695 if (!root)
696 goto end;
697
698 cur_dev = root;
699
700 /* Fill out the record */
701 cur_dev->next = NULL;
702 cur_dev->path = dev_path? strdup(dev_path): NULL;
703
704 /* VID/PID */
705 cur_dev->vendor_id = dev_vid;
706 cur_dev->product_id = dev_pid;
707
708 /* Serial Number */
709 cur_dev->serial_number = utf8_to_wchar_t(serial_number_utf8);
710
711 /* Release Number */
712 cur_dev->release_number = 0x0;
713
714 /* Interface Number */
715 cur_dev->interface_number = -1;
716
717 switch (bus_type) {
718 case BUS_USB:
719 /* The device pointed to by raw_dev contains information about
720 the hidraw device. In order to get information about the
721 USB device, get the parent device with the
722 subsystem/devtype pair of "usb"/"usb_device". This will
723 be several levels up the tree, but the function will find
724 it. */
725 usb_dev = udev_device_get_parent_with_subsystem_devtype(
726 raw_dev,
727 "usb",
728 "usb_device");
729
730 /* uhid USB devices
731 * Since this is a virtual hid interface, no USB information will
732 * be available. */
733 if (!usb_dev) {
734 /* Manufacturer and Product strings */
735 cur_dev->manufacturer_string = wcsdup(L"");
736 cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
737 break;
738 }
739
740 cur_dev->manufacturer_string = copy_udev_string(usb_dev, "manufacturer");
741 cur_dev->product_string = copy_udev_string(usb_dev, "product");
742
743 cur_dev->bus_type = HID_API_BUS_USB;
744
745 str = udev_device_get_sysattr_value(usb_dev, "bcdDevice");
746 cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0;
747
748 /* Get a handle to the interface's udev node. */
749 intf_dev = udev_device_get_parent_with_subsystem_devtype(
750 raw_dev,
751 "usb",
752 "usb_interface");
753 if (intf_dev) {
754 str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber");
755 cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1;
756 }
757
758 break;
759
760 case BUS_BLUETOOTH:
761 cur_dev->manufacturer_string = wcsdup(L"");
762 cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
763
764 cur_dev->bus_type = HID_API_BUS_BLUETOOTH;
765
766 break;
767 case BUS_I2C:
768 cur_dev->manufacturer_string = wcsdup(L"");
769 cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
770
771 cur_dev->bus_type = HID_API_BUS_I2C;
772
773 break;
774
775 case BUS_SPI:
776 cur_dev->manufacturer_string = wcsdup(L"");
777 cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
778
779 cur_dev->bus_type = HID_API_BUS_SPI;
780
781 break;
782
783 case BUS_VIRTUAL:
784 cur_dev->manufacturer_string = wcsdup(L"");
785 cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
786
787 cur_dev->bus_type = HID_API_BUS_VIRTUAL;
788
789 break;
790
791 default:
792 /* Unknown device type - this should never happen, as we
793 * check for USB and Bluetooth devices above */
794 break;
795 }
796
797 /* Usage Page and Usage */
798
799 if (sysfs_path) {
800 result = get_hid_report_descriptor_from_sysfs(sysfs_path, &report_desc);
801 }
802 else {
803 result = -1;
804 }
805
806 if (result >= 0) {
807 unsigned short page = 0, usage = 0;
808 struct hid_usage_iterator usage_iterator;
809 memset(&usage_iterator, 0, sizeof(usage_iterator));
810
811 /*
812 * Parse the first usage and usage page
813 * out of the report descriptor.
814 */
815 if (!get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage)) {
816 cur_dev->usage_page = page;
817 cur_dev->usage = usage;
818 }
819
820 /*
821 * Parse any additional usage and usage pages
822 * out of the report descriptor.
823 */
824 while (!get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage)) {
825 /* Create new record for additional usage pairs */
826 struct hid_device_info *tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
827 struct hid_device_info *prev_dev = cur_dev;
828
829 if (!tmp)
830 break;
831 cur_dev->next = tmp;
832 cur_dev = tmp;
833
834 /* Update fields */
835 cur_dev->path = dev_path? strdup(dev_path): NULL;
836 cur_dev->vendor_id = dev_vid;
837 cur_dev->product_id = dev_pid;
838 cur_dev->serial_number = prev_dev->serial_number? wcsdup(prev_dev->serial_number): NULL;
839 cur_dev->release_number = prev_dev->release_number;
840 cur_dev->interface_number = prev_dev->interface_number;
841 cur_dev->manufacturer_string = prev_dev->manufacturer_string? wcsdup(prev_dev->manufacturer_string): NULL;
842 cur_dev->product_string = prev_dev->product_string? wcsdup(prev_dev->product_string): NULL;
843 cur_dev->usage_page = page;
844 cur_dev->usage = usage;
845 cur_dev->bus_type = prev_dev->bus_type;
846 }
847 }
848
849 end:
850 free(serial_number_utf8);
851 free(product_name_utf8);
852
853 return root;
854 }
855
856 static struct hid_device_info * create_device_info_for_hid_device(hid_device *dev) {
857 struct udev *udev;
858 struct udev_device *udev_dev;
859 struct stat s;
860 int ret = -1;
861 struct hid_device_info *root = NULL;
862
863 register_device_error(dev, NULL);
864
865 /* Get the dev_t (major/minor numbers) from the file handle. */
866 ret = fstat(dev->device_handle, &s);
867 if (-1 == ret) {
868 register_device_error(dev, "Failed to stat device handle");
869 return NULL;
870 }
871
872 /* Create the udev object */
873 udev = udev_new();
874 if (!udev) {
875 errno = ENOMEM;
876 register_device_error(dev, "Couldn't create udev context");
877 return NULL;
878 }
879
880 /* Open a udev device from the dev_t. 'c' means character device. */
881 udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev);
882 if (udev_dev) {
883 root = create_device_info_for_device(udev_dev);
884 }
885
886 if (!root) {
887 /* TODO: have a better error reporting via create_device_info_for_device */
888 errno = EIO;
889 register_device_error(dev, "Couldn't create hid_device_info");
890 }
891
892 udev_device_unref(udev_dev);
893 udev_unref(udev);
894
895 return root;
896 }
897
898 HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void)
899 {
900 return &api_version;
901 }
902
903 HID_API_EXPORT const char* HID_API_CALL hid_version_str(void)
904 {
905 return HID_API_VERSION_STR;
906 }
907
908 int HID_API_EXPORT hid_init(void)
909 {
910 const char *locale;
911
912 /* indicate no error */
913 register_global_error(NULL);
914
915 /* Set the locale if it's not set. */
916 locale = setlocale(LC_CTYPE, NULL);
917 if (!locale)
918 setlocale(LC_CTYPE, "");
919
920 return 0;
921 }
922
923 int HID_API_EXPORT hid_exit(void)
924 {
925 /* Free global error message */
926 register_global_error(NULL);
927
928 return 0;
929 }
930
931 struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
932 {
933 struct udev *udev;
934 struct udev_enumerate *enumerate;
935 struct udev_list_entry *devices, *dev_list_entry;
936
937 struct hid_device_info *root = NULL; /* return object */
938 struct hid_device_info *cur_dev = NULL;
939
940 hid_init();
941 /* register_global_error: global error is reset by hid_init */
942
943 /* Create the udev object */
944 udev = udev_new();
945 if (!udev) {
946 register_global_error("Couldn't create udev context");
947 return NULL;
948 }
949
950 /* Create a list of the devices in the 'hidraw' subsystem. */
951 enumerate = udev_enumerate_new(udev);
952 udev_enumerate_add_match_subsystem(enumerate, "hidraw");
953 udev_enumerate_scan_devices(enumerate);
954 devices = udev_enumerate_get_list_entry(enumerate);
955 /* For each item, see if it matches the vid/pid, and if so
956 create a udev_device record for it */
957 udev_list_entry_foreach(dev_list_entry, devices) {
958 const char *sysfs_path;
959 unsigned short dev_vid = 0;
960 unsigned short dev_pid = 0;
961 unsigned bus_type = 0;
962 struct udev_device *raw_dev; /* The device's hidraw udev node. */
963 struct hid_device_info * tmp;
964
965 /* Get the filename of the /sys entry for the device
966 and create a udev_device object (dev) representing it */
967 sysfs_path = udev_list_entry_get_name(dev_list_entry);
968 if (!sysfs_path)
969 continue;
970
971 if (vendor_id != 0 || product_id != 0) {
972 if (!parse_hid_vid_pid_from_sysfs(sysfs_path, &bus_type, &dev_vid, &dev_pid))
973 continue;
974
975 if (vendor_id != 0 && vendor_id != dev_vid)
976 continue;
977 if (product_id != 0 && product_id != dev_pid)
978 continue;
979 }
980
981 raw_dev = udev_device_new_from_syspath(udev, sysfs_path);
982 if (!raw_dev)
983 continue;
984
985 tmp = create_device_info_for_device(raw_dev);
986 if (tmp) {
987 if (cur_dev) {
988 cur_dev->next = tmp;
989 }
990 else {
991 root = tmp;
992 }
993 cur_dev = tmp;
994
995 /* move the pointer to the tail of returned list */
996 while (cur_dev->next != NULL) {
997 cur_dev = cur_dev->next;
998 }
999 }
1000
1001 udev_device_unref(raw_dev);
1002 }
1003 /* Free the enumerator and udev objects. */
1004 udev_enumerate_unref(enumerate);
1005 udev_unref(udev);
1006
1007 if (root == NULL) {
1008 if (vendor_id == 0 && product_id == 0) {
1009 register_global_error("No HID devices found in the system.");
1010 } else {
1011 register_global_error("No HID devices with requested VID/PID found in the system.");
1012 }
1013 }
1014
1015 return root;
1016 }
1017
1018 void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
1019 {
1020 struct hid_device_info *d = devs;
1021 while (d) {
1022 struct hid_device_info *next = d->next;
1023 free(d->path);
1024 free(d->serial_number);
1025 free(d->manufacturer_string);
1026 free(d->product_string);
1027 free(d);
1028 d = next;
1029 }
1030 }
1031
1032 hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
1033 {
1034 struct hid_device_info *devs, *cur_dev;
1035 const char *path_to_open = NULL;
1036 hid_device *handle = NULL;
1037
1038 /* register_global_error: global error is reset by hid_enumerate/hid_init */
1039 devs = hid_enumerate(vendor_id, product_id);
1040 if (devs == NULL) {
1041 /* register_global_error: global error is already set by hid_enumerate */
1042 return NULL;
1043 }
1044
1045 cur_dev = devs;
1046 while (cur_dev) {
1047 if (cur_dev->vendor_id == vendor_id &&
1048 cur_dev->product_id == product_id) {
1049 if (serial_number) {
1050 if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
1051 path_to_open = cur_dev->path;
1052 break;
1053 }
1054 }
1055 else {
1056 path_to_open = cur_dev->path;
1057 break;
1058 }
1059 }
1060 cur_dev = cur_dev->next;
1061 }
1062
1063 if (path_to_open) {
1064 /* Open the device */
1065 handle = hid_open_path(path_to_open);
1066 } else {
1067 register_global_error("Device with requested VID/PID/(SerialNumber) not found");
1068 }
1069
1070 hid_free_enumeration(devs);
1071
1072 return handle;
1073 }
1074
1075 hid_device * HID_API_EXPORT hid_open_path(const char *path)
1076 {
1077 hid_device *dev = NULL;
1078
1079 hid_init();
1080 /* register_global_error: global error is reset by hid_init */
1081
1082 dev = new_hid_device();
1083 if (!dev) {
1084 errno = ENOMEM;
1085 register_global_error("Couldn't allocate memory");
1086 return NULL;
1087 }
1088
1089 dev->device_handle = open(path, O_RDWR | O_CLOEXEC);
1090
1091 if (dev->device_handle >= 0) {
1092 int res, desc_size = 0;
1093
1094 /* Make sure this is a HIDRAW device - responds to HIDIOCGRDESCSIZE */
1095 res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size);
1096 if (res < 0) {
1097 register_global_error_format("ioctl(GRDESCSIZE) error for '%s', not a HIDRAW device?: %s", path, strerror(errno));
1098 hid_close(dev);
1099 return NULL;
1100 }
1101
1102 return dev;
1103 }
1104 else {
1105 /* Unable to open a device. */
1106 free(dev);
1107 register_global_error_format("Failed to open a device with path '%s': %s", path, strerror(errno));
1108 return NULL;
1109 }
1110 }
1111
1112
1113 int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
1114 {
1115 int bytes_written;
1116
1117 if (!data || (length == 0)) {
1118 errno = EINVAL;
1119 register_device_error(dev, "Zero buffer/length");
1120 return -1;
1121 }
1122
1123 bytes_written = write(dev->device_handle, data, length);
1124
1125 register_device_error(dev, (bytes_written == -1)? strerror(errno): NULL);
1126
1127 return bytes_written;
1128 }
1129
1130
1131 int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
1132 {
1133 if (!data || (length == 0)) {
1134 errno = EINVAL;
1135 register_error_str(&dev->last_read_error_str, "Zero buffer/length");
1136 return -1;
1137 }
1138
1139 /* Set device error to none */
1140 register_error_str(&dev->last_read_error_str, NULL);
1141
1142 int bytes_read;
1143
1144 if (milliseconds >= 0) {
1145 /* Milliseconds is either 0 (non-blocking) or > 0 (contains
1146 a valid timeout). In both cases we want to call poll()
1147 and wait for data to arrive. Don't rely on non-blocking
1148 operation (O_NONBLOCK) since some kernels don't seem to
1149 properly report device disconnection through read() when
1150 in non-blocking mode. */
1151 int ret;
1152 struct pollfd fds;
1153
1154 fds.fd = dev->device_handle;
1155 fds.events = POLLIN;
1156 fds.revents = 0;
1157 ret = poll(&fds, 1, milliseconds);
1158 if (ret == 0) {
1159 /* Timeout */
1160 return ret;
1161 }
1162 if (ret == -1) {
1163 /* Error */
1164 register_error_str(&dev->last_read_error_str, strerror(errno));
1165 return ret;
1166 }
1167 else {
1168 /* Check for errors on the file descriptor. This will
1169 indicate a device disconnection. */
1170 if (fds.revents & (POLLERR | POLLHUP | POLLNVAL)) {
1171 // We cannot use strerror() here as no -1 was returned from poll().
1172 errno = EIO;
1173 register_error_str(&dev->last_read_error_str, "hid_read_timeout: unexpected poll error (device disconnected)");
1174 return -1;
1175 }
1176 }
1177 }
1178
1179 bytes_read = read(dev->device_handle, data, length);
1180 if (bytes_read < 0) {
1181 if (errno == EAGAIN || errno == EINPROGRESS)
1182 bytes_read = 0;
1183 else
1184 register_error_str(&dev->last_read_error_str, strerror(errno));
1185 }
1186
1187 return bytes_read;
1188 }
1189
1190 int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
1191 {
1192 return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
1193 }
1194
1195 HID_API_EXPORT const wchar_t * HID_API_CALL hid_read_error(hid_device *dev)
1196 {
1197 if (dev->last_read_error_str == NULL)
1198 return L"Success";
1199 return dev->last_read_error_str;
1200 }
1201
1202 int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
1203 {
1204 /* Do all non-blocking in userspace using poll(), since it looks
1205 like there's a bug in the kernel in some versions where
1206 read() will not return -1 on disconnection of the USB device */
1207
1208 dev->blocking = !nonblock;
1209 return 0; /* Success */
1210 }
1211
1212
1213 int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
1214 {
1215 int res;
1216
1217 if (!data || (length == 0)) {
1218 errno = EINVAL;
1219 register_device_error(dev, "Zero buffer/length");
1220 return -1;
1221 }
1222
1223 register_device_error(dev, NULL);
1224
1225 res = ioctl(dev->device_handle, HIDIOCSFEATURE(length), data);
1226 if (res < 0)
1227 register_device_error_format(dev, "ioctl (SFEATURE): %s", strerror(errno));
1228
1229 return res;
1230 }
1231
1232 int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
1233 {
1234 int res;
1235
1236 if (!data || (length == 0)) {
1237 errno = EINVAL;
1238 register_device_error(dev, "Zero buffer/length");
1239 return -1;
1240 }
1241
1242 register_device_error(dev, NULL);
1243
1244 res = ioctl(dev->device_handle, HIDIOCGFEATURE(length), data);
1245 if (res < 0)
1246 register_device_error_format(dev, "ioctl (GFEATURE): %s", strerror(errno));
1247
1248 return res;
1249 }
1250
1251 int HID_API_EXPORT HID_API_CALL hid_send_output_report(hid_device *dev, const unsigned char *data, size_t length)
1252 {
1253 int res;
1254
1255 if (!data || (length == 0)) {
1256 errno = EINVAL;
1257 register_device_error(dev, "Zero buffer/length");
1258 return -1;
1259 }
1260
1261 register_device_error(dev, NULL);
1262
1263 res = ioctl(dev->device_handle, HIDIOCSOUTPUT(length), data);
1264 if (res < 0)
1265 register_device_error_format(dev, "ioctl (SOUTPUT): %s", strerror(errno));
1266
1267 return res;
1268 }
1269
1270 int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length)
1271 {
1272 int res;
1273
1274 if (!data || (length == 0)) {
1275 errno = EINVAL;
1276 register_device_error(dev, "Zero buffer/length");
1277 return -1;
1278 }
1279
1280 register_device_error(dev, NULL);
1281
1282 res = ioctl(dev->device_handle, HIDIOCGINPUT(length), data);
1283 if (res < 0)
1284 register_device_error_format(dev, "ioctl (GINPUT): %s", strerror(errno));
1285
1286 return res;
1287 }
1288
1289 void HID_API_EXPORT hid_close(hid_device *dev)
1290 {
1291 if (!dev)
1292 return;
1293
1294 close(dev->device_handle);
1295
1296 free(dev->last_error_str);
1297 free(dev->last_read_error_str);
1298
1299 hid_free_enumeration(dev->device_info);
1300
1301 free(dev);
1302 }
1303
1304
1305 int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
1306 {
1307 if (!string || !maxlen) {
1308 errno = EINVAL;
1309 register_device_error(dev, "Zero buffer/length");
1310 return -1;
1311 }
1312
1313 struct hid_device_info *info = hid_get_device_info(dev);
1314 if (!info) {
1315 // hid_get_device_info will have set an error already
1316 return -1;
1317 }
1318
1319 if (info->manufacturer_string) {
1320 wcsncpy(string, info->manufacturer_string, maxlen);
1321 string[maxlen - 1] = L'\0';
1322 }
1323 else {
1324 string[0] = L'\0';
1325 }
1326
1327 return 0;
1328 }
1329
1330 int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
1331 {
1332 if (!string || !maxlen) {
1333 errno = EINVAL;
1334 register_device_error(dev, "Zero buffer/length");
1335 return -1;
1336 }
1337
1338 struct hid_device_info *info = hid_get_device_info(dev);
1339 if (!info) {
1340 // hid_get_device_info will have set an error already
1341 return -1;
1342 }
1343
1344 if (info->product_string) {
1345 wcsncpy(string, info->product_string, maxlen);
1346 string[maxlen - 1] = L'\0';
1347 }
1348 else {
1349 string[0] = L'\0';
1350 }
1351
1352 return 0;
1353 }
1354
1355 int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
1356 {
1357 if (!string || !maxlen) {
1358 errno = EINVAL;
1359 register_device_error(dev, "Zero buffer/length");
1360 return -1;
1361 }
1362
1363 struct hid_device_info *info = hid_get_device_info(dev);
1364 if (!info) {
1365 // hid_get_device_info will have set an error already
1366 return -1;
1367 }
1368
1369 if (info->serial_number) {
1370 wcsncpy(string, info->serial_number, maxlen);
1371 string[maxlen - 1] = L'\0';
1372 }
1373 else {
1374 string[0] = L'\0';
1375 }
1376
1377 return 0;
1378 }
1379
1380
1381 HID_API_EXPORT struct hid_device_info *HID_API_CALL hid_get_device_info(hid_device *dev) {
1382 if (dev->device_info) {
1383 register_device_error(dev, NULL);
1384 }
1385 else {
1386 // Lazy initialize device_info
1387 dev->device_info = create_device_info_for_hid_device(dev);
1388 }
1389
1390 // create_device_info_for_hid_device will set an error if needed
1391 return dev->device_info;
1392 }
1393
1394 int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
1395 {
1396 (void)string_index;
1397 (void)string;
1398 (void)maxlen;
1399
1400 errno = ENOSYS;
1401 register_device_error(dev, "hid_get_indexed_string: not supported by hidraw");
1402
1403 return -1;
1404 }
1405
1406
1407 int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size)
1408 {
1409 struct hidraw_report_descriptor rpt_desc;
1410
1411 if (!buf || !buf_size) {
1412 errno = EINVAL;
1413 register_device_error(dev, "Zero buffer/length");
1414 return -1;
1415 }
1416
1417 register_device_error(dev, NULL);
1418
1419 int res = get_hid_report_descriptor_from_hidraw(dev, &rpt_desc);
1420 if (res < 0) {
1421 /* error already registered */
1422 return res;
1423 }
1424
1425 if (rpt_desc.size < buf_size) {
1426 buf_size = (size_t) rpt_desc.size;
1427 }
1428
1429 memcpy(buf, rpt_desc.value, buf_size);
1430
1431 return (int) buf_size;
1432 }
1433
1434
1435 /* Passing in NULL means asking for the last global error message. */
1436 HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
1437 {
1438 if (dev) {
1439 if (dev->last_error_str == NULL)
1440 return L"Success";
1441 return dev->last_error_str;
1442 }
1443
1444 if (last_global_error_str == NULL)
1445 return L"Success";
1446 return last_global_error_str;
1447 }