From bb395cb37ac75da6c3a4ee3e5323dc5c7071ca04 Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Sat, 6 Jan 2024 01:22:27 +0100 Subject: [PATCH 1/9] Add binding for UI_GET_SYSNAME ioctl --- evdev/uinput.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/evdev/uinput.c b/evdev/uinput.c index 6848bc2..1581092 100644 --- a/evdev/uinput.c +++ b/evdev/uinput.c @@ -97,6 +97,24 @@ uinput_set_prop(PyObject *self, PyObject *args) return NULL; } +static PyObject * +uinput_get_sysname(PyObject *self, PyObject *args) +{ + int fd; + char sysname[64]; + + int ret = PyArg_ParseTuple(args, "i", &fd); + if (!ret) return NULL; + + if (ioctl(fd, UI_GET_SYSNAME(sizeof(sysname)), &sysname) < 0) + goto on_err; + + return Py_BuildValue("s", &sysname); + + on_err: + PyErr_SetFromErrno(PyExc_IOError); + return NULL; +} // Different kernel versions have different device setup methods. You can read // more about it here: @@ -361,6 +379,9 @@ static PyMethodDef MethodTable[] = { { "set_phys", uinput_set_phys, METH_VARARGS, "Set physical path"}, + { "get_sysname", uinput_get_sysname, METH_VARARGS, + "Obtain the sysname of the uinput device."}, + { "set_prop", uinput_set_prop, METH_VARARGS, "Set device input property"}, From 294bc47adaf5fbf981cc2ec6e7269ea9fb530471 Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Sat, 6 Jan 2024 01:23:14 +0100 Subject: [PATCH 2/9] New modern Linux-specific method to find device The old method of scanning the filesystem to find an event device with a matching name was prone to race conditions, required a time.sleep delay, unnecessarily opened many event devices, and had other fixable issues. The new UI_GET_SYSNAME-based method is immune to race conditions and does not require time.sleep(), while also not suffering from the aforementioned fixable issues. --- evdev/uinput.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/evdev/uinput.py b/evdev/uinput.py index 5b11bd7..4b8ba84 100644 --- a/evdev/uinput.py +++ b/evdev/uinput.py @@ -1,6 +1,8 @@ # encoding: utf-8 import os +import platform +import re import stat import time from collections import defaultdict @@ -159,7 +161,7 @@ def __init__(self, #: An :class:`InputDevice ` instance #: for the fake input device. ``None`` if the device cannot be #: opened for reading and writing. - self.device = self._find_device() + self.device = self._find_device(self.fd) def _prepare_events(self, events): '''Prepare events for passing to _uinput.enable and _uinput.setup''' @@ -281,7 +283,52 @@ def _verify(self): msg = 'uinput device name must not be longer than {} characters' raise UInputError(msg.format(_uinput.maxnamelen)) - def _find_device(self): + def _find_device(self, fd): + ''' + Tries to find the device node. Will delegate this task to one of + several platform-specific functions. + ''' + try: + sysname = _uinput.get_sysname(fd) + except OSError: + # UI_GET_SYSNAME returned an error code. We're likely dealing with + # an old kernel. Guess the device based on the filesystem. + return self._find_device_fallback() + + try: + if platform.system() == 'Linux': + return self._find_device_linux(sysname) + except OSError: + pass + + # If we're not running or Linux or the above method fails for any reason, + # use the generic fallback method. + return self._find_device_fallback() + + def _find_device_linux(self, sysname): + ''' + Tries to find the device node when running on Linux. + ''' + + syspath = f'/sys/devices/virtual/input/{sysname}' + + # The sysfs entry for event devices should contain exactly one folder + # whose name matches the format "event[0-9]+". It is then assumed that + # the device node in /dev/input uses the same name. + regex = re.compile('event[0-9]+') + for entry in os.listdir(syspath): + if regex.fullmatch(entry): + device_path = f'/dev/input/{entry}' + return device.InputDevice(device_path) + + raise FileNotFoundError() + + def _find_device_fallback(self): + ''' + Tries to find the device node when UI_GET_SYSNAME is not available or + we're running on a system sufficiently exotic that we do not know how + to interpret its return value. + ''' #:bug: the device node might not be immediately available time.sleep(0.1) From 2c0d9e343a9c78b627751e35c2642d34ed55fd16 Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Sat, 6 Jan 2024 13:48:55 +0000 Subject: [PATCH 3/9] Move get_sysname() to the same block as _find_device_linux() Co-authored-by: Tobi <28510156+sezanzeb@users.noreply.github.com> --- evdev/uinput.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/evdev/uinput.py b/evdev/uinput.py index 4b8ba84..6a1aa59 100644 --- a/evdev/uinput.py +++ b/evdev/uinput.py @@ -288,18 +288,14 @@ def _find_device(self, fd): Tries to find the device node. Will delegate this task to one of several platform-specific functions. ''' - try: - sysname = _uinput.get_sysname(fd) - except OSError: - # UI_GET_SYSNAME returned an error code. We're likely dealing with - # an old kernel. Guess the device based on the filesystem. - return self._find_device_fallback() - - try: - if platform.system() == 'Linux': + if platform.system() == 'Linux': + try: + sysname = _uinput.get_sysname(fd) return self._find_device_linux(sysname) - except OSError: - pass + except OSError: + # UI_GET_SYSNAME returned an error code. We're likely dealing with + # an old kernel. Guess the device based on the filesystem. + pass # If we're not running or Linux or the above method fails for any reason, # use the generic fallback method. From e0f45c204cc1b0127b72299906e277d6bfb4dd91 Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Sat, 6 Jan 2024 15:15:08 +0100 Subject: [PATCH 4/9] Sort event devices in _find_device_fallback() --- evdev/uinput.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/evdev/uinput.py b/evdev/uinput.py index 6a1aa59..9cb69f0 100644 --- a/evdev/uinput.py +++ b/evdev/uinput.py @@ -328,7 +328,21 @@ def _find_device_fallback(self): #:bug: the device node might not be immediately available time.sleep(0.1) + # Strictly speaking, we cannot be certain that everything returned by list_devices() + # ends at event[0-9]+: it might return something like "/dev/input/events_all". Find + # the devices that have the expected structure and extract their device number. + path_number_pairs = [] + regex = re.compile('/dev/input/event([0-9]+)') for path in util.list_devices('/dev/input/'): + regex_match = regex.fullmatch(path) + if not regex_match: + continue + device_number = int(regex_match[1]) + path_number_pairs.append((path, device_number)) + + path_number_pairs.sort(key=lambda pair: pair[1], reverse=True) + + for (path, _) in path_number_pairs: d = device.InputDevice(path) if d.name == self.name: return d From 05b5685bced758c35b0e1d049a62d91bd9cf7601 Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Sat, 6 Jan 2024 17:00:19 +0100 Subject: [PATCH 5/9] Wait 0.1s if /dev/input/event* does not exist Unlike what a previous commit claimed, the new method is only guaranteed to find the device name instantaneously, but if /dev is managed by udev, the corresponding /dev/input/input* file might not exist immediately. On modern Linux systems, those files are managed by devtmpfs so they do show up immediately and it would be a waste of time to sleep, but we do want a fallback time.sleep() call for those operating systems which do not use devtmpfs. It is assumed that on any linux system, /sys is managed by sysfs; it conceptually doesn't really make sense to let that directory be managed by any other filesystem because the files in /sys are basically syscalls. As such, we assume that /sys always updates instantaneously, and if for whatever reason it doesn't, _find_device_fallback shall be used instead. --- evdev/uinput.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/evdev/uinput.py b/evdev/uinput.py index 9cb69f0..9fb1a06 100644 --- a/evdev/uinput.py +++ b/evdev/uinput.py @@ -315,9 +315,18 @@ def _find_device_linux(self, sysname): for entry in os.listdir(syspath): if regex.fullmatch(entry): device_path = f'/dev/input/{entry}' - return device.InputDevice(device_path) + break + else: # no break + raise FileNotFoundError() - raise FileNotFoundError() + # It is possible that there is some delay before /dev/input/event* shows + # up on old systems that do not use devtmpfs, so if the device cannot be + # found, wait for a short amount and then try again once. + try: + return device.InputDevice(device_path) + except FileNotFoundError: + time.sleep(0.1) + return device.InputDevice(device_path) def _find_device_fallback(self): ''' From 6a83bcb289168d5af855b5d178c691ead54140bd Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Sun, 7 Jan 2024 10:53:19 +0000 Subject: [PATCH 6/9] Add a comment Co-authored-by: Tobi <28510156+sezanzeb@users.noreply.github.com> --- evdev/uinput.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/evdev/uinput.py b/evdev/uinput.py index 9fb1a06..373895e 100644 --- a/evdev/uinput.py +++ b/evdev/uinput.py @@ -349,6 +349,8 @@ def _find_device_fallback(self): device_number = int(regex_match[1]) path_number_pairs.append((path, device_number)) + # The modification date of the devnode is not reliable unfortunately, so we + # are sorting by the number in the name path_number_pairs.sort(key=lambda pair: pair[1], reverse=True) for (path, _) in path_number_pairs: From fc4c4e045fbbbce6dbc4c327bbd5e6042d54ae04 Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Sun, 7 Jan 2024 12:38:30 +0100 Subject: [PATCH 7/9] Replace IOError with OSError Since Python 3.3 (PEP 3151), IOError and OSError are aliases of each other, and OSError is the prefered name. Rename all mentions of IOError in the C bindings with OSError. --- evdev/input.c | 18 +++++++++--------- evdev/uinput.c | 22 +++++++++++----------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/evdev/input.c b/evdev/input.c index b1497a4..0256745 100644 --- a/evdev/input.c +++ b/evdev/input.c @@ -61,7 +61,7 @@ device_read(PyObject *self, PyObject *args) return Py_None; } - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -101,7 +101,7 @@ device_read_many(PyObject *self, PyObject *args) ssize_t nread = read(fd, event, event_size*64); if (nread < 0) { - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); Py_DECREF(event_list); return NULL; } @@ -208,7 +208,7 @@ ioctl_capabilities(PyObject *self, PyObject *args) return capabilities; on_err: - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -243,7 +243,7 @@ ioctl_devinfo(PyObject *self, PyObject *args) name, phys, uniq); on_err: - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -261,7 +261,7 @@ ioctl_EVIOCGABS(PyObject *self, PyObject *args) memset(&absinfo, 0, sizeof(absinfo)); ret = ioctl(fd, EVIOCGABS(ev_code), &absinfo); if (ret == -1) { - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -296,7 +296,7 @@ ioctl_EVIOCSABS(PyObject *self, PyObject *args) ret = ioctl(fd, EVIOCSABS(ev_code), &absinfo); if (ret == -1) { - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -362,7 +362,7 @@ ioctl_EVIOCGRAB(PyObject *self, PyObject *args) ret = ioctl(fd, EVIOCGRAB, (intptr_t)flag); if (ret != 0) { - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -485,7 +485,7 @@ upload_effect(PyObject *self, PyObject *args) ret = ioctl(fd, EVIOCSFF, &effect); if (ret != 0) { - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -504,7 +504,7 @@ erase_effect(PyObject *self, PyObject *args) long ff_id = PyLong_AsLong(ff_id_obj); ret = ioctl(fd, EVIOCRMFF, ff_id); if (ret != 0) { - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } diff --git a/evdev/uinput.c b/evdev/uinput.c index 1581092..2e2d8e5 100644 --- a/evdev/uinput.c +++ b/evdev/uinput.c @@ -49,7 +49,7 @@ uinput_open(PyObject *self, PyObject *args) int fd = open(devnode, O_RDWR | O_NONBLOCK); if (fd < 0) { - PyErr_SetString(PyExc_IOError, "could not open uinput device in write mode"); + PyErr_SetString(PyExc_OSError, "could not open uinput device in write mode"); return NULL; } @@ -73,7 +73,7 @@ uinput_set_phys(PyObject *self, PyObject *args) on_err: _uinput_close(fd); - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -93,7 +93,7 @@ uinput_set_prop(PyObject *self, PyObject *args) on_err: _uinput_close(fd); - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -112,7 +112,7 @@ uinput_get_sysname(PyObject *self, PyObject *args) return Py_BuildValue("s", &sysname); on_err: - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -175,7 +175,7 @@ uinput_setup(PyObject *self, PyObject *args) { on_err: _uinput_close(fd); - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -224,7 +224,7 @@ uinput_setup(PyObject *self, PyObject *args) { on_err: _uinput_close(fd); - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } #endif @@ -245,7 +245,7 @@ uinput_create(PyObject *self, PyObject *args) on_err: _uinput_close(fd); - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -259,7 +259,7 @@ uinput_close(PyObject *self, PyObject *args) if (!ret) return NULL; if (_uinput_close(fd) < 0) { - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -287,8 +287,8 @@ uinput_write(PyObject *self, PyObject *args) if (write(fd, &event, sizeof(event)) != sizeof(event)) { // @todo: elaborate - // PyErr_SetString(PyExc_IOError, "error writing event to uinput device"); - PyErr_SetFromErrno(PyExc_IOError); + // PyErr_SetString(PyExc_OSError, "error writing event to uinput device"); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } @@ -330,7 +330,7 @@ uinput_enable_event(PyObject *self, PyObject *args) on_err: _uinput_close(fd); - PyErr_SetFromErrno(PyExc_IOError); + PyErr_SetFromErrno(PyExc_OSError); return NULL; } From d7bdd182a7535ebeb5068c6293d91be8dcd20446 Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Sun, 7 Jan 2024 12:43:17 +0100 Subject: [PATCH 8/9] Replace IOError with OSError in documentation --- evdev/device.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/evdev/device.py b/evdev/device.py index dbfad5d..27c84a6 100644 --- a/evdev/device.py +++ b/evdev/device.py @@ -309,7 +309,7 @@ def grab(self): Warning ------- - Grabbing an already grabbed device will raise an ``IOError``. + Grabbing an already grabbed device will raise an ``OSError``. ''' _input.ioctl_EVIOCGRAB(self.fd, 1) @@ -321,7 +321,7 @@ def ungrab(self): Warning ------- Releasing an already released device will raise an - ``IOError('Invalid argument')``. + ``OSError('Invalid argument')``. ''' _input.ioctl_EVIOCGRAB(self.fd, 0) From 70bded39fd3422f37dc49c6a5ad990cf6e40f66f Mon Sep 17 00:00:00 2001 From: Kars Mulder Date: Mon, 8 Jan 2024 20:08:25 +0000 Subject: [PATCH 9/9] Explain why the sorting is necessary Co-authored-by: Tobi <28510156+sezanzeb@users.noreply.github.com> --- evdev/uinput.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/evdev/uinput.py b/evdev/uinput.py index 373895e..2c1424b 100644 --- a/evdev/uinput.py +++ b/evdev/uinput.py @@ -337,6 +337,8 @@ def _find_device_fallback(self): #:bug: the device node might not be immediately available time.sleep(0.1) + # There could also be another device with the same name already present, + # make sure to select the newest one. # Strictly speaking, we cannot be certain that everything returned by list_devices() # ends at event[0-9]+: it might return something like "/dev/input/events_all". Find # the devices that have the expected structure and extract their device number.