File: reader_service.py

package info (click to toggle)
input-remapper 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,876 kB
  • sloc: python: 27,262; sh: 191; xml: 33; makefile: 3
file content (451 lines) | stat: -rw-r--r-- 16,924 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# -*- coding: utf-8 -*-
# input-remapper - GUI for device specific keyboard mappings
# Copyright (C) 2023 sezanzeb <proxima@hip70890b.de>
#
# This file is part of input-remapper.
#
# input-remapper is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# input-remapper is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with input-remapper.  If not, see <https://www.gnu.org/licenses/>.

"""Process that sends stuff to the GUI.

It should be started via input-remapper-control and pkexec.

GUIs should not run as root
https://wiki.archlinux.org/index.php/Running_GUI_applications_as_root

The service shouldn't do that even though it has root rights, because that
would enable key-loggers to just ask input-remapper for all user-input.

Instead, the ReaderService is used, which will be stopped when the gui closes.

Whereas for the reader-service to start a password is needed and it stops whe
the ui closes.

This uses the backend injection.event_reader and mapping_handlers to process all the
different input-events into simple on/off events and sends them to the gui.
"""

from __future__ import annotations

import asyncio
import logging
import multiprocessing
import os
import subprocess
import sys
import time
from collections import defaultdict
from typing import Set, List, Tuple

import evdev
from evdev.ecodes import EV_KEY, EV_ABS, EV_REL, REL_HWHEEL, REL_WHEEL

from inputremapper.configs.input_config import InputCombination, InputConfig
from inputremapper.configs.mapping import Mapping
from inputremapper.groups import _Groups, _Group
from inputremapper.injection.event_reader import EventReader
from inputremapper.injection.global_uinputs import GlobalUInputs
from inputremapper.injection.mapping_handlers.abs_to_btn_handler import AbsToBtnHandler
from inputremapper.injection.mapping_handlers.mapping_handler import (
    NotifyCallback,
    InputEventHandler,
    MappingHandler,
)
from inputremapper.injection.mapping_handlers.rel_to_btn_handler import RelToBtnHandler
from inputremapper.input_event import InputEvent, EventActions
from inputremapper.ipc.pipe import Pipe
from inputremapper.logging.logger import logger
from inputremapper.user import UserUtils
from inputremapper.utils import get_device_hash

# received by the reader-service
CMD_TERMINATE = "terminate"
CMD_STOP_READING = "stop-reading"
CMD_REFRESH_GROUPS = "refresh_groups"

# sent by the reader-service to the reader
MSG_GROUPS = "groups"
MSG_EVENT = "event"
MSG_STATUS = "status"


