diff --git a/kitty/boss.py b/kitty/boss.py index 46fb6a62d..e09cc1382 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -3,6 +3,7 @@ # Imports {{{ import base64 +import errno import json import os import re @@ -252,12 +253,56 @@ class Atexit: self._write_line(f'rmtree {path}') +def remove_stale_unix_socket(socket_path: str) -> bool: + """Remove the UNIX socket at socket_path if no process is listening on + it, for example, because the kitty that created it was killed. Returns True + if the socket was removed.""" + import stat + + try: + if not stat.S_ISSOCK(os.lstat(socket_path).st_mode): + return False + except FileNotFoundError: + return True + with socket.socket(socket.AF_UNIX) as probe: + try: + probe.connect(socket_path) + except ConnectionRefusedError: + pass # stale + except OSError: + return False + else: + return False # some process is listening on it + try: + os.unlink(socket_path) + except FileNotFoundError: + pass + return True + + def listen_on(spec: str, robust_atexit: Atexit) -> tuple[int, str]: import socket family, address, socket_path = parse_address_spec(spec) s = socket.socket(family) - s.bind(address) + try: + s.bind(address) + except OSError as err: + if err.errno != errno.EADDRINUSE or not socket_path: + s.close() + raise + if not remove_stale_unix_socket(socket_path): + s.close() + import stat + + try: + is_socket = stat.S_ISSOCK(os.lstat(socket_path).st_mode) + except OSError: + is_socket = False + if is_socket: + raise OSError(err.errno, f'Another process is already listening on {socket_path}') from err + raise OSError(err.errno, f'A file that is not a socket already exists at {socket_path}') from err + s.bind(address) if family == socket.AF_UNIX and socket_path: robust_atexit.unlink(socket_path) s.listen() @@ -464,8 +509,8 @@ class Boss: if args.listen_on and self.allow_remote_control in ('y', 'socket', 'socket-only', 'password'): try: listen_fd, self.listening_on = listen_on(args.listen_on, self.atexit) - except Exception: - self.misc_config_errors.append(f'Invalid listen_on={args.listen_on}, ignoring') + except Exception as err: + self.misc_config_errors.append(f'Failed to listen on listen_on={args.listen_on} with error: {err}, ignoring') log_error(self.misc_config_errors[-1]) self.child_monitor: ChildMonitor = ChildMonitor( self.on_child_death, diff --git a/kitty_tests/remote_control.py b/kitty_tests/remote_control.py index 14bf91192..ac79be576 100644 --- a/kitty_tests/remote_control.py +++ b/kitty_tests/remote_control.py @@ -40,6 +40,50 @@ class Boss: class TestRemoteControl(BaseTest): + def test_listen_on_stale_socket(self): + import socket + from collections.abc import Callable + + from kitty.boss import listen_on + + unlinked: list[str] = [] + closers: list[Callable[[], None]] = [] + fake_atexit = cast(Any, Mock(unlink=unlinked.append)) + + def listen(spec: str) -> str: + return listen_on(spec, fake_atexit)[1] + + with patch('atexit.register', closers.append), tempfile.TemporaryDirectory() as tdir: + try: + path = os.path.join(tdir, 'sock') + # A socket left behind by a process that was killed + stale = socket.socket(socket.AF_UNIX) + stale.bind(path) + stale.close() + self.assertTrue(os.path.exists(path)) + self.ae(listen(f'unix:{path}'), f'unix:{path}') + self.ae(unlinked, [path]) + # The socket is now live, so a second listener must fail and not remove it + with self.assertRaisesRegex(OSError, 'Another process is already listening'): + listen(f'unix:{path}') + with socket.socket(socket.AF_UNIX) as c: + c.connect(path) + # A file that is not a socket must never be removed + fpath = os.path.join(tdir, 'file') + with open(fpath, 'w') as f: + f.write('x') + with self.assertRaisesRegex(OSError, 'not a socket'): + listen(f'unix:{fpath}') + self.assertTrue(os.path.exists(fpath)) + # Abstract sockets have no file and are unaffected + name = f'@kitty-test-listen-{os.getpid()}' + listen(f'unix:{name}') + with self.assertRaises(OSError): + listen(f'unix:{name}') + finally: + for close in closers: + close() + def test_set_font_size_mapping(self): from kitty.boss import Boss as KittyBoss from kitty.rc.base import RemoteControlErrorWithoutTraceback