input-remapper/inputremapper/ipc/pipe.py

140 lines
4.3 KiB
Python
Raw Normal View History

2021-03-21 18:15:20 +00:00
#!/usr/bin/python3
# -*- coding: utf-8 -*-
2022-01-01 12:00:49 +00:00
# input-remapper - GUI for device specific keyboard mappings
2022-01-01 12:52:33 +00:00
# Copyright (C) 2022 sezanzeb <proxima@sezanzeb.de>
2021-03-21 18:15:20 +00:00
#
2022-01-01 12:00:49 +00:00
# This file is part of input-remapper.
2021-03-21 18:15:20 +00:00
#
2022-01-01 12:00:49 +00:00
# input-remapper is free software: you can redistribute it and/or modify
2021-03-21 18:15:20 +00:00
# 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.
#
2022-01-01 12:00:49 +00:00
# input-remapper is distributed in the hope that it will be useful,
2021-03-21 18:15:20 +00:00
# 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
2022-01-01 12:00:49 +00:00
# along with input-remapper. If not, see <https://www.gnu.org/licenses/>.
2021-03-21 18:15:20 +00:00
"""Named bidirectional non-blocking pipes.
>>> p1 = Pipe('foo')
>>> p2 = Pipe('foo')
>>> p1.send(1)
>>> p2.poll()
>>> p2.recv()
>>> p2.send(2)
>>> p1.poll()
>>> p1.recv()
Beware that pipes read any available messages,
even those written by themselves.
"""
import os
import time
import json
2022-01-01 12:00:49 +00:00
from inputremapper.logger import logger
2022-01-31 19:58:37 +00:00
from inputremapper.configs.paths import mkdir, chown
2021-03-21 18:15:20 +00:00
class Pipe:
"""Pipe object."""
2021-09-26 10:44:56 +00:00
2021-03-21 18:15:20 +00:00
def __init__(self, path):
"""Create a pipe, or open it if it already exists."""
self._path = path
self._unread = []
self._created_at = time.time()
2021-09-26 10:44:56 +00:00
paths = (f"{path}r", f"{path}w")
2021-03-21 18:15:20 +00:00
mkdir(os.path.dirname(path))
if not os.path.exists(paths[0]):
logger.debug('Creating new pipe for "%s"', path)
2021-03-21 18:15:20 +00:00
# The fd the link points to is closed, or none ever existed
# If there is a link, remove it.
if os.path.islink(paths[0]):
os.remove(paths[0])
if os.path.islink(paths[1]):
os.remove(paths[1])
self._fds = os.pipe()
2021-09-26 10:44:56 +00:00
fds_dir = f"/proc/{os.getpid()}/fd/"
chown(f"{fds_dir}{self._fds[0]}")
chown(f"{fds_dir}{self._fds[1]}")
2021-03-21 18:15:20 +00:00
# to make it accessible by path constants, create symlinks
2021-09-26 10:44:56 +00:00
os.symlink(f"{fds_dir}{self._fds[0]}", paths[0])
os.symlink(f"{fds_dir}{self._fds[1]}", paths[1])
2021-03-21 18:15:20 +00:00
else:
logger.debug('Using existing pipe for "%s"', path)
2021-03-21 18:15:20 +00:00
# thanks to os.O_NONBLOCK, readline will return b'' when there
# is nothing to read
self._fds = (
os.open(paths[0], os.O_RDONLY | os.O_NONBLOCK),
2021-09-26 10:44:56 +00:00
os.open(paths[1], os.O_WRONLY | os.O_NONBLOCK),
2021-03-21 18:15:20 +00:00
)
2021-09-26 10:44:56 +00:00
self._handles = (open(self._fds[0], "r"), open(self._fds[1], "w"))
2021-03-21 18:15:20 +00:00
def recv(self):
"""Read an object from the pipe or None if nothing available.
Doesn't transmit pickles, to avoid injection attacks on the
privileged helper. Only messages that can be converted to json
are allowed.
"""
if len(self._unread) > 0:
return self._unread.pop(0)
line = self._handles[0].readline()
if len(line) == 0:
return None
parsed = json.loads(line)
2021-09-26 10:44:56 +00:00
if parsed[0] < self._created_at and os.environ.get("UNITTEST"):
2021-03-21 18:15:20 +00:00
# important to avoid race conditions between multiple unittests,
# for example old terminate messages reaching a new instance of
# the helper.
logger.debug("Ignoring old message %s", parsed)
2021-03-21 18:15:20 +00:00
return None
return parsed[1]
def send(self, message):
"""Write an object to the pipe."""
dump = json.dumps((time.time(), message))
# there aren't any newlines supposed to be,
# but if there are it breaks readline().
2021-09-26 10:44:56 +00:00
self._handles[1].write(dump.replace("\n", ""))
self._handles[1].write("\n")
2021-03-21 18:15:20 +00:00
self._handles[1].flush()
def poll(self):
"""Check if there is anything that can be read."""
if len(self._unread) > 0:
return True
# using select.select apparently won't mark the pipe as ready
# anymore when there are multiple lines to read but only a single
# line is retreived. Using read instead.
msg = self.recv()
if msg is not None:
self._unread.append(msg)
return len(self._unread) > 0
def fileno(self):
"""Compatibility to select.select."""
2021-03-21 18:15:20 +00:00
return self._handles[0].fileno()