class ReaderService:
    """Service that only reads events and is supposed to run as root.

    Sends device information and keycodes to the GUI.

    Commands are either numbers for generic commands,
    or strings to start listening on a specific device.
    """

    # the speed threshold at which relative axis are considered moving
    # and will be sent as "pressed" to the frontend.
    # We want to allow some mouse movement before we record it as an input
    rel_xy_speed = defaultdict(lambda: 3)
    # wheel events usually don't produce values higher than 1
    rel_xy_speed[REL_WHEEL] = 1
    rel_xy_speed[REL_HWHEEL] = 1

    # Polkit won't ask for another password if the pid stays the same or something, and
    # if the previous request was no more than 5 minutes ago. see
    # https://unix.stackexchange.com/a/458260.
    # If the user does something after 6 minutes they will get a prompt already if the
    # reader timed out already, which sounds annoying. Instead, I'd rather have the
    # password prompt appear at most every 15 minutes.
    _maximum_lifetime: int = 60 * 15
    _timeout_tolerance: int = 60

    def __init__(self, groups: _Groups, global_uinputs: GlobalUInputs) -> None:
        """Construct the reader-service and initialize its communication pipes."""
        self._start_time = time.time()
        self.groups = groups
        self.global_uinputs = global_uinputs
        self._results_pipe = Pipe(self.get_pipe_paths()[0])
        self._commands_pipe = Pipe(self.get_pipe_paths()[1])
        self._pipe = multiprocessing.Pipe()

        self._tasks: Set[asyncio.Task] = set()
        self._stop_event = asyncio.Event()

        self._results_pipe.send({"type": MSG_STATUS, "message": "ready"})

    @staticmethod
    def get_pipe_paths() -> Tuple[str, str]:
        """Get the path where the pipe can be found."""
        return (
            f"/tmp/input-remapper-{UserUtils.home}/reader-results",
            f"/tmp/input-remapper-{UserUtils.home}/reader-commands",
        )

    @staticmethod
    def pipes_exist() -> bool:
        # Just checking for one of the 4 files (results, commands both read and write)
        # should be enough I guess.
        path = f"{ReaderService.get_pipe_paths()[0]}r"
        # Use os.path.exists, not lexists or islink, because broken links are bad.
        # New pipes and symlinks need to be made.
        return os.path.exists(path)

    @staticmethod
    def is_running() -> bool:
        """Check if the reader-service is running."""
        try:
            subprocess.check_output(["pgrep", "-f", "input-remapper-reader-service"])
        except subprocess.CalledProcessError:
            return False
        return True

    @staticmethod
    def pkexec_reader_service():
        """Start reader-service via pkexec to run in the background."""
        debug = " -d" if logger.level <= logging.DEBUG else ""
        cmd = f"pkexec input-remapper-control --command start-reader-service{debug}"

        logger.debug("Running `%s`", cmd)
        exit_code = os.system(cmd)

        if exit_code != 0:
            raise Exception(f"Failed to pkexec the reader-service, code {exit_code}")

    async def run(self):
        """Start doing stuff."""
        # the reader will check for new commands later, once it is running
        # it keeps running for one device or another.
        logger.debug("Discovering initial groups")
        self.groups.refresh()
        self._send_groups()
        await asyncio.gather(
            self._read_commands(),
            self._timeout(),
            self._stop_if_pipes_broken(),
        )

    def _send_groups(self):
        """Send the groups to the gui."""
        logger.debug("Sending groups")
        self._results_pipe.send({"type": MSG_GROUPS, "message": self.groups.dumps()})

    async def _timeout(self):
        """Stop automatically after some time."""
        # Prevents a permanent hole for key-loggers to exist, in case the gui crashes.
        # If the ReaderService stops even though the gui needs it, it needs to restart
        # it. This makes it also more comfortable to have debug mode running during
        # development, because it won't keep writing inputs containing passwords and
        # such to the terminal forever.

        await asyncio.sleep(self._maximum_lifetime)

        # if it is currently reading, wait a bit longer for the gui to complete
        # what it is doing.
        if self._is_reading():
            logger.debug("Waiting a bit longer for the gui to finish reading")

            for _ in range(self._timeout_tolerance):
                if not self._is_reading():
                    # once reading completes, it should terminate right away
                    break

                await asyncio.sleep(1)

        logger.debug("Maximum life-span reached, terminating")
        sys.exit(1)

    async def _read_commands(self):
        """Handle all unread commands.
        this will run until it receives CMD_TERMINATE
        """
        logger.debug("Waiting for commands")
        async for cmd in self._commands_pipe:
            logger.debug('Received command "%s"', cmd)

            if cmd == CMD_TERMINATE:
                await self._stop_reading()
                logger.debug("Terminating")
                sys.exit(0)

            if cmd == CMD_REFRESH_GROUPS:
                self.groups.refresh()
                self._send_groups()
                continue

            if cmd == CMD_STOP_READING:
                await self._stop_reading()
                continue

            group = self.groups.find(key=cmd)
            if group is None:
                # this will block for a bit maybe we want to do this async?
                self.groups.refresh()
                group = self.groups.find(key=cmd)

            if group is not None:
                await self._stop_reading()
                self._start_reading(group)
                continue

            logger.error('Received unknown command "%s"', cmd)

    async def _stop_if_pipes_broken(self):
        # The GUI probably exited, and failed to tell the reader-service to stop.
        # Pipes are owned by the GUI process, because the non-privileged GUI process
        # needs to be able to read them. Therefore, they are gone.
        while True:
            await asyncio.sleep(1)
            if not self.pipes_exist():
                await self._stop_reading()
                logger.debug("Pipes broken, exiting")
                sys.exit(13)

    def _is_reading(self) -> bool:
        """Check if the ReaderService is currently sending events to the GUI."""
        return len(self._tasks) > 0

    def _start_reading(self, group: _Group):
        """Find all devices of that group, filter interesting ones and send the events
        to the gui."""
        sources = []
        for path in group.paths:
            try:
                device = evdev.InputDevice(path)
            except (FileNotFoundError, OSError):
                logger.error('Could not find "%s"', path)
                return None

            capabilities = device.capabilities(absinfo=False)
            if (
                EV_KEY in capabilities
                or EV_ABS in capabilities
                or EV_REL in capabilities
            ):
                sources.append(device)

        context = self._create_event_pipeline(sources)
        # create the event reader and start it
        for device in sources:
            reader = EventReader(context, device, self._stop_event)
            self._tasks.add(asyncio.create_task(reader.run()))

    async def _stop_reading(self):
        """Stop the running event_reader."""
        self._stop_event.set()
        if self._tasks:
            await asyncio.gather(*self._tasks)
        self._tasks = set()
        self._stop_event.clear()

    def _create_event_pipeline(self, sources: List[evdev.InputDevice]) -> ContextDummy:
        """Create a custom event pipeline for each event code in the capabilities.

        Instead of sending the events to an uinput they will be sent to the frontend.
        """
        context_dummy = ContextDummy()
        # create a context for each source
        for device in sources:
            device_hash = get_device_hash(device)
            capabilities = device.capabilities(absinfo=False)

            for ev_code in capabilities.get(EV_KEY) or ():
                input_config = InputConfig(
                    type=EV_KEY, code=ev_code, origin_hash=device_hash
                )
                context_dummy.add_handler(
                    input_config, ForwardToUIHandler(self._results_pipe)
                )

            for ev_code in capabilities.get(EV_ABS) or ():
                # positive direction
                input_config = InputConfig(
                    type=EV_ABS,
                    code=ev_code,
                    analog_threshold=30,
                    origin_hash=device_hash,
                )
                mapping = Mapping(
                    input_combination=InputCombination([input_config]),
                    target_uinput="keyboard",
                    output_symbol="KEY_A",
                )
                handler: MappingHandler = AbsToBtnHandler(
                    InputCombination([input_config]),
                    mapping,
                    self.global_uinputs,
                )
                handler.set_sub_handler(ForwardToUIHandler(self._results_pipe))
                context_dummy.add_handler(input_config, handler)

                # negative direction
                input_config = input_config.modify(analog_threshold=-30)
                mapping = Mapping(
                    input_combination=InputCombination([input_config]),
                    target_uinput="keyboard",
                    output_symbol="KEY_A",
                )
                handler = AbsToBtnHandler(
                    InputCombination([input_config]),
                    mapping,
                    self.global_uinputs,
                )
                handler.set_sub_handler(ForwardToUIHandler(self._results_pipe))
                context_dummy.add_handler(input_config, handler)

            for ev_code in capabilities.get(EV_REL) or ():
                # positive direction
                input_config = InputConfig(
                    type=EV_REL,
                    code=ev_code,
                    analog_threshold=self.rel_xy_speed[ev_code],
                    origin_hash=device_hash,
                )
                mapping = Mapping(
                    input_combination=InputCombination([input_config]),
                    target_uinput="keyboard",
                    output_symbol="KEY_A",
                    release_timeout=0.3,
                    force_release_timeout=True,
                )
                handler = RelToBtnHandler(
                    InputCombination([input_config]),
                    mapping,
                    self.global_uinputs,
                )
                handler.set_sub_handler(ForwardToUIHandler(self._results_pipe))
                context_dummy.add_handler(input_config, handler)

                # negative direction
                input_config = input_config.modify(
                    analog_threshold=-self.rel_xy_speed[ev_code]
                )
                mapping = Mapping(
                    input_combination=InputCombination([input_config]),
                    target_uinput="keyboard",
                    output_symbol="KEY_A",
                    release_timeout=0.3,
                    force_release_timeout=True,
                )
                handler = RelToBtnHandler(
                    InputCombination([input_config]),
                    mapping,
                    self.global_uinputs,
                )
                handler.set_sub_handler(ForwardToUIHandler(self._results_pipe))
                context_dummy.add_handler(input_config, handler)

        return context_dummy


