signal11 / hidapi

A Simple library for communicating with USB and Bluetooth HID devices on Linux, Mac, and Windows.
http://www.signal11.us/oss/hidapi/
Other
2.46k stars 901 forks source link

FD 0 is a valid file descriptor #462

Open mzyngier opened 4 years ago

mzyngier commented 4 years ago

Playing with usbrelay (which uses hidapi), I noticed that it fails if FD 0 is closed and that an open result is FD 0 being allocated by the kernel:

maz@pygmy-twylyte:~$ (exec 0<&-; usbrelay)
Device Found
  type: 16c0 05df
  path: /dev/hidraw0
  serial_number: 
  Manufacturer: www.dcttech.com
  Product:      USBRelay2
  Release:      100
  Interface:    0
  Number of Relays = 2
unable to open device

strace confirms this:

openat(AT_FDCWD, "/dev/hidraw0", O_RDWR) = 0
write(2, "unable to open device\n", 22) = 22

The bug seems to be here: https://github.com/signal11/hidapi/blob/98629a104b9f567e6cfde263febc3bc776970b50/linux/hid.c#L632

easily fixed with:

diff --git a/linux/hid.c b/linux/hid.c
index 56dac0f..f99cd5c 100644
--- a/linux/hid.c
+++ b/linux/hid.c
@@ -629,7 +629,7 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path)
    dev->device_handle = open(path, O_RDWR);

    /* If we have a good handle, return it. */
-   if (dev->device_handle > 0) {
+   if (dev->device_handle >= 0) {

        /* Get the report descriptor */
        int res, desc_size = 0;