class ForwardDummy:
    @staticmethod
    def write(*_):
        pass


class ContextDummy:
    """Used for the reader so that no events are actually written to any uinput."""

    def __init__(self):
        self.listeners = set()
        self._notify_callbacks = defaultdict(list)
        self.forward_dummy = ForwardDummy()

    def add_handler(self, input_config: InputConfig, handler: InputEventHandler):
        self._notify_callbacks[input_config.input_match_hash].append(handler.notify)

    def get_notify_callbacks(self, input_event: InputEvent) -> List[NotifyCallback]:
        return self._notify_callbacks[input_event.input_match_hash]

    def reset(self):
        pass

    def get_forward_uinput(self, origin_hash) -> evdev.UInput:
        """Don't actually write anything."""
        return self.forward_dummy


class ForwardToUIHandler:
    """Implements the InputEventHandler protocol. Sends all events into the pipe."""

    def __init__(self, pipe: Pipe):
        self.pipe = pipe
        self._last_event = InputEvent.from_tuple((99, 99, 99))

    def notify(
        self,
        event: InputEvent,
        source: evdev.InputDevice,
        suppress: bool = False,
    ) -> bool:
        """Filter duplicates and send into the pipe."""
        if event != self._last_event:
            self._last_event = event
            if EventActions.negative_trigger in event.actions:
                event = event.modify(value=-1)

            logger.debug("Sending to %s frontend", event)
            self.pipe.send(
                {
                    "type": MSG_EVENT,
                    "message": {
                        "sec": event.sec,
                        "usec": event.usec,
                        "type": event.type,
                        "code": event.code,
                        "value": event.value,
                        "origin_hash": event.origin_hash,
                    },
                }
            )
        return True

    def reset(self):
        pass