--- /srv/reproducible-results/rbuild-debian/r-b-build.fWH4IW2f/b1/cockpit_311-1_armhf.changes +++ /srv/reproducible-results/rbuild-debian/r-b-build.fWH4IW2f/b2/cockpit_311-1_armhf.changes ├── Files │ @@ -1,10 +1,10 @@ │ │ cf6e11841c7839c56944514d11f89c98 138212 debug optional cockpit-bridge-dbgsym_311-1_armhf.deb │ - 797438ab16c5264312e22f9cc4085d32 352276 admin optional cockpit-bridge_311-1_armhf.deb │ + 9373abbf727d0fc1b6749d2aa23aa88b 352160 admin optional cockpit-bridge_311-1_armhf.deb │ d6420f2f7547b4e22925ba79ff18803d 131364 doc optional cockpit-doc_311-1_all.deb │ 88b04dc126f5b100988e2bdf9812be7b 833092 admin optional cockpit-networkmanager_311-1_all.deb │ 270d4784b46c2aff32acab6a65b331f8 939100 admin optional cockpit-packagekit_311-1_all.deb │ f8f0abe7a7679703c2b319034bcb3343 231244 debug optional cockpit-pcp-dbgsym_311-1_armhf.deb │ bdd727962c92577ef1a24abf8491bc8c 70672 admin optional cockpit-pcp_311-1_armhf.deb │ e3b2783c793e9b15a89ff5b04c527610 557948 admin optional cockpit-sosreport_311-1_all.deb │ cdf3488303d663c6fd12c06a5f2b8016 872112 admin optional cockpit-storaged_311-1_all.deb ├── cockpit-bridge_311-1_armhf.deb │ ├── file list │ │ @@ -1,3 +1,3 @@ │ │ -rw-r--r-- 0 0 0 4 2024-02-15 08:39:16.000000 debian-binary │ │ -rw-r--r-- 0 0 0 3880 2024-02-15 08:39:16.000000 control.tar.xz │ │ --rw-r--r-- 0 0 0 348204 2024-02-15 08:39:16.000000 data.tar.xz │ │ +-rw-r--r-- 0 0 0 348088 2024-02-15 08:39:16.000000 data.tar.xz │ ├── control.tar.xz │ │ ├── control.tar │ │ │ ├── ./md5sums │ │ │ │ ├── ./md5sums │ │ │ │ │┄ Files differ │ ├── data.tar.xz │ │ ├── data.tar │ │ │ ├── file list │ │ │ │ @@ -60,15 +60,15 @@ │ │ │ │ -rw-r--r-- 0 root (0) root (0) 6861 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/channels/metrics.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 4053 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/channels/packages.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 4827 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/channels/stream.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 1171 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/channels/trivial.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 3188 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/config.py │ │ │ │ drwxr-xr-x 0 root (0) root (0) 0 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/data/ │ │ │ │ -rw-r--r-- 0 root (0) root (0) 574 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/data/__init__.py │ │ │ │ --rw-r--r-- 0 root (0) root (0) 85660 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/data/cockpit-bridge.beipack.xz │ │ │ │ +-rw-r--r-- 0 root (0) root (0) 85552 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/data/cockpit-bridge.beipack.xz │ │ │ │ -rw-r--r-- 0 root (0) root (0) 3212 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/data/fail.html │ │ │ │ -rw-r--r-- 0 root (0) root (0) 5517 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/internal_endpoints.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 6742 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/jsonutil.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 21539 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/packages.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 12729 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/peer.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 7580 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/polkit.py │ │ │ │ -rw-r--r-- 0 root (0) root (0) 2031 2024-02-15 08:39:16.000000 ./usr/lib/python3/dist-packages/cockpit/polyfills.py │ │ │ ├── ./usr/lib/python3/dist-packages/cockpit/data/cockpit-bridge.beipack.xz │ │ │ │ ├── cockpit-bridge.beipack │ │ │ │ │┄ Ordering differences only │ │ │ │ │ @@ -64,15 +64,15 @@ │ │ │ │ │ ) -> Optional[importlib.machinery.ModuleSpec]: │ │ │ │ │ if fullname not in self.modules: │ │ │ │ │ return None │ │ │ │ │ return importlib.util.spec_from_loader(fullname, self) │ │ │ │ │ │ │ │ │ │ import sys │ │ │ │ │ sys.meta_path.insert(0, BeipackLoader({ │ │ │ │ │ - 'cockpit/protocol.py': br'''# This file is part of Cockpit. │ │ │ │ │ + 'cockpit/transports.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ @@ -81,491 +81,1306 @@ │ │ │ │ │ # 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ +"""Bi-directional asyncio.Transport implementations based on file descriptors.""" │ │ │ │ │ + │ │ │ │ │ import asyncio │ │ │ │ │ -import json │ │ │ │ │ +import collections │ │ │ │ │ +import ctypes │ │ │ │ │ +import errno │ │ │ │ │ +import fcntl │ │ │ │ │ import logging │ │ │ │ │ -import uuid │ │ │ │ │ +import os │ │ │ │ │ +import select │ │ │ │ │ +import signal │ │ │ │ │ +import struct │ │ │ │ │ +import subprocess │ │ │ │ │ +import termios │ │ │ │ │ +from typing import Any, ClassVar, Sequence │ │ │ │ │ + │ │ │ │ │ +from .jsonutil import JsonObject, get_int │ │ │ │ │ + │ │ │ │ │ +libc6 = ctypes.cdll.LoadLibrary('libc.so.6') │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def prctl(*args: int) -> None: │ │ │ │ │ + if libc6.prctl(*args) != 0: │ │ │ │ │ + raise OSError('prctl() failed') │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +SET_PDEATHSIG = 1 │ │ │ │ │ │ │ │ │ │ -from .jsonutil import JsonError, JsonObject, JsonValue, create_object, get_int, get_str, typechecked │ │ │ │ │ │ │ │ │ │ logger = logging.getLogger(__name__) │ │ │ │ │ +IOV_MAX = 1024 # man 2 writev │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class CockpitProblem(Exception): │ │ │ │ │ - """A type of exception that carries a problem code and a message. │ │ │ │ │ +class _Transport(asyncio.Transport): │ │ │ │ │ + BLOCK_SIZE: ClassVar[int] = 1024 * 1024 │ │ │ │ │ │ │ │ │ │ - Depending on the scope, this is used to handle shutting down: │ │ │ │ │ + # A transport always has a loop and a protocol │ │ │ │ │ + _loop: asyncio.AbstractEventLoop │ │ │ │ │ + _protocol: asyncio.Protocol │ │ │ │ │ │ │ │ │ │ - - an individual channel (sends problem code in the close message) │ │ │ │ │ - - peer connections (sends problem code in close message for each open channel) │ │ │ │ │ - - the main stdio interaction with the bridge │ │ │ │ │ + _queue: 'collections.deque[bytes] | None' │ │ │ │ │ + _in_fd: int │ │ │ │ │ + _out_fd: int │ │ │ │ │ + _closing: bool │ │ │ │ │ + _is_reading: bool │ │ │ │ │ + _eof: bool │ │ │ │ │ + _eio_is_eof: bool = False │ │ │ │ │ │ │ │ │ │ - It is usually thrown in response to some violation of expected protocol │ │ │ │ │ - when parsing messages, connecting to a peer, or opening a channel. │ │ │ │ │ - """ │ │ │ │ │ - attrs: JsonObject │ │ │ │ │ + def __init__(self, │ │ │ │ │ + loop: asyncio.AbstractEventLoop, │ │ │ │ │ + protocol: asyncio.Protocol, │ │ │ │ │ + in_fd: int = -1, out_fd: int = -1, │ │ │ │ │ + extra: 'dict[str, object] | None' = None): │ │ │ │ │ + super().__init__(extra) │ │ │ │ │ │ │ │ │ │ - def __init__(self, problem: str, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> None: │ │ │ │ │ - kwargs['problem'] = problem │ │ │ │ │ - self.attrs = create_object(_msg, kwargs) │ │ │ │ │ - super().__init__(get_str(self.attrs, 'message', problem)) │ │ │ │ │ + self._loop = loop │ │ │ │ │ + self._protocol = protocol │ │ │ │ │ │ │ │ │ │ + logger.debug('Created transport %s for protocol %s, fds %d %d', self, protocol, in_fd, out_fd) │ │ │ │ │ │ │ │ │ │ -class CockpitProtocolError(CockpitProblem): │ │ │ │ │ - def __init__(self, message: str, problem: str = 'protocol-error'): │ │ │ │ │ - super().__init__(problem, message=message) │ │ │ │ │ + self._queue = None │ │ │ │ │ + self._is_reading = False │ │ │ │ │ + self._eof = False │ │ │ │ │ + self._closing = False │ │ │ │ │ │ │ │ │ │ + self._in_fd = in_fd │ │ │ │ │ + self._out_fd = out_fd │ │ │ │ │ │ │ │ │ │ -class CockpitProtocol(asyncio.Protocol): │ │ │ │ │ - """A naive implementation of the Cockpit frame protocol │ │ │ │ │ + os.set_blocking(in_fd, False) │ │ │ │ │ + if out_fd != in_fd: │ │ │ │ │ + os.set_blocking(out_fd, False) │ │ │ │ │ │ │ │ │ │ - We need to use this because Python's SelectorEventLoop doesn't supported │ │ │ │ │ - buffered protocols. │ │ │ │ │ - """ │ │ │ │ │ - transport: 'asyncio.Transport | None' = None │ │ │ │ │ - buffer = b'' │ │ │ │ │ - _closed: bool = False │ │ │ │ │ - _communication_done: 'asyncio.Future[None] | None' = None │ │ │ │ │ + self._protocol.connection_made(self) │ │ │ │ │ + self.resume_reading() │ │ │ │ │ │ │ │ │ │ - def do_ready(self) -> None: │ │ │ │ │ - pass │ │ │ │ │ + def _read_ready(self) -> None: │ │ │ │ │ + logger.debug('Read ready on %s %s %d', self, self._protocol, self._in_fd) │ │ │ │ │ + try: │ │ │ │ │ + data = os.read(self._in_fd, _Transport.BLOCK_SIZE) │ │ │ │ │ + except BlockingIOError: # pragma: no cover │ │ │ │ │ + return │ │ │ │ │ + except OSError as exc: │ │ │ │ │ + if self._eio_is_eof and exc.errno == errno.EIO: │ │ │ │ │ + # PTY devices return EIO to mean "EOF" │ │ │ │ │ + data = b'' │ │ │ │ │ + else: │ │ │ │ │ + # Other errors: terminate the connection │ │ │ │ │ + self.abort(exc) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - def do_closed(self, exc: 'Exception | None') -> None: │ │ │ │ │ + if data != b'': │ │ │ │ │ + logger.debug(' read %d bytes', len(data)) │ │ │ │ │ + self._protocol.data_received(data) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug(' got EOF') │ │ │ │ │ + self._close_reader() │ │ │ │ │ + keep_open = self._protocol.eof_received() │ │ │ │ │ + if not keep_open: │ │ │ │ │ + self.close() │ │ │ │ │ + │ │ │ │ │ + def is_reading(self) -> bool: │ │ │ │ │ + return self._is_reading │ │ │ │ │ + │ │ │ │ │ + def _close_reader(self) -> None: │ │ │ │ │ + self.pause_reading() │ │ │ │ │ + self._in_fd = -1 │ │ │ │ │ + │ │ │ │ │ + def pause_reading(self) -> None: │ │ │ │ │ + if self._is_reading: │ │ │ │ │ + self._loop.remove_reader(self._in_fd) │ │ │ │ │ + self._is_reading = False │ │ │ │ │ + │ │ │ │ │ + def resume_reading(self) -> None: │ │ │ │ │ + # It's possible that the Protocol could decide to attempt to unpause │ │ │ │ │ + # reading after _close_reader() got called. Check that the fd is != -1 │ │ │ │ │ + # before actually resuming. │ │ │ │ │ + if not self._is_reading and self._in_fd != -1: │ │ │ │ │ + self._loop.add_reader(self._in_fd, self._read_ready) │ │ │ │ │ + self._is_reading = True │ │ │ │ │ + │ │ │ │ │ + def _close(self) -> None: │ │ │ │ │ pass │ │ │ │ │ │ │ │ │ │ - def transport_control_received(self, command: str, message: JsonObject) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + def abort(self, exc: 'Exception | None' = None) -> None: │ │ │ │ │ + self._closing = True │ │ │ │ │ + self._close_reader() │ │ │ │ │ + self._remove_write_queue() │ │ │ │ │ + self._protocol.connection_lost(exc) │ │ │ │ │ + self._close() │ │ │ │ │ │ │ │ │ │ - def channel_control_received(self, channel: str, command: str, message: JsonObject) -> None: │ │ │ │ │ + def can_write_eof(self) -> bool: │ │ │ │ │ raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - def channel_data_received(self, channel: str, data: bytes) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + def write_eof(self) -> None: │ │ │ │ │ + assert not self._eof │ │ │ │ │ + self._eof = True │ │ │ │ │ + if self._queue is None: │ │ │ │ │ + logger.debug('%s got EOF. closing backend.', self) │ │ │ │ │ + self._write_eof_now() │ │ │ │ │ + else: │ │ │ │ │ + logger.debug('%s got EOF. bytes in queue, deferring close', self) │ │ │ │ │ │ │ │ │ │ - def frame_received(self, frame: bytes) -> None: │ │ │ │ │ - header, _, data = frame.partition(b'\n') │ │ │ │ │ + def get_write_buffer_size(self) -> int: │ │ │ │ │ + if self._queue is None: │ │ │ │ │ + return 0 │ │ │ │ │ + return sum(len(block) for block in self._queue) │ │ │ │ │ │ │ │ │ │ - if header != b'': │ │ │ │ │ - channel = header.decode('ascii') │ │ │ │ │ - logger.debug('data received: %d bytes of data for channel %s', len(data), channel) │ │ │ │ │ - self.channel_data_received(channel, data) │ │ │ │ │ + def get_write_buffer_limits(self) -> 'tuple[int, int]': │ │ │ │ │ + return (0, 0) │ │ │ │ │ │ │ │ │ │ - else: │ │ │ │ │ - self.control_received(data) │ │ │ │ │ + def set_write_buffer_limits(self, high: 'int | None' = None, low: 'int | None' = None) -> None: │ │ │ │ │ + assert high is None or high == 0 │ │ │ │ │ + assert low is None or low == 0 │ │ │ │ │ + │ │ │ │ │ + def _write_eof_now(self) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def _write_ready(self) -> None: │ │ │ │ │ + logger.debug('%s _write_ready', self) │ │ │ │ │ + assert self._queue is not None │ │ │ │ │ │ │ │ │ │ - def control_received(self, data: bytes) -> None: │ │ │ │ │ try: │ │ │ │ │ - message = typechecked(json.loads(data), dict) │ │ │ │ │ - command = get_str(message, 'command') │ │ │ │ │ - channel = get_str(message, 'channel', None) │ │ │ │ │ + n_bytes = os.writev(self._out_fd, self._queue) │ │ │ │ │ + except BlockingIOError: # pragma: no cover │ │ │ │ │ + n_bytes = 0 │ │ │ │ │ + except OSError as exc: │ │ │ │ │ + self.abort(exc) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - if channel is not None: │ │ │ │ │ - logger.debug('channel control received %s', message) │ │ │ │ │ - self.channel_control_received(channel, command, message) │ │ │ │ │ - else: │ │ │ │ │ - logger.debug('transport control received %s', message) │ │ │ │ │ - self.transport_control_received(command, message) │ │ │ │ │ + logger.debug(' successfully wrote %d bytes from the queue', n_bytes) │ │ │ │ │ │ │ │ │ │ - except (json.JSONDecodeError, JsonError) as exc: │ │ │ │ │ - raise CockpitProtocolError(f'control message: {exc!s}') from exc │ │ │ │ │ + while n_bytes: │ │ │ │ │ + block = self._queue.popleft() │ │ │ │ │ + if len(block) > n_bytes: │ │ │ │ │ + # This block wasn't completely written. │ │ │ │ │ + logger.debug(' incomplete block. Stop.') │ │ │ │ │ + self._queue.appendleft(block[n_bytes:]) │ │ │ │ │ + break │ │ │ │ │ + n_bytes -= len(block) │ │ │ │ │ + logger.debug(' removed complete block. %d remains.', n_bytes) │ │ │ │ │ │ │ │ │ │ - def consume_one_frame(self, data: bytes) -> int: │ │ │ │ │ - """Consumes a single frame from view. │ │ │ │ │ + if not self._queue: │ │ │ │ │ + logger.debug('%s queue drained.') │ │ │ │ │ + self._remove_write_queue() │ │ │ │ │ + if self._eof: │ │ │ │ │ + logger.debug('%s queue drained. closing backend now.') │ │ │ │ │ + self._write_eof_now() │ │ │ │ │ + if self._closing: │ │ │ │ │ + self.abort() │ │ │ │ │ │ │ │ │ │ - Returns positive if a number of bytes were consumed, or negative if no │ │ │ │ │ - work can be done because of a given number of bytes missing. │ │ │ │ │ - """ │ │ │ │ │ + def _remove_write_queue(self) -> None: │ │ │ │ │ + if self._queue is not None: │ │ │ │ │ + self._protocol.resume_writing() │ │ │ │ │ + self._loop.remove_writer(self._out_fd) │ │ │ │ │ + self._queue = None │ │ │ │ │ + │ │ │ │ │ + def _create_write_queue(self, data: bytes) -> None: │ │ │ │ │ + logger.debug('%s creating write queue for fd %s', self, self._out_fd) │ │ │ │ │ + assert self._queue is None │ │ │ │ │ + self._loop.add_writer(self._out_fd, self._write_ready) │ │ │ │ │ + self._queue = collections.deque((data,)) │ │ │ │ │ + self._protocol.pause_writing() │ │ │ │ │ + │ │ │ │ │ + def write(self, data: bytes) -> None: │ │ │ │ │ + # this is a race condition with subprocesses: if we get and process the the "exited" │ │ │ │ │ + # event before seeing BrokenPipeError, we'll try to write to a closed pipe. │ │ │ │ │ + # Do what the standard library does and ignore, instead of assert │ │ │ │ │ + if self._closing: │ │ │ │ │ + logger.debug('ignoring write() to closing transport fd %i', self._out_fd) │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + assert not self._eof │ │ │ │ │ + │ │ │ │ │ + if self._queue is not None: │ │ │ │ │ + self._queue.append(data) │ │ │ │ │ + │ │ │ │ │ + # writev() will complain if the queue is too long. Consolidate it. │ │ │ │ │ + if len(self._queue) > IOV_MAX: │ │ │ │ │ + all_data = b''.join(self._queue) │ │ │ │ │ + self._queue.clear() │ │ │ │ │ + self._queue.append(all_data) │ │ │ │ │ + │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ try: │ │ │ │ │ - newline = data.index(b'\n') │ │ │ │ │ - except ValueError as exc: │ │ │ │ │ - if len(data) < 10: │ │ │ │ │ - # Let's try reading more │ │ │ │ │ - return len(data) - 10 │ │ │ │ │ - raise CockpitProtocolError("size line is too long") from exc │ │ │ │ │ + n_bytes = os.write(self._out_fd, data) │ │ │ │ │ + except BlockingIOError: │ │ │ │ │ + n_bytes = 0 │ │ │ │ │ + except OSError as exc: │ │ │ │ │ + self.abort(exc) │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + if n_bytes != len(data): │ │ │ │ │ + self._create_write_queue(data[n_bytes:]) │ │ │ │ │ + │ │ │ │ │ + def close(self) -> None: │ │ │ │ │ + if self._closing: │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + self._closing = True │ │ │ │ │ + self._close_reader() │ │ │ │ │ + │ │ │ │ │ + if self._queue is not None: │ │ │ │ │ + # abort() will be called from _write_ready() when it's done │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + self.abort() │ │ │ │ │ + │ │ │ │ │ + def get_protocol(self) -> asyncio.BaseProtocol: │ │ │ │ │ + return self._protocol │ │ │ │ │ + │ │ │ │ │ + def is_closing(self) -> bool: │ │ │ │ │ + return self._closing │ │ │ │ │ + │ │ │ │ │ + def set_protocol(self, protocol: asyncio.BaseProtocol) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def __del__(self) -> None: │ │ │ │ │ + self._close() │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class SubprocessProtocol(asyncio.Protocol): │ │ │ │ │ + """An extension to asyncio.Protocol for use with SubprocessTransport.""" │ │ │ │ │ + def process_exited(self) -> None: │ │ │ │ │ + """Called when subprocess has exited.""" │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class WindowSize: │ │ │ │ │ + def __init__(self, value: JsonObject): │ │ │ │ │ + self.rows = get_int(value, 'rows') │ │ │ │ │ + self.cols = get_int(value, 'cols') │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class SubprocessTransport(_Transport, asyncio.SubprocessTransport): │ │ │ │ │ + """A bi-directional transport speaking with stdin/out of a subprocess. │ │ │ │ │ + │ │ │ │ │ + Note: this is not really a normal SubprocessTransport. Although it │ │ │ │ │ + implements the entire API of asyncio.SubprocessTransport, it is not │ │ │ │ │ + designed to be used with asyncio.SubprocessProtocol objects. Instead, it │ │ │ │ │ + pair with normal Protocol objects which also implement the │ │ │ │ │ + SubprocessProtocol defined in this module (which only has a │ │ │ │ │ + process_exited() method). Whatever the protocol writes is sent to stdin, │ │ │ │ │ + and whatever comes from stdout is given to the Protocol via the │ │ │ │ │ + .data_received() function. │ │ │ │ │ + │ │ │ │ │ + If stderr is configured as a pipe, the transport will separately collect │ │ │ │ │ + data from it, making it available via the .get_stderr() method. │ │ │ │ │ + """ │ │ │ │ │ + │ │ │ │ │ + _returncode: 'int | None' = None │ │ │ │ │ + │ │ │ │ │ + _pty_fd: 'int | None' = None │ │ │ │ │ + _process: 'subprocess.Popen[bytes] | None' = None │ │ │ │ │ + _stderr: 'Spooler | None' │ │ │ │ │ │ │ │ │ │ + @staticmethod │ │ │ │ │ + def _create_watcher() -> asyncio.AbstractChildWatcher: │ │ │ │ │ try: │ │ │ │ │ - length = int(data[:newline]) │ │ │ │ │ - except ValueError as exc: │ │ │ │ │ - raise CockpitProtocolError("frame size is not an integer") from exc │ │ │ │ │ + os.close(os.pidfd_open(os.getpid(), 0)) # check for kernel support │ │ │ │ │ + return asyncio.PidfdChildWatcher() │ │ │ │ │ + except (AttributeError, OSError): │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ - start = newline + 1 │ │ │ │ │ - end = start + length │ │ │ │ │ + return asyncio.SafeChildWatcher() │ │ │ │ │ │ │ │ │ │ - if end > len(data): │ │ │ │ │ - # We need to read more │ │ │ │ │ - return len(data) - end │ │ │ │ │ + @staticmethod │ │ │ │ │ + def _get_watcher(loop: asyncio.AbstractEventLoop) -> asyncio.AbstractChildWatcher: │ │ │ │ │ + quark = '_cockpit_transports_child_watcher' │ │ │ │ │ + watcher = getattr(loop, quark, None) │ │ │ │ │ │ │ │ │ │ - # We can consume a full frame │ │ │ │ │ - self.frame_received(data[start:end]) │ │ │ │ │ - return end │ │ │ │ │ + if watcher is None: │ │ │ │ │ + watcher = SubprocessTransport._create_watcher() │ │ │ │ │ + watcher.attach_loop(loop) │ │ │ │ │ + setattr(loop, quark, watcher) │ │ │ │ │ │ │ │ │ │ - def connection_made(self, transport: asyncio.BaseTransport) -> None: │ │ │ │ │ - logger.debug('connection_made(%s)', transport) │ │ │ │ │ - assert isinstance(transport, asyncio.Transport) │ │ │ │ │ - self.transport = transport │ │ │ │ │ - self.do_ready() │ │ │ │ │ + return watcher │ │ │ │ │ │ │ │ │ │ - if self._closed: │ │ │ │ │ - logger.debug(' but the protocol already was closed, so closing transport') │ │ │ │ │ - transport.close() │ │ │ │ │ + def get_stderr(self, *, reset: bool = False) -> str: │ │ │ │ │ + if self._stderr is not None: │ │ │ │ │ + return self._stderr.get(reset=reset).decode(errors='replace') │ │ │ │ │ + else: │ │ │ │ │ + return '' │ │ │ │ │ │ │ │ │ │ - def connection_lost(self, exc: 'Exception | None') -> None: │ │ │ │ │ - logger.debug('connection_lost') │ │ │ │ │ - assert self.transport is not None │ │ │ │ │ - self.transport = None │ │ │ │ │ - self.close(exc) │ │ │ │ │ + def _exited(self, pid: int, code: int) -> None: │ │ │ │ │ + # NB: per AbstractChildWatcher API, this handler should be thread-safe, │ │ │ │ │ + # but we only ever use non-threaded child watcher implementations, so │ │ │ │ │ + # we can assume we'll always be called in the main thread. │ │ │ │ │ │ │ │ │ │ - def close(self, exc: 'Exception | None' = None) -> None: │ │ │ │ │ - if self._closed: │ │ │ │ │ - return │ │ │ │ │ - self._closed = True │ │ │ │ │ + # NB: the subprocess is going to want to waitpid() itself as well, but │ │ │ │ │ + # will get ECHILD since we already reaped it. Fortunately, since │ │ │ │ │ + # Python 3.2 this is supported, and process gets a return status of │ │ │ │ │ + # zero. For that reason, we need to store our own copy of the return │ │ │ │ │ + # status. See https://github.com/python/cpython/issues/59960 │ │ │ │ │ + assert isinstance(self._protocol, SubprocessProtocol) │ │ │ │ │ + assert self._process is not None │ │ │ │ │ + assert self._process.pid == pid │ │ │ │ │ + self._returncode = code │ │ │ │ │ + logger.debug('Process exited with status %d', self._returncode) │ │ │ │ │ + if not self._closing: │ │ │ │ │ + self._protocol.process_exited() │ │ │ │ │ │ │ │ │ │ - if self.transport: │ │ │ │ │ - self.transport.close() │ │ │ │ │ + def __init__(self, │ │ │ │ │ + loop: asyncio.AbstractEventLoop, │ │ │ │ │ + protocol: SubprocessProtocol, │ │ │ │ │ + args: Sequence[str], │ │ │ │ │ + *, │ │ │ │ │ + pty: bool = False, │ │ │ │ │ + window: 'WindowSize | None' = None, │ │ │ │ │ + **kwargs: Any): │ │ │ │ │ │ │ │ │ │ - self.do_closed(exc) │ │ │ │ │ + # go down as a team -- we don't want any leaked processes when the bridge terminates │ │ │ │ │ + def preexec_fn() -> None: │ │ │ │ │ + prctl(SET_PDEATHSIG, signal.SIGTERM) │ │ │ │ │ + if pty: │ │ │ │ │ + fcntl.ioctl(0, termios.TIOCSCTTY, 0) │ │ │ │ │ + │ │ │ │ │ + if pty: │ │ │ │ │ + self._pty_fd, session_fd = os.openpty() │ │ │ │ │ + │ │ │ │ │ + if window is not None: │ │ │ │ │ + self.set_window_size(window) │ │ │ │ │ + │ │ │ │ │ + kwargs['stderr'] = session_fd │ │ │ │ │ + self._process = subprocess.Popen(args, │ │ │ │ │ + stdin=session_fd, stdout=session_fd, │ │ │ │ │ + preexec_fn=preexec_fn, start_new_session=True, **kwargs) │ │ │ │ │ + os.close(session_fd) │ │ │ │ │ + │ │ │ │ │ + in_fd, out_fd = self._pty_fd, self._pty_fd │ │ │ │ │ + self._eio_is_eof = True │ │ │ │ │ │ │ │ │ │ - def write_channel_data(self, channel: str, payload: bytes) -> None: │ │ │ │ │ - """Send a given payload (bytes) on channel (string)""" │ │ │ │ │ - # Channel is certainly ascii (as enforced by .encode() below) │ │ │ │ │ - frame_length = len(channel + '\n') + len(payload) │ │ │ │ │ - header = f'{frame_length}\n{channel}\n'.encode('ascii') │ │ │ │ │ - if self.transport is not None: │ │ │ │ │ - logger.debug('writing to transport %s', self.transport) │ │ │ │ │ - self.transport.write(header + payload) │ │ │ │ │ else: │ │ │ │ │ - logger.debug('cannot write to closed transport') │ │ │ │ │ + self._process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, │ │ │ │ │ + preexec_fn=preexec_fn, **kwargs) │ │ │ │ │ + assert self._process.stdin │ │ │ │ │ + assert self._process.stdout │ │ │ │ │ + in_fd = self._process.stdout.fileno() │ │ │ │ │ + out_fd = self._process.stdin.fileno() │ │ │ │ │ │ │ │ │ │ - def write_control(self, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> None: │ │ │ │ │ - """Write a control message. See jsonutil.create_object() for details.""" │ │ │ │ │ - logger.debug('sending control message %r %r', _msg, kwargs) │ │ │ │ │ - pretty = json.dumps(create_object(_msg, kwargs), indent=2) + '\n' │ │ │ │ │ - self.write_channel_data('', pretty.encode()) │ │ │ │ │ + if self._process.stderr is not None: │ │ │ │ │ + self._stderr = Spooler(loop, self._process.stderr.fileno()) │ │ │ │ │ + else: │ │ │ │ │ + self._stderr = None │ │ │ │ │ + │ │ │ │ │ + super().__init__(loop, protocol, in_fd, out_fd) │ │ │ │ │ + │ │ │ │ │ + self._get_watcher(loop).add_child_handler(self._process.pid, self._exited) │ │ │ │ │ + │ │ │ │ │ + def set_window_size(self, size: WindowSize) -> None: │ │ │ │ │ + assert self._pty_fd is not None │ │ │ │ │ + fcntl.ioctl(self._pty_fd, termios.TIOCSWINSZ, struct.pack('2H4x', size.rows, size.cols)) │ │ │ │ │ + │ │ │ │ │ + def can_write_eof(self) -> bool: │ │ │ │ │ + assert self._process is not None │ │ │ │ │ + return self._process.stdin is not None │ │ │ │ │ + │ │ │ │ │ + def _write_eof_now(self) -> None: │ │ │ │ │ + assert self._process is not None │ │ │ │ │ + assert self._process.stdin is not None │ │ │ │ │ + self._process.stdin.close() │ │ │ │ │ + self._out_fd = -1 │ │ │ │ │ + │ │ │ │ │ + def get_pid(self) -> int: │ │ │ │ │ + assert self._process is not None │ │ │ │ │ + return self._process.pid │ │ │ │ │ + │ │ │ │ │ + def get_returncode(self) -> 'int | None': │ │ │ │ │ + return self._returncode │ │ │ │ │ + │ │ │ │ │ + def get_pipe_transport(self, fd: int) -> asyncio.Transport: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def send_signal(self, sig: signal.Signals) -> None: # type: ignore[override] # mypy/issues/13885 │ │ │ │ │ + assert self._process is not None │ │ │ │ │ + # We try to avoid using subprocess.send_signal(). It contains a call │ │ │ │ │ + # to waitpid() internally to avoid signalling the wrong process (if a │ │ │ │ │ + # PID gets reused), but: │ │ │ │ │ + # │ │ │ │ │ + # - we already detect the process exiting via our PidfdChildWatcher │ │ │ │ │ + # │ │ │ │ │ + # - the check is actually harmful since collecting the process via │ │ │ │ │ + # waitpid() prevents the PidfdChildWatcher from doing the same, │ │ │ │ │ + # resulting in an error. │ │ │ │ │ + # │ │ │ │ │ + # It's on us now to check it, but that's easy: │ │ │ │ │ + if self._returncode is not None: │ │ │ │ │ + logger.debug("won't attempt %s to process %i. It exited already.", sig, self._process.pid) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - def data_received(self, data: bytes) -> None: │ │ │ │ │ try: │ │ │ │ │ - self.buffer += data │ │ │ │ │ - while self.buffer: │ │ │ │ │ - result = self.consume_one_frame(self.buffer) │ │ │ │ │ - if result <= 0: │ │ │ │ │ - return │ │ │ │ │ - self.buffer = self.buffer[result:] │ │ │ │ │ - except CockpitProtocolError as exc: │ │ │ │ │ - self.close(exc) │ │ │ │ │ + os.kill(self._process.pid, sig) │ │ │ │ │ + logger.debug('sent %s to process %i', sig, self._process.pid) │ │ │ │ │ + except ProcessLookupError: │ │ │ │ │ + # already gone? fine │ │ │ │ │ + logger.debug("can't send %s to process %i. It's exited just now.", sig, self._process.pid) │ │ │ │ │ │ │ │ │ │ - def eof_received(self) -> bool: │ │ │ │ │ + def terminate(self) -> None: │ │ │ │ │ + self.send_signal(signal.SIGTERM) │ │ │ │ │ + │ │ │ │ │ + def kill(self) -> None: │ │ │ │ │ + self.send_signal(signal.SIGKILL) │ │ │ │ │ + │ │ │ │ │ + def _close(self) -> None: │ │ │ │ │ + if self._pty_fd is not None: │ │ │ │ │ + os.close(self._pty_fd) │ │ │ │ │ + self._pty_fd = None │ │ │ │ │ + │ │ │ │ │ + if self._process is not None: │ │ │ │ │ + if self._process.stdin is not None: │ │ │ │ │ + self._process.stdin.close() │ │ │ │ │ + self._process.stdin = None │ │ │ │ │ + try: │ │ │ │ │ + self.terminate() # best effort... │ │ │ │ │ + except PermissionError: │ │ │ │ │ + logger.debug("can't kill %i due to EPERM", self._process.pid) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class StdioTransport(_Transport): │ │ │ │ │ + """A bi-directional transport that corresponds to stdin/out. │ │ │ │ │ + │ │ │ │ │ + Can talk to just about anything: │ │ │ │ │ + - files │ │ │ │ │ + - pipes │ │ │ │ │ + - character devices (including terminals) │ │ │ │ │ + - sockets │ │ │ │ │ + """ │ │ │ │ │ + │ │ │ │ │ + def __init__(self, loop: asyncio.AbstractEventLoop, protocol: asyncio.Protocol, stdin: int = 0, stdout: int = 1): │ │ │ │ │ + super().__init__(loop, protocol, stdin, stdout) │ │ │ │ │ + │ │ │ │ │ + def can_write_eof(self) -> bool: │ │ │ │ │ return False │ │ │ │ │ │ │ │ │ │ + def _write_eof_now(self) -> None: │ │ │ │ │ + raise RuntimeError("Can't write EOF to stdout") │ │ │ │ │ │ │ │ │ │ -# Helpful functionality for "server"-side protocol implementations │ │ │ │ │ -class CockpitProtocolServer(CockpitProtocol): │ │ │ │ │ - init_host: 'str | None' = None │ │ │ │ │ - authorizations: 'dict[str, asyncio.Future[str]] | None' = None │ │ │ │ │ │ │ │ │ │ - def do_send_init(self) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ +class Spooler: │ │ │ │ │ + """Consumes data from an fd, storing it in a buffer. │ │ │ │ │ │ │ │ │ │ - def do_init(self, message: JsonObject) -> None: │ │ │ │ │ - pass │ │ │ │ │ + This makes a copy of the fd, so you don't have to worry about holding it │ │ │ │ │ + open. │ │ │ │ │ + """ │ │ │ │ │ │ │ │ │ │ - def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + _loop: asyncio.AbstractEventLoop │ │ │ │ │ + _fd: int │ │ │ │ │ + _contents: 'list[bytes]' │ │ │ │ │ │ │ │ │ │ - def transport_control_received(self, command: str, message: JsonObject) -> None: │ │ │ │ │ - if command == 'init': │ │ │ │ │ - if get_int(message, 'version') != 1: │ │ │ │ │ - raise CockpitProtocolError('incorrect version number') │ │ │ │ │ - self.init_host = get_str(message, 'host') │ │ │ │ │ - self.do_init(message) │ │ │ │ │ - elif command == 'kill': │ │ │ │ │ - self.do_kill(get_str(message, 'host', None), get_str(message, 'group', None), message) │ │ │ │ │ - elif command == 'authorize': │ │ │ │ │ - self.do_authorize(message) │ │ │ │ │ - else: │ │ │ │ │ - raise CockpitProtocolError(f'unexpected control message {command} received') │ │ │ │ │ + def __init__(self, loop: asyncio.AbstractEventLoop, fd: int): │ │ │ │ │ + self._loop = loop │ │ │ │ │ + self._fd = -1 # in case dup() raises an exception │ │ │ │ │ + self._contents = [] │ │ │ │ │ │ │ │ │ │ - def do_ready(self) -> None: │ │ │ │ │ - self.do_send_init() │ │ │ │ │ + self._fd = os.dup(fd) │ │ │ │ │ │ │ │ │ │ - # authorize request/response API │ │ │ │ │ - async def request_authorization( │ │ │ │ │ - self, challenge: str, timeout: 'int | None' = None, **kwargs: JsonValue │ │ │ │ │ - ) -> str: │ │ │ │ │ - if self.authorizations is None: │ │ │ │ │ - self.authorizations = {} │ │ │ │ │ - cookie = str(uuid.uuid4()) │ │ │ │ │ - future = asyncio.get_running_loop().create_future() │ │ │ │ │ + os.set_blocking(self._fd, False) │ │ │ │ │ + loop.add_reader(self._fd, self._read_ready) │ │ │ │ │ + │ │ │ │ │ + def _read_ready(self) -> None: │ │ │ │ │ try: │ │ │ │ │ - self.authorizations[cookie] = future │ │ │ │ │ - self.write_control(None, command='authorize', challenge=challenge, cookie=cookie, **kwargs) │ │ │ │ │ - return await asyncio.wait_for(future, timeout) │ │ │ │ │ - finally: │ │ │ │ │ - self.authorizations.pop(cookie) │ │ │ │ │ + data = os.read(self._fd, 8192) │ │ │ │ │ + except BlockingIOError: # pragma: no cover │ │ │ │ │ + return │ │ │ │ │ + except OSError: │ │ │ │ │ + # all other errors -> EOF │ │ │ │ │ + data = b'' │ │ │ │ │ │ │ │ │ │ - def do_authorize(self, message: JsonObject) -> None: │ │ │ │ │ - cookie = get_str(message, 'cookie') │ │ │ │ │ - response = get_str(message, 'response') │ │ │ │ │ + if data != b'': │ │ │ │ │ + self._contents.append(data) │ │ │ │ │ + else: │ │ │ │ │ + self.close() │ │ │ │ │ │ │ │ │ │ - if self.authorizations is None or cookie not in self.authorizations: │ │ │ │ │ - logger.warning('no matching authorize request') │ │ │ │ │ - return │ │ │ │ │ + def _is_ready(self) -> bool: │ │ │ │ │ + if self._fd == -1: │ │ │ │ │ + return False │ │ │ │ │ + return select.select([self._fd], [], [], 0) != ([], [], []) │ │ │ │ │ │ │ │ │ │ - self.authorizations[cookie].set_result(response) │ │ │ │ │ + def get(self, *, reset: bool = False) -> bytes: │ │ │ │ │ + while self._is_ready(): │ │ │ │ │ + self._read_ready() │ │ │ │ │ + │ │ │ │ │ + result = b''.join(self._contents) │ │ │ │ │ + if reset: │ │ │ │ │ + self._contents = [] │ │ │ │ │ + return result │ │ │ │ │ + │ │ │ │ │ + def close(self) -> None: │ │ │ │ │ + if self._fd != -1: │ │ │ │ │ + self._loop.remove_reader(self._fd) │ │ │ │ │ + os.close(self._fd) │ │ │ │ │ + self._fd = -1 │ │ │ │ │ + │ │ │ │ │ + def __del__(self) -> None: │ │ │ │ │ + self.close() │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/superuser.py': br'''# This file is part of Cockpit. │ │ │ │ │ + 'cockpit/polkit.py': r'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ +# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import array │ │ │ │ │ import asyncio │ │ │ │ │ -import contextlib │ │ │ │ │ -import getpass │ │ │ │ │ +import locale │ │ │ │ │ import logging │ │ │ │ │ import os │ │ │ │ │ -import socket │ │ │ │ │ -from tempfile import TemporaryDirectory │ │ │ │ │ -from typing import List, Optional, Sequence, Tuple │ │ │ │ │ +import pwd │ │ │ │ │ +from typing import Dict, List, Sequence, Tuple │ │ │ │ │ │ │ │ │ │ -from cockpit._vendor import ferny │ │ │ │ │ -from cockpit._vendor.bei.bootloader import make_bootloader │ │ │ │ │ +from cockpit._vendor.ferny import AskpassHandler │ │ │ │ │ from cockpit._vendor.systemd_ctypes import Variant, bus │ │ │ │ │ │ │ │ │ │ -from .beipack import BridgeBeibootHelper │ │ │ │ │ -from .jsonutil import JsonObject, get_str │ │ │ │ │ -from .packages import BridgeConfig │ │ │ │ │ -from .peer import ConfiguredPeer, Peer, PeerError │ │ │ │ │ -from .polkit import PolkitAgent │ │ │ │ │ -from .router import Router, RoutingError, RoutingRule │ │ │ │ │ +# that path is valid on at least Debian, Fedora/RHEL, and Arch │ │ │ │ │ +HELPER_PATH = '/usr/lib/polkit-1/polkit-agent-helper-1' │ │ │ │ │ + │ │ │ │ │ +AGENT_DBUS_PATH = '/PolkitAgent' │ │ │ │ │ │ │ │ │ │ logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ +Identity = Tuple[str, Dict[str, Variant]] │ │ │ │ │ │ │ │ │ │ -class SuperuserPeer(ConfiguredPeer): │ │ │ │ │ - responder: ferny.AskpassHandler │ │ │ │ │ │ │ │ │ │ - def __init__(self, router: Router, config: BridgeConfig, responder: ferny.AskpassHandler): │ │ │ │ │ - super().__init__(router, config) │ │ │ │ │ +# https://www.freedesktop.org/software/polkit/docs/latest/eggdbus-interface-org.freedesktop.PolicyKit1.AuthenticationAgent.html │ │ │ │ │ + │ │ │ │ │ +# Note that we don't implement the CancelAuthentication() API. pkexec gets called in a way that has no opportunity to │ │ │ │ │ +# cancel an ongoing authentication from the pkexec side. On the UI side cancellation is implemented via the standard │ │ │ │ │ +# asyncio process mechanism. If we ever need CancelAuthentication(), we could keep a cookie → get_current_task() │ │ │ │ │ +# mapping, but that method is not available for Python 3.6 yet. │ │ │ │ │ + │ │ │ │ │ +class org_freedesktop_PolicyKit1_AuthenticationAgent(bus.Object): │ │ │ │ │ + def __init__(self, responder: AskpassHandler): │ │ │ │ │ + super().__init__() │ │ │ │ │ self.responder = responder │ │ │ │ │ │ │ │ │ │ - async def do_connect_transport(self) -> None: │ │ │ │ │ - async with contextlib.AsyncExitStack() as context: │ │ │ │ │ - if 'pkexec' in self.args: │ │ │ │ │ - logger.debug('connecting polkit superuser peer transport %r', self.args) │ │ │ │ │ - await context.enter_async_context(PolkitAgent(self.responder)) │ │ │ │ │ - else: │ │ │ │ │ - logger.debug('connecting non-polkit superuser peer transport %r', self.args) │ │ │ │ │ + # confusingly named: this actually does the whole authentication dialog, see docs │ │ │ │ │ + @bus.Interface.Method('', ['s', 's', 's', 'a{ss}', 's', 'a(sa{sv})']) │ │ │ │ │ + async def begin_authentication(self, action_id: str, message: str, icon_name: str, │ │ │ │ │ + details: Dict[str, str], cookie: str, identities: Sequence[Identity]) -> None: │ │ │ │ │ + logger.debug('BeginAuthentication: action %s, message "%s", icon %s, details %s, cookie %s, identities %r', │ │ │ │ │ + action_id, message, icon_name, details, cookie, identities) │ │ │ │ │ + # only support authentication as ourselves, as we don't yet have the │ │ │ │ │ + # protocol plumbing and UI to select an admin user │ │ │ │ │ + my_uid = os.geteuid() │ │ │ │ │ + for (auth_type, subject) in identities: │ │ │ │ │ + if auth_type == 'unix-user' and 'uid' in subject and subject['uid'].value == my_uid: │ │ │ │ │ + logger.debug('Authentication subject %s matches our uid %d', subject, my_uid) │ │ │ │ │ + break │ │ │ │ │ + else: │ │ │ │ │ + logger.warning('Not supporting authentication as any of %s', identities) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - responders: 'list[ferny.InteractionHandler]' = [self.responder] │ │ │ │ │ + user_name = pwd.getpwuid(my_uid).pw_name │ │ │ │ │ + process = await asyncio.create_subprocess_exec(HELPER_PATH, user_name, cookie, │ │ │ │ │ + stdin=asyncio.subprocess.PIPE, │ │ │ │ │ + stdout=asyncio.subprocess.PIPE) │ │ │ │ │ + try: │ │ │ │ │ + await self._communicate(process) │ │ │ │ │ + except asyncio.CancelledError: │ │ │ │ │ + logger.debug('Cancelled authentication') │ │ │ │ │ + process.terminate() │ │ │ │ │ + finally: │ │ │ │ │ + res = await process.wait() │ │ │ │ │ + logger.debug('helper exited with code %i', res) │ │ │ │ │ │ │ │ │ │ - if '# cockpit-bridge' in self.args: │ │ │ │ │ - logger.debug('going to beiboot superuser bridge %r', self.args) │ │ │ │ │ - helper = BridgeBeibootHelper(self, ['--privileged']) │ │ │ │ │ - responders.append(helper) │ │ │ │ │ - stage1 = make_bootloader(helper.steps, gadgets=ferny.BEIBOOT_GADGETS).encode() │ │ │ │ │ - else: │ │ │ │ │ - stage1 = None │ │ │ │ │ + async def _communicate(self, process: asyncio.subprocess.Process) -> None: │ │ │ │ │ + assert process.stdin │ │ │ │ │ + assert process.stdout │ │ │ │ │ │ │ │ │ │ - agent = ferny.InteractionAgent(responders) │ │ │ │ │ + messages: List[str] = [] │ │ │ │ │ │ │ │ │ │ - if 'SUDO_ASKPASS=ferny-askpass' in self.env: │ │ │ │ │ - tmpdir = context.enter_context(TemporaryDirectory()) │ │ │ │ │ - ferny_askpass = ferny.write_askpass_to_tmpdir(tmpdir) │ │ │ │ │ - env: Sequence[str] = [f'SUDO_ASKPASS={ferny_askpass}'] │ │ │ │ │ + async for line in process.stdout: │ │ │ │ │ + logger.debug('Read line from helper: %s', line) │ │ │ │ │ + command, _, value = line.strip().decode().partition(' ') │ │ │ │ │ + │ │ │ │ │ + # usually: PAM_PROMPT_ECHO_OFF Password: \n │ │ │ │ │ + if command.startswith('PAM_PROMPT'): │ │ │ │ │ + # Don't pass this to the UI if it's "Password" (the usual case), │ │ │ │ │ + # so that superuser.py uses the translated default │ │ │ │ │ + if value.startswith('Password'): │ │ │ │ │ + value = '' │ │ │ │ │ + │ │ │ │ │ + # flush out accumulated info/error messages │ │ │ │ │ + passwd = await self.responder.do_askpass('\n'.join(messages), value, '') │ │ │ │ │ + messages.clear() │ │ │ │ │ + if passwd is None: │ │ │ │ │ + logger.debug('got PAM_PROMPT %s, but do_askpass returned None', value) │ │ │ │ │ + raise asyncio.CancelledError('no password given') │ │ │ │ │ + logger.debug('got PAM_PROMPT %s, do_askpass returned a password', value) │ │ │ │ │ + process.stdin.write(passwd.encode()) │ │ │ │ │ + process.stdin.write(b'\n') │ │ │ │ │ + del passwd # don't keep this around longer than necessary │ │ │ │ │ + await process.stdin.drain() │ │ │ │ │ + logger.debug('got PAM_PROMPT, wrote password to helper') │ │ │ │ │ + elif command in ('PAM_TEXT_INFO', 'PAM_ERROR'): │ │ │ │ │ + messages.append(value) │ │ │ │ │ + elif command == 'SUCCESS': │ │ │ │ │ + logger.debug('Authentication succeeded') │ │ │ │ │ + break │ │ │ │ │ + elif command == 'FAILURE': │ │ │ │ │ + logger.warning('Authentication failed') │ │ │ │ │ + break │ │ │ │ │ else: │ │ │ │ │ - env = self.env │ │ │ │ │ + logger.warning('Unknown line from helper, aborting: %s', line) │ │ │ │ │ + process.terminate() │ │ │ │ │ + break │ │ │ │ │ │ │ │ │ │ - transport = await self.spawn(self.args, env, stderr=agent, start_new_session=True) │ │ │ │ │ │ │ │ │ │ - if stage1 is not None: │ │ │ │ │ - transport.write(stage1) │ │ │ │ │ +class PolkitAgent: │ │ │ │ │ + """Register polkit agent when required │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - await agent.communicate() │ │ │ │ │ - except ferny.InteractionError as exc: │ │ │ │ │ - raise PeerError('authentication-failed', message=str(exc)) from exc │ │ │ │ │ + Use this as a context manager to ensure that the agent gets unregistered again. │ │ │ │ │ + """ │ │ │ │ │ + def __init__(self, responder: AskpassHandler): │ │ │ │ │ + self.responder = responder │ │ │ │ │ + self.agent_slot = None │ │ │ │ │ │ │ │ │ │ + async def __aenter__(self): │ │ │ │ │ + try: │ │ │ │ │ + self.system_bus = bus.Bus.default_system() │ │ │ │ │ + except OSError as e: │ │ │ │ │ + logger.warning('cannot connect to system bus, not registering polkit agent: %s', e) │ │ │ │ │ + return self │ │ │ │ │ │ │ │ │ │ -class CockpitResponder(ferny.AskpassHandler): │ │ │ │ │ - commands = ('ferny.askpass', 'cockpit.send-stderr') │ │ │ │ │ + try: │ │ │ │ │ + # may refine that with a D-Bus call to logind │ │ │ │ │ + self.subject = ('unix-session', {'session-id': Variant(os.environ['XDG_SESSION_ID'], 's')}) │ │ │ │ │ + except KeyError: │ │ │ │ │ + logger.debug('XDG_SESSION_ID not set, not registering polkit agent') │ │ │ │ │ + return self │ │ │ │ │ │ │ │ │ │ - async def do_custom_command(self, command: str, args: Tuple, fds: List[int], stderr: str) -> None: │ │ │ │ │ - if command == 'cockpit.send-stderr': │ │ │ │ │ - with socket.socket(fileno=fds[0]) as sock: │ │ │ │ │ - fds.pop(0) │ │ │ │ │ - # socket.send_fds(sock, [b'\0'], [2]) # New in Python 3.9 │ │ │ │ │ - sock.sendmsg([b'\0'], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [2]))]) │ │ │ │ │ + agent_object = org_freedesktop_PolicyKit1_AuthenticationAgent(self.responder) │ │ │ │ │ + self.agent_slot = self.system_bus.add_object(AGENT_DBUS_PATH, agent_object) │ │ │ │ │ │ │ │ │ │ + # register agent │ │ │ │ │ + locale_name = locale.setlocale(locale.LC_MESSAGES, None) │ │ │ │ │ + await self.system_bus.call_method_async( │ │ │ │ │ + 'org.freedesktop.PolicyKit1', │ │ │ │ │ + '/org/freedesktop/PolicyKit1/Authority', │ │ │ │ │ + 'org.freedesktop.PolicyKit1.Authority', │ │ │ │ │ + 'RegisterAuthenticationAgent', │ │ │ │ │ + '(sa{sv})ss', │ │ │ │ │ + self.subject, locale_name, AGENT_DBUS_PATH) │ │ │ │ │ + logger.debug('Registered agent for %r and locale %s', self.subject, locale_name) │ │ │ │ │ + return self │ │ │ │ │ │ │ │ │ │ -class AuthorizeResponder(CockpitResponder): │ │ │ │ │ - def __init__(self, router: Router): │ │ │ │ │ - self.router = router │ │ │ │ │ + async def __aexit__(self, _exc_type, _exc_value, _traceback): │ │ │ │ │ + if self.agent_slot: │ │ │ │ │ + await self.system_bus.call_method_async( │ │ │ │ │ + 'org.freedesktop.PolicyKit1', │ │ │ │ │ + '/org/freedesktop/PolicyKit1/Authority', │ │ │ │ │ + 'org.freedesktop.PolicyKit1.Authority', │ │ │ │ │ + 'UnregisterAuthenticationAgent', │ │ │ │ │ + '(sa{sv})s', │ │ │ │ │ + self.subject, AGENT_DBUS_PATH) │ │ │ │ │ + self.agent_slot.cancel() │ │ │ │ │ + logger.debug('Unregistered agent for %r', self.subject) │ │ │ │ │ +'''.encode('utf-8'), │ │ │ │ │ + 'cockpit/beipack.py': br'''# This file is part of Cockpit. │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ - async def do_askpass(self, messages: str, prompt: str, hint: str) -> str: │ │ │ │ │ - hexuser = ''.join(f'{c:02x}' for c in getpass.getuser().encode('ascii')) │ │ │ │ │ - return await self.router.request_authorization(f'plain1:{hexuser}') │ │ │ │ │ +import logging │ │ │ │ │ +import lzma │ │ │ │ │ +from typing import List, Sequence, Tuple │ │ │ │ │ │ │ │ │ │ +from cockpit._vendor import ferny │ │ │ │ │ +from cockpit._vendor.bei import beipack │ │ │ │ │ │ │ │ │ │ -class SuperuserRoutingRule(RoutingRule, CockpitResponder, bus.Object, interface='cockpit.Superuser'): │ │ │ │ │ - superuser_configs: Sequence[BridgeConfig] = () │ │ │ │ │ - pending_prompt: Optional[asyncio.Future] │ │ │ │ │ - peer: Optional[SuperuserPeer] │ │ │ │ │ +from .data import read_cockpit_data_file │ │ │ │ │ +from .peer import Peer, PeerError │ │ │ │ │ │ │ │ │ │ - # D-Bus signals │ │ │ │ │ - prompt = bus.Interface.Signal('s', 's', 's', 'b', 's') # message, prompt, default, echo, error │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ - # D-Bus properties │ │ │ │ │ - bridges = bus.Interface.Property('as', value=[]) │ │ │ │ │ - current = bus.Interface.Property('s', value='none') │ │ │ │ │ - methods = bus.Interface.Property('a{sv}', value={}) │ │ │ │ │ │ │ │ │ │ - # RoutingRule │ │ │ │ │ - def apply_rule(self, options: JsonObject) -> Optional[Peer]: │ │ │ │ │ - superuser = options.get('superuser') │ │ │ │ │ +def get_bridge_beipack_xz() -> Tuple[str, bytes]: │ │ │ │ │ + try: │ │ │ │ │ + bridge_beipack_xz = read_cockpit_data_file('cockpit-bridge.beipack.xz') │ │ │ │ │ + logger.debug('Got pre-built cockpit-bridge.beipack.xz') │ │ │ │ │ + except FileNotFoundError: │ │ │ │ │ + logger.debug('Pre-built cockpit-bridge.beipack.xz; building our own.') │ │ │ │ │ + # beipack ourselves │ │ │ │ │ + cockpit_contents = beipack.collect_module('cockpit', recursive=True) │ │ │ │ │ + bridge_beipack = beipack.pack(cockpit_contents, entrypoint='cockpit.bridge:main', args='beipack=True') │ │ │ │ │ + bridge_beipack_xz = lzma.compress(bridge_beipack.encode()) │ │ │ │ │ + logger.debug(' ... done!') │ │ │ │ │ │ │ │ │ │ - if not superuser or self.current == 'root': │ │ │ │ │ - # superuser not requested, or already superuser? Next rule. │ │ │ │ │ - return None │ │ │ │ │ - elif self.peer or superuser == 'try': │ │ │ │ │ - # superuser requested and active? Return it. │ │ │ │ │ - # 'try' requested? Either return the peer, or None. │ │ │ │ │ - return self.peer │ │ │ │ │ + return 'cockpit/data/cockpit-bridge.beipack.xz', bridge_beipack_xz │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class BridgeBeibootHelper(ferny.InteractionHandler): │ │ │ │ │ + # ferny.InteractionHandler ClassVar │ │ │ │ │ + commands = ['beiboot.provide', 'beiboot.exc'] │ │ │ │ │ + │ │ │ │ │ + peer: Peer │ │ │ │ │ + payload: bytes │ │ │ │ │ + steps: Sequence[Tuple[str, Sequence[object]]] │ │ │ │ │ + │ │ │ │ │ + def __init__(self, peer: Peer, args: Sequence[str] = ()) -> None: │ │ │ │ │ + filename, payload = get_bridge_beipack_xz() │ │ │ │ │ + │ │ │ │ │ + self.peer = peer │ │ │ │ │ + self.payload = payload │ │ │ │ │ + self.steps = (('boot_xz', (filename, len(payload), tuple(args))),) │ │ │ │ │ + │ │ │ │ │ + async def run_command(self, command: str, args: Tuple, fds: List[int], stderr: str) -> None: │ │ │ │ │ + logger.debug('Got ferny request %s %s %s %s', command, args, fds, stderr) │ │ │ │ │ + if command == 'beiboot.provide': │ │ │ │ │ + try: │ │ │ │ │ + size, = args │ │ │ │ │ + assert size == len(self.payload) │ │ │ │ │ + except (AssertionError, ValueError) as exc: │ │ │ │ │ + raise PeerError('internal-error', message=f'ferny interaction error {exc!s}') from exc │ │ │ │ │ + │ │ │ │ │ + assert self.peer.transport is not None │ │ │ │ │ + logger.debug('Writing %d bytes of payload', len(self.payload)) │ │ │ │ │ + self.peer.transport.write(self.payload) │ │ │ │ │ + elif command == 'beiboot.exc': │ │ │ │ │ + raise PeerError('internal-error', message=f'Remote exception: {args[0]}') │ │ │ │ │ else: │ │ │ │ │ - # superuser requested, but not active? That's an error. │ │ │ │ │ - raise RoutingError('access-denied') │ │ │ │ │ + raise PeerError('internal-error', message=f'Unexpected ferny interaction command {command}') │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_version.py': br'''__version__ = '311' │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/jsonutil.py': r'''# This file is part of Cockpit. │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ - # ferny.AskpassHandler │ │ │ │ │ - async def do_askpass(self, messages: str, prompt: str, hint: str) -> Optional[str]: │ │ │ │ │ - assert self.pending_prompt is None │ │ │ │ │ - echo = hint == "confirm" │ │ │ │ │ - self.pending_prompt = asyncio.get_running_loop().create_future() │ │ │ │ │ - try: │ │ │ │ │ - logger.debug('prompting for %s', prompt) │ │ │ │ │ - # with sudo, all stderr messages are treated as warning/errors by the UI │ │ │ │ │ - # (such as the lecture or "wrong password"), so pass them in the "error" field │ │ │ │ │ - self.prompt('', prompt, '', echo, messages) │ │ │ │ │ - return await self.pending_prompt │ │ │ │ │ - finally: │ │ │ │ │ - self.pending_prompt = None │ │ │ │ │ +from enum import Enum │ │ │ │ │ +from typing import Callable, Dict, List, Mapping, Optional, Sequence, Type, TypeVar, Union │ │ │ │ │ │ │ │ │ │ - def __init__(self, router: Router, *, privileged: bool = False): │ │ │ │ │ - super().__init__(router) │ │ │ │ │ +JsonLiteral = Union[str, float, bool, None] │ │ │ │ │ │ │ │ │ │ - self.pending_prompt = None │ │ │ │ │ - self.peer = None │ │ │ │ │ - self.startup = None │ │ │ │ │ +# immutable │ │ │ │ │ +JsonValue = Union['JsonObject', Sequence['JsonValue'], JsonLiteral] │ │ │ │ │ +JsonObject = Mapping[str, JsonValue] │ │ │ │ │ │ │ │ │ │ - if privileged or os.getuid() == 0: │ │ │ │ │ - self.current = 'root' │ │ │ │ │ +# mutable │ │ │ │ │ +JsonDocument = Union['JsonDict', 'JsonList', JsonLiteral] │ │ │ │ │ +JsonDict = Dict[str, JsonDocument] │ │ │ │ │ +JsonList = List[JsonDocument] │ │ │ │ │ │ │ │ │ │ - def peer_done(self): │ │ │ │ │ - self.current = 'none' │ │ │ │ │ - self.peer = None │ │ │ │ │ │ │ │ │ │ - async def go(self, name: str, responder: ferny.AskpassHandler) -> None: │ │ │ │ │ - if self.current != 'none': │ │ │ │ │ - raise bus.BusError('cockpit.Superuser.Error', 'Superuser bridge already running') │ │ │ │ │ +DT = TypeVar('DT') │ │ │ │ │ +T = TypeVar('T') │ │ │ │ │ │ │ │ │ │ - assert self.peer is None │ │ │ │ │ - assert self.startup is None │ │ │ │ │ │ │ │ │ │ - for config in self.superuser_configs: │ │ │ │ │ - if name in (config.name, 'any'): │ │ │ │ │ - break │ │ │ │ │ +class JsonError(Exception): │ │ │ │ │ + value: object │ │ │ │ │ + │ │ │ │ │ + def __init__(self, value: object, msg: str): │ │ │ │ │ + super().__init__(msg) │ │ │ │ │ + self.value = value │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def typechecked(value: JsonValue, expected_type: Type[T]) -> T: │ │ │ │ │ + """Ensure a JSON value has the expected type, returning it if so.""" │ │ │ │ │ + if not isinstance(value, expected_type): │ │ │ │ │ + raise JsonError(value, f'must have type {expected_type.__name__}') │ │ │ │ │ + return value │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +# We can't use None as a sentinel because it's often the actual default value │ │ │ │ │ +# EllipsisType is difficult because it's not available before 3.10. │ │ │ │ │ +# See https://peps.python.org/pep-0484/#support-for-singleton-types-in-unions │ │ │ │ │ +class _Empty(Enum): │ │ │ │ │ + TOKEN = 0 │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +_empty = _Empty.TOKEN │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def _get(obj: JsonObject, cast: Callable[[JsonValue], T], key: str, default: Union[DT, _Empty]) -> Union[T, DT]: │ │ │ │ │ + try: │ │ │ │ │ + return cast(obj[key]) │ │ │ │ │ + except KeyError: │ │ │ │ │ + if default is not _empty: │ │ │ │ │ + return default │ │ │ │ │ + raise JsonError(obj, f"attribute '{key}' required") from None │ │ │ │ │ + except JsonError as exc: │ │ │ │ │ + target = f"attribute '{key}'" + (' elements:' if exc.value is not obj[key] else ':') │ │ │ │ │ + raise JsonError(obj, f"{target} {exc!s}") from exc │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_bool(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, bool]: │ │ │ │ │ + return _get(obj, lambda v: typechecked(v, bool), key, default) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_int(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, int]: │ │ │ │ │ + return _get(obj, lambda v: typechecked(v, int), key, default) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_str(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, str]: │ │ │ │ │ + return _get(obj, lambda v: typechecked(v, str), key, default) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_str_or_none(obj: JsonObject, key: str, default: Optional[str]) -> Optional[str]: │ │ │ │ │ + return _get(obj, lambda v: None if v is None else typechecked(v, str), key, default) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_dict(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, JsonObject]: │ │ │ │ │ + return _get(obj, lambda v: typechecked(v, dict), key, default) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_object( │ │ │ │ │ + obj: JsonObject, │ │ │ │ │ + key: str, │ │ │ │ │ + constructor: Callable[[JsonObject], T], │ │ │ │ │ + default: Union[DT, _Empty] = _empty │ │ │ │ │ +) -> Union[DT, T]: │ │ │ │ │ + return _get(obj, lambda v: constructor(typechecked(v, dict)), key, default) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_strv(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, Sequence[str]]: │ │ │ │ │ + def as_strv(value: JsonValue) -> Sequence[str]: │ │ │ │ │ + return tuple(typechecked(item, str) for item in typechecked(value, list)) │ │ │ │ │ + return _get(obj, as_strv, key, default) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_objv(obj: JsonObject, key: str, constructor: Callable[[JsonObject], T]) -> Union[DT, Sequence[T]]: │ │ │ │ │ + def as_objv(value: JsonValue) -> Sequence[T]: │ │ │ │ │ + return tuple(constructor(typechecked(item, dict)) for item in typechecked(value, list)) │ │ │ │ │ + return _get(obj, as_objv, key, ()) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def create_object(message: 'JsonObject | None', kwargs: JsonObject) -> JsonObject: │ │ │ │ │ + """Constructs a JSON object based on message and kwargs. │ │ │ │ │ + │ │ │ │ │ + If only message is given, it is returned, unmodified. If message is None, │ │ │ │ │ + it is equivalent to an empty dictionary. A copy is always made. │ │ │ │ │ + │ │ │ │ │ + If kwargs are present, then any underscore ('_') present in a key name is │ │ │ │ │ + rewritten to a dash ('-'). This is intended to bridge between the required │ │ │ │ │ + Python syntax when providing kwargs and idiomatic JSON (which uses '-' for │ │ │ │ │ + attributes). These values override values in message. │ │ │ │ │ + │ │ │ │ │ + The idea is that `message` should be used for passing data along, and │ │ │ │ │ + kwargs used for data originating at a given call site, possibly including │ │ │ │ │ + modifications to an original message. │ │ │ │ │ + """ │ │ │ │ │ + result = dict(message or {}) │ │ │ │ │ + │ │ │ │ │ + for key, value in kwargs.items(): │ │ │ │ │ + # rewrite '_' (necessary in Python syntax kwargs list) to '-' (idiomatic JSON) │ │ │ │ │ + json_key = key.replace('_', '-') │ │ │ │ │ + result[json_key] = value │ │ │ │ │ + │ │ │ │ │ + return result │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def json_merge_patch(current: JsonObject, patch: JsonObject) -> JsonObject: │ │ │ │ │ + """Perform a JSON merge patch (RFC 7396) using 'current' and 'patch'. │ │ │ │ │ + Neither of the original dictionaries is modified — the result is returned. │ │ │ │ │ + """ │ │ │ │ │ + # Always take a copy ('result') — we never modify the input ('current') │ │ │ │ │ + result = dict(current) │ │ │ │ │ + for key, patch_value in patch.items(): │ │ │ │ │ + if isinstance(patch_value, Mapping): │ │ │ │ │ + current_value = current.get(key, None) │ │ │ │ │ + if not isinstance(current_value, Mapping): │ │ │ │ │ + current_value = {} │ │ │ │ │ + result[key] = json_merge_patch(current_value, patch_value) │ │ │ │ │ + elif patch_value is not None: │ │ │ │ │ + result[key] = patch_value │ │ │ │ │ else: │ │ │ │ │ - raise bus.BusError('cockpit.Superuser.Error', f'Unknown superuser bridge type "{name}"') │ │ │ │ │ + result.pop(key, None) │ │ │ │ │ │ │ │ │ │ - self.current = 'init' │ │ │ │ │ - self.peer = SuperuserPeer(self.router, config, responder) │ │ │ │ │ - self.peer.add_done_callback(self.peer_done) │ │ │ │ │ + return result │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - await self.peer.start(init_host=self.router.init_host) │ │ │ │ │ - except asyncio.CancelledError: │ │ │ │ │ - raise bus.BusError('cockpit.Superuser.Error.Cancelled', 'Operation aborted') from None │ │ │ │ │ - except (OSError, PeerError) as exc: │ │ │ │ │ - raise bus.BusError('cockpit.Superuser.Error', str(exc)) from exc │ │ │ │ │ │ │ │ │ │ - self.current = self.peer.config.name │ │ │ │ │ +def json_merge_and_filter_patch(current: JsonDict, patch: JsonDict) -> None: │ │ │ │ │ + """Perform a JSON merge patch (RFC 7396) modifying 'current' with 'patch'. │ │ │ │ │ + Also modifies 'patch' to remove redundant operations. │ │ │ │ │ + """ │ │ │ │ │ + for key, patch_value in tuple(patch.items()): │ │ │ │ │ + current_value = current.get(key, None) │ │ │ │ │ │ │ │ │ │ - def set_configs(self, configs: Sequence[BridgeConfig]): │ │ │ │ │ - logger.debug("set_configs() with %d items", len(configs)) │ │ │ │ │ - configs = [config for config in configs if config.privileged] │ │ │ │ │ - self.superuser_configs = tuple(configs) │ │ │ │ │ - self.bridges = [config.name for config in self.superuser_configs] │ │ │ │ │ - self.methods = {c.label: Variant({'label': Variant(c.label)}, 'a{sv}') for c in configs if c.label} │ │ │ │ │ + if isinstance(patch_value, dict): │ │ │ │ │ + if not isinstance(current_value, dict): │ │ │ │ │ + current[key] = current_value = {} │ │ │ │ │ + json_merge_and_filter_patch(current_value, patch_value) │ │ │ │ │ + else: │ │ │ │ │ + json_merge_and_filter_patch(current_value, patch_value) │ │ │ │ │ + if not patch_value: │ │ │ │ │ + del patch[key] │ │ │ │ │ + elif current_value == patch_value: │ │ │ │ │ + del patch[key] │ │ │ │ │ + elif patch_value is not None: │ │ │ │ │ + current[key] = patch_value │ │ │ │ │ + else: │ │ │ │ │ + del current[key] │ │ │ │ │ +'''.encode('utf-8'), │ │ │ │ │ + 'cockpit/polyfills.py': br'''# This file is part of Cockpit. │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ - logger.debug(" bridges are now %s", self.bridges) │ │ │ │ │ +import contextlib │ │ │ │ │ +import socket │ │ │ │ │ │ │ │ │ │ - # If the currently active bridge config is not in the new set of configs, stop it │ │ │ │ │ - if self.peer is not None: │ │ │ │ │ - if self.peer.config not in self.superuser_configs: │ │ │ │ │ - logger.debug(" stopping superuser bridge '%s': it disappeared from configs", self.peer.config.name) │ │ │ │ │ - self.stop() │ │ │ │ │ │ │ │ │ │ - def cancel_prompt(self): │ │ │ │ │ - if self.pending_prompt is not None: │ │ │ │ │ - self.pending_prompt.cancel() │ │ │ │ │ - self.pending_prompt = None │ │ │ │ │ +def install(): │ │ │ │ │ + """Add shims for older Python versions""" │ │ │ │ │ + │ │ │ │ │ + # introduced in 3.9 │ │ │ │ │ + if not hasattr(socket, 'recv_fds'): │ │ │ │ │ + import array │ │ │ │ │ + │ │ │ │ │ + import _socket │ │ │ │ │ + │ │ │ │ │ + def recv_fds(sock, bufsize, maxfds, flags=0): │ │ │ │ │ + fds = array.array("i") │ │ │ │ │ + msg, ancdata, flags, addr = sock.recvmsg(bufsize, _socket.CMSG_LEN(maxfds * fds.itemsize)) │ │ │ │ │ + for cmsg_level, cmsg_type, cmsg_data in ancdata: │ │ │ │ │ + if (cmsg_level == _socket.SOL_SOCKET and cmsg_type == _socket.SCM_RIGHTS): │ │ │ │ │ + fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) │ │ │ │ │ + return msg, list(fds), flags, addr │ │ │ │ │ + │ │ │ │ │ + socket.recv_fds = recv_fds │ │ │ │ │ + │ │ │ │ │ + # introduced in 3.7 │ │ │ │ │ + if not hasattr(contextlib, 'AsyncExitStack'): │ │ │ │ │ + class AsyncExitStack: │ │ │ │ │ + async def __aenter__(self): │ │ │ │ │ + self.cms = [] │ │ │ │ │ + return self │ │ │ │ │ + │ │ │ │ │ + async def enter_async_context(self, cm): │ │ │ │ │ + result = await cm.__aenter__() │ │ │ │ │ + self.cms.append(cm) │ │ │ │ │ + return result │ │ │ │ │ + │ │ │ │ │ + async def __aexit__(self, exc_type, exc_value, traceback): │ │ │ │ │ + for cm in self.cms: │ │ │ │ │ + cm.__aexit__(exc_type, exc_value, traceback) │ │ │ │ │ + │ │ │ │ │ + contextlib.AsyncExitStack = AsyncExitStack │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/router.py': br'''# This file is part of Cockpit. │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ + │ │ │ │ │ +import asyncio │ │ │ │ │ +import collections │ │ │ │ │ +import logging │ │ │ │ │ +from typing import Dict, List, Optional │ │ │ │ │ + │ │ │ │ │ +from .jsonutil import JsonObject, JsonValue │ │ │ │ │ +from .protocol import CockpitProblem, CockpitProtocolError, CockpitProtocolServer │ │ │ │ │ + │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class ExecutionQueue: │ │ │ │ │ + """Temporarily delay calls to a given set of class methods. │ │ │ │ │ + │ │ │ │ │ + Functions by replacing the named function at the instance __dict__ │ │ │ │ │ + level, effectively providing an override for exactly one instance │ │ │ │ │ + of `method`'s object. │ │ │ │ │ + Queues the invocations. Run them later with .run(), which also reverses │ │ │ │ │ + the redirection by deleting the named methods from the instance. │ │ │ │ │ + """ │ │ │ │ │ + def __init__(self, methods): │ │ │ │ │ + self.queue = collections.deque() │ │ │ │ │ + self.methods = methods │ │ │ │ │ + │ │ │ │ │ + for method in self.methods: │ │ │ │ │ + self._wrap(method) │ │ │ │ │ + │ │ │ │ │ + def _wrap(self, method): │ │ │ │ │ + # NB: this function is stored in the instance dict and therefore │ │ │ │ │ + # doesn't function as a descriptor, isn't a method, doesn't get bound, │ │ │ │ │ + # and therefore doesn't receive a self parameter │ │ │ │ │ + setattr(method.__self__, method.__func__.__name__, lambda *args: self.queue.append((method, args))) │ │ │ │ │ + │ │ │ │ │ + def run(self): │ │ │ │ │ + logger.debug('ExecutionQueue: Running %d queued method calls', len(self.queue)) │ │ │ │ │ + for method, args in self.queue: │ │ │ │ │ + method(*args) │ │ │ │ │ + │ │ │ │ │ + for method in self.methods: │ │ │ │ │ + delattr(method.__self__, method.__func__.__name__) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class Endpoint: │ │ │ │ │ + router: 'Router' │ │ │ │ │ + __endpoint_frozen_queue: Optional[ExecutionQueue] = None │ │ │ │ │ + │ │ │ │ │ + def __init__(self, router: 'Router'): │ │ │ │ │ + router.add_endpoint(self) │ │ │ │ │ + self.router = router │ │ │ │ │ + │ │ │ │ │ + def freeze_endpoint(self): │ │ │ │ │ + assert self.__endpoint_frozen_queue is None │ │ │ │ │ + logger.debug('Freezing endpoint %s', self) │ │ │ │ │ + self.__endpoint_frozen_queue = ExecutionQueue({self.do_channel_control, self.do_channel_data, self.do_kill}) │ │ │ │ │ + │ │ │ │ │ + def thaw_endpoint(self): │ │ │ │ │ + assert self.__endpoint_frozen_queue is not None │ │ │ │ │ + logger.debug('Thawing endpoint %s', self) │ │ │ │ │ + self.__endpoint_frozen_queue.run() │ │ │ │ │ + self.__endpoint_frozen_queue = None │ │ │ │ │ + │ │ │ │ │ + # interface for receiving messages │ │ │ │ │ + def do_close(self): │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def do_channel_control(self, channel: str, command: str, message: JsonObject) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def do_channel_data(self, channel: str, data: bytes) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + # interface for sending messages │ │ │ │ │ + def send_channel_data(self, channel: str, data: bytes) -> None: │ │ │ │ │ + self.router.write_channel_data(channel, data) │ │ │ │ │ + │ │ │ │ │ + def send_channel_control( │ │ │ │ │ + self, channel: str, command: str, _msg: 'JsonObject | None', **kwargs: JsonValue │ │ │ │ │ + ) -> None: │ │ │ │ │ + self.router.write_control(_msg, channel=channel, command=command, **kwargs) │ │ │ │ │ + if command == 'close': │ │ │ │ │ + self.router.endpoints[self].remove(channel) │ │ │ │ │ + self.router.drop_channel(channel) │ │ │ │ │ + │ │ │ │ │ + def shutdown_endpoint(self, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> None: │ │ │ │ │ + self.router.shutdown_endpoint(self, _msg, **kwargs) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class RoutingError(CockpitProblem): │ │ │ │ │ + pass │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class RoutingRule: │ │ │ │ │ + router: 'Router' │ │ │ │ │ + │ │ │ │ │ + def __init__(self, router: 'Router'): │ │ │ │ │ + self.router = router │ │ │ │ │ + │ │ │ │ │ + def apply_rule(self, options: JsonObject) -> Optional[Endpoint]: │ │ │ │ │ + """Check if a routing rule applies to a given 'open' message. │ │ │ │ │ + │ │ │ │ │ + This should inspect the options dictionary and do one of the following three things: │ │ │ │ │ + │ │ │ │ │ + - return an Endpoint to handle this channel │ │ │ │ │ + - raise a RoutingError to indicate that the open should be rejected │ │ │ │ │ + - return None to let the next rule run │ │ │ │ │ + """ │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ def shutdown(self): │ │ │ │ │ - self.cancel_prompt() │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - if self.peer is not None: │ │ │ │ │ - self.peer.close() │ │ │ │ │ │ │ │ │ │ - # close() should have disconnected the peer immediately │ │ │ │ │ - assert self.peer is None │ │ │ │ │ +class Router(CockpitProtocolServer): │ │ │ │ │ + routing_rules: List[RoutingRule] │ │ │ │ │ + open_channels: Dict[str, Endpoint] │ │ │ │ │ + endpoints: 'dict[Endpoint, set[str]]' │ │ │ │ │ + no_endpoints: asyncio.Event # set if endpoints dict is empty │ │ │ │ │ + _eof: bool = False │ │ │ │ │ │ │ │ │ │ - # Connect-on-startup functionality │ │ │ │ │ - def init(self, params: JsonObject) -> None: │ │ │ │ │ - name = get_str(params, 'id', 'any') │ │ │ │ │ - responder = AuthorizeResponder(self.router) │ │ │ │ │ - self._init_task = asyncio.create_task(self.go(name, responder)) │ │ │ │ │ - self._init_task.add_done_callback(self._init_done) │ │ │ │ │ + def __init__(self, routing_rules: List[RoutingRule]): │ │ │ │ │ + for rule in routing_rules: │ │ │ │ │ + rule.router = self │ │ │ │ │ + self.routing_rules = routing_rules │ │ │ │ │ + self.open_channels = {} │ │ │ │ │ + self.endpoints = {} │ │ │ │ │ + self.no_endpoints = asyncio.Event() │ │ │ │ │ + self.no_endpoints.set() # at first there are no endpoints │ │ │ │ │ │ │ │ │ │ - def _init_done(self, task: 'asyncio.Task[None]') -> None: │ │ │ │ │ - logger.debug('superuser init done! %s', task.exception()) │ │ │ │ │ - self.router.write_control(command='superuser-init-done') │ │ │ │ │ - del self._init_task │ │ │ │ │ + def check_rules(self, options: JsonObject) -> Endpoint: │ │ │ │ │ + for rule in self.routing_rules: │ │ │ │ │ + logger.debug(' applying rule %s', rule) │ │ │ │ │ + endpoint = rule.apply_rule(options) │ │ │ │ │ + if endpoint is not None: │ │ │ │ │ + logger.debug(' resulting endpoint is %s', endpoint) │ │ │ │ │ + return endpoint │ │ │ │ │ + else: │ │ │ │ │ + logger.debug(' No rules matched') │ │ │ │ │ + raise RoutingError('not-supported') │ │ │ │ │ │ │ │ │ │ - # D-Bus methods │ │ │ │ │ - @bus.Interface.Method(in_types=['s']) │ │ │ │ │ - async def start(self, name: str) -> None: │ │ │ │ │ - await self.go(name, self) │ │ │ │ │ + def drop_channel(self, channel: str) -> None: │ │ │ │ │ + try: │ │ │ │ │ + self.open_channels.pop(channel) │ │ │ │ │ + logger.debug('router dropped channel %s', channel) │ │ │ │ │ + except KeyError: │ │ │ │ │ + logger.error('trying to drop non-existent channel %s from %s', channel, self.open_channels) │ │ │ │ │ │ │ │ │ │ - @bus.Interface.Method() │ │ │ │ │ - def stop(self) -> None: │ │ │ │ │ - self.shutdown() │ │ │ │ │ + def add_endpoint(self, endpoint: Endpoint) -> None: │ │ │ │ │ + self.endpoints[endpoint] = set() │ │ │ │ │ + self.no_endpoints.clear() │ │ │ │ │ │ │ │ │ │ - @bus.Interface.Method(in_types=['s']) │ │ │ │ │ - def answer(self, reply: str) -> None: │ │ │ │ │ - if self.pending_prompt is not None: │ │ │ │ │ - logger.debug('responding to pending prompt') │ │ │ │ │ - self.pending_prompt.set_result(reply) │ │ │ │ │ + def shutdown_endpoint(self, endpoint: Endpoint, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> None: │ │ │ │ │ + channels = self.endpoints.pop(endpoint) │ │ │ │ │ + logger.debug('shutdown_endpoint(%s, %s) will close %s', endpoint, kwargs, channels) │ │ │ │ │ + for channel in channels: │ │ │ │ │ + self.write_control(_msg, command='close', channel=channel, **kwargs) │ │ │ │ │ + self.drop_channel(channel) │ │ │ │ │ + │ │ │ │ │ + if not self.endpoints: │ │ │ │ │ + self.no_endpoints.set() │ │ │ │ │ + │ │ │ │ │ + # were we waiting to exit? │ │ │ │ │ + if self._eof: │ │ │ │ │ + logger.debug(' endpoints remaining: %r', self.endpoints) │ │ │ │ │ + if not self.endpoints and self.transport: │ │ │ │ │ + logger.debug(' close transport') │ │ │ │ │ + self.transport.close() │ │ │ │ │ + │ │ │ │ │ + def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None: │ │ │ │ │ + endpoints = set(self.endpoints) │ │ │ │ │ + logger.debug('do_kill(%s, %s). Considering %d endpoints.', host, group, len(endpoints)) │ │ │ │ │ + for endpoint in endpoints: │ │ │ │ │ + endpoint.do_kill(host, group, message) │ │ │ │ │ + │ │ │ │ │ + def channel_control_received(self, channel: str, command: str, message: JsonObject) -> None: │ │ │ │ │ + # If this is an open message then we need to apply the routing rules to │ │ │ │ │ + # figure out the correct endpoint to connect. If it's not an open │ │ │ │ │ + # message, then we expect the endpoint to already exist. │ │ │ │ │ + if command == 'open': │ │ │ │ │ + if channel in self.open_channels: │ │ │ │ │ + raise CockpitProtocolError('channel is already open') │ │ │ │ │ + │ │ │ │ │ + try: │ │ │ │ │ + logger.debug('Trying to find endpoint for new channel %s payload=%s', channel, message.get('payload')) │ │ │ │ │ + endpoint = self.check_rules(message) │ │ │ │ │ + except RoutingError as exc: │ │ │ │ │ + self.write_control(exc.attrs, command='close', channel=channel) │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + self.open_channels[channel] = endpoint │ │ │ │ │ + self.endpoints[endpoint].add(channel) │ │ │ │ │ else: │ │ │ │ │ - logger.debug('got Answer, but no prompt pending') │ │ │ │ │ + try: │ │ │ │ │ + endpoint = self.open_channels[channel] │ │ │ │ │ + except KeyError: │ │ │ │ │ + # sending to a non-existent channel can happen due to races and is not an error │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + # At this point, we have the endpoint. Route the message. │ │ │ │ │ + endpoint.do_channel_control(channel, command, message) │ │ │ │ │ + │ │ │ │ │ + def channel_data_received(self, channel: str, data: bytes) -> None: │ │ │ │ │ + try: │ │ │ │ │ + endpoint = self.open_channels[channel] │ │ │ │ │ + except KeyError: │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + endpoint.do_channel_data(channel, data) │ │ │ │ │ + │ │ │ │ │ + def eof_received(self) -> bool: │ │ │ │ │ + logger.debug('eof_received(%r)', self) │ │ │ │ │ + │ │ │ │ │ + endpoints = set(self.endpoints) │ │ │ │ │ + for endpoint in endpoints: │ │ │ │ │ + endpoint.do_close() │ │ │ │ │ + │ │ │ │ │ + self._eof = True │ │ │ │ │ + logger.debug(' endpoints remaining: %r', self.endpoints) │ │ │ │ │ + return bool(self.endpoints) │ │ │ │ │ + │ │ │ │ │ + _communication_done: Optional[asyncio.Future] = None │ │ │ │ │ + │ │ │ │ │ + def do_closed(self, exc: Optional[Exception]) -> None: │ │ │ │ │ + # If we didn't send EOF yet, do it now. │ │ │ │ │ + if not self._eof: │ │ │ │ │ + self.eof_received() │ │ │ │ │ + │ │ │ │ │ + if self._communication_done is not None: │ │ │ │ │ + if exc is None: │ │ │ │ │ + self._communication_done.set_result(None) │ │ │ │ │ + else: │ │ │ │ │ + self._communication_done.set_exception(exc) │ │ │ │ │ + │ │ │ │ │ + async def communicate(self) -> None: │ │ │ │ │ + """Wait until communication is complete on the router and all endpoints are done.""" │ │ │ │ │ + assert self._communication_done is None │ │ │ │ │ + self._communication_done = asyncio.get_running_loop().create_future() │ │ │ │ │ + try: │ │ │ │ │ + await self._communication_done │ │ │ │ │ + except (BrokenPipeError, ConnectionResetError): │ │ │ │ │ + pass # these are normal occurrences when closed from the other side │ │ │ │ │ + finally: │ │ │ │ │ + self._communication_done = None │ │ │ │ │ + │ │ │ │ │ + # In an orderly exit, this is already done, but in case it wasn't │ │ │ │ │ + # orderly, we need to make sure the endpoints shut down anyway... │ │ │ │ │ + await self.no_endpoints.wait() │ │ │ │ │ ''', │ │ │ │ │ 'cockpit/beiboot.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program is free software: you can redistribute it and/or modify │ │ │ │ │ # it under the terms of the GNU General Public License as published by │ │ │ │ │ @@ -1339,16 +2154,14 @@ │ │ │ │ │ CPUTemperatureSampler, │ │ │ │ │ DiskSampler, │ │ │ │ │ MemorySampler, │ │ │ │ │ MountSampler, │ │ │ │ │ NetworkSampler, │ │ │ │ │ ] │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_version.py': br'''__version__ = '311' │ │ │ │ │ -''', │ │ │ │ │ 'cockpit/bridge.py': r'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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 │ │ │ │ │ @@ -1657,2100 +2470,14 @@ │ │ │ │ │ # asyncio.run() shim for Python 3.6 support │ │ │ │ │ run_async(run(args), debug=args.debug) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ if __name__ == '__main__': │ │ │ │ │ main() │ │ │ │ │ '''.encode('utf-8'), │ │ │ │ │ - 'cockpit/channel.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import asyncio │ │ │ │ │ -import json │ │ │ │ │ -import logging │ │ │ │ │ -from typing import BinaryIO, ClassVar, Dict, Generator, List, Optional, Sequence, Set, Tuple, Type │ │ │ │ │ - │ │ │ │ │ -from .jsonutil import JsonError, JsonObject, JsonValue, create_object, get_bool, get_str │ │ │ │ │ -from .protocol import CockpitProblem │ │ │ │ │ -from .router import Endpoint, Router, RoutingRule │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class ChannelRoutingRule(RoutingRule): │ │ │ │ │ - table: Dict[str, List[Type['Channel']]] │ │ │ │ │ - │ │ │ │ │ - def __init__(self, router: Router, channel_types: List[Type['Channel']]): │ │ │ │ │ - super().__init__(router) │ │ │ │ │ - self.table = {} │ │ │ │ │ - │ │ │ │ │ - # Sort the channels into buckets by payload type │ │ │ │ │ - for cls in channel_types: │ │ │ │ │ - entry = self.table.setdefault(cls.payload, []) │ │ │ │ │ - entry.append(cls) │ │ │ │ │ - │ │ │ │ │ - # Within each bucket, sort the channels so those with more │ │ │ │ │ - # restrictions are considered first. │ │ │ │ │ - for entry in self.table.values(): │ │ │ │ │ - entry.sort(key=lambda cls: len(cls.restrictions), reverse=True) │ │ │ │ │ - │ │ │ │ │ - def check_restrictions(self, restrictions: Sequence[Tuple[str, object]], options: JsonObject) -> bool: │ │ │ │ │ - for key, expected_value in restrictions: │ │ │ │ │ - our_value = options.get(key) │ │ │ │ │ - │ │ │ │ │ - # If the match rule specifies that a value must be present and │ │ │ │ │ - # we don't have it, then fail. │ │ │ │ │ - if our_value is None: │ │ │ │ │ - return False │ │ │ │ │ - │ │ │ │ │ - # If the match rule specified a specific expected value, and │ │ │ │ │ - # our value doesn't match it, then fail. │ │ │ │ │ - if expected_value is not None and our_value != expected_value: │ │ │ │ │ - return False │ │ │ │ │ - │ │ │ │ │ - # Everything checked out │ │ │ │ │ - return True │ │ │ │ │ - │ │ │ │ │ - def apply_rule(self, options: JsonObject) -> Optional['Channel']: │ │ │ │ │ - assert self.router is not None │ │ │ │ │ - │ │ │ │ │ - payload = options.get('payload') │ │ │ │ │ - if not isinstance(payload, str): │ │ │ │ │ - return None │ │ │ │ │ - │ │ │ │ │ - for cls in self.table.get(payload, []): │ │ │ │ │ - if self.check_restrictions(cls.restrictions, options): │ │ │ │ │ - return cls(self.router) │ │ │ │ │ - else: │ │ │ │ │ - return None │ │ │ │ │ - │ │ │ │ │ - def shutdown(self): │ │ │ │ │ - pass # we don't hold any state │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class ChannelError(CockpitProblem): │ │ │ │ │ - pass │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class Channel(Endpoint): │ │ │ │ │ - # Values borrowed from C implementation │ │ │ │ │ - BLOCK_SIZE = 16 * 1024 │ │ │ │ │ - SEND_WINDOW = 2 * 1024 * 1024 │ │ │ │ │ - │ │ │ │ │ - # Flow control book-keeping │ │ │ │ │ - _send_pings: bool = False │ │ │ │ │ - _out_sequence: int = 0 │ │ │ │ │ - _out_window: int = SEND_WINDOW │ │ │ │ │ - │ │ │ │ │ - # Task management │ │ │ │ │ - _tasks: Set[asyncio.Task] │ │ │ │ │ - _close_args: Optional[JsonObject] = None │ │ │ │ │ - │ │ │ │ │ - # Must be filled in by the channel implementation │ │ │ │ │ - payload: ClassVar[str] │ │ │ │ │ - restrictions: ClassVar[Sequence[Tuple[str, object]]] = () │ │ │ │ │ - │ │ │ │ │ - # These get filled in from .do_open() │ │ │ │ │ - channel = '' │ │ │ │ │ - group = '' │ │ │ │ │ - │ │ │ │ │ - # input │ │ │ │ │ - def do_control(self, command, message): │ │ │ │ │ - # Break the various different kinds of control messages out into the │ │ │ │ │ - # things that our subclass may be interested in handling. We drop the │ │ │ │ │ - # 'message' field for handlers that don't need it. │ │ │ │ │ - if command == 'open': │ │ │ │ │ - self._tasks = set() │ │ │ │ │ - self.channel = message['channel'] │ │ │ │ │ - if get_bool(message, 'flow-control', default=False): │ │ │ │ │ - self._send_pings = True │ │ │ │ │ - self.group = get_str(message, 'group', 'default') │ │ │ │ │ - self.freeze_endpoint() │ │ │ │ │ - self.do_open(message) │ │ │ │ │ - elif command == 'ready': │ │ │ │ │ - self.do_ready() │ │ │ │ │ - elif command == 'done': │ │ │ │ │ - self.do_done() │ │ │ │ │ - elif command == 'close': │ │ │ │ │ - self.do_close() │ │ │ │ │ - elif command == 'ping': │ │ │ │ │ - self.do_ping(message) │ │ │ │ │ - elif command == 'pong': │ │ │ │ │ - self.do_pong(message) │ │ │ │ │ - elif command == 'options': │ │ │ │ │ - self.do_options(message) │ │ │ │ │ - │ │ │ │ │ - def do_channel_control(self, channel: str, command: str, message: JsonObject) -> None: │ │ │ │ │ - # Already closing? Ignore. │ │ │ │ │ - if self._close_args is not None: │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - # Catch errors and turn them into close messages │ │ │ │ │ - try: │ │ │ │ │ - try: │ │ │ │ │ - self.do_control(command, message) │ │ │ │ │ - except JsonError as exc: │ │ │ │ │ - raise ChannelError('protocol-error', message=str(exc)) from exc │ │ │ │ │ - except ChannelError as exc: │ │ │ │ │ - self.close(exc.attrs) │ │ │ │ │ - │ │ │ │ │ - def do_kill(self, host: 'str | None', group: 'str | None', _message: JsonObject) -> None: │ │ │ │ │ - # Already closing? Ignore. │ │ │ │ │ - if self._close_args is not None: │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - if host is not None: │ │ │ │ │ - return │ │ │ │ │ - if group is not None and self.group != group: │ │ │ │ │ - return │ │ │ │ │ - self.do_close() │ │ │ │ │ - │ │ │ │ │ - # At least this one really ought to be implemented... │ │ │ │ │ - def do_open(self, options: JsonObject) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - # ... but many subclasses may reasonably want to ignore some of these. │ │ │ │ │ - def do_ready(self) -> None: │ │ │ │ │ - pass │ │ │ │ │ - │ │ │ │ │ - def do_done(self) -> None: │ │ │ │ │ - pass │ │ │ │ │ - │ │ │ │ │ - def do_close(self) -> None: │ │ │ │ │ - self.close() │ │ │ │ │ - │ │ │ │ │ - def do_options(self, message: JsonObject) -> None: │ │ │ │ │ - raise ChannelError('not-supported', message='This channel does not implement "options"') │ │ │ │ │ - │ │ │ │ │ - # 'reasonable' default, overridden in other channels for receive-side flow control │ │ │ │ │ - def do_ping(self, message: JsonObject) -> None: │ │ │ │ │ - self.send_pong(message) │ │ │ │ │ - │ │ │ │ │ - def do_channel_data(self, channel: str, data: bytes) -> None: │ │ │ │ │ - # Already closing? Ignore. │ │ │ │ │ - if self._close_args is not None: │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - # Catch errors and turn them into close messages │ │ │ │ │ - try: │ │ │ │ │ - self.do_data(data) │ │ │ │ │ - except ChannelError as exc: │ │ │ │ │ - self.close(exc.attrs) │ │ │ │ │ - │ │ │ │ │ - def do_data(self, _data: bytes) -> None: │ │ │ │ │ - # By default, channels can't receive data. │ │ │ │ │ - self.close() │ │ │ │ │ - │ │ │ │ │ - # output │ │ │ │ │ - def ready(self, **kwargs: JsonValue) -> None: │ │ │ │ │ - self.thaw_endpoint() │ │ │ │ │ - self.send_control(command='ready', **kwargs) │ │ │ │ │ - │ │ │ │ │ - def done(self) -> None: │ │ │ │ │ - self.send_control(command='done') │ │ │ │ │ - │ │ │ │ │ - # tasks and close management │ │ │ │ │ - def is_closing(self) -> bool: │ │ │ │ │ - return self._close_args is not None │ │ │ │ │ - │ │ │ │ │ - def _close_now(self) -> None: │ │ │ │ │ - self.shutdown_endpoint(self._close_args) │ │ │ │ │ - │ │ │ │ │ - def _task_done(self, task): │ │ │ │ │ - # Strictly speaking, we should read the result and check for exceptions but: │ │ │ │ │ - # - exceptions bubbling out of the task are programming errors │ │ │ │ │ - # - the only thing we'd do with it anyway, is to show it │ │ │ │ │ - # - Python already does that with its "Task exception was never retrieved" messages │ │ │ │ │ - self._tasks.remove(task) │ │ │ │ │ - if self._close_args is not None and not self._tasks: │ │ │ │ │ - self._close_now() │ │ │ │ │ - │ │ │ │ │ - def create_task(self, coroutine, name=None): │ │ │ │ │ - """Create a task associated with the channel. │ │ │ │ │ - │ │ │ │ │ - All tasks must exit before the channel can close. You may not create │ │ │ │ │ - new tasks after calling .close(). │ │ │ │ │ - """ │ │ │ │ │ - assert self._close_args is None │ │ │ │ │ - task = asyncio.create_task(coroutine) │ │ │ │ │ - self._tasks.add(task) │ │ │ │ │ - task.add_done_callback(self._task_done) │ │ │ │ │ - return task │ │ │ │ │ - │ │ │ │ │ - def close(self, close_args: 'JsonObject | None' = None) -> None: │ │ │ │ │ - """Requests the channel to be closed. │ │ │ │ │ - │ │ │ │ │ - After you call this method, you won't get anymore `.do_*()` calls. │ │ │ │ │ - │ │ │ │ │ - This will wait for any running tasks to complete before sending the │ │ │ │ │ - close message. │ │ │ │ │ - """ │ │ │ │ │ - if self._close_args is not None: │ │ │ │ │ - # close already requested │ │ │ │ │ - return │ │ │ │ │ - self._close_args = close_args or {} │ │ │ │ │ - if not self._tasks: │ │ │ │ │ - self._close_now() │ │ │ │ │ - │ │ │ │ │ - def send_data(self, data: bytes) -> bool: │ │ │ │ │ - """Send data and handle book-keeping for flow control. │ │ │ │ │ - │ │ │ │ │ - The flow control is "advisory". The data is sent immediately, even if │ │ │ │ │ - it's larger than the window. In general you should try to send packets │ │ │ │ │ - which are approximately Channel.BLOCK_SIZE in size. │ │ │ │ │ - │ │ │ │ │ - Returns True if there is still room in the window, or False if you │ │ │ │ │ - should stop writing for now. In that case, `.do_resume_send()` will be │ │ │ │ │ - called later when there is more room. │ │ │ │ │ - """ │ │ │ │ │ - self.send_channel_data(self.channel, data) │ │ │ │ │ - │ │ │ │ │ - if self._send_pings: │ │ │ │ │ - out_sequence = self._out_sequence + len(data) │ │ │ │ │ - if self._out_sequence // Channel.BLOCK_SIZE != out_sequence // Channel.BLOCK_SIZE: │ │ │ │ │ - self.send_control(command='ping', sequence=out_sequence) │ │ │ │ │ - self._out_sequence = out_sequence │ │ │ │ │ - │ │ │ │ │ - return self._out_sequence < self._out_window │ │ │ │ │ - │ │ │ │ │ - def do_pong(self, message): │ │ │ │ │ - if not self._send_pings: # huh? │ │ │ │ │ - logger.warning("Got wild pong on channel %s", self.channel) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - self._out_window = message['sequence'] + Channel.SEND_WINDOW │ │ │ │ │ - if self._out_sequence < self._out_window: │ │ │ │ │ - self.do_resume_send() │ │ │ │ │ - │ │ │ │ │ - def do_resume_send(self) -> None: │ │ │ │ │ - """Called to indicate that the channel may start sending again.""" │ │ │ │ │ - # change to `raise NotImplementedError` after everyone implements it │ │ │ │ │ - │ │ │ │ │ - json_encoder: ClassVar[json.JSONEncoder] = json.JSONEncoder(indent=2) │ │ │ │ │ - │ │ │ │ │ - def send_json(self, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> bool: │ │ │ │ │ - pretty = self.json_encoder.encode(create_object(_msg, kwargs)) + '\n' │ │ │ │ │ - return self.send_data(pretty.encode()) │ │ │ │ │ - │ │ │ │ │ - def send_control(self, command: str, **kwargs: JsonValue) -> None: │ │ │ │ │ - self.send_channel_control(self.channel, command, None, **kwargs) │ │ │ │ │ - │ │ │ │ │ - def send_pong(self, message: JsonObject) -> None: │ │ │ │ │ - self.send_channel_control(self.channel, 'pong', message) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class ProtocolChannel(Channel, asyncio.Protocol): │ │ │ │ │ - """A channel subclass that implements the asyncio Protocol interface. │ │ │ │ │ - │ │ │ │ │ - In effect, data sent to this channel will be written to the connected │ │ │ │ │ - transport, and vice-versa. Flow control is supported. │ │ │ │ │ - │ │ │ │ │ - The default implementation of the .do_open() method calls the │ │ │ │ │ - .create_transport() abstract method. This method should return a transport │ │ │ │ │ - which will be used for communication on the channel. │ │ │ │ │ - │ │ │ │ │ - Otherwise, if the subclass implements .do_open() itself, it is responsible │ │ │ │ │ - for setting up the connection and ensuring that .connection_made() is called. │ │ │ │ │ - """ │ │ │ │ │ - _transport: Optional[asyncio.Transport] │ │ │ │ │ - _loop: Optional[asyncio.AbstractEventLoop] │ │ │ │ │ - _send_pongs: bool = True │ │ │ │ │ - _last_ping: Optional[JsonObject] = None │ │ │ │ │ - _create_transport_task = None │ │ │ │ │ - │ │ │ │ │ - # read-side EOF handling │ │ │ │ │ - _close_on_eof: bool = False │ │ │ │ │ - _eof: bool = False │ │ │ │ │ - │ │ │ │ │ - async def create_transport(self, loop: asyncio.AbstractEventLoop, options: JsonObject) -> asyncio.Transport: │ │ │ │ │ - """Creates the transport for this channel, according to options. │ │ │ │ │ - │ │ │ │ │ - The event loop for the transport is passed to the function. The │ │ │ │ │ - protocol for the transport is the channel object, itself (self). │ │ │ │ │ - │ │ │ │ │ - This needs to be implemented by the subclass. │ │ │ │ │ - """ │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def do_open(self, options: JsonObject) -> None: │ │ │ │ │ - loop = asyncio.get_running_loop() │ │ │ │ │ - self._create_transport_task = asyncio.create_task(self.create_transport(loop, options)) │ │ │ │ │ - self._create_transport_task.add_done_callback(self.create_transport_done) │ │ │ │ │ - │ │ │ │ │ - def create_transport_done(self, task: 'asyncio.Task[asyncio.Transport]') -> None: │ │ │ │ │ - assert task is self._create_transport_task │ │ │ │ │ - self._create_transport_task = None │ │ │ │ │ - try: │ │ │ │ │ - transport = task.result() │ │ │ │ │ - except ChannelError as exc: │ │ │ │ │ - self.close(exc.attrs) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - self.connection_made(transport) │ │ │ │ │ - self.ready() │ │ │ │ │ - │ │ │ │ │ - def connection_made(self, transport: asyncio.BaseTransport) -> None: │ │ │ │ │ - assert isinstance(transport, asyncio.Transport) │ │ │ │ │ - self._transport = transport │ │ │ │ │ - │ │ │ │ │ - def _get_close_args(self) -> JsonObject: │ │ │ │ │ - return {} │ │ │ │ │ - │ │ │ │ │ - def connection_lost(self, exc: Optional[Exception]) -> None: │ │ │ │ │ - self.close(self._get_close_args()) │ │ │ │ │ - │ │ │ │ │ - def do_data(self, data: bytes) -> None: │ │ │ │ │ - assert self._transport is not None │ │ │ │ │ - self._transport.write(data) │ │ │ │ │ - │ │ │ │ │ - def do_done(self) -> None: │ │ │ │ │ - assert self._transport is not None │ │ │ │ │ - if self._transport.can_write_eof(): │ │ │ │ │ - self._transport.write_eof() │ │ │ │ │ - │ │ │ │ │ - def do_close(self) -> None: │ │ │ │ │ - if self._transport is not None: │ │ │ │ │ - self._transport.close() │ │ │ │ │ - │ │ │ │ │ - def data_received(self, data: bytes) -> None: │ │ │ │ │ - assert self._transport is not None │ │ │ │ │ - if not self.send_data(data): │ │ │ │ │ - self._transport.pause_reading() │ │ │ │ │ - │ │ │ │ │ - def do_resume_send(self) -> None: │ │ │ │ │ - assert self._transport is not None │ │ │ │ │ - self._transport.resume_reading() │ │ │ │ │ - │ │ │ │ │ - def close_on_eof(self) -> None: │ │ │ │ │ - """Mark the channel to be closed on EOF. │ │ │ │ │ - │ │ │ │ │ - Normally, ProtocolChannel tries to keep the channel half-open after │ │ │ │ │ - receiving EOF from the transport. This instructs that the channel │ │ │ │ │ - should be closed on EOF. │ │ │ │ │ - │ │ │ │ │ - If EOF was already received, then calling this function will close the │ │ │ │ │ - channel immediately. │ │ │ │ │ - │ │ │ │ │ - If you don't call this function, you are responsible for closing the │ │ │ │ │ - channel yourself. │ │ │ │ │ - """ │ │ │ │ │ - self._close_on_eof = True │ │ │ │ │ - if self._eof: │ │ │ │ │ - assert self._transport is not None │ │ │ │ │ - self._transport.close() │ │ │ │ │ - │ │ │ │ │ - def eof_received(self) -> bool: │ │ │ │ │ - self._eof = True │ │ │ │ │ - self.done() │ │ │ │ │ - return not self._close_on_eof │ │ │ │ │ - │ │ │ │ │ - # Channel receive-side flow control │ │ │ │ │ - def do_ping(self, message): │ │ │ │ │ - if self._send_pongs: │ │ │ │ │ - self.send_pong(message) │ │ │ │ │ - else: │ │ │ │ │ - # we'll have to pong later │ │ │ │ │ - self._last_ping = message │ │ │ │ │ - │ │ │ │ │ - def pause_writing(self) -> None: │ │ │ │ │ - # We can't actually stop writing, but we can stop replying to pings │ │ │ │ │ - self._send_pongs = False │ │ │ │ │ - │ │ │ │ │ - def resume_writing(self) -> None: │ │ │ │ │ - self._send_pongs = True │ │ │ │ │ - if self._last_ping is not None: │ │ │ │ │ - self.send_pong(self._last_ping) │ │ │ │ │ - self._last_ping = None │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class AsyncChannel(Channel): │ │ │ │ │ - """A subclass for async/await-style implementation of channels, with flow control │ │ │ │ │ - │ │ │ │ │ - This subclass provides asynchronous `read()` and `write()` calls for │ │ │ │ │ - subclasses, with familiar semantics. `write()` doesn't buffer, so the │ │ │ │ │ - `done()` method on the base channel class can be used in a way similar to │ │ │ │ │ - `shutdown()`. A high-level `sendfile()` method is available to send the │ │ │ │ │ - entire contents of a binary-mode file-like object. │ │ │ │ │ - │ │ │ │ │ - The subclass must provide an async `run()` function, which will be spawned │ │ │ │ │ - as a task. │ │ │ │ │ - │ │ │ │ │ - On the receiving side, the channel will respond to flow control pings to │ │ │ │ │ - indicate that it has received the data, but only after it has been consumed │ │ │ │ │ - by `read()`. │ │ │ │ │ - │ │ │ │ │ - On the sending side, write() will block if the channel backs up. │ │ │ │ │ - """ │ │ │ │ │ - │ │ │ │ │ - # Receive-side flow control: intermix pings and data in the queue and reply │ │ │ │ │ - # to pings as we dequeue them. This is a buffer: since we need to handle │ │ │ │ │ - # do_data() without blocking, we have no choice. │ │ │ │ │ - receive_queue = None │ │ │ │ │ - │ │ │ │ │ - # Send-side flow control │ │ │ │ │ - write_waiter = None │ │ │ │ │ - │ │ │ │ │ - async def run(self, options): │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - async def run_wrapper(self, options): │ │ │ │ │ - try: │ │ │ │ │ - await self.run(options) │ │ │ │ │ - self.close() │ │ │ │ │ - except ChannelError as exc: │ │ │ │ │ - self.close(exc.attrs) │ │ │ │ │ - │ │ │ │ │ - async def read(self): │ │ │ │ │ - while True: │ │ │ │ │ - item = await self.receive_queue.get() │ │ │ │ │ - if isinstance(item, bytes): │ │ │ │ │ - return item │ │ │ │ │ - self.send_pong(item) │ │ │ │ │ - │ │ │ │ │ - async def write(self, data): │ │ │ │ │ - if not self.send_data(data): │ │ │ │ │ - self.write_waiter = asyncio.get_running_loop().create_future() │ │ │ │ │ - await self.write_waiter │ │ │ │ │ - │ │ │ │ │ - async def sendfile(self, stream: BinaryIO) -> None: │ │ │ │ │ - loop = asyncio.get_running_loop() │ │ │ │ │ - with stream: │ │ │ │ │ - while True: │ │ │ │ │ - data = await loop.run_in_executor(None, stream.read, Channel.BLOCK_SIZE) │ │ │ │ │ - if data == b'': │ │ │ │ │ - break │ │ │ │ │ - await self.write(data) │ │ │ │ │ - │ │ │ │ │ - self.done() │ │ │ │ │ - │ │ │ │ │ - def do_resume_send(self) -> None: │ │ │ │ │ - if self.write_waiter is not None: │ │ │ │ │ - self.write_waiter.set_result(None) │ │ │ │ │ - self.write_waiter = None │ │ │ │ │ - │ │ │ │ │ - def do_open(self, options): │ │ │ │ │ - self.receive_queue = asyncio.Queue() │ │ │ │ │ - self.create_task(self.run_wrapper(options), name=f'{self.__class__.__name__}.run_wrapper({options})') │ │ │ │ │ - │ │ │ │ │ - def do_done(self): │ │ │ │ │ - self.receive_queue.put_nowait(b'') │ │ │ │ │ - │ │ │ │ │ - def do_close(self): │ │ │ │ │ - # we might have already sent EOF for done, but two EOFs won't hurt anyone │ │ │ │ │ - self.receive_queue.put_nowait(b'') │ │ │ │ │ - │ │ │ │ │ - def do_ping(self, message): │ │ │ │ │ - self.receive_queue.put_nowait(message) │ │ │ │ │ - │ │ │ │ │ - def do_data(self, data): │ │ │ │ │ - if not isinstance(data, bytes): │ │ │ │ │ - # this will persist past this callback, so make sure we take our │ │ │ │ │ - # own copy, in case this was a memoryview into a bytearray. │ │ │ │ │ - data = bytes(data) │ │ │ │ │ - │ │ │ │ │ - self.receive_queue.put_nowait(data) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class GeneratorChannel(Channel): │ │ │ │ │ - """A trivial Channel subclass for sending data from a generator with flow control. │ │ │ │ │ - │ │ │ │ │ - Calls the .do_yield_data() generator with the options from the open message │ │ │ │ │ - and sends the data which it yields. If the generator returns a value it │ │ │ │ │ - will be used for the close message. │ │ │ │ │ - """ │ │ │ │ │ - DataGenerator = Generator[bytes, None, Optional[JsonObject]] │ │ │ │ │ - __generator: DataGenerator │ │ │ │ │ - │ │ │ │ │ - def do_yield_data(self, options: JsonObject) -> 'DataGenerator': │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def do_open(self, options: JsonObject) -> None: │ │ │ │ │ - self.__generator = self.do_yield_data(options) │ │ │ │ │ - self.do_resume_send() │ │ │ │ │ - │ │ │ │ │ - def do_resume_send(self) -> None: │ │ │ │ │ - try: │ │ │ │ │ - while self.send_data(next(self.__generator)): │ │ │ │ │ - pass │ │ │ │ │ - except StopIteration as stop: │ │ │ │ │ - self.done() │ │ │ │ │ - self.close(stop.value) │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/polkit.py': r'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import asyncio │ │ │ │ │ -import locale │ │ │ │ │ -import logging │ │ │ │ │ -import os │ │ │ │ │ -import pwd │ │ │ │ │ -from typing import Dict, List, Sequence, Tuple │ │ │ │ │ - │ │ │ │ │ -from cockpit._vendor.ferny import AskpassHandler │ │ │ │ │ -from cockpit._vendor.systemd_ctypes import Variant, bus │ │ │ │ │ - │ │ │ │ │ -# that path is valid on at least Debian, Fedora/RHEL, and Arch │ │ │ │ │ -HELPER_PATH = '/usr/lib/polkit-1/polkit-agent-helper-1' │ │ │ │ │ - │ │ │ │ │ -AGENT_DBUS_PATH = '/PolkitAgent' │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ -Identity = Tuple[str, Dict[str, Variant]] │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -# https://www.freedesktop.org/software/polkit/docs/latest/eggdbus-interface-org.freedesktop.PolicyKit1.AuthenticationAgent.html │ │ │ │ │ - │ │ │ │ │ -# Note that we don't implement the CancelAuthentication() API. pkexec gets called in a way that has no opportunity to │ │ │ │ │ -# cancel an ongoing authentication from the pkexec side. On the UI side cancellation is implemented via the standard │ │ │ │ │ -# asyncio process mechanism. If we ever need CancelAuthentication(), we could keep a cookie → get_current_task() │ │ │ │ │ -# mapping, but that method is not available for Python 3.6 yet. │ │ │ │ │ - │ │ │ │ │ -class org_freedesktop_PolicyKit1_AuthenticationAgent(bus.Object): │ │ │ │ │ - def __init__(self, responder: AskpassHandler): │ │ │ │ │ - super().__init__() │ │ │ │ │ - self.responder = responder │ │ │ │ │ - │ │ │ │ │ - # confusingly named: this actually does the whole authentication dialog, see docs │ │ │ │ │ - @bus.Interface.Method('', ['s', 's', 's', 'a{ss}', 's', 'a(sa{sv})']) │ │ │ │ │ - async def begin_authentication(self, action_id: str, message: str, icon_name: str, │ │ │ │ │ - details: Dict[str, str], cookie: str, identities: Sequence[Identity]) -> None: │ │ │ │ │ - logger.debug('BeginAuthentication: action %s, message "%s", icon %s, details %s, cookie %s, identities %r', │ │ │ │ │ - action_id, message, icon_name, details, cookie, identities) │ │ │ │ │ - # only support authentication as ourselves, as we don't yet have the │ │ │ │ │ - # protocol plumbing and UI to select an admin user │ │ │ │ │ - my_uid = os.geteuid() │ │ │ │ │ - for (auth_type, subject) in identities: │ │ │ │ │ - if auth_type == 'unix-user' and 'uid' in subject and subject['uid'].value == my_uid: │ │ │ │ │ - logger.debug('Authentication subject %s matches our uid %d', subject, my_uid) │ │ │ │ │ - break │ │ │ │ │ - else: │ │ │ │ │ - logger.warning('Not supporting authentication as any of %s', identities) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - user_name = pwd.getpwuid(my_uid).pw_name │ │ │ │ │ - process = await asyncio.create_subprocess_exec(HELPER_PATH, user_name, cookie, │ │ │ │ │ - stdin=asyncio.subprocess.PIPE, │ │ │ │ │ - stdout=asyncio.subprocess.PIPE) │ │ │ │ │ - try: │ │ │ │ │ - await self._communicate(process) │ │ │ │ │ - except asyncio.CancelledError: │ │ │ │ │ - logger.debug('Cancelled authentication') │ │ │ │ │ - process.terminate() │ │ │ │ │ - finally: │ │ │ │ │ - res = await process.wait() │ │ │ │ │ - logger.debug('helper exited with code %i', res) │ │ │ │ │ - │ │ │ │ │ - async def _communicate(self, process: asyncio.subprocess.Process) -> None: │ │ │ │ │ - assert process.stdin │ │ │ │ │ - assert process.stdout │ │ │ │ │ - │ │ │ │ │ - messages: List[str] = [] │ │ │ │ │ - │ │ │ │ │ - async for line in process.stdout: │ │ │ │ │ - logger.debug('Read line from helper: %s', line) │ │ │ │ │ - command, _, value = line.strip().decode().partition(' ') │ │ │ │ │ - │ │ │ │ │ - # usually: PAM_PROMPT_ECHO_OFF Password: \n │ │ │ │ │ - if command.startswith('PAM_PROMPT'): │ │ │ │ │ - # Don't pass this to the UI if it's "Password" (the usual case), │ │ │ │ │ - # so that superuser.py uses the translated default │ │ │ │ │ - if value.startswith('Password'): │ │ │ │ │ - value = '' │ │ │ │ │ - │ │ │ │ │ - # flush out accumulated info/error messages │ │ │ │ │ - passwd = await self.responder.do_askpass('\n'.join(messages), value, '') │ │ │ │ │ - messages.clear() │ │ │ │ │ - if passwd is None: │ │ │ │ │ - logger.debug('got PAM_PROMPT %s, but do_askpass returned None', value) │ │ │ │ │ - raise asyncio.CancelledError('no password given') │ │ │ │ │ - logger.debug('got PAM_PROMPT %s, do_askpass returned a password', value) │ │ │ │ │ - process.stdin.write(passwd.encode()) │ │ │ │ │ - process.stdin.write(b'\n') │ │ │ │ │ - del passwd # don't keep this around longer than necessary │ │ │ │ │ - await process.stdin.drain() │ │ │ │ │ - logger.debug('got PAM_PROMPT, wrote password to helper') │ │ │ │ │ - elif command in ('PAM_TEXT_INFO', 'PAM_ERROR'): │ │ │ │ │ - messages.append(value) │ │ │ │ │ - elif command == 'SUCCESS': │ │ │ │ │ - logger.debug('Authentication succeeded') │ │ │ │ │ - break │ │ │ │ │ - elif command == 'FAILURE': │ │ │ │ │ - logger.warning('Authentication failed') │ │ │ │ │ - break │ │ │ │ │ - else: │ │ │ │ │ - logger.warning('Unknown line from helper, aborting: %s', line) │ │ │ │ │ - process.terminate() │ │ │ │ │ - break │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class PolkitAgent: │ │ │ │ │ - """Register polkit agent when required │ │ │ │ │ - │ │ │ │ │ - Use this as a context manager to ensure that the agent gets unregistered again. │ │ │ │ │ - """ │ │ │ │ │ - def __init__(self, responder: AskpassHandler): │ │ │ │ │ - self.responder = responder │ │ │ │ │ - self.agent_slot = None │ │ │ │ │ - │ │ │ │ │ - async def __aenter__(self): │ │ │ │ │ - try: │ │ │ │ │ - self.system_bus = bus.Bus.default_system() │ │ │ │ │ - except OSError as e: │ │ │ │ │ - logger.warning('cannot connect to system bus, not registering polkit agent: %s', e) │ │ │ │ │ - return self │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - # may refine that with a D-Bus call to logind │ │ │ │ │ - self.subject = ('unix-session', {'session-id': Variant(os.environ['XDG_SESSION_ID'], 's')}) │ │ │ │ │ - except KeyError: │ │ │ │ │ - logger.debug('XDG_SESSION_ID not set, not registering polkit agent') │ │ │ │ │ - return self │ │ │ │ │ - │ │ │ │ │ - agent_object = org_freedesktop_PolicyKit1_AuthenticationAgent(self.responder) │ │ │ │ │ - self.agent_slot = self.system_bus.add_object(AGENT_DBUS_PATH, agent_object) │ │ │ │ │ - │ │ │ │ │ - # register agent │ │ │ │ │ - locale_name = locale.setlocale(locale.LC_MESSAGES, None) │ │ │ │ │ - await self.system_bus.call_method_async( │ │ │ │ │ - 'org.freedesktop.PolicyKit1', │ │ │ │ │ - '/org/freedesktop/PolicyKit1/Authority', │ │ │ │ │ - 'org.freedesktop.PolicyKit1.Authority', │ │ │ │ │ - 'RegisterAuthenticationAgent', │ │ │ │ │ - '(sa{sv})ss', │ │ │ │ │ - self.subject, locale_name, AGENT_DBUS_PATH) │ │ │ │ │ - logger.debug('Registered agent for %r and locale %s', self.subject, locale_name) │ │ │ │ │ - return self │ │ │ │ │ - │ │ │ │ │ - async def __aexit__(self, _exc_type, _exc_value, _traceback): │ │ │ │ │ - if self.agent_slot: │ │ │ │ │ - await self.system_bus.call_method_async( │ │ │ │ │ - 'org.freedesktop.PolicyKit1', │ │ │ │ │ - '/org/freedesktop/PolicyKit1/Authority', │ │ │ │ │ - 'org.freedesktop.PolicyKit1.Authority', │ │ │ │ │ - 'UnregisterAuthenticationAgent', │ │ │ │ │ - '(sa{sv})s', │ │ │ │ │ - self.subject, AGENT_DBUS_PATH) │ │ │ │ │ - self.agent_slot.cancel() │ │ │ │ │ - logger.debug('Unregistered agent for %r', self.subject) │ │ │ │ │ -'''.encode('utf-8'), │ │ │ │ │ - 'cockpit/config.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import configparser │ │ │ │ │ -import logging │ │ │ │ │ -import os │ │ │ │ │ -from pathlib import Path │ │ │ │ │ - │ │ │ │ │ -from cockpit._vendor.systemd_ctypes import bus │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ -XDG_CONFIG_HOME = Path(os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config')) │ │ │ │ │ -DOT_CONFIG_COCKPIT = XDG_CONFIG_HOME / 'cockpit' │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def lookup_config(filename: str) -> Path: │ │ │ │ │ - config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc').split(':') │ │ │ │ │ - fallback = None │ │ │ │ │ - for config_dir in config_dirs: │ │ │ │ │ - config_path = Path(config_dir, 'cockpit', filename) │ │ │ │ │ - if not fallback: │ │ │ │ │ - fallback = config_path │ │ │ │ │ - if config_path.exists(): │ │ │ │ │ - logger.debug('lookup_config(%s): found %s', filename, config_path) │ │ │ │ │ - return config_path │ │ │ │ │ - │ │ │ │ │ - # default to the first entry in XDG_CONFIG_DIRS; that's not according to the spec, │ │ │ │ │ - # but what Cockpit has done for years │ │ │ │ │ - logger.debug('lookup_config(%s): defaulting to %s', filename, fallback) │ │ │ │ │ - assert fallback # mypy; config_dirs always has at least one string │ │ │ │ │ - return fallback │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class Config(bus.Object, interface='cockpit.Config'): │ │ │ │ │ - def __init__(self): │ │ │ │ │ - self.reload() │ │ │ │ │ - │ │ │ │ │ - @bus.Interface.Method(out_types='s', in_types='ss') │ │ │ │ │ - def get_string(self, section, key): │ │ │ │ │ - try: │ │ │ │ │ - return self.config[section][key] │ │ │ │ │ - except KeyError as exc: │ │ │ │ │ - raise bus.BusError('cockpit.Config.KeyError', f'key {key} in section {section} does not exist') from exc │ │ │ │ │ - │ │ │ │ │ - @bus.Interface.Method(out_types='u', in_types='ssuuu') │ │ │ │ │ - def get_u_int(self, section, key, default, maximum, minimum): │ │ │ │ │ - try: │ │ │ │ │ - value = self.config[section][key] │ │ │ │ │ - except KeyError: │ │ │ │ │ - return default │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - int_val = int(value) │ │ │ │ │ - except ValueError: │ │ │ │ │ - logger.warning('cockpit.conf: [%s] %s is not an integer', section, key) │ │ │ │ │ - return default │ │ │ │ │ - │ │ │ │ │ - return min(max(int_val, minimum), maximum) │ │ │ │ │ - │ │ │ │ │ - @bus.Interface.Method() │ │ │ │ │ - def reload(self): │ │ │ │ │ - self.config = configparser.ConfigParser(interpolation=None) │ │ │ │ │ - cockpit_conf = lookup_config('cockpit.conf') │ │ │ │ │ - logger.debug("cockpit.Config: loading %s", cockpit_conf) │ │ │ │ │ - # this may not exist, but it's ok to not have a config file and thus leave self.config empty │ │ │ │ │ - self.config.read(cockpit_conf) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class Environment(bus.Object, interface='cockpit.Environment'): │ │ │ │ │ - variables = bus.Interface.Property('a{ss}') │ │ │ │ │ - │ │ │ │ │ - @variables.getter │ │ │ │ │ - def get_variables(self): │ │ │ │ │ - return os.environ.copy() │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/jsonutil.py': r'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -from enum import Enum │ │ │ │ │ -from typing import Callable, Dict, List, Mapping, Optional, Sequence, Type, TypeVar, Union │ │ │ │ │ - │ │ │ │ │ -JsonLiteral = Union[str, float, bool, None] │ │ │ │ │ - │ │ │ │ │ -# immutable │ │ │ │ │ -JsonValue = Union['JsonObject', Sequence['JsonValue'], JsonLiteral] │ │ │ │ │ -JsonObject = Mapping[str, JsonValue] │ │ │ │ │ - │ │ │ │ │ -# mutable │ │ │ │ │ -JsonDocument = Union['JsonDict', 'JsonList', JsonLiteral] │ │ │ │ │ -JsonDict = Dict[str, JsonDocument] │ │ │ │ │ -JsonList = List[JsonDocument] │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -DT = TypeVar('DT') │ │ │ │ │ -T = TypeVar('T') │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class JsonError(Exception): │ │ │ │ │ - value: object │ │ │ │ │ - │ │ │ │ │ - def __init__(self, value: object, msg: str): │ │ │ │ │ - super().__init__(msg) │ │ │ │ │ - self.value = value │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def typechecked(value: JsonValue, expected_type: Type[T]) -> T: │ │ │ │ │ - """Ensure a JSON value has the expected type, returning it if so.""" │ │ │ │ │ - if not isinstance(value, expected_type): │ │ │ │ │ - raise JsonError(value, f'must have type {expected_type.__name__}') │ │ │ │ │ - return value │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -# We can't use None as a sentinel because it's often the actual default value │ │ │ │ │ -# EllipsisType is difficult because it's not available before 3.10. │ │ │ │ │ -# See https://peps.python.org/pep-0484/#support-for-singleton-types-in-unions │ │ │ │ │ -class _Empty(Enum): │ │ │ │ │ - TOKEN = 0 │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -_empty = _Empty.TOKEN │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def _get(obj: JsonObject, cast: Callable[[JsonValue], T], key: str, default: Union[DT, _Empty]) -> Union[T, DT]: │ │ │ │ │ - try: │ │ │ │ │ - return cast(obj[key]) │ │ │ │ │ - except KeyError: │ │ │ │ │ - if default is not _empty: │ │ │ │ │ - return default │ │ │ │ │ - raise JsonError(obj, f"attribute '{key}' required") from None │ │ │ │ │ - except JsonError as exc: │ │ │ │ │ - target = f"attribute '{key}'" + (' elements:' if exc.value is not obj[key] else ':') │ │ │ │ │ - raise JsonError(obj, f"{target} {exc!s}") from exc │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_bool(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, bool]: │ │ │ │ │ - return _get(obj, lambda v: typechecked(v, bool), key, default) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_int(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, int]: │ │ │ │ │ - return _get(obj, lambda v: typechecked(v, int), key, default) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_str(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, str]: │ │ │ │ │ - return _get(obj, lambda v: typechecked(v, str), key, default) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_str_or_none(obj: JsonObject, key: str, default: Optional[str]) -> Optional[str]: │ │ │ │ │ - return _get(obj, lambda v: None if v is None else typechecked(v, str), key, default) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_dict(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, JsonObject]: │ │ │ │ │ - return _get(obj, lambda v: typechecked(v, dict), key, default) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_object( │ │ │ │ │ - obj: JsonObject, │ │ │ │ │ - key: str, │ │ │ │ │ - constructor: Callable[[JsonObject], T], │ │ │ │ │ - default: Union[DT, _Empty] = _empty │ │ │ │ │ -) -> Union[DT, T]: │ │ │ │ │ - return _get(obj, lambda v: constructor(typechecked(v, dict)), key, default) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_strv(obj: JsonObject, key: str, default: Union[DT, _Empty] = _empty) -> Union[DT, Sequence[str]]: │ │ │ │ │ - def as_strv(value: JsonValue) -> Sequence[str]: │ │ │ │ │ - return tuple(typechecked(item, str) for item in typechecked(value, list)) │ │ │ │ │ - return _get(obj, as_strv, key, default) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_objv(obj: JsonObject, key: str, constructor: Callable[[JsonObject], T]) -> Union[DT, Sequence[T]]: │ │ │ │ │ - def as_objv(value: JsonValue) -> Sequence[T]: │ │ │ │ │ - return tuple(constructor(typechecked(item, dict)) for item in typechecked(value, list)) │ │ │ │ │ - return _get(obj, as_objv, key, ()) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def create_object(message: 'JsonObject | None', kwargs: JsonObject) -> JsonObject: │ │ │ │ │ - """Constructs a JSON object based on message and kwargs. │ │ │ │ │ - │ │ │ │ │ - If only message is given, it is returned, unmodified. If message is None, │ │ │ │ │ - it is equivalent to an empty dictionary. A copy is always made. │ │ │ │ │ - │ │ │ │ │ - If kwargs are present, then any underscore ('_') present in a key name is │ │ │ │ │ - rewritten to a dash ('-'). This is intended to bridge between the required │ │ │ │ │ - Python syntax when providing kwargs and idiomatic JSON (which uses '-' for │ │ │ │ │ - attributes). These values override values in message. │ │ │ │ │ - │ │ │ │ │ - The idea is that `message` should be used for passing data along, and │ │ │ │ │ - kwargs used for data originating at a given call site, possibly including │ │ │ │ │ - modifications to an original message. │ │ │ │ │ - """ │ │ │ │ │ - result = dict(message or {}) │ │ │ │ │ - │ │ │ │ │ - for key, value in kwargs.items(): │ │ │ │ │ - # rewrite '_' (necessary in Python syntax kwargs list) to '-' (idiomatic JSON) │ │ │ │ │ - json_key = key.replace('_', '-') │ │ │ │ │ - result[json_key] = value │ │ │ │ │ - │ │ │ │ │ - return result │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def json_merge_patch(current: JsonObject, patch: JsonObject) -> JsonObject: │ │ │ │ │ - """Perform a JSON merge patch (RFC 7396) using 'current' and 'patch'. │ │ │ │ │ - Neither of the original dictionaries is modified — the result is returned. │ │ │ │ │ - """ │ │ │ │ │ - # Always take a copy ('result') — we never modify the input ('current') │ │ │ │ │ - result = dict(current) │ │ │ │ │ - for key, patch_value in patch.items(): │ │ │ │ │ - if isinstance(patch_value, Mapping): │ │ │ │ │ - current_value = current.get(key, None) │ │ │ │ │ - if not isinstance(current_value, Mapping): │ │ │ │ │ - current_value = {} │ │ │ │ │ - result[key] = json_merge_patch(current_value, patch_value) │ │ │ │ │ - elif patch_value is not None: │ │ │ │ │ - result[key] = patch_value │ │ │ │ │ - else: │ │ │ │ │ - result.pop(key, None) │ │ │ │ │ - │ │ │ │ │ - return result │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def json_merge_and_filter_patch(current: JsonDict, patch: JsonDict) -> None: │ │ │ │ │ - """Perform a JSON merge patch (RFC 7396) modifying 'current' with 'patch'. │ │ │ │ │ - Also modifies 'patch' to remove redundant operations. │ │ │ │ │ - """ │ │ │ │ │ - for key, patch_value in tuple(patch.items()): │ │ │ │ │ - current_value = current.get(key, None) │ │ │ │ │ - │ │ │ │ │ - if isinstance(patch_value, dict): │ │ │ │ │ - if not isinstance(current_value, dict): │ │ │ │ │ - current[key] = current_value = {} │ │ │ │ │ - json_merge_and_filter_patch(current_value, patch_value) │ │ │ │ │ - else: │ │ │ │ │ - json_merge_and_filter_patch(current_value, patch_value) │ │ │ │ │ - if not patch_value: │ │ │ │ │ - del patch[key] │ │ │ │ │ - elif current_value == patch_value: │ │ │ │ │ - del patch[key] │ │ │ │ │ - elif patch_value is not None: │ │ │ │ │ - current[key] = patch_value │ │ │ │ │ - else: │ │ │ │ │ - del current[key] │ │ │ │ │ -'''.encode('utf-8'), │ │ │ │ │ - 'cockpit/__init__.py': br'''from ._version import __version__ # noqa: F401 │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/transports.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -"""Bi-directional asyncio.Transport implementations based on file descriptors.""" │ │ │ │ │ - │ │ │ │ │ -import asyncio │ │ │ │ │ -import collections │ │ │ │ │ -import ctypes │ │ │ │ │ -import errno │ │ │ │ │ -import fcntl │ │ │ │ │ -import logging │ │ │ │ │ -import os │ │ │ │ │ -import select │ │ │ │ │ -import signal │ │ │ │ │ -import struct │ │ │ │ │ -import subprocess │ │ │ │ │ -import termios │ │ │ │ │ -from typing import Any, ClassVar, Sequence │ │ │ │ │ - │ │ │ │ │ -from .jsonutil import JsonObject, get_int │ │ │ │ │ - │ │ │ │ │ -libc6 = ctypes.cdll.LoadLibrary('libc.so.6') │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def prctl(*args: int) -> None: │ │ │ │ │ - if libc6.prctl(*args) != 0: │ │ │ │ │ - raise OSError('prctl() failed') │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -SET_PDEATHSIG = 1 │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ -IOV_MAX = 1024 # man 2 writev │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class _Transport(asyncio.Transport): │ │ │ │ │ - BLOCK_SIZE: ClassVar[int] = 1024 * 1024 │ │ │ │ │ - │ │ │ │ │ - # A transport always has a loop and a protocol │ │ │ │ │ - _loop: asyncio.AbstractEventLoop │ │ │ │ │ - _protocol: asyncio.Protocol │ │ │ │ │ - │ │ │ │ │ - _queue: 'collections.deque[bytes] | None' │ │ │ │ │ - _in_fd: int │ │ │ │ │ - _out_fd: int │ │ │ │ │ - _closing: bool │ │ │ │ │ - _is_reading: bool │ │ │ │ │ - _eof: bool │ │ │ │ │ - _eio_is_eof: bool = False │ │ │ │ │ - │ │ │ │ │ - def __init__(self, │ │ │ │ │ - loop: asyncio.AbstractEventLoop, │ │ │ │ │ - protocol: asyncio.Protocol, │ │ │ │ │ - in_fd: int = -1, out_fd: int = -1, │ │ │ │ │ - extra: 'dict[str, object] | None' = None): │ │ │ │ │ - super().__init__(extra) │ │ │ │ │ - │ │ │ │ │ - self._loop = loop │ │ │ │ │ - self._protocol = protocol │ │ │ │ │ - │ │ │ │ │ - logger.debug('Created transport %s for protocol %s, fds %d %d', self, protocol, in_fd, out_fd) │ │ │ │ │ - │ │ │ │ │ - self._queue = None │ │ │ │ │ - self._is_reading = False │ │ │ │ │ - self._eof = False │ │ │ │ │ - self._closing = False │ │ │ │ │ - │ │ │ │ │ - self._in_fd = in_fd │ │ │ │ │ - self._out_fd = out_fd │ │ │ │ │ - │ │ │ │ │ - os.set_blocking(in_fd, False) │ │ │ │ │ - if out_fd != in_fd: │ │ │ │ │ - os.set_blocking(out_fd, False) │ │ │ │ │ - │ │ │ │ │ - self._protocol.connection_made(self) │ │ │ │ │ - self.resume_reading() │ │ │ │ │ - │ │ │ │ │ - def _read_ready(self) -> None: │ │ │ │ │ - logger.debug('Read ready on %s %s %d', self, self._protocol, self._in_fd) │ │ │ │ │ - try: │ │ │ │ │ - data = os.read(self._in_fd, _Transport.BLOCK_SIZE) │ │ │ │ │ - except BlockingIOError: # pragma: no cover │ │ │ │ │ - return │ │ │ │ │ - except OSError as exc: │ │ │ │ │ - if self._eio_is_eof and exc.errno == errno.EIO: │ │ │ │ │ - # PTY devices return EIO to mean "EOF" │ │ │ │ │ - data = b'' │ │ │ │ │ - else: │ │ │ │ │ - # Other errors: terminate the connection │ │ │ │ │ - self.abort(exc) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - if data != b'': │ │ │ │ │ - logger.debug(' read %d bytes', len(data)) │ │ │ │ │ - self._protocol.data_received(data) │ │ │ │ │ - else: │ │ │ │ │ - logger.debug(' got EOF') │ │ │ │ │ - self._close_reader() │ │ │ │ │ - keep_open = self._protocol.eof_received() │ │ │ │ │ - if not keep_open: │ │ │ │ │ - self.close() │ │ │ │ │ - │ │ │ │ │ - def is_reading(self) -> bool: │ │ │ │ │ - return self._is_reading │ │ │ │ │ - │ │ │ │ │ - def _close_reader(self) -> None: │ │ │ │ │ - self.pause_reading() │ │ │ │ │ - self._in_fd = -1 │ │ │ │ │ - │ │ │ │ │ - def pause_reading(self) -> None: │ │ │ │ │ - if self._is_reading: │ │ │ │ │ - self._loop.remove_reader(self._in_fd) │ │ │ │ │ - self._is_reading = False │ │ │ │ │ - │ │ │ │ │ - def resume_reading(self) -> None: │ │ │ │ │ - # It's possible that the Protocol could decide to attempt to unpause │ │ │ │ │ - # reading after _close_reader() got called. Check that the fd is != -1 │ │ │ │ │ - # before actually resuming. │ │ │ │ │ - if not self._is_reading and self._in_fd != -1: │ │ │ │ │ - self._loop.add_reader(self._in_fd, self._read_ready) │ │ │ │ │ - self._is_reading = True │ │ │ │ │ - │ │ │ │ │ - def _close(self) -> None: │ │ │ │ │ - pass │ │ │ │ │ - │ │ │ │ │ - def abort(self, exc: 'Exception | None' = None) -> None: │ │ │ │ │ - self._closing = True │ │ │ │ │ - self._close_reader() │ │ │ │ │ - self._remove_write_queue() │ │ │ │ │ - self._protocol.connection_lost(exc) │ │ │ │ │ - self._close() │ │ │ │ │ - │ │ │ │ │ - def can_write_eof(self) -> bool: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def write_eof(self) -> None: │ │ │ │ │ - assert not self._eof │ │ │ │ │ - self._eof = True │ │ │ │ │ - if self._queue is None: │ │ │ │ │ - logger.debug('%s got EOF. closing backend.', self) │ │ │ │ │ - self._write_eof_now() │ │ │ │ │ - else: │ │ │ │ │ - logger.debug('%s got EOF. bytes in queue, deferring close', self) │ │ │ │ │ - │ │ │ │ │ - def get_write_buffer_size(self) -> int: │ │ │ │ │ - if self._queue is None: │ │ │ │ │ - return 0 │ │ │ │ │ - return sum(len(block) for block in self._queue) │ │ │ │ │ - │ │ │ │ │ - def get_write_buffer_limits(self) -> 'tuple[int, int]': │ │ │ │ │ - return (0, 0) │ │ │ │ │ - │ │ │ │ │ - def set_write_buffer_limits(self, high: 'int | None' = None, low: 'int | None' = None) -> None: │ │ │ │ │ - assert high is None or high == 0 │ │ │ │ │ - assert low is None or low == 0 │ │ │ │ │ - │ │ │ │ │ - def _write_eof_now(self) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def _write_ready(self) -> None: │ │ │ │ │ - logger.debug('%s _write_ready', self) │ │ │ │ │ - assert self._queue is not None │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - n_bytes = os.writev(self._out_fd, self._queue) │ │ │ │ │ - except BlockingIOError: # pragma: no cover │ │ │ │ │ - n_bytes = 0 │ │ │ │ │ - except OSError as exc: │ │ │ │ │ - self.abort(exc) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - logger.debug(' successfully wrote %d bytes from the queue', n_bytes) │ │ │ │ │ - │ │ │ │ │ - while n_bytes: │ │ │ │ │ - block = self._queue.popleft() │ │ │ │ │ - if len(block) > n_bytes: │ │ │ │ │ - # This block wasn't completely written. │ │ │ │ │ - logger.debug(' incomplete block. Stop.') │ │ │ │ │ - self._queue.appendleft(block[n_bytes:]) │ │ │ │ │ - break │ │ │ │ │ - n_bytes -= len(block) │ │ │ │ │ - logger.debug(' removed complete block. %d remains.', n_bytes) │ │ │ │ │ - │ │ │ │ │ - if not self._queue: │ │ │ │ │ - logger.debug('%s queue drained.') │ │ │ │ │ - self._remove_write_queue() │ │ │ │ │ - if self._eof: │ │ │ │ │ - logger.debug('%s queue drained. closing backend now.') │ │ │ │ │ - self._write_eof_now() │ │ │ │ │ - if self._closing: │ │ │ │ │ - self.abort() │ │ │ │ │ - │ │ │ │ │ - def _remove_write_queue(self) -> None: │ │ │ │ │ - if self._queue is not None: │ │ │ │ │ - self._protocol.resume_writing() │ │ │ │ │ - self._loop.remove_writer(self._out_fd) │ │ │ │ │ - self._queue = None │ │ │ │ │ - │ │ │ │ │ - def _create_write_queue(self, data: bytes) -> None: │ │ │ │ │ - logger.debug('%s creating write queue for fd %s', self, self._out_fd) │ │ │ │ │ - assert self._queue is None │ │ │ │ │ - self._loop.add_writer(self._out_fd, self._write_ready) │ │ │ │ │ - self._queue = collections.deque((data,)) │ │ │ │ │ - self._protocol.pause_writing() │ │ │ │ │ - │ │ │ │ │ - def write(self, data: bytes) -> None: │ │ │ │ │ - # this is a race condition with subprocesses: if we get and process the the "exited" │ │ │ │ │ - # event before seeing BrokenPipeError, we'll try to write to a closed pipe. │ │ │ │ │ - # Do what the standard library does and ignore, instead of assert │ │ │ │ │ - if self._closing: │ │ │ │ │ - logger.debug('ignoring write() to closing transport fd %i', self._out_fd) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - assert not self._eof │ │ │ │ │ - │ │ │ │ │ - if self._queue is not None: │ │ │ │ │ - self._queue.append(data) │ │ │ │ │ - │ │ │ │ │ - # writev() will complain if the queue is too long. Consolidate it. │ │ │ │ │ - if len(self._queue) > IOV_MAX: │ │ │ │ │ - all_data = b''.join(self._queue) │ │ │ │ │ - self._queue.clear() │ │ │ │ │ - self._queue.append(all_data) │ │ │ │ │ - │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - n_bytes = os.write(self._out_fd, data) │ │ │ │ │ - except BlockingIOError: │ │ │ │ │ - n_bytes = 0 │ │ │ │ │ - except OSError as exc: │ │ │ │ │ - self.abort(exc) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - if n_bytes != len(data): │ │ │ │ │ - self._create_write_queue(data[n_bytes:]) │ │ │ │ │ - │ │ │ │ │ - def close(self) -> None: │ │ │ │ │ - if self._closing: │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - self._closing = True │ │ │ │ │ - self._close_reader() │ │ │ │ │ - │ │ │ │ │ - if self._queue is not None: │ │ │ │ │ - # abort() will be called from _write_ready() when it's done │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - self.abort() │ │ │ │ │ - │ │ │ │ │ - def get_protocol(self) -> asyncio.BaseProtocol: │ │ │ │ │ - return self._protocol │ │ │ │ │ - │ │ │ │ │ - def is_closing(self) -> bool: │ │ │ │ │ - return self._closing │ │ │ │ │ - │ │ │ │ │ - def set_protocol(self, protocol: asyncio.BaseProtocol) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def __del__(self) -> None: │ │ │ │ │ - self._close() │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class SubprocessProtocol(asyncio.Protocol): │ │ │ │ │ - """An extension to asyncio.Protocol for use with SubprocessTransport.""" │ │ │ │ │ - def process_exited(self) -> None: │ │ │ │ │ - """Called when subprocess has exited.""" │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class WindowSize: │ │ │ │ │ - def __init__(self, value: JsonObject): │ │ │ │ │ - self.rows = get_int(value, 'rows') │ │ │ │ │ - self.cols = get_int(value, 'cols') │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class SubprocessTransport(_Transport, asyncio.SubprocessTransport): │ │ │ │ │ - """A bi-directional transport speaking with stdin/out of a subprocess. │ │ │ │ │ - │ │ │ │ │ - Note: this is not really a normal SubprocessTransport. Although it │ │ │ │ │ - implements the entire API of asyncio.SubprocessTransport, it is not │ │ │ │ │ - designed to be used with asyncio.SubprocessProtocol objects. Instead, it │ │ │ │ │ - pair with normal Protocol objects which also implement the │ │ │ │ │ - SubprocessProtocol defined in this module (which only has a │ │ │ │ │ - process_exited() method). Whatever the protocol writes is sent to stdin, │ │ │ │ │ - and whatever comes from stdout is given to the Protocol via the │ │ │ │ │ - .data_received() function. │ │ │ │ │ - │ │ │ │ │ - If stderr is configured as a pipe, the transport will separately collect │ │ │ │ │ - data from it, making it available via the .get_stderr() method. │ │ │ │ │ - """ │ │ │ │ │ - │ │ │ │ │ - _returncode: 'int | None' = None │ │ │ │ │ - │ │ │ │ │ - _pty_fd: 'int | None' = None │ │ │ │ │ - _process: 'subprocess.Popen[bytes] | None' = None │ │ │ │ │ - _stderr: 'Spooler | None' │ │ │ │ │ - │ │ │ │ │ - @staticmethod │ │ │ │ │ - def _create_watcher() -> asyncio.AbstractChildWatcher: │ │ │ │ │ - try: │ │ │ │ │ - os.close(os.pidfd_open(os.getpid(), 0)) # check for kernel support │ │ │ │ │ - return asyncio.PidfdChildWatcher() │ │ │ │ │ - except (AttributeError, OSError): │ │ │ │ │ - pass │ │ │ │ │ - │ │ │ │ │ - return asyncio.SafeChildWatcher() │ │ │ │ │ - │ │ │ │ │ - @staticmethod │ │ │ │ │ - def _get_watcher(loop: asyncio.AbstractEventLoop) -> asyncio.AbstractChildWatcher: │ │ │ │ │ - quark = '_cockpit_transports_child_watcher' │ │ │ │ │ - watcher = getattr(loop, quark, None) │ │ │ │ │ - │ │ │ │ │ - if watcher is None: │ │ │ │ │ - watcher = SubprocessTransport._create_watcher() │ │ │ │ │ - watcher.attach_loop(loop) │ │ │ │ │ - setattr(loop, quark, watcher) │ │ │ │ │ - │ │ │ │ │ - return watcher │ │ │ │ │ - │ │ │ │ │ - def get_stderr(self, *, reset: bool = False) -> str: │ │ │ │ │ - if self._stderr is not None: │ │ │ │ │ - return self._stderr.get(reset=reset).decode(errors='replace') │ │ │ │ │ - else: │ │ │ │ │ - return '' │ │ │ │ │ - │ │ │ │ │ - def _exited(self, pid: int, code: int) -> None: │ │ │ │ │ - # NB: per AbstractChildWatcher API, this handler should be thread-safe, │ │ │ │ │ - # but we only ever use non-threaded child watcher implementations, so │ │ │ │ │ - # we can assume we'll always be called in the main thread. │ │ │ │ │ - │ │ │ │ │ - # NB: the subprocess is going to want to waitpid() itself as well, but │ │ │ │ │ - # will get ECHILD since we already reaped it. Fortunately, since │ │ │ │ │ - # Python 3.2 this is supported, and process gets a return status of │ │ │ │ │ - # zero. For that reason, we need to store our own copy of the return │ │ │ │ │ - # status. See https://github.com/python/cpython/issues/59960 │ │ │ │ │ - assert isinstance(self._protocol, SubprocessProtocol) │ │ │ │ │ - assert self._process is not None │ │ │ │ │ - assert self._process.pid == pid │ │ │ │ │ - self._returncode = code │ │ │ │ │ - logger.debug('Process exited with status %d', self._returncode) │ │ │ │ │ - if not self._closing: │ │ │ │ │ - self._protocol.process_exited() │ │ │ │ │ - │ │ │ │ │ - def __init__(self, │ │ │ │ │ - loop: asyncio.AbstractEventLoop, │ │ │ │ │ - protocol: SubprocessProtocol, │ │ │ │ │ - args: Sequence[str], │ │ │ │ │ - *, │ │ │ │ │ - pty: bool = False, │ │ │ │ │ - window: 'WindowSize | None' = None, │ │ │ │ │ - **kwargs: Any): │ │ │ │ │ - │ │ │ │ │ - # go down as a team -- we don't want any leaked processes when the bridge terminates │ │ │ │ │ - def preexec_fn() -> None: │ │ │ │ │ - prctl(SET_PDEATHSIG, signal.SIGTERM) │ │ │ │ │ - if pty: │ │ │ │ │ - fcntl.ioctl(0, termios.TIOCSCTTY, 0) │ │ │ │ │ - │ │ │ │ │ - if pty: │ │ │ │ │ - self._pty_fd, session_fd = os.openpty() │ │ │ │ │ - │ │ │ │ │ - if window is not None: │ │ │ │ │ - self.set_window_size(window) │ │ │ │ │ - │ │ │ │ │ - kwargs['stderr'] = session_fd │ │ │ │ │ - self._process = subprocess.Popen(args, │ │ │ │ │ - stdin=session_fd, stdout=session_fd, │ │ │ │ │ - preexec_fn=preexec_fn, start_new_session=True, **kwargs) │ │ │ │ │ - os.close(session_fd) │ │ │ │ │ - │ │ │ │ │ - in_fd, out_fd = self._pty_fd, self._pty_fd │ │ │ │ │ - self._eio_is_eof = True │ │ │ │ │ - │ │ │ │ │ - else: │ │ │ │ │ - self._process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, │ │ │ │ │ - preexec_fn=preexec_fn, **kwargs) │ │ │ │ │ - assert self._process.stdin │ │ │ │ │ - assert self._process.stdout │ │ │ │ │ - in_fd = self._process.stdout.fileno() │ │ │ │ │ - out_fd = self._process.stdin.fileno() │ │ │ │ │ - │ │ │ │ │ - if self._process.stderr is not None: │ │ │ │ │ - self._stderr = Spooler(loop, self._process.stderr.fileno()) │ │ │ │ │ - else: │ │ │ │ │ - self._stderr = None │ │ │ │ │ - │ │ │ │ │ - super().__init__(loop, protocol, in_fd, out_fd) │ │ │ │ │ - │ │ │ │ │ - self._get_watcher(loop).add_child_handler(self._process.pid, self._exited) │ │ │ │ │ - │ │ │ │ │ - def set_window_size(self, size: WindowSize) -> None: │ │ │ │ │ - assert self._pty_fd is not None │ │ │ │ │ - fcntl.ioctl(self._pty_fd, termios.TIOCSWINSZ, struct.pack('2H4x', size.rows, size.cols)) │ │ │ │ │ - │ │ │ │ │ - def can_write_eof(self) -> bool: │ │ │ │ │ - assert self._process is not None │ │ │ │ │ - return self._process.stdin is not None │ │ │ │ │ - │ │ │ │ │ - def _write_eof_now(self) -> None: │ │ │ │ │ - assert self._process is not None │ │ │ │ │ - assert self._process.stdin is not None │ │ │ │ │ - self._process.stdin.close() │ │ │ │ │ - self._out_fd = -1 │ │ │ │ │ - │ │ │ │ │ - def get_pid(self) -> int: │ │ │ │ │ - assert self._process is not None │ │ │ │ │ - return self._process.pid │ │ │ │ │ - │ │ │ │ │ - def get_returncode(self) -> 'int | None': │ │ │ │ │ - return self._returncode │ │ │ │ │ - │ │ │ │ │ - def get_pipe_transport(self, fd: int) -> asyncio.Transport: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def send_signal(self, sig: signal.Signals) -> None: # type: ignore[override] # mypy/issues/13885 │ │ │ │ │ - assert self._process is not None │ │ │ │ │ - # We try to avoid using subprocess.send_signal(). It contains a call │ │ │ │ │ - # to waitpid() internally to avoid signalling the wrong process (if a │ │ │ │ │ - # PID gets reused), but: │ │ │ │ │ - # │ │ │ │ │ - # - we already detect the process exiting via our PidfdChildWatcher │ │ │ │ │ - # │ │ │ │ │ - # - the check is actually harmful since collecting the process via │ │ │ │ │ - # waitpid() prevents the PidfdChildWatcher from doing the same, │ │ │ │ │ - # resulting in an error. │ │ │ │ │ - # │ │ │ │ │ - # It's on us now to check it, but that's easy: │ │ │ │ │ - if self._returncode is not None: │ │ │ │ │ - logger.debug("won't attempt %s to process %i. It exited already.", sig, self._process.pid) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - os.kill(self._process.pid, sig) │ │ │ │ │ - logger.debug('sent %s to process %i', sig, self._process.pid) │ │ │ │ │ - except ProcessLookupError: │ │ │ │ │ - # already gone? fine │ │ │ │ │ - logger.debug("can't send %s to process %i. It's exited just now.", sig, self._process.pid) │ │ │ │ │ - │ │ │ │ │ - def terminate(self) -> None: │ │ │ │ │ - self.send_signal(signal.SIGTERM) │ │ │ │ │ - │ │ │ │ │ - def kill(self) -> None: │ │ │ │ │ - self.send_signal(signal.SIGKILL) │ │ │ │ │ - │ │ │ │ │ - def _close(self) -> None: │ │ │ │ │ - if self._pty_fd is not None: │ │ │ │ │ - os.close(self._pty_fd) │ │ │ │ │ - self._pty_fd = None │ │ │ │ │ - │ │ │ │ │ - if self._process is not None: │ │ │ │ │ - if self._process.stdin is not None: │ │ │ │ │ - self._process.stdin.close() │ │ │ │ │ - self._process.stdin = None │ │ │ │ │ - try: │ │ │ │ │ - self.terminate() # best effort... │ │ │ │ │ - except PermissionError: │ │ │ │ │ - logger.debug("can't kill %i due to EPERM", self._process.pid) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class StdioTransport(_Transport): │ │ │ │ │ - """A bi-directional transport that corresponds to stdin/out. │ │ │ │ │ - │ │ │ │ │ - Can talk to just about anything: │ │ │ │ │ - - files │ │ │ │ │ - - pipes │ │ │ │ │ - - character devices (including terminals) │ │ │ │ │ - - sockets │ │ │ │ │ - """ │ │ │ │ │ - │ │ │ │ │ - def __init__(self, loop: asyncio.AbstractEventLoop, protocol: asyncio.Protocol, stdin: int = 0, stdout: int = 1): │ │ │ │ │ - super().__init__(loop, protocol, stdin, stdout) │ │ │ │ │ - │ │ │ │ │ - def can_write_eof(self) -> bool: │ │ │ │ │ - return False │ │ │ │ │ - │ │ │ │ │ - def _write_eof_now(self) -> None: │ │ │ │ │ - raise RuntimeError("Can't write EOF to stdout") │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class Spooler: │ │ │ │ │ - """Consumes data from an fd, storing it in a buffer. │ │ │ │ │ - │ │ │ │ │ - This makes a copy of the fd, so you don't have to worry about holding it │ │ │ │ │ - open. │ │ │ │ │ - """ │ │ │ │ │ - │ │ │ │ │ - _loop: asyncio.AbstractEventLoop │ │ │ │ │ - _fd: int │ │ │ │ │ - _contents: 'list[bytes]' │ │ │ │ │ - │ │ │ │ │ - def __init__(self, loop: asyncio.AbstractEventLoop, fd: int): │ │ │ │ │ - self._loop = loop │ │ │ │ │ - self._fd = -1 # in case dup() raises an exception │ │ │ │ │ - self._contents = [] │ │ │ │ │ - │ │ │ │ │ - self._fd = os.dup(fd) │ │ │ │ │ - │ │ │ │ │ - os.set_blocking(self._fd, False) │ │ │ │ │ - loop.add_reader(self._fd, self._read_ready) │ │ │ │ │ - │ │ │ │ │ - def _read_ready(self) -> None: │ │ │ │ │ - try: │ │ │ │ │ - data = os.read(self._fd, 8192) │ │ │ │ │ - except BlockingIOError: # pragma: no cover │ │ │ │ │ - return │ │ │ │ │ - except OSError: │ │ │ │ │ - # all other errors -> EOF │ │ │ │ │ - data = b'' │ │ │ │ │ - │ │ │ │ │ - if data != b'': │ │ │ │ │ - self._contents.append(data) │ │ │ │ │ - else: │ │ │ │ │ - self.close() │ │ │ │ │ - │ │ │ │ │ - def _is_ready(self) -> bool: │ │ │ │ │ - if self._fd == -1: │ │ │ │ │ - return False │ │ │ │ │ - return select.select([self._fd], [], [], 0) != ([], [], []) │ │ │ │ │ - │ │ │ │ │ - def get(self, *, reset: bool = False) -> bytes: │ │ │ │ │ - while self._is_ready(): │ │ │ │ │ - self._read_ready() │ │ │ │ │ - │ │ │ │ │ - result = b''.join(self._contents) │ │ │ │ │ - if reset: │ │ │ │ │ - self._contents = [] │ │ │ │ │ - return result │ │ │ │ │ - │ │ │ │ │ - def close(self) -> None: │ │ │ │ │ - if self._fd != -1: │ │ │ │ │ - self._loop.remove_reader(self._fd) │ │ │ │ │ - os.close(self._fd) │ │ │ │ │ - self._fd = -1 │ │ │ │ │ - │ │ │ │ │ - def __del__(self) -> None: │ │ │ │ │ - self.close() │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/router.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import asyncio │ │ │ │ │ -import collections │ │ │ │ │ -import logging │ │ │ │ │ -from typing import Dict, List, Optional │ │ │ │ │ - │ │ │ │ │ -from .jsonutil import JsonObject, JsonValue │ │ │ │ │ -from .protocol import CockpitProblem, CockpitProtocolError, CockpitProtocolServer │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class ExecutionQueue: │ │ │ │ │ - """Temporarily delay calls to a given set of class methods. │ │ │ │ │ - │ │ │ │ │ - Functions by replacing the named function at the instance __dict__ │ │ │ │ │ - level, effectively providing an override for exactly one instance │ │ │ │ │ - of `method`'s object. │ │ │ │ │ - Queues the invocations. Run them later with .run(), which also reverses │ │ │ │ │ - the redirection by deleting the named methods from the instance. │ │ │ │ │ - """ │ │ │ │ │ - def __init__(self, methods): │ │ │ │ │ - self.queue = collections.deque() │ │ │ │ │ - self.methods = methods │ │ │ │ │ - │ │ │ │ │ - for method in self.methods: │ │ │ │ │ - self._wrap(method) │ │ │ │ │ - │ │ │ │ │ - def _wrap(self, method): │ │ │ │ │ - # NB: this function is stored in the instance dict and therefore │ │ │ │ │ - # doesn't function as a descriptor, isn't a method, doesn't get bound, │ │ │ │ │ - # and therefore doesn't receive a self parameter │ │ │ │ │ - setattr(method.__self__, method.__func__.__name__, lambda *args: self.queue.append((method, args))) │ │ │ │ │ - │ │ │ │ │ - def run(self): │ │ │ │ │ - logger.debug('ExecutionQueue: Running %d queued method calls', len(self.queue)) │ │ │ │ │ - for method, args in self.queue: │ │ │ │ │ - method(*args) │ │ │ │ │ - │ │ │ │ │ - for method in self.methods: │ │ │ │ │ - delattr(method.__self__, method.__func__.__name__) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class Endpoint: │ │ │ │ │ - router: 'Router' │ │ │ │ │ - __endpoint_frozen_queue: Optional[ExecutionQueue] = None │ │ │ │ │ - │ │ │ │ │ - def __init__(self, router: 'Router'): │ │ │ │ │ - router.add_endpoint(self) │ │ │ │ │ - self.router = router │ │ │ │ │ - │ │ │ │ │ - def freeze_endpoint(self): │ │ │ │ │ - assert self.__endpoint_frozen_queue is None │ │ │ │ │ - logger.debug('Freezing endpoint %s', self) │ │ │ │ │ - self.__endpoint_frozen_queue = ExecutionQueue({self.do_channel_control, self.do_channel_data, self.do_kill}) │ │ │ │ │ - │ │ │ │ │ - def thaw_endpoint(self): │ │ │ │ │ - assert self.__endpoint_frozen_queue is not None │ │ │ │ │ - logger.debug('Thawing endpoint %s', self) │ │ │ │ │ - self.__endpoint_frozen_queue.run() │ │ │ │ │ - self.__endpoint_frozen_queue = None │ │ │ │ │ - │ │ │ │ │ - # interface for receiving messages │ │ │ │ │ - def do_close(self): │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def do_channel_control(self, channel: str, command: str, message: JsonObject) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def do_channel_data(self, channel: str, data: bytes) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - # interface for sending messages │ │ │ │ │ - def send_channel_data(self, channel: str, data: bytes) -> None: │ │ │ │ │ - self.router.write_channel_data(channel, data) │ │ │ │ │ - │ │ │ │ │ - def send_channel_control( │ │ │ │ │ - self, channel: str, command: str, _msg: 'JsonObject | None', **kwargs: JsonValue │ │ │ │ │ - ) -> None: │ │ │ │ │ - self.router.write_control(_msg, channel=channel, command=command, **kwargs) │ │ │ │ │ - if command == 'close': │ │ │ │ │ - self.router.endpoints[self].remove(channel) │ │ │ │ │ - self.router.drop_channel(channel) │ │ │ │ │ - │ │ │ │ │ - def shutdown_endpoint(self, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> None: │ │ │ │ │ - self.router.shutdown_endpoint(self, _msg, **kwargs) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class RoutingError(CockpitProblem): │ │ │ │ │ - pass │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class RoutingRule: │ │ │ │ │ - router: 'Router' │ │ │ │ │ - │ │ │ │ │ - def __init__(self, router: 'Router'): │ │ │ │ │ - self.router = router │ │ │ │ │ - │ │ │ │ │ - def apply_rule(self, options: JsonObject) -> Optional[Endpoint]: │ │ │ │ │ - """Check if a routing rule applies to a given 'open' message. │ │ │ │ │ - │ │ │ │ │ - This should inspect the options dictionary and do one of the following three things: │ │ │ │ │ - │ │ │ │ │ - - return an Endpoint to handle this channel │ │ │ │ │ - - raise a RoutingError to indicate that the open should be rejected │ │ │ │ │ - - return None to let the next rule run │ │ │ │ │ - """ │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - def shutdown(self): │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class Router(CockpitProtocolServer): │ │ │ │ │ - routing_rules: List[RoutingRule] │ │ │ │ │ - open_channels: Dict[str, Endpoint] │ │ │ │ │ - endpoints: 'dict[Endpoint, set[str]]' │ │ │ │ │ - no_endpoints: asyncio.Event # set if endpoints dict is empty │ │ │ │ │ - _eof: bool = False │ │ │ │ │ - │ │ │ │ │ - def __init__(self, routing_rules: List[RoutingRule]): │ │ │ │ │ - for rule in routing_rules: │ │ │ │ │ - rule.router = self │ │ │ │ │ - self.routing_rules = routing_rules │ │ │ │ │ - self.open_channels = {} │ │ │ │ │ - self.endpoints = {} │ │ │ │ │ - self.no_endpoints = asyncio.Event() │ │ │ │ │ - self.no_endpoints.set() # at first there are no endpoints │ │ │ │ │ - │ │ │ │ │ - def check_rules(self, options: JsonObject) -> Endpoint: │ │ │ │ │ - for rule in self.routing_rules: │ │ │ │ │ - logger.debug(' applying rule %s', rule) │ │ │ │ │ - endpoint = rule.apply_rule(options) │ │ │ │ │ - if endpoint is not None: │ │ │ │ │ - logger.debug(' resulting endpoint is %s', endpoint) │ │ │ │ │ - return endpoint │ │ │ │ │ - else: │ │ │ │ │ - logger.debug(' No rules matched') │ │ │ │ │ - raise RoutingError('not-supported') │ │ │ │ │ - │ │ │ │ │ - def drop_channel(self, channel: str) -> None: │ │ │ │ │ - try: │ │ │ │ │ - self.open_channels.pop(channel) │ │ │ │ │ - logger.debug('router dropped channel %s', channel) │ │ │ │ │ - except KeyError: │ │ │ │ │ - logger.error('trying to drop non-existent channel %s from %s', channel, self.open_channels) │ │ │ │ │ - │ │ │ │ │ - def add_endpoint(self, endpoint: Endpoint) -> None: │ │ │ │ │ - self.endpoints[endpoint] = set() │ │ │ │ │ - self.no_endpoints.clear() │ │ │ │ │ - │ │ │ │ │ - def shutdown_endpoint(self, endpoint: Endpoint, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> None: │ │ │ │ │ - channels = self.endpoints.pop(endpoint) │ │ │ │ │ - logger.debug('shutdown_endpoint(%s, %s) will close %s', endpoint, kwargs, channels) │ │ │ │ │ - for channel in channels: │ │ │ │ │ - self.write_control(_msg, command='close', channel=channel, **kwargs) │ │ │ │ │ - self.drop_channel(channel) │ │ │ │ │ - │ │ │ │ │ - if not self.endpoints: │ │ │ │ │ - self.no_endpoints.set() │ │ │ │ │ - │ │ │ │ │ - # were we waiting to exit? │ │ │ │ │ - if self._eof: │ │ │ │ │ - logger.debug(' endpoints remaining: %r', self.endpoints) │ │ │ │ │ - if not self.endpoints and self.transport: │ │ │ │ │ - logger.debug(' close transport') │ │ │ │ │ - self.transport.close() │ │ │ │ │ - │ │ │ │ │ - def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None: │ │ │ │ │ - endpoints = set(self.endpoints) │ │ │ │ │ - logger.debug('do_kill(%s, %s). Considering %d endpoints.', host, group, len(endpoints)) │ │ │ │ │ - for endpoint in endpoints: │ │ │ │ │ - endpoint.do_kill(host, group, message) │ │ │ │ │ - │ │ │ │ │ - def channel_control_received(self, channel: str, command: str, message: JsonObject) -> None: │ │ │ │ │ - # If this is an open message then we need to apply the routing rules to │ │ │ │ │ - # figure out the correct endpoint to connect. If it's not an open │ │ │ │ │ - # message, then we expect the endpoint to already exist. │ │ │ │ │ - if command == 'open': │ │ │ │ │ - if channel in self.open_channels: │ │ │ │ │ - raise CockpitProtocolError('channel is already open') │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - logger.debug('Trying to find endpoint for new channel %s payload=%s', channel, message.get('payload')) │ │ │ │ │ - endpoint = self.check_rules(message) │ │ │ │ │ - except RoutingError as exc: │ │ │ │ │ - self.write_control(exc.attrs, command='close', channel=channel) │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - self.open_channels[channel] = endpoint │ │ │ │ │ - self.endpoints[endpoint].add(channel) │ │ │ │ │ - else: │ │ │ │ │ - try: │ │ │ │ │ - endpoint = self.open_channels[channel] │ │ │ │ │ - except KeyError: │ │ │ │ │ - # sending to a non-existent channel can happen due to races and is not an error │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - # At this point, we have the endpoint. Route the message. │ │ │ │ │ - endpoint.do_channel_control(channel, command, message) │ │ │ │ │ - │ │ │ │ │ - def channel_data_received(self, channel: str, data: bytes) -> None: │ │ │ │ │ - try: │ │ │ │ │ - endpoint = self.open_channels[channel] │ │ │ │ │ - except KeyError: │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - endpoint.do_channel_data(channel, data) │ │ │ │ │ - │ │ │ │ │ - def eof_received(self) -> bool: │ │ │ │ │ - logger.debug('eof_received(%r)', self) │ │ │ │ │ - │ │ │ │ │ - endpoints = set(self.endpoints) │ │ │ │ │ - for endpoint in endpoints: │ │ │ │ │ - endpoint.do_close() │ │ │ │ │ - │ │ │ │ │ - self._eof = True │ │ │ │ │ - logger.debug(' endpoints remaining: %r', self.endpoints) │ │ │ │ │ - return bool(self.endpoints) │ │ │ │ │ - │ │ │ │ │ - _communication_done: Optional[asyncio.Future] = None │ │ │ │ │ - │ │ │ │ │ - def do_closed(self, exc: Optional[Exception]) -> None: │ │ │ │ │ - # If we didn't send EOF yet, do it now. │ │ │ │ │ - if not self._eof: │ │ │ │ │ - self.eof_received() │ │ │ │ │ - │ │ │ │ │ - if self._communication_done is not None: │ │ │ │ │ - if exc is None: │ │ │ │ │ - self._communication_done.set_result(None) │ │ │ │ │ - else: │ │ │ │ │ - self._communication_done.set_exception(exc) │ │ │ │ │ - │ │ │ │ │ - async def communicate(self) -> None: │ │ │ │ │ - """Wait until communication is complete on the router and all endpoints are done.""" │ │ │ │ │ - assert self._communication_done is None │ │ │ │ │ - self._communication_done = asyncio.get_running_loop().create_future() │ │ │ │ │ - try: │ │ │ │ │ - await self._communication_done │ │ │ │ │ - except (BrokenPipeError, ConnectionResetError): │ │ │ │ │ - pass # these are normal occurrences when closed from the other side │ │ │ │ │ - finally: │ │ │ │ │ - self._communication_done = None │ │ │ │ │ - │ │ │ │ │ - # In an orderly exit, this is already done, but in case it wasn't │ │ │ │ │ - # orderly, we need to make sure the endpoints shut down anyway... │ │ │ │ │ - await self.no_endpoints.wait() │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/polyfills.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import contextlib │ │ │ │ │ -import socket │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def install(): │ │ │ │ │ - """Add shims for older Python versions""" │ │ │ │ │ - │ │ │ │ │ - # introduced in 3.9 │ │ │ │ │ - if not hasattr(socket, 'recv_fds'): │ │ │ │ │ - import array │ │ │ │ │ - │ │ │ │ │ - import _socket │ │ │ │ │ - │ │ │ │ │ - def recv_fds(sock, bufsize, maxfds, flags=0): │ │ │ │ │ - fds = array.array("i") │ │ │ │ │ - msg, ancdata, flags, addr = sock.recvmsg(bufsize, _socket.CMSG_LEN(maxfds * fds.itemsize)) │ │ │ │ │ - for cmsg_level, cmsg_type, cmsg_data in ancdata: │ │ │ │ │ - if (cmsg_level == _socket.SOL_SOCKET and cmsg_type == _socket.SCM_RIGHTS): │ │ │ │ │ - fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) │ │ │ │ │ - return msg, list(fds), flags, addr │ │ │ │ │ - │ │ │ │ │ - socket.recv_fds = recv_fds │ │ │ │ │ - │ │ │ │ │ - # introduced in 3.7 │ │ │ │ │ - if not hasattr(contextlib, 'AsyncExitStack'): │ │ │ │ │ - class AsyncExitStack: │ │ │ │ │ - async def __aenter__(self): │ │ │ │ │ - self.cms = [] │ │ │ │ │ - return self │ │ │ │ │ - │ │ │ │ │ - async def enter_async_context(self, cm): │ │ │ │ │ - result = await cm.__aenter__() │ │ │ │ │ - self.cms.append(cm) │ │ │ │ │ - return result │ │ │ │ │ - │ │ │ │ │ - async def __aexit__(self, exc_type, exc_value, traceback): │ │ │ │ │ - for cm in self.cms: │ │ │ │ │ - cm.__aexit__(exc_type, exc_value, traceback) │ │ │ │ │ - │ │ │ │ │ - contextlib.AsyncExitStack = AsyncExitStack │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/internal_endpoints.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import asyncio │ │ │ │ │ -import glob │ │ │ │ │ -import grp │ │ │ │ │ -import json │ │ │ │ │ -import logging │ │ │ │ │ -import os │ │ │ │ │ -import pwd │ │ │ │ │ -from pathlib import Path │ │ │ │ │ -from typing import Dict, Optional │ │ │ │ │ - │ │ │ │ │ -from cockpit._vendor.systemd_ctypes import Variant, bus, inotify, pathwatch │ │ │ │ │ - │ │ │ │ │ -from . import config │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class cockpit_LoginMessages(bus.Object): │ │ │ │ │ - messages: Optional[str] = None │ │ │ │ │ - │ │ │ │ │ - def __init__(self): │ │ │ │ │ - fdstr = os.environ.pop('COCKPIT_LOGIN_MESSAGES_MEMFD', None) │ │ │ │ │ - if fdstr is None: │ │ │ │ │ - logger.debug("COCKPIT_LOGIN_MESSAGES_MEMFD wasn't set. No login messages today.") │ │ │ │ │ - return │ │ │ │ │ - │ │ │ │ │ - logger.debug("Trying to read login messages from fd %s", fdstr) │ │ │ │ │ - try: │ │ │ │ │ - with open(int(fdstr), 'r') as login_messages: │ │ │ │ │ - login_messages.seek(0) │ │ │ │ │ - self.messages = login_messages.read() │ │ │ │ │ - except (ValueError, OSError, UnicodeDecodeError) as exc: │ │ │ │ │ - # ValueError - the envvar wasn't an int │ │ │ │ │ - # OSError - the fd wasn't open, or other read failure │ │ │ │ │ - # UnicodeDecodeError - didn't contain utf-8 │ │ │ │ │ - # For all of these, we simply failed to get the message. │ │ │ │ │ - logger.debug("Reading login messages failed: %s", exc) │ │ │ │ │ - else: │ │ │ │ │ - logger.debug("Successfully read login messages: %s", self.messages) │ │ │ │ │ - │ │ │ │ │ - @bus.Interface.Method(out_types=['s']) │ │ │ │ │ - def get(self): │ │ │ │ │ - return self.messages or '{}' │ │ │ │ │ - │ │ │ │ │ - @bus.Interface.Method(out_types=[]) │ │ │ │ │ - def dismiss(self): │ │ │ │ │ - self.messages = None │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class cockpit_Machines(bus.Object): │ │ │ │ │ - path: Path │ │ │ │ │ - watch: pathwatch.PathWatch │ │ │ │ │ - pending_notify: Optional[asyncio.Handle] │ │ │ │ │ - │ │ │ │ │ - # D-Bus implementation │ │ │ │ │ - machines = bus.Interface.Property('a{sa{sv}}') │ │ │ │ │ - │ │ │ │ │ - @machines.getter │ │ │ │ │ - def get_machines(self) -> Dict[str, Dict[str, Variant]]: │ │ │ │ │ - results: Dict[str, Dict[str, Variant]] = {} │ │ │ │ │ - │ │ │ │ │ - for filename in glob.glob(f'{self.path}/*.json'): │ │ │ │ │ - with open(filename) as fp: │ │ │ │ │ - try: │ │ │ │ │ - contents = json.load(fp) │ │ │ │ │ - except json.JSONDecodeError: │ │ │ │ │ - logger.warning('Invalid JSON in file %s. Ignoring.', filename) │ │ │ │ │ - continue │ │ │ │ │ - # merge │ │ │ │ │ - for hostname, attrs in contents.items(): │ │ │ │ │ - results[hostname] = {key: Variant(value) for key, value in attrs.items()} │ │ │ │ │ - │ │ │ │ │ - return results │ │ │ │ │ - │ │ │ │ │ - @bus.Interface.Method(in_types=['s', 's', 'a{sv}']) │ │ │ │ │ - def update(self, filename: str, hostname: str, attrs: Dict[str, Variant]) -> None: │ │ │ │ │ - try: │ │ │ │ │ - with self.path.joinpath(filename).open() as fp: │ │ │ │ │ - contents = json.load(fp) │ │ │ │ │ - except json.JSONDecodeError as exc: │ │ │ │ │ - # Refuse to replace corrupted file │ │ │ │ │ - raise bus.BusError('cockpit.Machines.Error', f'File {filename} is in invalid format: {exc}.') from exc │ │ │ │ │ - except FileNotFoundError: │ │ │ │ │ - # But an empty file is an expected case │ │ │ │ │ - contents = {} │ │ │ │ │ - │ │ │ │ │ - contents.setdefault(hostname, {}).update({key: value.value for key, value in attrs.items()}) │ │ │ │ │ - │ │ │ │ │ - self.path.mkdir(parents=True, exist_ok=True) │ │ │ │ │ - with open(self.path.joinpath(filename), 'w') as fp: │ │ │ │ │ - json.dump(contents, fp, indent=2) │ │ │ │ │ - │ │ │ │ │ - def notify(self): │ │ │ │ │ - def _notify_now(): │ │ │ │ │ - self.properties_changed('cockpit.Machines', {}, ['Machines']) │ │ │ │ │ - self.pending_notify = None │ │ │ │ │ - │ │ │ │ │ - # avoid a flurry of update notifications │ │ │ │ │ - if self.pending_notify is None: │ │ │ │ │ - self.pending_notify = asyncio.get_running_loop().call_later(1.0, _notify_now) │ │ │ │ │ - │ │ │ │ │ - # inotify events │ │ │ │ │ - def do_inotify_event(self, mask: inotify.Event, cookie: int, name: Optional[str]) -> None: │ │ │ │ │ - self.notify() │ │ │ │ │ - │ │ │ │ │ - def do_identity_changed(self, fd: Optional[int], errno: Optional[int]) -> None: │ │ │ │ │ - self.notify() │ │ │ │ │ - │ │ │ │ │ - def __init__(self): │ │ │ │ │ - self.path = config.lookup_config('machines.d') │ │ │ │ │ - │ │ │ │ │ - # ignore the first callback │ │ │ │ │ - self.pending_notify = ... │ │ │ │ │ - self.watch = pathwatch.PathWatch(str(self.path), self) │ │ │ │ │ - self.pending_notify = None │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class cockpit_User(bus.Object): │ │ │ │ │ - name = bus.Interface.Property('s', value='') │ │ │ │ │ - full = bus.Interface.Property('s', value='') │ │ │ │ │ - id = bus.Interface.Property('i', value=0) │ │ │ │ │ - home = bus.Interface.Property('s', value='') │ │ │ │ │ - shell = bus.Interface.Property('s', value='') │ │ │ │ │ - groups = bus.Interface.Property('as', value=[]) │ │ │ │ │ - │ │ │ │ │ - def __init__(self): │ │ │ │ │ - user = pwd.getpwuid(os.getuid()) │ │ │ │ │ - self.name = user.pw_name │ │ │ │ │ - self.full = user.pw_gecos │ │ │ │ │ - self.id = user.pw_uid │ │ │ │ │ - self.home = user.pw_dir │ │ │ │ │ - self.shell = user.pw_shell │ │ │ │ │ - self.groups = [gr.gr_name for gr in grp.getgrall() if user.pw_name in gr.gr_mem] │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -EXPORTS = [ │ │ │ │ │ - ('/LoginMessages', cockpit_LoginMessages), │ │ │ │ │ - ('/machines', cockpit_Machines), │ │ │ │ │ - ('/user', cockpit_User), │ │ │ │ │ -] │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/beipack.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import logging │ │ │ │ │ -import lzma │ │ │ │ │ -from typing import List, Sequence, Tuple │ │ │ │ │ - │ │ │ │ │ -from cockpit._vendor import ferny │ │ │ │ │ -from cockpit._vendor.bei import beipack │ │ │ │ │ - │ │ │ │ │ -from .data import read_cockpit_data_file │ │ │ │ │ -from .peer import Peer, PeerError │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def get_bridge_beipack_xz() -> Tuple[str, bytes]: │ │ │ │ │ - try: │ │ │ │ │ - bridge_beipack_xz = read_cockpit_data_file('cockpit-bridge.beipack.xz') │ │ │ │ │ - logger.debug('Got pre-built cockpit-bridge.beipack.xz') │ │ │ │ │ - except FileNotFoundError: │ │ │ │ │ - logger.debug('Pre-built cockpit-bridge.beipack.xz; building our own.') │ │ │ │ │ - # beipack ourselves │ │ │ │ │ - cockpit_contents = beipack.collect_module('cockpit', recursive=True) │ │ │ │ │ - bridge_beipack = beipack.pack(cockpit_contents, entrypoint='cockpit.bridge:main', args='beipack=True') │ │ │ │ │ - bridge_beipack_xz = lzma.compress(bridge_beipack.encode()) │ │ │ │ │ - logger.debug(' ... done!') │ │ │ │ │ - │ │ │ │ │ - return 'cockpit/data/cockpit-bridge.beipack.xz', bridge_beipack_xz │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class BridgeBeibootHelper(ferny.InteractionHandler): │ │ │ │ │ - # ferny.InteractionHandler ClassVar │ │ │ │ │ - commands = ['beiboot.provide', 'beiboot.exc'] │ │ │ │ │ - │ │ │ │ │ - peer: Peer │ │ │ │ │ - payload: bytes │ │ │ │ │ - steps: Sequence[Tuple[str, Sequence[object]]] │ │ │ │ │ - │ │ │ │ │ - def __init__(self, peer: Peer, args: Sequence[str] = ()) -> None: │ │ │ │ │ - filename, payload = get_bridge_beipack_xz() │ │ │ │ │ - │ │ │ │ │ - self.peer = peer │ │ │ │ │ - self.payload = payload │ │ │ │ │ - self.steps = (('boot_xz', (filename, len(payload), tuple(args))),) │ │ │ │ │ - │ │ │ │ │ - async def run_command(self, command: str, args: Tuple, fds: List[int], stderr: str) -> None: │ │ │ │ │ - logger.debug('Got ferny request %s %s %s %s', command, args, fds, stderr) │ │ │ │ │ - if command == 'beiboot.provide': │ │ │ │ │ - try: │ │ │ │ │ - size, = args │ │ │ │ │ - assert size == len(self.payload) │ │ │ │ │ - except (AssertionError, ValueError) as exc: │ │ │ │ │ - raise PeerError('internal-error', message=f'ferny interaction error {exc!s}') from exc │ │ │ │ │ - │ │ │ │ │ - assert self.peer.transport is not None │ │ │ │ │ - logger.debug('Writing %d bytes of payload', len(self.payload)) │ │ │ │ │ - self.peer.transport.write(self.payload) │ │ │ │ │ - elif command == 'beiboot.exc': │ │ │ │ │ - raise PeerError('internal-error', message=f'Remote exception: {args[0]}') │ │ │ │ │ - else: │ │ │ │ │ - raise PeerError('internal-error', message=f'Unexpected ferny interaction command {command}') │ │ │ │ │ -''', │ │ │ │ │ 'cockpit/peer.py': r'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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 │ │ │ │ │ @@ -4074,15 +2801,15 @@ │ │ │ │ │ for rule in old_rules: │ │ │ │ │ rule.shutdown() │ │ │ │ │ │ │ │ │ │ def shutdown(self): │ │ │ │ │ for rule in self.rules: │ │ │ │ │ rule.shutdown() │ │ │ │ │ '''.encode('utf-8'), │ │ │ │ │ - 'cockpit/remote.py': r'''# This file is part of Cockpit. │ │ │ │ │ + 'cockpit/internal_endpoints.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ @@ -4091,231 +2818,155 @@ │ │ │ │ │ # 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import getpass │ │ │ │ │ +import asyncio │ │ │ │ │ +import glob │ │ │ │ │ +import grp │ │ │ │ │ +import json │ │ │ │ │ import logging │ │ │ │ │ -import re │ │ │ │ │ -import socket │ │ │ │ │ -from typing import Dict, List, Optional, Tuple │ │ │ │ │ +import os │ │ │ │ │ +import pwd │ │ │ │ │ +from pathlib import Path │ │ │ │ │ +from typing import Dict, Optional │ │ │ │ │ │ │ │ │ │ -from cockpit._vendor import ferny │ │ │ │ │ +from cockpit._vendor.systemd_ctypes import Variant, bus, inotify, pathwatch │ │ │ │ │ │ │ │ │ │ -from .jsonutil import JsonObject, JsonValue, get_str, get_str_or_none │ │ │ │ │ -from .peer import Peer, PeerError │ │ │ │ │ -from .router import Router, RoutingRule │ │ │ │ │ +from . import config │ │ │ │ │ │ │ │ │ │ logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class PasswordResponder(ferny.AskpassHandler): │ │ │ │ │ - PASSPHRASE_RE = re.compile(r"Enter passphrase for key '(.*)': ") │ │ │ │ │ - │ │ │ │ │ - password: Optional[str] │ │ │ │ │ - │ │ │ │ │ - hostkeys_seen: List[Tuple[str, str, str, str, str]] │ │ │ │ │ - error_message: Optional[str] │ │ │ │ │ - password_attempts: int │ │ │ │ │ - │ │ │ │ │ - def __init__(self, password: Optional[str]): │ │ │ │ │ - self.password = password │ │ │ │ │ - │ │ │ │ │ - self.hostkeys_seen = [] │ │ │ │ │ - self.error_message = None │ │ │ │ │ - self.password_attempts = 0 │ │ │ │ │ - │ │ │ │ │ - async def do_hostkey(self, reason: str, host: str, algorithm: str, key: str, fingerprint: str) -> bool: │ │ │ │ │ - self.hostkeys_seen.append((reason, host, algorithm, key, fingerprint)) │ │ │ │ │ - return False │ │ │ │ │ - │ │ │ │ │ - async def do_askpass(self, messages: str, prompt: str, hint: str) -> Optional[str]: │ │ │ │ │ - logger.debug('Got askpass(%s): %s', hint, prompt) │ │ │ │ │ - │ │ │ │ │ - match = PasswordResponder.PASSPHRASE_RE.fullmatch(prompt) │ │ │ │ │ - if match is not None: │ │ │ │ │ - # We never unlock private keys — we rather need to throw a │ │ │ │ │ - # specially-formatted error message which will cause the frontend │ │ │ │ │ - # to load the named key into the agent for us and try again. │ │ │ │ │ - path = match.group(1) │ │ │ │ │ - logger.debug("This is a passphrase request for %s, but we don't do those. Abort.", path) │ │ │ │ │ - self.error_message = f'locked identity: {path}' │ │ │ │ │ - return None │ │ │ │ │ - │ │ │ │ │ - assert self.password is not None │ │ │ │ │ - assert self.password_attempts == 0 │ │ │ │ │ - self.password_attempts += 1 │ │ │ │ │ - return self.password │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class SshPeer(Peer): │ │ │ │ │ - session: Optional[ferny.Session] = None │ │ │ │ │ - host: str │ │ │ │ │ - user: Optional[str] │ │ │ │ │ - password: Optional[str] │ │ │ │ │ - private: bool │ │ │ │ │ - │ │ │ │ │ - async def do_connect_transport(self) -> None: │ │ │ │ │ - assert self.session is not None │ │ │ │ │ - logger.debug('Starting ssh session user=%s, host=%s, private=%s', self.user, self.host, self.private) │ │ │ │ │ - │ │ │ │ │ - basename, colon, portstr = self.host.rpartition(':') │ │ │ │ │ - if colon and portstr.isdigit(): │ │ │ │ │ - host = basename │ │ │ │ │ - port = int(portstr) │ │ │ │ │ - else: │ │ │ │ │ - host = self.host │ │ │ │ │ - port = None │ │ │ │ │ - │ │ │ │ │ - responder = PasswordResponder(self.password) │ │ │ │ │ - options = {"StrictHostKeyChecking": 'yes'} │ │ │ │ │ +class cockpit_LoginMessages(bus.Object): │ │ │ │ │ + messages: Optional[str] = None │ │ │ │ │ │ │ │ │ │ - if self.password is not None: │ │ │ │ │ - options.update(NumberOfPasswordPrompts='1') │ │ │ │ │ - else: │ │ │ │ │ - options.update(PasswordAuthentication="no", KbdInteractiveAuthentication="no") │ │ │ │ │ + def __init__(self): │ │ │ │ │ + fdstr = os.environ.pop('COCKPIT_LOGIN_MESSAGES_MEMFD', None) │ │ │ │ │ + if fdstr is None: │ │ │ │ │ + logger.debug("COCKPIT_LOGIN_MESSAGES_MEMFD wasn't set. No login messages today.") │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ + logger.debug("Trying to read login messages from fd %s", fdstr) │ │ │ │ │ try: │ │ │ │ │ - await self.session.connect(host, login_name=self.user, port=port, │ │ │ │ │ - handle_host_key=self.private, options=options, │ │ │ │ │ - interaction_responder=responder) │ │ │ │ │ - except (OSError, socket.gaierror) as exc: │ │ │ │ │ - logger.debug('connecting to host %s failed: %s', host, exc) │ │ │ │ │ - raise PeerError('no-host', error='no-host', message=str(exc)) from exc │ │ │ │ │ - │ │ │ │ │ - except ferny.SshHostKeyError as exc: │ │ │ │ │ - if responder.hostkeys_seen: │ │ │ │ │ - # If we saw a hostkey then we can issue a detailed error message │ │ │ │ │ - # containing the key that would need to be accepted. That will │ │ │ │ │ - # cause the front-end to present a dialog. │ │ │ │ │ - _reason, host, algorithm, key, fingerprint = responder.hostkeys_seen[0] │ │ │ │ │ - error_args = {'host-key': f'{host} {algorithm} {key}', 'host-fingerprint': fingerprint} │ │ │ │ │ - else: │ │ │ │ │ - error_args = {} │ │ │ │ │ - │ │ │ │ │ - if isinstance(exc, ferny.SshChangedHostKeyError): │ │ │ │ │ - error = 'invalid-hostkey' │ │ │ │ │ - elif self.private: │ │ │ │ │ - error = 'unknown-hostkey' │ │ │ │ │ - else: │ │ │ │ │ - # non-private session case. throw a generic error. │ │ │ │ │ - error = 'unknown-host' │ │ │ │ │ - │ │ │ │ │ - logger.debug('SshPeer got a %s %s; private %s, seen hostkeys %r; raising %s with extra args %r', │ │ │ │ │ - type(exc), exc, self.private, responder.hostkeys_seen, error, error_args) │ │ │ │ │ - raise PeerError(error, error_args, error=error, auth_method_results={}) from exc │ │ │ │ │ - │ │ │ │ │ - except ferny.SshAuthenticationError as exc: │ │ │ │ │ - logger.debug('authentication to host %s failed: %s', host, exc) │ │ │ │ │ - │ │ │ │ │ - results = {method: 'not-provided' for method in exc.methods} │ │ │ │ │ - if 'password' in results and self.password is not None: │ │ │ │ │ - if responder.password_attempts == 0: │ │ │ │ │ - results['password'] = 'not-tried' │ │ │ │ │ - else: │ │ │ │ │ - results['password'] = 'denied' │ │ │ │ │ - │ │ │ │ │ - raise PeerError('authentication-failed', │ │ │ │ │ - error=responder.error_message or 'authentication-failed', │ │ │ │ │ - auth_method_results=results) from exc │ │ │ │ │ + with open(int(fdstr), 'r') as login_messages: │ │ │ │ │ + login_messages.seek(0) │ │ │ │ │ + self.messages = login_messages.read() │ │ │ │ │ + except (ValueError, OSError, UnicodeDecodeError) as exc: │ │ │ │ │ + # ValueError - the envvar wasn't an int │ │ │ │ │ + # OSError - the fd wasn't open, or other read failure │ │ │ │ │ + # UnicodeDecodeError - didn't contain utf-8 │ │ │ │ │ + # For all of these, we simply failed to get the message. │ │ │ │ │ + logger.debug("Reading login messages failed: %s", exc) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug("Successfully read login messages: %s", self.messages) │ │ │ │ │ │ │ │ │ │ - except ferny.SshError as exc: │ │ │ │ │ - logger.debug('unknown failure connecting to host %s: %s', host, exc) │ │ │ │ │ - raise PeerError('internal-error', message=str(exc)) from exc │ │ │ │ │ + @bus.Interface.Method(out_types=['s']) │ │ │ │ │ + def get(self): │ │ │ │ │ + return self.messages or '{}' │ │ │ │ │ │ │ │ │ │ - args = self.session.wrap_subprocess_args(['cockpit-bridge']) │ │ │ │ │ - await self.spawn(args, []) │ │ │ │ │ + @bus.Interface.Method(out_types=[]) │ │ │ │ │ + def dismiss(self): │ │ │ │ │ + self.messages = None │ │ │ │ │ │ │ │ │ │ - def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None: │ │ │ │ │ - if host == self.host: │ │ │ │ │ - self.close() │ │ │ │ │ - elif host is None: │ │ │ │ │ - super().do_kill(host, group, message) │ │ │ │ │ │ │ │ │ │ - def do_authorize(self, message: JsonObject) -> None: │ │ │ │ │ - if get_str(message, 'challenge').startswith('plain1:'): │ │ │ │ │ - cookie = get_str(message, 'cookie') │ │ │ │ │ - self.write_control(command='authorize', cookie=cookie, response=self.password or '') │ │ │ │ │ - self.password = None # once is enough... │ │ │ │ │ +class cockpit_Machines(bus.Object): │ │ │ │ │ + path: Path │ │ │ │ │ + watch: pathwatch.PathWatch │ │ │ │ │ + pending_notify: Optional[asyncio.Handle] │ │ │ │ │ │ │ │ │ │ - def do_superuser_init_done(self) -> None: │ │ │ │ │ - self.password = None │ │ │ │ │ + # D-Bus implementation │ │ │ │ │ + machines = bus.Interface.Property('a{sa{sv}}') │ │ │ │ │ │ │ │ │ │ - def __init__(self, router: Router, host: str, user: Optional[str], options: JsonObject, *, private: bool) -> None: │ │ │ │ │ - super().__init__(router) │ │ │ │ │ - self.host = host │ │ │ │ │ - self.user = user │ │ │ │ │ - self.password = get_str(options, 'password', None) │ │ │ │ │ - self.private = private │ │ │ │ │ + @machines.getter │ │ │ │ │ + def get_machines(self) -> Dict[str, Dict[str, Variant]]: │ │ │ │ │ + results: Dict[str, Dict[str, Variant]] = {} │ │ │ │ │ │ │ │ │ │ - self.session = ferny.Session() │ │ │ │ │ + for filename in glob.glob(f'{self.path}/*.json'): │ │ │ │ │ + with open(filename) as fp: │ │ │ │ │ + try: │ │ │ │ │ + contents = json.load(fp) │ │ │ │ │ + except json.JSONDecodeError: │ │ │ │ │ + logger.warning('Invalid JSON in file %s. Ignoring.', filename) │ │ │ │ │ + continue │ │ │ │ │ + # merge │ │ │ │ │ + for hostname, attrs in contents.items(): │ │ │ │ │ + results[hostname] = {key: Variant(value) for key, value in attrs.items()} │ │ │ │ │ │ │ │ │ │ - superuser: JsonValue │ │ │ │ │ - init_superuser = get_str_or_none(options, 'init-superuser', None) │ │ │ │ │ - if init_superuser in (None, 'none'): │ │ │ │ │ - superuser = False │ │ │ │ │ - else: │ │ │ │ │ - superuser = {'id': init_superuser} │ │ │ │ │ + return results │ │ │ │ │ │ │ │ │ │ - self.start_in_background(init_host=host, superuser=superuser) │ │ │ │ │ + @bus.Interface.Method(in_types=['s', 's', 'a{sv}']) │ │ │ │ │ + def update(self, filename: str, hostname: str, attrs: Dict[str, Variant]) -> None: │ │ │ │ │ + try: │ │ │ │ │ + with self.path.joinpath(filename).open() as fp: │ │ │ │ │ + contents = json.load(fp) │ │ │ │ │ + except json.JSONDecodeError as exc: │ │ │ │ │ + # Refuse to replace corrupted file │ │ │ │ │ + raise bus.BusError('cockpit.Machines.Error', f'File {filename} is in invalid format: {exc}.') from exc │ │ │ │ │ + except FileNotFoundError: │ │ │ │ │ + # But an empty file is an expected case │ │ │ │ │ + contents = {} │ │ │ │ │ │ │ │ │ │ + contents.setdefault(hostname, {}).update({key: value.value for key, value in attrs.items()}) │ │ │ │ │ │ │ │ │ │ -class HostRoutingRule(RoutingRule): │ │ │ │ │ - remotes: Dict[Tuple[str, Optional[str], Optional[str]], Peer] │ │ │ │ │ + self.path.mkdir(parents=True, exist_ok=True) │ │ │ │ │ + with open(self.path.joinpath(filename), 'w') as fp: │ │ │ │ │ + json.dump(contents, fp, indent=2) │ │ │ │ │ │ │ │ │ │ - def __init__(self, router): │ │ │ │ │ - super().__init__(router) │ │ │ │ │ - self.remotes = {} │ │ │ │ │ + def notify(self): │ │ │ │ │ + def _notify_now(): │ │ │ │ │ + self.properties_changed('cockpit.Machines', {}, ['Machines']) │ │ │ │ │ + self.pending_notify = None │ │ │ │ │ │ │ │ │ │ - def apply_rule(self, options: JsonObject) -> Optional[Peer]: │ │ │ │ │ - assert self.router is not None │ │ │ │ │ - assert self.router.init_host is not None │ │ │ │ │ + # avoid a flurry of update notifications │ │ │ │ │ + if self.pending_notify is None: │ │ │ │ │ + self.pending_notify = asyncio.get_running_loop().call_later(1.0, _notify_now) │ │ │ │ │ │ │ │ │ │ - host = get_str(options, 'host', self.router.init_host) │ │ │ │ │ - if host == self.router.init_host: │ │ │ │ │ - return None │ │ │ │ │ + # inotify events │ │ │ │ │ + def do_inotify_event(self, mask: inotify.Event, cookie: int, name: Optional[str]) -> None: │ │ │ │ │ + self.notify() │ │ │ │ │ │ │ │ │ │ - user = get_str(options, 'user', None) │ │ │ │ │ - # HACK: the front-end relies on this for tracking connections without an explicit user name; │ │ │ │ │ - # the user will then be determined by SSH (`User` in the config or the current user) │ │ │ │ │ - # See cockpit_router_normalize_host_params() in src/bridge/cockpitrouter.c │ │ │ │ │ - if user == getpass.getuser(): │ │ │ │ │ - user = None │ │ │ │ │ - if not user: │ │ │ │ │ - user_from_host, _, _ = host.rpartition('@') │ │ │ │ │ - user = user_from_host or None # avoid '' │ │ │ │ │ + def do_identity_changed(self, fd: Optional[int], errno: Optional[int]) -> None: │ │ │ │ │ + self.notify() │ │ │ │ │ │ │ │ │ │ - if get_str(options, 'session', None) == 'private': │ │ │ │ │ - nonce = get_str(options, 'channel') │ │ │ │ │ - else: │ │ │ │ │ - nonce = None │ │ │ │ │ + def __init__(self): │ │ │ │ │ + self.path = config.lookup_config('machines.d') │ │ │ │ │ │ │ │ │ │ - assert isinstance(host, str) │ │ │ │ │ - assert user is None or isinstance(user, str) │ │ │ │ │ - assert nonce is None or isinstance(nonce, str) │ │ │ │ │ + # ignore the first callback │ │ │ │ │ + self.pending_notify = ... │ │ │ │ │ + self.watch = pathwatch.PathWatch(str(self.path), self) │ │ │ │ │ + self.pending_notify = None │ │ │ │ │ │ │ │ │ │ - key = host, user, nonce │ │ │ │ │ │ │ │ │ │ - logger.debug('Request for channel %s is remote.', options) │ │ │ │ │ - logger.debug('key=%s', key) │ │ │ │ │ +class cockpit_User(bus.Object): │ │ │ │ │ + name = bus.Interface.Property('s', value='') │ │ │ │ │ + full = bus.Interface.Property('s', value='') │ │ │ │ │ + id = bus.Interface.Property('i', value=0) │ │ │ │ │ + home = bus.Interface.Property('s', value='') │ │ │ │ │ + shell = bus.Interface.Property('s', value='') │ │ │ │ │ + groups = bus.Interface.Property('as', value=[]) │ │ │ │ │ │ │ │ │ │ - if key not in self.remotes: │ │ │ │ │ - logger.debug('%s is not among the existing remotes %s. Opening a new connection.', key, self.remotes) │ │ │ │ │ - peer = SshPeer(self.router, host, user, options, private=nonce is not None) │ │ │ │ │ - peer.add_done_callback(lambda: self.remotes.__delitem__(key)) │ │ │ │ │ - self.remotes[key] = peer │ │ │ │ │ + def __init__(self): │ │ │ │ │ + user = pwd.getpwuid(os.getuid()) │ │ │ │ │ + self.name = user.pw_name │ │ │ │ │ + self.full = user.pw_gecos │ │ │ │ │ + self.id = user.pw_uid │ │ │ │ │ + self.home = user.pw_dir │ │ │ │ │ + self.shell = user.pw_shell │ │ │ │ │ + self.groups = [gr.gr_name for gr in grp.getgrall() if user.pw_name in gr.gr_mem] │ │ │ │ │ │ │ │ │ │ - return self.remotes[key] │ │ │ │ │ │ │ │ │ │ - def shutdown(self): │ │ │ │ │ - for peer in set(self.remotes.values()): │ │ │ │ │ - peer.close() │ │ │ │ │ -'''.encode('utf-8'), │ │ │ │ │ +EXPORTS = [ │ │ │ │ │ + ('/LoginMessages', cockpit_LoginMessages), │ │ │ │ │ + ('/machines', cockpit_Machines), │ │ │ │ │ + ('/user', cockpit_User), │ │ │ │ │ +] │ │ │ │ │ +''', │ │ │ │ │ 'cockpit/packages.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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 │ │ │ │ │ @@ -4889,1981 +3540,2843 @@ │ │ │ │ │ elif filename == 'manifests.js': │ │ │ │ │ return self.load_manifests_js(headers) │ │ │ │ │ elif filename == 'manifests.json': │ │ │ │ │ return self.load_manifests_json() │ │ │ │ │ else: │ │ │ │ │ raise KeyError │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/__init__.py': br'''''', │ │ │ │ │ - 'cockpit/_vendor/bei/beiboot.py': br"""# beiboot - Remote bootloader for Python │ │ │ │ │ + 'cockpit/channel.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ +# along with this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import argparse │ │ │ │ │ import asyncio │ │ │ │ │ -import os │ │ │ │ │ -import shlex │ │ │ │ │ -import subprocess │ │ │ │ │ -import sys │ │ │ │ │ -import threading │ │ │ │ │ -from typing import IO, List, Sequence, Tuple │ │ │ │ │ +import json │ │ │ │ │ +import logging │ │ │ │ │ +from typing import BinaryIO, ClassVar, Dict, Generator, List, Optional, Sequence, Set, Tuple, Type │ │ │ │ │ │ │ │ │ │ -from .bootloader import make_bootloader │ │ │ │ │ +from .jsonutil import JsonError, JsonObject, JsonValue, create_object, get_bool, get_str │ │ │ │ │ +from .protocol import CockpitProblem │ │ │ │ │ +from .router import Endpoint, Router, RoutingRule │ │ │ │ │ │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ -def get_python_command(local: bool = False, │ │ │ │ │ - tty: bool = False, │ │ │ │ │ - sh: bool = False) -> Sequence[str]: │ │ │ │ │ - interpreter = sys.executable if local else 'python3' │ │ │ │ │ - command: Sequence[str] │ │ │ │ │ │ │ │ │ │ - if tty: │ │ │ │ │ - command = (interpreter, '-iq') │ │ │ │ │ - else: │ │ │ │ │ - command = ( │ │ │ │ │ - interpreter, '-ic', │ │ │ │ │ - # https://github.com/python/cpython/issues/93139 │ │ │ │ │ - '''" - beiboot - "; import sys; sys.ps1 = ''; sys.ps2 = '';''' │ │ │ │ │ - ) │ │ │ │ │ +class ChannelRoutingRule(RoutingRule): │ │ │ │ │ + table: Dict[str, List[Type['Channel']]] │ │ │ │ │ │ │ │ │ │ - if sh: │ │ │ │ │ - command = (' '.join(shlex.quote(arg) for arg in command),) │ │ │ │ │ + def __init__(self, router: Router, channel_types: List[Type['Channel']]): │ │ │ │ │ + super().__init__(router) │ │ │ │ │ + self.table = {} │ │ │ │ │ │ │ │ │ │ - return command │ │ │ │ │ + # Sort the channels into buckets by payload type │ │ │ │ │ + for cls in channel_types: │ │ │ │ │ + entry = self.table.setdefault(cls.payload, []) │ │ │ │ │ + entry.append(cls) │ │ │ │ │ │ │ │ │ │ + # Within each bucket, sort the channels so those with more │ │ │ │ │ + # restrictions are considered first. │ │ │ │ │ + for entry in self.table.values(): │ │ │ │ │ + entry.sort(key=lambda cls: len(cls.restrictions), reverse=True) │ │ │ │ │ │ │ │ │ │ -def get_ssh_command(*args: str, tty: bool = False) -> Sequence[str]: │ │ │ │ │ - return ('ssh', │ │ │ │ │ - *(['-t'] if tty else ()), │ │ │ │ │ - *args, │ │ │ │ │ - *get_python_command(tty=tty, sh=True)) │ │ │ │ │ + def check_restrictions(self, restrictions: Sequence[Tuple[str, object]], options: JsonObject) -> bool: │ │ │ │ │ + for key, expected_value in restrictions: │ │ │ │ │ + our_value = options.get(key) │ │ │ │ │ │ │ │ │ │ + # If the match rule specifies that a value must be present and │ │ │ │ │ + # we don't have it, then fail. │ │ │ │ │ + if our_value is None: │ │ │ │ │ + return False │ │ │ │ │ │ │ │ │ │ -def get_container_command(*args: str, tty: bool = False) -> Sequence[str]: │ │ │ │ │ - return ('podman', 'exec', '--interactive', │ │ │ │ │ - *(['--tty'] if tty else ()), │ │ │ │ │ - *args, │ │ │ │ │ - *get_python_command(tty=tty)) │ │ │ │ │ + # If the match rule specified a specific expected value, and │ │ │ │ │ + # our value doesn't match it, then fail. │ │ │ │ │ + if expected_value is not None and our_value != expected_value: │ │ │ │ │ + return False │ │ │ │ │ │ │ │ │ │ + # Everything checked out │ │ │ │ │ + return True │ │ │ │ │ │ │ │ │ │ -def get_command(*args: str, tty: bool = False, sh: bool = False) -> Sequence[str]: │ │ │ │ │ - return (*args, *get_python_command(local=True, tty=tty, sh=sh)) │ │ │ │ │ + def apply_rule(self, options: JsonObject) -> Optional['Channel']: │ │ │ │ │ + assert self.router is not None │ │ │ │ │ │ │ │ │ │ + payload = options.get('payload') │ │ │ │ │ + if not isinstance(payload, str): │ │ │ │ │ + return None │ │ │ │ │ │ │ │ │ │ -def splice_in_thread(src: int, dst: IO[bytes]) -> None: │ │ │ │ │ - def _thread() -> None: │ │ │ │ │ - # os.splice() only in Python 3.10 │ │ │ │ │ - with dst: │ │ │ │ │ - block_size = 1 << 20 │ │ │ │ │ - while True: │ │ │ │ │ - data = os.read(src, block_size) │ │ │ │ │ - if not data: │ │ │ │ │ - break │ │ │ │ │ - dst.write(data) │ │ │ │ │ - dst.flush() │ │ │ │ │ + for cls in self.table.get(payload, []): │ │ │ │ │ + if self.check_restrictions(cls.restrictions, options): │ │ │ │ │ + return cls(self.router) │ │ │ │ │ + else: │ │ │ │ │ + return None │ │ │ │ │ │ │ │ │ │ - threading.Thread(target=_thread, daemon=True).start() │ │ │ │ │ + def shutdown(self): │ │ │ │ │ + pass # we don't hold any state │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -def send_and_splice(command: Sequence[str], script: bytes) -> None: │ │ │ │ │ - with subprocess.Popen(command, stdin=subprocess.PIPE) as proc: │ │ │ │ │ - assert proc.stdin is not None │ │ │ │ │ - proc.stdin.write(script) │ │ │ │ │ +class ChannelError(CockpitProblem): │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ - splice_in_thread(0, proc.stdin) │ │ │ │ │ - sys.exit(proc.wait()) │ │ │ │ │ │ │ │ │ │ +class Channel(Endpoint): │ │ │ │ │ + # Values borrowed from C implementation │ │ │ │ │ + BLOCK_SIZE = 16 * 1024 │ │ │ │ │ + SEND_WINDOW = 2 * 1024 * 1024 │ │ │ │ │ │ │ │ │ │ -def send_xz_and_splice(command: Sequence[str], script: bytes) -> None: │ │ │ │ │ - import ferny │ │ │ │ │ + # Flow control book-keeping │ │ │ │ │ + _send_pings: bool = False │ │ │ │ │ + _out_sequence: int = 0 │ │ │ │ │ + _out_window: int = SEND_WINDOW │ │ │ │ │ │ │ │ │ │ - class Responder(ferny.InteractionResponder): │ │ │ │ │ - async def do_custom_command(self, │ │ │ │ │ - command: str, │ │ │ │ │ - args: Tuple, │ │ │ │ │ - fds: List[int], │ │ │ │ │ - stderr: str) -> None: │ │ │ │ │ - assert proc.stdin is not None │ │ │ │ │ - if command == 'beiboot.provide': │ │ │ │ │ - proc.stdin.write(script) │ │ │ │ │ - proc.stdin.flush() │ │ │ │ │ + # Task management │ │ │ │ │ + _tasks: Set[asyncio.Task] │ │ │ │ │ + _close_args: Optional[JsonObject] = None │ │ │ │ │ │ │ │ │ │ - agent = ferny.InteractionAgent(Responder()) │ │ │ │ │ - with subprocess.Popen(command, stdin=subprocess.PIPE, stderr=agent) as proc: │ │ │ │ │ - assert proc.stdin is not None │ │ │ │ │ - proc.stdin.write(make_bootloader([ │ │ │ │ │ - ('boot_xz', ('script.py.xz', len(script), [], True)), │ │ │ │ │ - ], gadgets=ferny.BEIBOOT_GADGETS).encode()) │ │ │ │ │ - proc.stdin.flush() │ │ │ │ │ + # Must be filled in by the channel implementation │ │ │ │ │ + payload: ClassVar[str] │ │ │ │ │ + restrictions: ClassVar[Sequence[Tuple[str, object]]] = () │ │ │ │ │ │ │ │ │ │ - asyncio.run(agent.communicate()) │ │ │ │ │ - splice_in_thread(0, proc.stdin) │ │ │ │ │ - sys.exit(proc.wait()) │ │ │ │ │ + # These get filled in from .do_open() │ │ │ │ │ + channel = '' │ │ │ │ │ + group = '' │ │ │ │ │ │ │ │ │ │ + # input │ │ │ │ │ + def do_control(self, command, message): │ │ │ │ │ + # Break the various different kinds of control messages out into the │ │ │ │ │ + # things that our subclass may be interested in handling. We drop the │ │ │ │ │ + # 'message' field for handlers that don't need it. │ │ │ │ │ + if command == 'open': │ │ │ │ │ + self._tasks = set() │ │ │ │ │ + self.channel = message['channel'] │ │ │ │ │ + if get_bool(message, 'flow-control', default=False): │ │ │ │ │ + self._send_pings = True │ │ │ │ │ + self.group = get_str(message, 'group', 'default') │ │ │ │ │ + self.freeze_endpoint() │ │ │ │ │ + self.do_open(message) │ │ │ │ │ + elif command == 'ready': │ │ │ │ │ + self.do_ready() │ │ │ │ │ + elif command == 'done': │ │ │ │ │ + self.do_done() │ │ │ │ │ + elif command == 'close': │ │ │ │ │ + self.do_close() │ │ │ │ │ + elif command == 'ping': │ │ │ │ │ + self.do_ping(message) │ │ │ │ │ + elif command == 'pong': │ │ │ │ │ + self.do_pong(message) │ │ │ │ │ + elif command == 'options': │ │ │ │ │ + self.do_options(message) │ │ │ │ │ │ │ │ │ │ -def main() -> None: │ │ │ │ │ - parser = argparse.ArgumentParser() │ │ │ │ │ - parser.add_argument('--sh', action='store_true', │ │ │ │ │ - help='Pass Python interpreter command as shell-script') │ │ │ │ │ - parser.add_argument('--xz', help="the xz to run remotely") │ │ │ │ │ - parser.add_argument('--script', │ │ │ │ │ - help="the script to run remotely (must be repl-friendly)") │ │ │ │ │ - parser.add_argument('command', nargs='*') │ │ │ │ │ + def do_channel_control(self, channel: str, command: str, message: JsonObject) -> None: │ │ │ │ │ + # Already closing? Ignore. │ │ │ │ │ + if self._close_args is not None: │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - args = parser.parse_args() │ │ │ │ │ - tty = not args.script and os.isatty(0) │ │ │ │ │ + # Catch errors and turn them into close messages │ │ │ │ │ + try: │ │ │ │ │ + try: │ │ │ │ │ + self.do_control(command, message) │ │ │ │ │ + except JsonError as exc: │ │ │ │ │ + raise ChannelError('protocol-error', message=str(exc)) from exc │ │ │ │ │ + except ChannelError as exc: │ │ │ │ │ + self.close(exc.attrs) │ │ │ │ │ │ │ │ │ │ - if args.command == []: │ │ │ │ │ - command = get_python_command(tty=tty) │ │ │ │ │ - elif args.command[0] == 'ssh': │ │ │ │ │ - command = get_ssh_command(*args.command[1:], tty=tty) │ │ │ │ │ - elif args.command[0] == 'container': │ │ │ │ │ - command = get_container_command(*args.command[1:], tty=tty) │ │ │ │ │ - else: │ │ │ │ │ - command = get_command(*args.command, tty=tty, sh=args.sh) │ │ │ │ │ + def do_kill(self, host: 'str | None', group: 'str | None', _message: JsonObject) -> None: │ │ │ │ │ + # Already closing? Ignore. │ │ │ │ │ + if self._close_args is not None: │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - if args.script: │ │ │ │ │ - with open(args.script, 'rb') as file: │ │ │ │ │ - script = file.read() │ │ │ │ │ + if host is not None: │ │ │ │ │ + return │ │ │ │ │ + if group is not None and self.group != group: │ │ │ │ │ + return │ │ │ │ │ + self.do_close() │ │ │ │ │ │ │ │ │ │ - send_and_splice(command, script) │ │ │ │ │ + # At least this one really ought to be implemented... │ │ │ │ │ + def do_open(self, options: JsonObject) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - elif args.xz: │ │ │ │ │ - with open(args.xz, 'rb') as file: │ │ │ │ │ - script = file.read() │ │ │ │ │ + # ... but many subclasses may reasonably want to ignore some of these. │ │ │ │ │ + def do_ready(self) -> None: │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ - send_xz_and_splice(command, script) │ │ │ │ │ + def do_done(self) -> None: │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ - else: │ │ │ │ │ - # If we're streaming from stdin then this is a lot easier... │ │ │ │ │ - os.execlp(command[0], *command) │ │ │ │ │ + def do_close(self) -> None: │ │ │ │ │ + self.close() │ │ │ │ │ │ │ │ │ │ - # Otherwise, "full strength" │ │ │ │ │ + def do_options(self, message: JsonObject) -> None: │ │ │ │ │ + raise ChannelError('not-supported', message='This channel does not implement "options"') │ │ │ │ │ │ │ │ │ │ -if __name__ == '__main__': │ │ │ │ │ - main() │ │ │ │ │ -""", │ │ │ │ │ - 'cockpit/_vendor/bei/bootloader.py': br'''# beiboot - Remote bootloader for Python │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ + # 'reasonable' default, overridden in other channels for receive-side flow control │ │ │ │ │ + def do_ping(self, message: JsonObject) -> None: │ │ │ │ │ + self.send_pong(message) │ │ │ │ │ │ │ │ │ │ -import textwrap │ │ │ │ │ -from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple │ │ │ │ │ + def do_channel_data(self, channel: str, data: bytes) -> None: │ │ │ │ │ + # Already closing? Ignore. │ │ │ │ │ + if self._close_args is not None: │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ -GADGETS = { │ │ │ │ │ - "_frame": r""" │ │ │ │ │ - import sys │ │ │ │ │ - import traceback │ │ │ │ │ + # Catch errors and turn them into close messages │ │ │ │ │ try: │ │ │ │ │ - ... │ │ │ │ │ - except SystemExit: │ │ │ │ │ - raise │ │ │ │ │ - except BaseException: │ │ │ │ │ - command('beiboot.exc', traceback.format_exc()) │ │ │ │ │ - sys.exit(37) │ │ │ │ │ - """, │ │ │ │ │ - "try_exec": r""" │ │ │ │ │ - import contextlib │ │ │ │ │ - import os │ │ │ │ │ - def try_exec(argv): │ │ │ │ │ - with contextlib.suppress(OSError): │ │ │ │ │ - os.execvp(argv[0], argv) │ │ │ │ │ - """, │ │ │ │ │ - "boot_xz": r""" │ │ │ │ │ - import lzma │ │ │ │ │ - import sys │ │ │ │ │ - def boot_xz(filename, size, args=[], send_end=False): │ │ │ │ │ - command('beiboot.provide', size) │ │ │ │ │ - src_xz = sys.stdin.buffer.read(size) │ │ │ │ │ - src = lzma.decompress(src_xz) │ │ │ │ │ - sys.argv = [filename, *args] │ │ │ │ │ - if send_end: │ │ │ │ │ - end() │ │ │ │ │ - exec(src, { │ │ │ │ │ - '__name__': '__main__', │ │ │ │ │ - '__self_source__': src_xz, │ │ │ │ │ - '__file__': filename}) │ │ │ │ │ - sys.exit() │ │ │ │ │ - """, │ │ │ │ │ -} │ │ │ │ │ + self.do_data(data) │ │ │ │ │ + except ChannelError as exc: │ │ │ │ │ + self.close(exc.attrs) │ │ │ │ │ │ │ │ │ │ + def do_data(self, _data: bytes) -> None: │ │ │ │ │ + # By default, channels can't receive data. │ │ │ │ │ + self.close() │ │ │ │ │ │ │ │ │ │ -def split_code(code: str, imports: Set[str]) -> Iterable[Tuple[str, str]]: │ │ │ │ │ - for line in textwrap.dedent(code).splitlines(): │ │ │ │ │ - text = line.lstrip(" ") │ │ │ │ │ - if text.startswith("import "): │ │ │ │ │ - imports.add(text) │ │ │ │ │ - elif text: │ │ │ │ │ - spaces = len(line) - len(text) │ │ │ │ │ - assert (spaces % 4) == 0 │ │ │ │ │ - yield "\t" * (spaces // 4), text │ │ │ │ │ + # output │ │ │ │ │ + def ready(self, **kwargs: JsonValue) -> None: │ │ │ │ │ + self.thaw_endpoint() │ │ │ │ │ + self.send_control(command='ready', **kwargs) │ │ │ │ │ │ │ │ │ │ + def done(self) -> None: │ │ │ │ │ + self.send_control(command='done') │ │ │ │ │ │ │ │ │ │ -def yield_body(user_gadgets: Dict[str, str], │ │ │ │ │ - steps: Sequence[Tuple[str, Sequence[object]]], │ │ │ │ │ - imports: Set[str]) -> Iterable[Tuple[str, str]]: │ │ │ │ │ - # Allow the caller to override our gadgets, but keep the original │ │ │ │ │ - # variable for use in the next step. │ │ │ │ │ - gadgets = dict(GADGETS, **user_gadgets) │ │ │ │ │ + # tasks and close management │ │ │ │ │ + def is_closing(self) -> bool: │ │ │ │ │ + return self._close_args is not None │ │ │ │ │ │ │ │ │ │ - # First emit the gadgets. Emit all gadgets provided by the caller, │ │ │ │ │ - # plus any referred to by the caller's list of steps. │ │ │ │ │ - provided_gadgets = set(user_gadgets) │ │ │ │ │ - step_gadgets = {name for name, _args in steps} │ │ │ │ │ - for name in provided_gadgets | step_gadgets: │ │ │ │ │ - yield from split_code(gadgets[name], imports) │ │ │ │ │ + def _close_now(self) -> None: │ │ │ │ │ + self.shutdown_endpoint(self._close_args) │ │ │ │ │ │ │ │ │ │ - # Yield functions mentioned in steps from the caller │ │ │ │ │ - for name, args in steps: │ │ │ │ │ - yield '', name + repr(tuple(args)) │ │ │ │ │ + def _task_done(self, task): │ │ │ │ │ + # Strictly speaking, we should read the result and check for exceptions but: │ │ │ │ │ + # - exceptions bubbling out of the task are programming errors │ │ │ │ │ + # - the only thing we'd do with it anyway, is to show it │ │ │ │ │ + # - Python already does that with its "Task exception was never retrieved" messages │ │ │ │ │ + self._tasks.remove(task) │ │ │ │ │ + if self._close_args is not None and not self._tasks: │ │ │ │ │ + self._close_now() │ │ │ │ │ │ │ │ │ │ + def create_task(self, coroutine, name=None): │ │ │ │ │ + """Create a task associated with the channel. │ │ │ │ │ │ │ │ │ │ -def make_bootloader(steps: Sequence[Tuple[str, Sequence[object]]], │ │ │ │ │ - gadgets: Optional[Dict[str, str]] = None) -> str: │ │ │ │ │ - imports: Set[str] = set() │ │ │ │ │ - lines: List[str] = [] │ │ │ │ │ + All tasks must exit before the channel can close. You may not create │ │ │ │ │ + new tasks after calling .close(). │ │ │ │ │ + """ │ │ │ │ │ + assert self._close_args is None │ │ │ │ │ + task = asyncio.create_task(coroutine) │ │ │ │ │ + self._tasks.add(task) │ │ │ │ │ + task.add_done_callback(self._task_done) │ │ │ │ │ + return task │ │ │ │ │ │ │ │ │ │ - for frame_spaces, frame_text in split_code(GADGETS["_frame"], imports): │ │ │ │ │ - if frame_text == "...": │ │ │ │ │ - for spaces, text in yield_body(gadgets or {}, steps, imports): │ │ │ │ │ - lines.append(frame_spaces + spaces + text) │ │ │ │ │ - else: │ │ │ │ │ - lines.append(frame_spaces + frame_text) │ │ │ │ │ + def close(self, close_args: 'JsonObject | None' = None) -> None: │ │ │ │ │ + """Requests the channel to be closed. │ │ │ │ │ │ │ │ │ │ - return "".join(f"{line}\n" for line in [*imports, *lines]) + "\n" │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/bei/__init__.py': br'''''', │ │ │ │ │ - 'cockpit/_vendor/bei/tmpfs.py': br'''import os │ │ │ │ │ -import subprocess │ │ │ │ │ -import sys │ │ │ │ │ -import tempfile │ │ │ │ │ + After you call this method, you won't get anymore `.do_*()` calls. │ │ │ │ │ │ │ │ │ │ + This will wait for any running tasks to complete before sending the │ │ │ │ │ + close message. │ │ │ │ │ + """ │ │ │ │ │ + if self._close_args is not None: │ │ │ │ │ + # close already requested │ │ │ │ │ + return │ │ │ │ │ + self._close_args = close_args or {} │ │ │ │ │ + if not self._tasks: │ │ │ │ │ + self._close_now() │ │ │ │ │ │ │ │ │ │ -def main(*command: str) -> None: │ │ │ │ │ - with tempfile.TemporaryDirectory() as tmpdir: │ │ │ │ │ - os.chdir(tmpdir) │ │ │ │ │ + def send_data(self, data: bytes) -> bool: │ │ │ │ │ + """Send data and handle book-keeping for flow control. │ │ │ │ │ │ │ │ │ │ - for key, value in __loader__.get_contents().items(): │ │ │ │ │ - if key.startswith('tmpfs/'): │ │ │ │ │ - subdir = os.path.dirname(key) │ │ │ │ │ - os.makedirs(subdir, exist_ok=True) │ │ │ │ │ - with open(key, 'wb') as fp: │ │ │ │ │ - fp.write(value) │ │ │ │ │ + The flow control is "advisory". The data is sent immediately, even if │ │ │ │ │ + it's larger than the window. In general you should try to send packets │ │ │ │ │ + which are approximately Channel.BLOCK_SIZE in size. │ │ │ │ │ │ │ │ │ │ - os.chdir('tmpfs') │ │ │ │ │ + Returns True if there is still room in the window, or False if you │ │ │ │ │ + should stop writing for now. In that case, `.do_resume_send()` will be │ │ │ │ │ + called later when there is more room. │ │ │ │ │ + """ │ │ │ │ │ + self.send_channel_data(self.channel, data) │ │ │ │ │ │ │ │ │ │ - result = subprocess.run(command, check=False) │ │ │ │ │ - sys.exit(result.returncode) │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/bei/beipack.py': br'''# beipack - Remote bootloader for Python │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ + if self._send_pings: │ │ │ │ │ + out_sequence = self._out_sequence + len(data) │ │ │ │ │ + if self._out_sequence // Channel.BLOCK_SIZE != out_sequence // Channel.BLOCK_SIZE: │ │ │ │ │ + self.send_control(command='ping', sequence=out_sequence) │ │ │ │ │ + self._out_sequence = out_sequence │ │ │ │ │ │ │ │ │ │ -import argparse │ │ │ │ │ -import binascii │ │ │ │ │ -import lzma │ │ │ │ │ -import os │ │ │ │ │ -import sys │ │ │ │ │ -import tempfile │ │ │ │ │ -import zipfile │ │ │ │ │ -from typing import Dict, Iterable, List, Optional, Set, Tuple │ │ │ │ │ + return self._out_sequence < self._out_window │ │ │ │ │ │ │ │ │ │ -from .data import read_data_file │ │ │ │ │ + def do_pong(self, message): │ │ │ │ │ + if not self._send_pings: # huh? │ │ │ │ │ + logger.warning("Got wild pong on channel %s", self.channel) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ + self._out_window = message['sequence'] + Channel.SEND_WINDOW │ │ │ │ │ + if self._out_sequence < self._out_window: │ │ │ │ │ + self.do_resume_send() │ │ │ │ │ │ │ │ │ │ -def escape_string(data: str) -> str: │ │ │ │ │ - # Avoid mentioning ' ' ' literally, to make our own packing a bit prettier │ │ │ │ │ - triplequote = "'" * 3 │ │ │ │ │ - if triplequote not in data: │ │ │ │ │ - return "r" + triplequote + data + triplequote │ │ │ │ │ - if '"""' not in data: │ │ │ │ │ - return 'r"""' + data + '"""' │ │ │ │ │ - return repr(data) │ │ │ │ │ + def do_resume_send(self) -> None: │ │ │ │ │ + """Called to indicate that the channel may start sending again.""" │ │ │ │ │ + # change to `raise NotImplementedError` after everyone implements it │ │ │ │ │ │ │ │ │ │ + json_encoder: ClassVar[json.JSONEncoder] = json.JSONEncoder(indent=2) │ │ │ │ │ │ │ │ │ │ -def ascii_bytes_repr(data: bytes) -> str: │ │ │ │ │ - return 'b' + escape_string(data.decode('ascii')) │ │ │ │ │ + def send_json(self, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> bool: │ │ │ │ │ + pretty = self.json_encoder.encode(create_object(_msg, kwargs)) + '\n' │ │ │ │ │ + return self.send_data(pretty.encode()) │ │ │ │ │ │ │ │ │ │ + def send_control(self, command: str, **kwargs: JsonValue) -> None: │ │ │ │ │ + self.send_channel_control(self.channel, command, None, **kwargs) │ │ │ │ │ │ │ │ │ │ -def utf8_bytes_repr(data: bytes) -> str: │ │ │ │ │ - return escape_string(data.decode('utf-8')) + ".encode('utf-8')" │ │ │ │ │ + def send_pong(self, message: JsonObject) -> None: │ │ │ │ │ + self.send_channel_control(self.channel, 'pong', message) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -def base64_bytes_repr(data: bytes, imports: Set[str]) -> str: │ │ │ │ │ - # base85 is smaller, but base64 is in C, and ~20x faster. │ │ │ │ │ - # when compressing with `xz -e` the size difference is marginal. │ │ │ │ │ - imports.add('from binascii import a2b_base64') │ │ │ │ │ - encoded = binascii.b2a_base64(data).decode('ascii').strip() │ │ │ │ │ - return f'a2b_base64("{encoded}")' │ │ │ │ │ +class ProtocolChannel(Channel, asyncio.Protocol): │ │ │ │ │ + """A channel subclass that implements the asyncio Protocol interface. │ │ │ │ │ │ │ │ │ │ + In effect, data sent to this channel will be written to the connected │ │ │ │ │ + transport, and vice-versa. Flow control is supported. │ │ │ │ │ │ │ │ │ │ -def bytes_repr(data: bytes, imports: Set[str]) -> str: │ │ │ │ │ - # Strategy: │ │ │ │ │ - # if the file is ascii, encode it directly as bytes │ │ │ │ │ - # otherwise, if it's UTF-8, use a unicode string and encode │ │ │ │ │ - # otherwise, base64 │ │ │ │ │ + The default implementation of the .do_open() method calls the │ │ │ │ │ + .create_transport() abstract method. This method should return a transport │ │ │ │ │ + which will be used for communication on the channel. │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - return ascii_bytes_repr(data) │ │ │ │ │ - except UnicodeDecodeError: │ │ │ │ │ - # it's not ascii │ │ │ │ │ - pass │ │ │ │ │ + Otherwise, if the subclass implements .do_open() itself, it is responsible │ │ │ │ │ + for setting up the connection and ensuring that .connection_made() is called. │ │ │ │ │ + """ │ │ │ │ │ + _transport: Optional[asyncio.Transport] │ │ │ │ │ + _loop: Optional[asyncio.AbstractEventLoop] │ │ │ │ │ + _send_pongs: bool = True │ │ │ │ │ + _last_ping: Optional[JsonObject] = None │ │ │ │ │ + _create_transport_task = None │ │ │ │ │ │ │ │ │ │ - # utf-8 │ │ │ │ │ - try: │ │ │ │ │ - return utf8_bytes_repr(data) │ │ │ │ │ - except UnicodeDecodeError: │ │ │ │ │ - # it's not utf-8 │ │ │ │ │ - pass │ │ │ │ │ + # read-side EOF handling │ │ │ │ │ + _close_on_eof: bool = False │ │ │ │ │ + _eof: bool = False │ │ │ │ │ │ │ │ │ │ - return base64_bytes_repr(data, imports) │ │ │ │ │ + async def create_transport(self, loop: asyncio.AbstractEventLoop, options: JsonObject) -> asyncio.Transport: │ │ │ │ │ + """Creates the transport for this channel, according to options. │ │ │ │ │ │ │ │ │ │ + The event loop for the transport is passed to the function. The │ │ │ │ │ + protocol for the transport is the channel object, itself (self). │ │ │ │ │ │ │ │ │ │ -def dict_repr(contents: Dict[str, bytes], imports: Set[str]) -> str: │ │ │ │ │ - return ('{\n' + │ │ │ │ │ - ''.join(f' {repr(k)}: {bytes_repr(v, imports)},\n' │ │ │ │ │ - for k, v in contents.items()) + │ │ │ │ │ - '}') │ │ │ │ │ + This needs to be implemented by the subclass. │ │ │ │ │ + """ │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ + def do_open(self, options: JsonObject) -> None: │ │ │ │ │ + loop = asyncio.get_running_loop() │ │ │ │ │ + self._create_transport_task = asyncio.create_task(self.create_transport(loop, options)) │ │ │ │ │ + self._create_transport_task.add_done_callback(self.create_transport_done) │ │ │ │ │ │ │ │ │ │ -def pack(contents: Dict[str, bytes], │ │ │ │ │ - entrypoint: Optional[str] = None, │ │ │ │ │ - args: str = '') -> str: │ │ │ │ │ - """Creates a beipack with the given `contents`. │ │ │ │ │ + def create_transport_done(self, task: 'asyncio.Task[asyncio.Transport]') -> None: │ │ │ │ │ + assert task is self._create_transport_task │ │ │ │ │ + self._create_transport_task = None │ │ │ │ │ + try: │ │ │ │ │ + transport = task.result() │ │ │ │ │ + except ChannelError as exc: │ │ │ │ │ + self.close(exc.attrs) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - If `entrypoint` is given, it should be an entry point which is run as the │ │ │ │ │ - "main" function. It is given in the `package.module:func format` such that │ │ │ │ │ - the following code is emitted: │ │ │ │ │ + self.connection_made(transport) │ │ │ │ │ + self.ready() │ │ │ │ │ │ │ │ │ │ - from package.module import func as main │ │ │ │ │ - main() │ │ │ │ │ + def connection_made(self, transport: asyncio.BaseTransport) -> None: │ │ │ │ │ + assert isinstance(transport, asyncio.Transport) │ │ │ │ │ + self._transport = transport │ │ │ │ │ │ │ │ │ │ - Additionally, if `args` is given, it is written verbatim between the parens │ │ │ │ │ - of the call to main (ie: it should already be in Python syntax). │ │ │ │ │ - """ │ │ │ │ │ + def _get_close_args(self) -> JsonObject: │ │ │ │ │ + return {} │ │ │ │ │ │ │ │ │ │ - loader = read_data_file('beipack_loader.py') │ │ │ │ │ - lines = [line for line in loader.splitlines() if line] │ │ │ │ │ - lines.append('') │ │ │ │ │ + def connection_lost(self, exc: Optional[Exception]) -> None: │ │ │ │ │ + self.close(self._get_close_args()) │ │ │ │ │ │ │ │ │ │ - imports = {'import sys'} │ │ │ │ │ - contents_txt = dict_repr(contents, imports) │ │ │ │ │ - lines.extend(imports) │ │ │ │ │ - lines.append(f'sys.meta_path.insert(0, BeipackLoader({contents_txt}))') │ │ │ │ │ + def do_data(self, data: bytes) -> None: │ │ │ │ │ + assert self._transport is not None │ │ │ │ │ + self._transport.write(data) │ │ │ │ │ │ │ │ │ │ - if entrypoint: │ │ │ │ │ - package, main = entrypoint.split(':') │ │ │ │ │ - lines.append(f'from {package} import {main} as main') │ │ │ │ │ - lines.append(f'main({args})') │ │ │ │ │ + def do_done(self) -> None: │ │ │ │ │ + assert self._transport is not None │ │ │ │ │ + if self._transport.can_write_eof(): │ │ │ │ │ + self._transport.write_eof() │ │ │ │ │ │ │ │ │ │ - return ''.join(f'{line}\n' for line in lines) │ │ │ │ │ + def do_close(self) -> None: │ │ │ │ │ + if self._transport is not None: │ │ │ │ │ + self._transport.close() │ │ │ │ │ │ │ │ │ │ + def data_received(self, data: bytes) -> None: │ │ │ │ │ + assert self._transport is not None │ │ │ │ │ + if not self.send_data(data): │ │ │ │ │ + self._transport.pause_reading() │ │ │ │ │ │ │ │ │ │ -def collect_contents(filenames: List[str], │ │ │ │ │ - relative_to: Optional[str] = None) -> Dict[str, bytes]: │ │ │ │ │ - contents: Dict[str, bytes] = {} │ │ │ │ │ + def do_resume_send(self) -> None: │ │ │ │ │ + assert self._transport is not None │ │ │ │ │ + self._transport.resume_reading() │ │ │ │ │ │ │ │ │ │ - for filename in filenames: │ │ │ │ │ - with open(filename, 'rb') as file: │ │ │ │ │ - contents[os.path.relpath(filename, start=relative_to)] = file.read() │ │ │ │ │ + def close_on_eof(self) -> None: │ │ │ │ │ + """Mark the channel to be closed on EOF. │ │ │ │ │ │ │ │ │ │ - return contents │ │ │ │ │ + Normally, ProtocolChannel tries to keep the channel half-open after │ │ │ │ │ + receiving EOF from the transport. This instructs that the channel │ │ │ │ │ + should be closed on EOF. │ │ │ │ │ │ │ │ │ │ + If EOF was already received, then calling this function will close the │ │ │ │ │ + channel immediately. │ │ │ │ │ │ │ │ │ │ -def collect_module(name: str, *, recursive: bool) -> Dict[str, bytes]: │ │ │ │ │ - import importlib.resources │ │ │ │ │ - from importlib.resources.abc import Traversable │ │ │ │ │ + If you don't call this function, you are responsible for closing the │ │ │ │ │ + channel yourself. │ │ │ │ │ + """ │ │ │ │ │ + self._close_on_eof = True │ │ │ │ │ + if self._eof: │ │ │ │ │ + assert self._transport is not None │ │ │ │ │ + self._transport.close() │ │ │ │ │ │ │ │ │ │ - def walk(path: str, entry: Traversable) -> Iterable[Tuple[str, bytes]]: │ │ │ │ │ - for item in entry.iterdir(): │ │ │ │ │ - itemname = f'{path}/{item.name}' │ │ │ │ │ - if item.is_file(): │ │ │ │ │ - yield itemname, item.read_bytes() │ │ │ │ │ - elif recursive and item.name != '__pycache__': │ │ │ │ │ - yield from walk(itemname, item) │ │ │ │ │ + def eof_received(self) -> bool: │ │ │ │ │ + self._eof = True │ │ │ │ │ + self.done() │ │ │ │ │ + return not self._close_on_eof │ │ │ │ │ │ │ │ │ │ - return dict(walk(name.replace('.', '/'), importlib.resources.files(name))) │ │ │ │ │ + # Channel receive-side flow control │ │ │ │ │ + def do_ping(self, message): │ │ │ │ │ + if self._send_pongs: │ │ │ │ │ + self.send_pong(message) │ │ │ │ │ + else: │ │ │ │ │ + # we'll have to pong later │ │ │ │ │ + self._last_ping = message │ │ │ │ │ │ │ │ │ │ + def pause_writing(self) -> None: │ │ │ │ │ + # We can't actually stop writing, but we can stop replying to pings │ │ │ │ │ + self._send_pongs = False │ │ │ │ │ │ │ │ │ │ -def collect_zip(filename: str) -> Dict[str, bytes]: │ │ │ │ │ - contents = {} │ │ │ │ │ + def resume_writing(self) -> None: │ │ │ │ │ + self._send_pongs = True │ │ │ │ │ + if self._last_ping is not None: │ │ │ │ │ + self.send_pong(self._last_ping) │ │ │ │ │ + self._last_ping = None │ │ │ │ │ │ │ │ │ │ - with zipfile.ZipFile(filename) as file: │ │ │ │ │ - for entry in file.filelist: │ │ │ │ │ - if '.dist-info/' in entry.filename: │ │ │ │ │ - continue │ │ │ │ │ - contents[entry.filename] = file.read(entry) │ │ │ │ │ │ │ │ │ │ - return contents │ │ │ │ │ +class AsyncChannel(Channel): │ │ │ │ │ + """A subclass for async/await-style implementation of channels, with flow control │ │ │ │ │ │ │ │ │ │ + This subclass provides asynchronous `read()` and `write()` calls for │ │ │ │ │ + subclasses, with familiar semantics. `write()` doesn't buffer, so the │ │ │ │ │ + `done()` method on the base channel class can be used in a way similar to │ │ │ │ │ + `shutdown()`. A high-level `sendfile()` method is available to send the │ │ │ │ │ + entire contents of a binary-mode file-like object. │ │ │ │ │ │ │ │ │ │ -def collect_pep517(path: str) -> Dict[str, bytes]: │ │ │ │ │ - with tempfile.TemporaryDirectory() as tmpdir: │ │ │ │ │ - import build │ │ │ │ │ - builder = build.ProjectBuilder(path) │ │ │ │ │ - wheel = builder.build('wheel', tmpdir) │ │ │ │ │ - return collect_zip(wheel) │ │ │ │ │ + The subclass must provide an async `run()` function, which will be spawned │ │ │ │ │ + as a task. │ │ │ │ │ │ │ │ │ │ + On the receiving side, the channel will respond to flow control pings to │ │ │ │ │ + indicate that it has received the data, but only after it has been consumed │ │ │ │ │ + by `read()`. │ │ │ │ │ │ │ │ │ │ -def main() -> None: │ │ │ │ │ - parser = argparse.ArgumentParser() │ │ │ │ │ - parser.add_argument('--python', '-p', │ │ │ │ │ - help="add a #!python3 interpreter line using the given path") │ │ │ │ │ - parser.add_argument('--xz', '-J', action='store_true', │ │ │ │ │ - help="compress the output with `xz`") │ │ │ │ │ - parser.add_argument('--topdir', │ │ │ │ │ - help="toplevel directory (paths are stored relative to this)") │ │ │ │ │ - parser.add_argument('--output', '-o', │ │ │ │ │ - help="write output to a file (default: stdout)") │ │ │ │ │ - parser.add_argument('--main', '-m', metavar='MODULE:FUNC', │ │ │ │ │ - help="use FUNC from MODULE as the main function") │ │ │ │ │ - parser.add_argument('--main-args', metavar='ARGS', │ │ │ │ │ - help="arguments to main() in Python syntax", default='') │ │ │ │ │ - parser.add_argument('--module', action='append', default=[], │ │ │ │ │ - help="collect installed modules (recursively)") │ │ │ │ │ - parser.add_argument('--zip', '-z', action='append', default=[], │ │ │ │ │ - help="include files from a zipfile (or wheel)") │ │ │ │ │ - parser.add_argument('--build', metavar='DIR', action='append', default=[], │ │ │ │ │ - help="PEP-517 from a given source directory") │ │ │ │ │ - parser.add_argument('files', nargs='*', │ │ │ │ │ - help="files to include in the beipack") │ │ │ │ │ - args = parser.parse_args() │ │ │ │ │ + On the sending side, write() will block if the channel backs up. │ │ │ │ │ + """ │ │ │ │ │ │ │ │ │ │ - contents = collect_contents(args.files, relative_to=args.topdir) │ │ │ │ │ + # Receive-side flow control: intermix pings and data in the queue and reply │ │ │ │ │ + # to pings as we dequeue them. This is a buffer: since we need to handle │ │ │ │ │ + # do_data() without blocking, we have no choice. │ │ │ │ │ + receive_queue = None │ │ │ │ │ │ │ │ │ │ - for file in args.zip: │ │ │ │ │ - contents.update(collect_zip(file)) │ │ │ │ │ + # Send-side flow control │ │ │ │ │ + write_waiter = None │ │ │ │ │ │ │ │ │ │ - for name in args.module: │ │ │ │ │ - contents.update(collect_module(name, recursive=True)) │ │ │ │ │ + async def run(self, options): │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - for path in args.build: │ │ │ │ │ - contents.update(collect_pep517(path)) │ │ │ │ │ + async def run_wrapper(self, options): │ │ │ │ │ + try: │ │ │ │ │ + await self.run(options) │ │ │ │ │ + self.close() │ │ │ │ │ + except ChannelError as exc: │ │ │ │ │ + self.close(exc.attrs) │ │ │ │ │ │ │ │ │ │ - result = pack(contents, args.main, args.main_args).encode('utf-8') │ │ │ │ │ + async def read(self): │ │ │ │ │ + while True: │ │ │ │ │ + item = await self.receive_queue.get() │ │ │ │ │ + if isinstance(item, bytes): │ │ │ │ │ + return item │ │ │ │ │ + self.send_pong(item) │ │ │ │ │ │ │ │ │ │ - if args.python: │ │ │ │ │ - result = b'#!' + args.python.encode('ascii') + b'\n' + result │ │ │ │ │ + async def write(self, data): │ │ │ │ │ + if not self.send_data(data): │ │ │ │ │ + self.write_waiter = asyncio.get_running_loop().create_future() │ │ │ │ │ + await self.write_waiter │ │ │ │ │ │ │ │ │ │ - if args.xz: │ │ │ │ │ - result = lzma.compress(result, preset=lzma.PRESET_EXTREME) │ │ │ │ │ + async def sendfile(self, stream: BinaryIO) -> None: │ │ │ │ │ + loop = asyncio.get_running_loop() │ │ │ │ │ + with stream: │ │ │ │ │ + while True: │ │ │ │ │ + data = await loop.run_in_executor(None, stream.read, Channel.BLOCK_SIZE) │ │ │ │ │ + if data == b'': │ │ │ │ │ + break │ │ │ │ │ + await self.write(data) │ │ │ │ │ │ │ │ │ │ - if args.output: │ │ │ │ │ - with open(args.output, 'wb') as file: │ │ │ │ │ - file.write(result) │ │ │ │ │ - else: │ │ │ │ │ - if args.xz and os.isatty(1): │ │ │ │ │ - sys.exit('refusing to write compressed output to a terminal') │ │ │ │ │ - sys.stdout.buffer.write(result) │ │ │ │ │ + self.done() │ │ │ │ │ │ │ │ │ │ + def do_resume_send(self) -> None: │ │ │ │ │ + if self.write_waiter is not None: │ │ │ │ │ + self.write_waiter.set_result(None) │ │ │ │ │ + self.write_waiter = None │ │ │ │ │ │ │ │ │ │ -if __name__ == '__main__': │ │ │ │ │ - main() │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/bei/spawn.py': br'''"""Helper to create a beipack to spawn a command with files in a tmpdir""" │ │ │ │ │ + def do_open(self, options): │ │ │ │ │ + self.receive_queue = asyncio.Queue() │ │ │ │ │ + self.create_task(self.run_wrapper(options), name=f'{self.__class__.__name__}.run_wrapper({options})') │ │ │ │ │ │ │ │ │ │ -import argparse │ │ │ │ │ -import os │ │ │ │ │ -import sys │ │ │ │ │ + def do_done(self): │ │ │ │ │ + self.receive_queue.put_nowait(b'') │ │ │ │ │ │ │ │ │ │ -from . import pack, tmpfs │ │ │ │ │ + def do_close(self): │ │ │ │ │ + # we might have already sent EOF for done, but two EOFs won't hurt anyone │ │ │ │ │ + self.receive_queue.put_nowait(b'') │ │ │ │ │ │ │ │ │ │ + def do_ping(self, message): │ │ │ │ │ + self.receive_queue.put_nowait(message) │ │ │ │ │ │ │ │ │ │ -def main() -> None: │ │ │ │ │ - parser = argparse.ArgumentParser() │ │ │ │ │ - parser.add_argument('--file', '-f', action='append') │ │ │ │ │ - parser.add_argument('command', nargs='+', help='The command to execute') │ │ │ │ │ - args = parser.parse_args() │ │ │ │ │ + def do_data(self, data): │ │ │ │ │ + if not isinstance(data, bytes): │ │ │ │ │ + # this will persist past this callback, so make sure we take our │ │ │ │ │ + # own copy, in case this was a memoryview into a bytearray. │ │ │ │ │ + data = bytes(data) │ │ │ │ │ │ │ │ │ │ - contents = { │ │ │ │ │ - '_beitmpfs.py': tmpfs.__spec__.loader.get_data(tmpfs.__spec__.origin) │ │ │ │ │ - } │ │ │ │ │ + self.receive_queue.put_nowait(data) │ │ │ │ │ │ │ │ │ │ - if args.file is not None: │ │ │ │ │ - files = args.file │ │ │ │ │ - else: │ │ │ │ │ - file = args.command[-1] │ │ │ │ │ - files = [file] │ │ │ │ │ - args.command[-1] = './' + os.path.basename(file) │ │ │ │ │ │ │ │ │ │ - for filename in files: │ │ │ │ │ - with open(filename, 'rb') as file: │ │ │ │ │ - basename = os.path.basename(filename) │ │ │ │ │ - contents[f'tmpfs/{basename}'] = file.read() │ │ │ │ │ +class GeneratorChannel(Channel): │ │ │ │ │ + """A trivial Channel subclass for sending data from a generator with flow control. │ │ │ │ │ │ │ │ │ │ - script = pack.pack(contents, '_beitmpfs:main', '*' + repr(args.command)) │ │ │ │ │ - sys.stdout.write(script) │ │ │ │ │ + Calls the .do_yield_data() generator with the options from the open message │ │ │ │ │ + and sends the data which it yields. If the generator returns a value it │ │ │ │ │ + will be used for the close message. │ │ │ │ │ + """ │ │ │ │ │ + DataGenerator = Generator[bytes, None, Optional[JsonObject]] │ │ │ │ │ + __generator: DataGenerator │ │ │ │ │ │ │ │ │ │ + def do_yield_data(self, options: JsonObject) -> 'DataGenerator': │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ -if __name__ == '__main__': │ │ │ │ │ - main() │ │ │ │ │ + def do_open(self, options: JsonObject) -> None: │ │ │ │ │ + self.__generator = self.do_yield_data(options) │ │ │ │ │ + self.do_resume_send() │ │ │ │ │ + │ │ │ │ │ + def do_resume_send(self) -> None: │ │ │ │ │ + try: │ │ │ │ │ + while self.send_data(next(self.__generator)): │ │ │ │ │ + pass │ │ │ │ │ + except StopIteration as stop: │ │ │ │ │ + self.done() │ │ │ │ │ + self.close(stop.value) │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/bei/data/__init__.py': br'''import sys │ │ │ │ │ + 'cockpit/__init__.py': br'''from ._version import __version__ # noqa: F401 │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/protocol.py': br'''# This file is part of Cockpit. │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -if sys.version_info >= (3, 9): │ │ │ │ │ - import importlib.abc │ │ │ │ │ - import importlib.resources │ │ │ │ │ +import asyncio │ │ │ │ │ +import json │ │ │ │ │ +import logging │ │ │ │ │ +import uuid │ │ │ │ │ │ │ │ │ │ - def read_data_file(filename: str) -> str: │ │ │ │ │ - return (importlib.resources.files(__name__) / filename).read_text() │ │ │ │ │ -else: │ │ │ │ │ - def read_data_file(filename: str) -> str: │ │ │ │ │ - loader = __loader__ # type: ignore[name-defined] │ │ │ │ │ - data = loader.get_data(__file__.replace('__init__.py', filename)) │ │ │ │ │ - return data.decode('utf-8') │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/bei/data/beipack_loader.py': br'''# beipack https://github.com/allisonkarlitskaya/beipack │ │ │ │ │ +from .jsonutil import JsonError, JsonObject, JsonValue, create_object, get_int, get_str, typechecked │ │ │ │ │ │ │ │ │ │ -import importlib.abc │ │ │ │ │ -import importlib.util │ │ │ │ │ -import io │ │ │ │ │ -import sys │ │ │ │ │ -from types import ModuleType │ │ │ │ │ -from typing import BinaryIO, Dict, Iterator, Optional, Sequence │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class BeipackLoader(importlib.abc.SourceLoader, importlib.abc.MetaPathFinder): │ │ │ │ │ - if sys.version_info >= (3, 11): │ │ │ │ │ - from importlib.resources.abc import ResourceReader as AbstractResourceReader │ │ │ │ │ - else: │ │ │ │ │ - AbstractResourceReader = object │ │ │ │ │ +class CockpitProblem(Exception): │ │ │ │ │ + """A type of exception that carries a problem code and a message. │ │ │ │ │ │ │ │ │ │ - class ResourceReader(AbstractResourceReader): │ │ │ │ │ - def __init__(self, contents: Dict[str, bytes], filename: str) -> None: │ │ │ │ │ - self._contents = contents │ │ │ │ │ - self._dir = f'{filename}/' │ │ │ │ │ + Depending on the scope, this is used to handle shutting down: │ │ │ │ │ │ │ │ │ │ - def is_resource(self, resource: str) -> bool: │ │ │ │ │ - return f'{self._dir}{resource}' in self._contents │ │ │ │ │ + - an individual channel (sends problem code in the close message) │ │ │ │ │ + - peer connections (sends problem code in close message for each open channel) │ │ │ │ │ + - the main stdio interaction with the bridge │ │ │ │ │ │ │ │ │ │ - def open_resource(self, resource: str) -> BinaryIO: │ │ │ │ │ - return io.BytesIO(self._contents[f'{self._dir}{resource}']) │ │ │ │ │ + It is usually thrown in response to some violation of expected protocol │ │ │ │ │ + when parsing messages, connecting to a peer, or opening a channel. │ │ │ │ │ + """ │ │ │ │ │ + attrs: JsonObject │ │ │ │ │ │ │ │ │ │ - def resource_path(self, resource: str) -> str: │ │ │ │ │ - raise FileNotFoundError │ │ │ │ │ + def __init__(self, problem: str, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> None: │ │ │ │ │ + kwargs['problem'] = problem │ │ │ │ │ + self.attrs = create_object(_msg, kwargs) │ │ │ │ │ + super().__init__(get_str(self.attrs, 'message', problem)) │ │ │ │ │ │ │ │ │ │ - def contents(self) -> Iterator[str]: │ │ │ │ │ - dir_length = len(self._dir) │ │ │ │ │ - result = set() │ │ │ │ │ │ │ │ │ │ - for filename in self._contents: │ │ │ │ │ - if filename.startswith(self._dir): │ │ │ │ │ - try: │ │ │ │ │ - next_slash = filename.index('/', dir_length) │ │ │ │ │ - except ValueError: │ │ │ │ │ - next_slash = None │ │ │ │ │ - result.add(filename[dir_length:next_slash]) │ │ │ │ │ +class CockpitProtocolError(CockpitProblem): │ │ │ │ │ + def __init__(self, message: str, problem: str = 'protocol-error'): │ │ │ │ │ + super().__init__(problem, message=message) │ │ │ │ │ │ │ │ │ │ - return iter(result) │ │ │ │ │ │ │ │ │ │ - contents: Dict[str, bytes] │ │ │ │ │ - modules: Dict[str, str] │ │ │ │ │ +class CockpitProtocol(asyncio.Protocol): │ │ │ │ │ + """A naive implementation of the Cockpit frame protocol │ │ │ │ │ │ │ │ │ │ - def __init__(self, contents: Dict[str, bytes]) -> None: │ │ │ │ │ + We need to use this because Python's SelectorEventLoop doesn't supported │ │ │ │ │ + buffered protocols. │ │ │ │ │ + """ │ │ │ │ │ + transport: 'asyncio.Transport | None' = None │ │ │ │ │ + buffer = b'' │ │ │ │ │ + _closed: bool = False │ │ │ │ │ + _communication_done: 'asyncio.Future[None] | None' = None │ │ │ │ │ + │ │ │ │ │ + def do_ready(self) -> None: │ │ │ │ │ + pass │ │ │ │ │ + │ │ │ │ │ + def do_closed(self, exc: 'Exception | None') -> None: │ │ │ │ │ + pass │ │ │ │ │ + │ │ │ │ │ + def transport_control_received(self, command: str, message: JsonObject) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def channel_control_received(self, channel: str, command: str, message: JsonObject) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def channel_data_received(self, channel: str, data: bytes) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def frame_received(self, frame: bytes) -> None: │ │ │ │ │ + header, _, data = frame.partition(b'\n') │ │ │ │ │ + │ │ │ │ │ + if header != b'': │ │ │ │ │ + channel = header.decode('ascii') │ │ │ │ │ + logger.debug('data received: %d bytes of data for channel %s', len(data), channel) │ │ │ │ │ + self.channel_data_received(channel, data) │ │ │ │ │ + │ │ │ │ │ + else: │ │ │ │ │ + self.control_received(data) │ │ │ │ │ + │ │ │ │ │ + def control_received(self, data: bytes) -> None: │ │ │ │ │ try: │ │ │ │ │ - contents[__file__] = __self_source__ # type: ignore[name-defined] │ │ │ │ │ - except NameError: │ │ │ │ │ - pass │ │ │ │ │ + message = typechecked(json.loads(data), dict) │ │ │ │ │ + command = get_str(message, 'command') │ │ │ │ │ + channel = get_str(message, 'channel', None) │ │ │ │ │ │ │ │ │ │ - self.contents = contents │ │ │ │ │ - self.modules = { │ │ │ │ │ - self.get_fullname(filename): filename │ │ │ │ │ - for filename in contents │ │ │ │ │ - if filename.endswith(".py") │ │ │ │ │ - } │ │ │ │ │ + if channel is not None: │ │ │ │ │ + logger.debug('channel control received %s', message) │ │ │ │ │ + self.channel_control_received(channel, command, message) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug('transport control received %s', message) │ │ │ │ │ + self.transport_control_received(command, message) │ │ │ │ │ │ │ │ │ │ - def get_fullname(self, filename: str) -> str: │ │ │ │ │ - assert filename.endswith(".py") │ │ │ │ │ - filename = filename[:-3] │ │ │ │ │ - if filename.endswith("/__init__"): │ │ │ │ │ - filename = filename[:-9] │ │ │ │ │ - return filename.replace("/", ".") │ │ │ │ │ + except (json.JSONDecodeError, JsonError) as exc: │ │ │ │ │ + raise CockpitProtocolError(f'control message: {exc!s}') from exc │ │ │ │ │ │ │ │ │ │ - def get_resource_reader(self, fullname: str) -> ResourceReader: │ │ │ │ │ - return BeipackLoader.ResourceReader(self.contents, fullname.replace('.', '/')) │ │ │ │ │ + def consume_one_frame(self, data: bytes) -> int: │ │ │ │ │ + """Consumes a single frame from view. │ │ │ │ │ │ │ │ │ │ - def get_data(self, path: str) -> bytes: │ │ │ │ │ - return self.contents[path] │ │ │ │ │ + Returns positive if a number of bytes were consumed, or negative if no │ │ │ │ │ + work can be done because of a given number of bytes missing. │ │ │ │ │ + """ │ │ │ │ │ │ │ │ │ │ - def get_filename(self, fullname: str) -> str: │ │ │ │ │ - return self.modules[fullname] │ │ │ │ │ + try: │ │ │ │ │ + newline = data.index(b'\n') │ │ │ │ │ + except ValueError as exc: │ │ │ │ │ + if len(data) < 10: │ │ │ │ │ + # Let's try reading more │ │ │ │ │ + return len(data) - 10 │ │ │ │ │ + raise CockpitProtocolError("size line is too long") from exc │ │ │ │ │ │ │ │ │ │ - def find_spec( │ │ │ │ │ - self, │ │ │ │ │ - fullname: str, │ │ │ │ │ - path: Optional[Sequence[str]], │ │ │ │ │ - target: Optional[ModuleType] = None │ │ │ │ │ - ) -> Optional[importlib.machinery.ModuleSpec]: │ │ │ │ │ - if fullname not in self.modules: │ │ │ │ │ - return None │ │ │ │ │ - return importlib.util.spec_from_loader(fullname, self) │ │ │ │ │ + try: │ │ │ │ │ + length = int(data[:newline]) │ │ │ │ │ + except ValueError as exc: │ │ │ │ │ + raise CockpitProtocolError("frame size is not an integer") from exc │ │ │ │ │ + │ │ │ │ │ + start = newline + 1 │ │ │ │ │ + end = start + length │ │ │ │ │ + │ │ │ │ │ + if end > len(data): │ │ │ │ │ + # We need to read more │ │ │ │ │ + return len(data) - end │ │ │ │ │ + │ │ │ │ │ + # We can consume a full frame │ │ │ │ │ + self.frame_received(data[start:end]) │ │ │ │ │ + return end │ │ │ │ │ + │ │ │ │ │ + def connection_made(self, transport: asyncio.BaseTransport) -> None: │ │ │ │ │ + logger.debug('connection_made(%s)', transport) │ │ │ │ │ + assert isinstance(transport, asyncio.Transport) │ │ │ │ │ + self.transport = transport │ │ │ │ │ + self.do_ready() │ │ │ │ │ + │ │ │ │ │ + if self._closed: │ │ │ │ │ + logger.debug(' but the protocol already was closed, so closing transport') │ │ │ │ │ + transport.close() │ │ │ │ │ + │ │ │ │ │ + def connection_lost(self, exc: 'Exception | None') -> None: │ │ │ │ │ + logger.debug('connection_lost') │ │ │ │ │ + assert self.transport is not None │ │ │ │ │ + self.transport = None │ │ │ │ │ + self.close(exc) │ │ │ │ │ + │ │ │ │ │ + def close(self, exc: 'Exception | None' = None) -> None: │ │ │ │ │ + if self._closed: │ │ │ │ │ + return │ │ │ │ │ + self._closed = True │ │ │ │ │ + │ │ │ │ │ + if self.transport: │ │ │ │ │ + self.transport.close() │ │ │ │ │ + │ │ │ │ │ + self.do_closed(exc) │ │ │ │ │ + │ │ │ │ │ + def write_channel_data(self, channel: str, payload: bytes) -> None: │ │ │ │ │ + """Send a given payload (bytes) on channel (string)""" │ │ │ │ │ + # Channel is certainly ascii (as enforced by .encode() below) │ │ │ │ │ + frame_length = len(channel + '\n') + len(payload) │ │ │ │ │ + header = f'{frame_length}\n{channel}\n'.encode('ascii') │ │ │ │ │ + if self.transport is not None: │ │ │ │ │ + logger.debug('writing to transport %s', self.transport) │ │ │ │ │ + self.transport.write(header + payload) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug('cannot write to closed transport') │ │ │ │ │ + │ │ │ │ │ + def write_control(self, _msg: 'JsonObject | None' = None, **kwargs: JsonValue) -> None: │ │ │ │ │ + """Write a control message. See jsonutil.create_object() for details.""" │ │ │ │ │ + logger.debug('sending control message %r %r', _msg, kwargs) │ │ │ │ │ + pretty = json.dumps(create_object(_msg, kwargs), indent=2) + '\n' │ │ │ │ │ + self.write_channel_data('', pretty.encode()) │ │ │ │ │ + │ │ │ │ │ + def data_received(self, data: bytes) -> None: │ │ │ │ │ + try: │ │ │ │ │ + self.buffer += data │ │ │ │ │ + while self.buffer: │ │ │ │ │ + result = self.consume_one_frame(self.buffer) │ │ │ │ │ + if result <= 0: │ │ │ │ │ + return │ │ │ │ │ + self.buffer = self.buffer[result:] │ │ │ │ │ + except CockpitProtocolError as exc: │ │ │ │ │ + self.close(exc) │ │ │ │ │ + │ │ │ │ │ + def eof_received(self) -> bool: │ │ │ │ │ + return False │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +# Helpful functionality for "server"-side protocol implementations │ │ │ │ │ +class CockpitProtocolServer(CockpitProtocol): │ │ │ │ │ + init_host: 'str | None' = None │ │ │ │ │ + authorizations: 'dict[str, asyncio.Future[str]] | None' = None │ │ │ │ │ + │ │ │ │ │ + def do_send_init(self) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def do_init(self, message: JsonObject) -> None: │ │ │ │ │ + pass │ │ │ │ │ + │ │ │ │ │ + def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def transport_control_received(self, command: str, message: JsonObject) -> None: │ │ │ │ │ + if command == 'init': │ │ │ │ │ + if get_int(message, 'version') != 1: │ │ │ │ │ + raise CockpitProtocolError('incorrect version number') │ │ │ │ │ + self.init_host = get_str(message, 'host') │ │ │ │ │ + self.do_init(message) │ │ │ │ │ + elif command == 'kill': │ │ │ │ │ + self.do_kill(get_str(message, 'host', None), get_str(message, 'group', None), message) │ │ │ │ │ + elif command == 'authorize': │ │ │ │ │ + self.do_authorize(message) │ │ │ │ │ + else: │ │ │ │ │ + raise CockpitProtocolError(f'unexpected control message {command} received') │ │ │ │ │ + │ │ │ │ │ + def do_ready(self) -> None: │ │ │ │ │ + self.do_send_init() │ │ │ │ │ + │ │ │ │ │ + # authorize request/response API │ │ │ │ │ + async def request_authorization( │ │ │ │ │ + self, challenge: str, timeout: 'int | None' = None, **kwargs: JsonValue │ │ │ │ │ + ) -> str: │ │ │ │ │ + if self.authorizations is None: │ │ │ │ │ + self.authorizations = {} │ │ │ │ │ + cookie = str(uuid.uuid4()) │ │ │ │ │ + future = asyncio.get_running_loop().create_future() │ │ │ │ │ + try: │ │ │ │ │ + self.authorizations[cookie] = future │ │ │ │ │ + self.write_control(None, command='authorize', challenge=challenge, cookie=cookie, **kwargs) │ │ │ │ │ + return await asyncio.wait_for(future, timeout) │ │ │ │ │ + finally: │ │ │ │ │ + self.authorizations.pop(cookie) │ │ │ │ │ + │ │ │ │ │ + def do_authorize(self, message: JsonObject) -> None: │ │ │ │ │ + cookie = get_str(message, 'cookie') │ │ │ │ │ + response = get_str(message, 'response') │ │ │ │ │ + │ │ │ │ │ + if self.authorizations is None or cookie not in self.authorizations: │ │ │ │ │ + logger.warning('no matching authorize request') │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + self.authorizations[cookie].set_result(response) │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/librarywrapper.py': br'''# systemd_ctypes │ │ │ │ │ + 'cockpit/superuser.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ +# along with this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import ctypes │ │ │ │ │ -import inspect │ │ │ │ │ +import array │ │ │ │ │ +import asyncio │ │ │ │ │ +import contextlib │ │ │ │ │ +import getpass │ │ │ │ │ import logging │ │ │ │ │ import os │ │ │ │ │ -import sys │ │ │ │ │ -import types │ │ │ │ │ -from typing import ( │ │ │ │ │ - Any, │ │ │ │ │ - Callable, │ │ │ │ │ - Dict, │ │ │ │ │ - Generic, │ │ │ │ │ - NewType, │ │ │ │ │ - NoReturn, │ │ │ │ │ - Optional, │ │ │ │ │ - Tuple, │ │ │ │ │ - Type, │ │ │ │ │ - TypeVar, │ │ │ │ │ - Union, │ │ │ │ │ -) │ │ │ │ │ +import socket │ │ │ │ │ +from tempfile import TemporaryDirectory │ │ │ │ │ +from typing import List, Optional, Sequence, Tuple │ │ │ │ │ │ │ │ │ │ -from . import typing │ │ │ │ │ +from cockpit._vendor import ferny │ │ │ │ │ +from cockpit._vendor.bei.bootloader import make_bootloader │ │ │ │ │ +from cockpit._vendor.systemd_ctypes import Variant, bus │ │ │ │ │ │ │ │ │ │ -# First in 3.10, and conditional import gives type errors │ │ │ │ │ -NoneType = type(None) │ │ │ │ │ +from .beipack import BridgeBeibootHelper │ │ │ │ │ +from .jsonutil import JsonObject, get_str │ │ │ │ │ +from .packages import BridgeConfig │ │ │ │ │ +from .peer import ConfiguredPeer, Peer, PeerError │ │ │ │ │ +from .polkit import PolkitAgent │ │ │ │ │ +from .router import Router, RoutingError, RoutingRule │ │ │ │ │ │ │ │ │ │ logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ -if typing.TYPE_CHECKING: │ │ │ │ │ - CType = TypeVar("CType", bound=ctypes._CData) │ │ │ │ │ - Callback = ctypes._FuncPointer │ │ │ │ │ -else: │ │ │ │ │ - CType = TypeVar("CType") │ │ │ │ │ - Callback = ctypes.c_void_p │ │ │ │ │ │ │ │ │ │ +class SuperuserPeer(ConfiguredPeer): │ │ │ │ │ + responder: ferny.AskpassHandler │ │ │ │ │ │ │ │ │ │ -if typing.TYPE_CHECKING: │ │ │ │ │ - class Reference(Generic[CType], ctypes._Pointer[CType]): │ │ │ │ │ - pass │ │ │ │ │ + def __init__(self, router: Router, config: BridgeConfig, responder: ferny.AskpassHandler): │ │ │ │ │ + super().__init__(router, config) │ │ │ │ │ + self.responder = responder │ │ │ │ │ │ │ │ │ │ - def byref(x: CType) -> Reference[CType]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ -else: │ │ │ │ │ - class Reference(Generic[CType]): │ │ │ │ │ - pass │ │ │ │ │ + async def do_connect_transport(self) -> None: │ │ │ │ │ + async with contextlib.AsyncExitStack() as context: │ │ │ │ │ + if 'pkexec' in self.args: │ │ │ │ │ + logger.debug('connecting polkit superuser peer transport %r', self.args) │ │ │ │ │ + await context.enter_async_context(PolkitAgent(self.responder)) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug('connecting non-polkit superuser peer transport %r', self.args) │ │ │ │ │ │ │ │ │ │ - byref = ctypes.byref │ │ │ │ │ + responders: 'list[ferny.InteractionHandler]' = [self.responder] │ │ │ │ │ │ │ │ │ │ + if '# cockpit-bridge' in self.args: │ │ │ │ │ + logger.debug('going to beiboot superuser bridge %r', self.args) │ │ │ │ │ + helper = BridgeBeibootHelper(self, ['--privileged']) │ │ │ │ │ + responders.append(helper) │ │ │ │ │ + stage1 = make_bootloader(helper.steps, gadgets=ferny.BEIBOOT_GADGETS).encode() │ │ │ │ │ + else: │ │ │ │ │ + stage1 = None │ │ │ │ │ │ │ │ │ │ -UserData = Optional[ctypes.c_void_p] │ │ │ │ │ + agent = ferny.InteractionAgent(responders) │ │ │ │ │ │ │ │ │ │ + if 'SUDO_ASKPASS=ferny-askpass' in self.env: │ │ │ │ │ + tmpdir = context.enter_context(TemporaryDirectory()) │ │ │ │ │ + ferny_askpass = ferny.write_askpass_to_tmpdir(tmpdir) │ │ │ │ │ + env: Sequence[str] = [f'SUDO_ASKPASS={ferny_askpass}'] │ │ │ │ │ + else: │ │ │ │ │ + env = self.env │ │ │ │ │ │ │ │ │ │ -class negative_errno(ctypes.c_int): │ │ │ │ │ - def errcheck(self, func: Callable[..., object], _args: Tuple[object, ...]) -> int: │ │ │ │ │ - result = self.value │ │ │ │ │ - if result < 0: │ │ │ │ │ - raise OSError(-result, f"{func.__name__}: {os.strerror(-result)}") │ │ │ │ │ - return result │ │ │ │ │ + transport = await self.spawn(self.args, env, stderr=agent, start_new_session=True) │ │ │ │ │ │ │ │ │ │ + if stage1 is not None: │ │ │ │ │ + transport.write(stage1) │ │ │ │ │ │ │ │ │ │ -class utf8(ctypes.c_char_p): │ │ │ │ │ - def errcheck(self, func: Callable[..., object], _args: Tuple[object, ...]) -> str: │ │ │ │ │ - assert self.value is not None │ │ │ │ │ - return self.value.decode() │ │ │ │ │ + try: │ │ │ │ │ + await agent.communicate() │ │ │ │ │ + except ferny.InteractionError as exc: │ │ │ │ │ + raise PeerError('authentication-failed', message=str(exc)) from exc │ │ │ │ │ │ │ │ │ │ - @classmethod │ │ │ │ │ - def from_param(cls, value: str) -> 'utf8': │ │ │ │ │ - return cls(value.encode()) │ │ │ │ │ │ │ │ │ │ +class CockpitResponder(ferny.AskpassHandler): │ │ │ │ │ + commands = ('ferny.askpass', 'cockpit.send-stderr') │ │ │ │ │ │ │ │ │ │ -class utf8_or_null(ctypes.c_char_p): │ │ │ │ │ - def errcheck(self, │ │ │ │ │ - func: Callable[..., object], │ │ │ │ │ - _args: Tuple[object, ...]) -> Optional[str]: │ │ │ │ │ - return self.value.decode() if self.value is not None else None │ │ │ │ │ + async def do_custom_command(self, command: str, args: Tuple, fds: List[int], stderr: str) -> None: │ │ │ │ │ + if command == 'cockpit.send-stderr': │ │ │ │ │ + with socket.socket(fileno=fds[0]) as sock: │ │ │ │ │ + fds.pop(0) │ │ │ │ │ + # socket.send_fds(sock, [b'\0'], [2]) # New in Python 3.9 │ │ │ │ │ + sock.sendmsg([b'\0'], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [2]))]) │ │ │ │ │ │ │ │ │ │ - @classmethod │ │ │ │ │ - def from_param(cls, value: Optional[str]) -> 'utf8_or_null': │ │ │ │ │ - return cls(value.encode() if value is not None else None) │ │ │ │ │ │ │ │ │ │ +class AuthorizeResponder(CockpitResponder): │ │ │ │ │ + def __init__(self, router: Router): │ │ │ │ │ + self.router = router │ │ │ │ │ │ │ │ │ │ -class boolint(ctypes.c_int): │ │ │ │ │ - def errcheck(self, func: Callable[..., object], _args: Tuple[object, ...]) -> bool: │ │ │ │ │ - return bool(self.value) │ │ │ │ │ + async def do_askpass(self, messages: str, prompt: str, hint: str) -> str: │ │ │ │ │ + hexuser = ''.join(f'{c:02x}' for c in getpass.getuser().encode('ascii')) │ │ │ │ │ + return await self.router.request_authorization(f'plain1:{hexuser}') │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -WeakReference = NewType("WeakReference", int) │ │ │ │ │ -Errno = typing.Annotated[NoReturn, "errno"] │ │ │ │ │ +class SuperuserRoutingRule(RoutingRule, CockpitResponder, bus.Object, interface='cockpit.Superuser'): │ │ │ │ │ + superuser_configs: Sequence[BridgeConfig] = () │ │ │ │ │ + pending_prompt: Optional[asyncio.Future] │ │ │ │ │ + peer: Optional[SuperuserPeer] │ │ │ │ │ │ │ │ │ │ + # D-Bus signals │ │ │ │ │ + prompt = bus.Interface.Signal('s', 's', 's', 'b', 's') # message, prompt, default, echo, error │ │ │ │ │ │ │ │ │ │ -type_map = { │ │ │ │ │ - Union[None, Errno]: negative_errno, # technically returns int │ │ │ │ │ - Union[bool, Errno]: negative_errno, # technically returns int │ │ │ │ │ - Union[int, Errno]: negative_errno, │ │ │ │ │ - bool: boolint, │ │ │ │ │ - Optional[str]: utf8_or_null, │ │ │ │ │ - str: utf8, │ │ │ │ │ - int: ctypes.c_int, │ │ │ │ │ - WeakReference: ctypes.c_void_p │ │ │ │ │ -} │ │ │ │ │ + # D-Bus properties │ │ │ │ │ + bridges = bus.Interface.Property('as', value=[]) │ │ │ │ │ + current = bus.Interface.Property('s', value='none') │ │ │ │ │ + methods = bus.Interface.Property('a{sv}', value={}) │ │ │ │ │ │ │ │ │ │ + # RoutingRule │ │ │ │ │ + def apply_rule(self, options: JsonObject) -> Optional[Peer]: │ │ │ │ │ + superuser = options.get('superuser') │ │ │ │ │ │ │ │ │ │ -def map_type(annotation: Any, global_vars: Dict[str, object]) -> Any: │ │ │ │ │ - try: │ │ │ │ │ - return type_map[annotation] │ │ │ │ │ - except KeyError: │ │ │ │ │ - pass # ... and try more cases below │ │ │ │ │ + if not superuser or self.current == 'root': │ │ │ │ │ + # superuser not requested, or already superuser? Next rule. │ │ │ │ │ + return None │ │ │ │ │ + elif self.peer or superuser == 'try': │ │ │ │ │ + # superuser requested and active? Return it. │ │ │ │ │ + # 'try' requested? Either return the peer, or None. │ │ │ │ │ + return self.peer │ │ │ │ │ + else: │ │ │ │ │ + # superuser requested, but not active? That's an error. │ │ │ │ │ + raise RoutingError('access-denied') │ │ │ │ │ │ │ │ │ │ - if isinstance(annotation, typing.ForwardRef): │ │ │ │ │ - annotation = annotation.__forward_arg__ │ │ │ │ │ + # ferny.AskpassHandler │ │ │ │ │ + async def do_askpass(self, messages: str, prompt: str, hint: str) -> Optional[str]: │ │ │ │ │ + assert self.pending_prompt is None │ │ │ │ │ + echo = hint == "confirm" │ │ │ │ │ + self.pending_prompt = asyncio.get_running_loop().create_future() │ │ │ │ │ + try: │ │ │ │ │ + logger.debug('prompting for %s', prompt) │ │ │ │ │ + # with sudo, all stderr messages are treated as warning/errors by the UI │ │ │ │ │ + # (such as the lecture or "wrong password"), so pass them in the "error" field │ │ │ │ │ + self.prompt('', prompt, '', echo, messages) │ │ │ │ │ + return await self.pending_prompt │ │ │ │ │ + finally: │ │ │ │ │ + self.pending_prompt = None │ │ │ │ │ │ │ │ │ │ - if isinstance(annotation, str): │ │ │ │ │ - annotation = global_vars[annotation] │ │ │ │ │ + def __init__(self, router: Router, *, privileged: bool = False): │ │ │ │ │ + super().__init__(router) │ │ │ │ │ │ │ │ │ │ - origin = typing.get_origin(annotation) │ │ │ │ │ - args = typing.get_args(annotation) │ │ │ │ │ + self.pending_prompt = None │ │ │ │ │ + self.peer = None │ │ │ │ │ + self.startup = None │ │ │ │ │ │ │ │ │ │ - if origin is Reference: │ │ │ │ │ - return ctypes.POINTER(map_type(args[0], global_vars)) │ │ │ │ │ + if privileged or os.getuid() == 0: │ │ │ │ │ + self.current = 'root' │ │ │ │ │ │ │ │ │ │ - elif origin is Union and NoneType in args: │ │ │ │ │ - # the C pointer types are already nullable │ │ │ │ │ - other_arg, = set(args) - {NoneType} │ │ │ │ │ - return map_type(other_arg, global_vars) │ │ │ │ │ + def peer_done(self): │ │ │ │ │ + self.current = 'none' │ │ │ │ │ + self.peer = None │ │ │ │ │ │ │ │ │ │ - elif origin is typing.Annotated: │ │ │ │ │ - return args[1] │ │ │ │ │ + async def go(self, name: str, responder: ferny.AskpassHandler) -> None: │ │ │ │ │ + if self.current != 'none': │ │ │ │ │ + raise bus.BusError('cockpit.Superuser.Error', 'Superuser bridge already running') │ │ │ │ │ │ │ │ │ │ - else: │ │ │ │ │ - assert origin is None, origin │ │ │ │ │ - return annotation │ │ │ │ │ + assert self.peer is None │ │ │ │ │ + assert self.startup is None │ │ │ │ │ │ │ │ │ │ + for config in self.superuser_configs: │ │ │ │ │ + if name in (config.name, 'any'): │ │ │ │ │ + break │ │ │ │ │ + else: │ │ │ │ │ + raise bus.BusError('cockpit.Superuser.Error', f'Unknown superuser bridge type "{name}"') │ │ │ │ │ │ │ │ │ │ -class ReferenceType(ctypes.c_void_p): │ │ │ │ │ - @classmethod │ │ │ │ │ - def _install_cfuncs(cls, cdll: ctypes.CDLL) -> None: │ │ │ │ │ - logger.debug('Installing stubs for %s:', cls) │ │ │ │ │ - stubs = tuple(cls.__dict__.items()) │ │ │ │ │ - for name, stub in stubs: │ │ │ │ │ - if name.startswith("__"): │ │ │ │ │ - continue │ │ │ │ │ - cls._wrap(cdll, stub) │ │ │ │ │ + self.current = 'init' │ │ │ │ │ + self.peer = SuperuserPeer(self.router, config, responder) │ │ │ │ │ + self.peer.add_done_callback(self.peer_done) │ │ │ │ │ │ │ │ │ │ - cls._wrap(cdll, cls._ref) │ │ │ │ │ - cls._wrap(cdll, cls._unref) │ │ │ │ │ + try: │ │ │ │ │ + await self.peer.start(init_host=self.router.init_host) │ │ │ │ │ + except asyncio.CancelledError: │ │ │ │ │ + raise bus.BusError('cockpit.Superuser.Error.Cancelled', 'Operation aborted') from None │ │ │ │ │ + except (OSError, PeerError) as exc: │ │ │ │ │ + raise bus.BusError('cockpit.Superuser.Error', str(exc)) from exc │ │ │ │ │ │ │ │ │ │ - @classmethod │ │ │ │ │ - def _wrap(cls, cdll: ctypes.CDLL, stub: object) -> None: │ │ │ │ │ - stub_type = type(stub) │ │ │ │ │ - if isinstance(stub, staticmethod): │ │ │ │ │ - # In older Python versions, staticmethod() isn't considered │ │ │ │ │ - # callable, doesn't have a name, and can't be introspected with │ │ │ │ │ - # inspect.signature(). Unwrap it. │ │ │ │ │ - stub = stub.__func__ │ │ │ │ │ - assert isinstance(stub, types.FunctionType) │ │ │ │ │ - name = stub.__name__ │ │ │ │ │ - signature = inspect.signature(stub) │ │ │ │ │ - stub_globals = sys.modules.get(cls.__module__).__dict__ │ │ │ │ │ + self.current = self.peer.config.name │ │ │ │ │ │ │ │ │ │ - func = cdll[f'{cls.__name__}_{name.lstrip("_")}'] │ │ │ │ │ - func.argtypes = tuple( │ │ │ │ │ - map_type(parameter.annotation, stub_globals) │ │ │ │ │ - for parameter in signature.parameters.values() │ │ │ │ │ - ) │ │ │ │ │ - func.restype = map_type(signature.return_annotation, stub_globals) │ │ │ │ │ - errcheck = getattr(func.restype, 'errcheck', None) │ │ │ │ │ - if errcheck is not None: │ │ │ │ │ - func.errcheck = errcheck │ │ │ │ │ + def set_configs(self, configs: Sequence[BridgeConfig]): │ │ │ │ │ + logger.debug("set_configs() with %d items", len(configs)) │ │ │ │ │ + configs = [config for config in configs if config.privileged] │ │ │ │ │ + self.superuser_configs = tuple(configs) │ │ │ │ │ + self.bridges = [config.name for config in self.superuser_configs] │ │ │ │ │ + self.methods = {c.label: Variant({'label': Variant(c.label)}, 'a{sv}') for c in configs if c.label} │ │ │ │ │ │ │ │ │ │ - logger.debug(' create wrapper %s.%s%s', cls.__name__, name, signature) │ │ │ │ │ - logger.debug(' args %s res %s', func.argtypes, func.restype) │ │ │ │ │ + logger.debug(" bridges are now %s", self.bridges) │ │ │ │ │ │ │ │ │ │ - # ctypes function pointer objects don't implement the usual function │ │ │ │ │ - # descriptor logic, which means they won't bind as methods. For static │ │ │ │ │ - # methods, that's good, but for instance methods, we add a wrapper as │ │ │ │ │ - # the easiest and most performant way to get the binding behaviour. │ │ │ │ │ - if stub_type is not staticmethod: │ │ │ │ │ - setattr(cls, name, lambda *args: func(*args)) │ │ │ │ │ - else: │ │ │ │ │ - setattr(cls, name, func) │ │ │ │ │ + # If the currently active bridge config is not in the new set of configs, stop it │ │ │ │ │ + if self.peer is not None: │ │ │ │ │ + if self.peer.config not in self.superuser_configs: │ │ │ │ │ + logger.debug(" stopping superuser bridge '%s': it disappeared from configs", self.peer.config.name) │ │ │ │ │ + self.stop() │ │ │ │ │ │ │ │ │ │ - def _unref(self: 'ReferenceType') -> None: │ │ │ │ │ - ... │ │ │ │ │ + def cancel_prompt(self): │ │ │ │ │ + if self.pending_prompt is not None: │ │ │ │ │ + self.pending_prompt.cancel() │ │ │ │ │ + self.pending_prompt = None │ │ │ │ │ │ │ │ │ │ - def _ref(self: 'ReferenceType') -> None: │ │ │ │ │ - ... │ │ │ │ │ + def shutdown(self): │ │ │ │ │ + self.cancel_prompt() │ │ │ │ │ │ │ │ │ │ - T = TypeVar("T", bound='ReferenceType') │ │ │ │ │ + if self.peer is not None: │ │ │ │ │ + self.peer.close() │ │ │ │ │ │ │ │ │ │ - @classmethod │ │ │ │ │ - def ref(cls: Type[T], origin: WeakReference) -> T: │ │ │ │ │ - self = cls(origin) │ │ │ │ │ - self._ref() │ │ │ │ │ - return self │ │ │ │ │ + # close() should have disconnected the peer immediately │ │ │ │ │ + assert self.peer is None │ │ │ │ │ │ │ │ │ │ - def __del__(self) -> None: │ │ │ │ │ - if self.value is not None: │ │ │ │ │ - self._unref() │ │ │ │ │ + # Connect-on-startup functionality │ │ │ │ │ + def init(self, params: JsonObject) -> None: │ │ │ │ │ + name = get_str(params, 'id', 'any') │ │ │ │ │ + responder = AuthorizeResponder(self.router) │ │ │ │ │ + self._init_task = asyncio.create_task(self.go(name, responder)) │ │ │ │ │ + self._init_task.add_done_callback(self._init_done) │ │ │ │ │ + │ │ │ │ │ + def _init_done(self, task: 'asyncio.Task[None]') -> None: │ │ │ │ │ + logger.debug('superuser init done! %s', task.exception()) │ │ │ │ │ + self.router.write_control(command='superuser-init-done') │ │ │ │ │ + del self._init_task │ │ │ │ │ + │ │ │ │ │ + # D-Bus methods │ │ │ │ │ + @bus.Interface.Method(in_types=['s']) │ │ │ │ │ + async def start(self, name: str) -> None: │ │ │ │ │ + await self.go(name, self) │ │ │ │ │ + │ │ │ │ │ + @bus.Interface.Method() │ │ │ │ │ + def stop(self) -> None: │ │ │ │ │ + self.shutdown() │ │ │ │ │ + │ │ │ │ │ + @bus.Interface.Method(in_types=['s']) │ │ │ │ │ + def answer(self, reply: str) -> None: │ │ │ │ │ + if self.pending_prompt is not None: │ │ │ │ │ + logger.debug('responding to pending prompt') │ │ │ │ │ + self.pending_prompt.set_result(reply) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug('got Answer, but no prompt pending') │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/event.py': br'''# systemd_ctypes │ │ │ │ │ + 'cockpit/config.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# Copyright (C) 2023 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ +# along with this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import asyncio │ │ │ │ │ -import selectors │ │ │ │ │ -import sys │ │ │ │ │ -from typing import Callable, ClassVar, Coroutine, List, Optional, Tuple │ │ │ │ │ +import configparser │ │ │ │ │ +import logging │ │ │ │ │ +import os │ │ │ │ │ +from pathlib import Path │ │ │ │ │ │ │ │ │ │ -from . import inotify, libsystemd │ │ │ │ │ -from .librarywrapper import Reference, UserData, byref │ │ │ │ │ +from cockpit._vendor.systemd_ctypes import bus │ │ │ │ │ │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ -class Event(libsystemd.sd_event): │ │ │ │ │ - class Source(libsystemd.sd_event_source): │ │ │ │ │ - def cancel(self) -> None: │ │ │ │ │ - self._unref() │ │ │ │ │ - self.value = None │ │ │ │ │ +XDG_CONFIG_HOME = Path(os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config')) │ │ │ │ │ +DOT_CONFIG_COCKPIT = XDG_CONFIG_HOME / 'cockpit' │ │ │ │ │ │ │ │ │ │ - _default_instance: ClassVar[Optional['Event']] = None │ │ │ │ │ │ │ │ │ │ - @staticmethod │ │ │ │ │ - def default() -> 'Event': │ │ │ │ │ - if Event._default_instance is None: │ │ │ │ │ - Event._default_instance = Event() │ │ │ │ │ - Event._default(byref(Event._default_instance)) │ │ │ │ │ - return Event._default_instance │ │ │ │ │ +def lookup_config(filename: str) -> Path: │ │ │ │ │ + config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc').split(':') │ │ │ │ │ + fallback = None │ │ │ │ │ + for config_dir in config_dirs: │ │ │ │ │ + config_path = Path(config_dir, 'cockpit', filename) │ │ │ │ │ + if not fallback: │ │ │ │ │ + fallback = config_path │ │ │ │ │ + if config_path.exists(): │ │ │ │ │ + logger.debug('lookup_config(%s): found %s', filename, config_path) │ │ │ │ │ + return config_path │ │ │ │ │ │ │ │ │ │ - InotifyHandler = Callable[[inotify.Event, int, Optional[bytes]], None] │ │ │ │ │ + # default to the first entry in XDG_CONFIG_DIRS; that's not according to the spec, │ │ │ │ │ + # but what Cockpit has done for years │ │ │ │ │ + logger.debug('lookup_config(%s): defaulting to %s', filename, fallback) │ │ │ │ │ + assert fallback # mypy; config_dirs always has at least one string │ │ │ │ │ + return fallback │ │ │ │ │ │ │ │ │ │ - class InotifySource(Source): │ │ │ │ │ - def __init__(self, handler: 'Event.InotifyHandler') -> None: │ │ │ │ │ - def callback(source: libsystemd.sd_event_source, │ │ │ │ │ - _event: Reference[inotify.inotify_event], │ │ │ │ │ - userdata: UserData) -> int: │ │ │ │ │ - event = _event.contents │ │ │ │ │ - handler(inotify.Event(event.mask), event.cookie, event.name) │ │ │ │ │ - return 0 │ │ │ │ │ - self.trampoline = libsystemd.sd_event_inotify_handler_t(callback) │ │ │ │ │ │ │ │ │ │ - def add_inotify(self, path: str, mask: inotify.Event, handler: InotifyHandler) -> InotifySource: │ │ │ │ │ - source = Event.InotifySource(handler) │ │ │ │ │ - self._add_inotify(byref(source), path, mask, source.trampoline, source.userdata) │ │ │ │ │ - return source │ │ │ │ │ +class Config(bus.Object, interface='cockpit.Config'): │ │ │ │ │ + def __init__(self): │ │ │ │ │ + self.reload() │ │ │ │ │ │ │ │ │ │ - def add_inotify_fd(self, fd: int, mask: inotify.Event, handler: InotifyHandler) -> InotifySource: │ │ │ │ │ - # HACK: sd_event_add_inotify_fd() got added in 250, which is too new. Fake it. │ │ │ │ │ - return self.add_inotify(f'/proc/self/fd/{fd}', mask, handler) │ │ │ │ │ + @bus.Interface.Method(out_types='s', in_types='ss') │ │ │ │ │ + def get_string(self, section, key): │ │ │ │ │ + try: │ │ │ │ │ + return self.config[section][key] │ │ │ │ │ + except KeyError as exc: │ │ │ │ │ + raise bus.BusError('cockpit.Config.KeyError', f'key {key} in section {section} does not exist') from exc │ │ │ │ │ │ │ │ │ │ + @bus.Interface.Method(out_types='u', in_types='ssuuu') │ │ │ │ │ + def get_u_int(self, section, key, default, maximum, minimum): │ │ │ │ │ + try: │ │ │ │ │ + value = self.config[section][key] │ │ │ │ │ + except KeyError: │ │ │ │ │ + return default │ │ │ │ │ │ │ │ │ │ -# This is all a bit more awkward than it should have to be: systemd's event │ │ │ │ │ -# loop chaining model is designed for glib's prepare/check/dispatch paradigm; │ │ │ │ │ -# failing to call prepare() can lead to deadlocks, for example. │ │ │ │ │ + try: │ │ │ │ │ + int_val = int(value) │ │ │ │ │ + except ValueError: │ │ │ │ │ + logger.warning('cockpit.conf: [%s] %s is not an integer', section, key) │ │ │ │ │ + return default │ │ │ │ │ + │ │ │ │ │ + return min(max(int_val, minimum), maximum) │ │ │ │ │ + │ │ │ │ │ + @bus.Interface.Method() │ │ │ │ │ + def reload(self): │ │ │ │ │ + self.config = configparser.ConfigParser(interpolation=None) │ │ │ │ │ + cockpit_conf = lookup_config('cockpit.conf') │ │ │ │ │ + logger.debug("cockpit.Config: loading %s", cockpit_conf) │ │ │ │ │ + # this may not exist, but it's ok to not have a config file and thus leave self.config empty │ │ │ │ │ + self.config.read(cockpit_conf) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class Environment(bus.Object, interface='cockpit.Environment'): │ │ │ │ │ + variables = bus.Interface.Property('a{ss}') │ │ │ │ │ + │ │ │ │ │ + @variables.getter │ │ │ │ │ + def get_variables(self): │ │ │ │ │ + return os.environ.copy() │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/remote.py': r'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ -# Hack a selector subclass which calls prepare() before sleeping and this for us. │ │ │ │ │ -class Selector(selectors.DefaultSelector): │ │ │ │ │ - def __init__(self, event: Optional[Event] = None) -> None: │ │ │ │ │ - super().__init__() │ │ │ │ │ - self.sd_event = event or Event.default() │ │ │ │ │ - self.key = self.register(self.sd_event.get_fd(), selectors.EVENT_READ) │ │ │ │ │ +# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ - def select( │ │ │ │ │ - self, timeout: Optional[float] = None │ │ │ │ │ - ) -> List[Tuple[selectors.SelectorKey, int]]: │ │ │ │ │ - # It's common to drop the last reference to a Source or Slot object on │ │ │ │ │ - # a dispatch of that same source/slot from the main loop. If we happen │ │ │ │ │ - # to garbage collect before returning, the trampoline could be │ │ │ │ │ - # destroyed before we're done using it. Provide a mechanism to defer │ │ │ │ │ - # the destruction of trampolines for as long as we might be │ │ │ │ │ - # dispatching. This gets cleared again at the bottom, before return. │ │ │ │ │ - libsystemd.Trampoline.deferred = [] │ │ │ │ │ +import getpass │ │ │ │ │ +import logging │ │ │ │ │ +import re │ │ │ │ │ +import socket │ │ │ │ │ +from typing import Dict, List, Optional, Tuple │ │ │ │ │ │ │ │ │ │ - while self.sd_event.prepare(): │ │ │ │ │ - self.sd_event.dispatch() │ │ │ │ │ - ready = super().select(timeout) │ │ │ │ │ - # workaround https://github.com/systemd/systemd/issues/23826 │ │ │ │ │ - # keep calling wait() until there's nothing left │ │ │ │ │ - while self.sd_event.wait(0): │ │ │ │ │ - self.sd_event.dispatch() │ │ │ │ │ - while self.sd_event.prepare(): │ │ │ │ │ - self.sd_event.dispatch() │ │ │ │ │ +from cockpit._vendor import ferny │ │ │ │ │ │ │ │ │ │ - # We can be sure we're not dispatching callbacks anymore │ │ │ │ │ - libsystemd.Trampoline.deferred = None │ │ │ │ │ +from .jsonutil import JsonObject, JsonValue, get_str, get_str_or_none │ │ │ │ │ +from .peer import Peer, PeerError │ │ │ │ │ +from .router import Router, RoutingRule │ │ │ │ │ │ │ │ │ │ - # This could return zero events with infinite timeout, but nobody seems to mind. │ │ │ │ │ - return [(key, events) for (key, events) in ready if key != self.key] │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class EventLoopPolicy(asyncio.DefaultEventLoopPolicy): │ │ │ │ │ - def new_event_loop(self) -> asyncio.AbstractEventLoop: │ │ │ │ │ - return asyncio.SelectorEventLoop(Selector()) │ │ │ │ │ +class PasswordResponder(ferny.AskpassHandler): │ │ │ │ │ + PASSPHRASE_RE = re.compile(r"Enter passphrase for key '(.*)': ") │ │ │ │ │ │ │ │ │ │ + password: Optional[str] │ │ │ │ │ │ │ │ │ │ -def run_async(main: Coroutine[None, None, None], debug: Optional[bool] = None) -> None: │ │ │ │ │ - asyncio.set_event_loop_policy(EventLoopPolicy()) │ │ │ │ │ + hostkeys_seen: List[Tuple[str, str, str, str, str]] │ │ │ │ │ + error_message: Optional[str] │ │ │ │ │ + password_attempts: int │ │ │ │ │ │ │ │ │ │ - polyfill = sys.version_info < (3, 7, 0) and not hasattr(asyncio, 'run') │ │ │ │ │ - if polyfill: │ │ │ │ │ - # Polyfills for Python 3.6: │ │ │ │ │ - loop = asyncio.get_event_loop() │ │ │ │ │ + def __init__(self, password: Optional[str]): │ │ │ │ │ + self.password = password │ │ │ │ │ │ │ │ │ │ - assert not hasattr(asyncio, 'get_running_loop') │ │ │ │ │ - asyncio.get_running_loop = lambda: loop │ │ │ │ │ + self.hostkeys_seen = [] │ │ │ │ │ + self.error_message = None │ │ │ │ │ + self.password_attempts = 0 │ │ │ │ │ │ │ │ │ │ - assert not hasattr(asyncio, 'create_task') │ │ │ │ │ - asyncio.create_task = loop.create_task │ │ │ │ │ + async def do_hostkey(self, reason: str, host: str, algorithm: str, key: str, fingerprint: str) -> bool: │ │ │ │ │ + self.hostkeys_seen.append((reason, host, algorithm, key, fingerprint)) │ │ │ │ │ + return False │ │ │ │ │ │ │ │ │ │ - assert not hasattr(asyncio, 'run') │ │ │ │ │ + async def do_askpass(self, messages: str, prompt: str, hint: str) -> Optional[str]: │ │ │ │ │ + logger.debug('Got askpass(%s): %s', hint, prompt) │ │ │ │ │ │ │ │ │ │ - def run( │ │ │ │ │ - main: Coroutine[None, None, None], debug: Optional[bool] = None │ │ │ │ │ - ) -> None: │ │ │ │ │ - if debug is not None: │ │ │ │ │ - loop.set_debug(debug) │ │ │ │ │ - loop.run_until_complete(main) │ │ │ │ │ + match = PasswordResponder.PASSPHRASE_RE.fullmatch(prompt) │ │ │ │ │ + if match is not None: │ │ │ │ │ + # We never unlock private keys — we rather need to throw a │ │ │ │ │ + # specially-formatted error message which will cause the frontend │ │ │ │ │ + # to load the named key into the agent for us and try again. │ │ │ │ │ + path = match.group(1) │ │ │ │ │ + logger.debug("This is a passphrase request for %s, but we don't do those. Abort.", path) │ │ │ │ │ + self.error_message = f'locked identity: {path}' │ │ │ │ │ + return None │ │ │ │ │ │ │ │ │ │ - asyncio.run = run # type: ignore[assignment] │ │ │ │ │ + assert self.password is not None │ │ │ │ │ + assert self.password_attempts == 0 │ │ │ │ │ + self.password_attempts += 1 │ │ │ │ │ + return self.password │ │ │ │ │ │ │ │ │ │ - asyncio._systemd_ctypes_polyfills = True # type: ignore[attr-defined] │ │ │ │ │ │ │ │ │ │ - asyncio.run(main, debug=debug) │ │ │ │ │ +class SshPeer(Peer): │ │ │ │ │ + session: Optional[ferny.Session] = None │ │ │ │ │ + host: str │ │ │ │ │ + user: Optional[str] │ │ │ │ │ + password: Optional[str] │ │ │ │ │ + private: bool │ │ │ │ │ │ │ │ │ │ - if polyfill: │ │ │ │ │ - del asyncio.create_task, asyncio.get_running_loop, asyncio.run │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/bustypes.py': br'''# systemd_ctypes │ │ │ │ │ + async def do_connect_transport(self) -> None: │ │ │ │ │ + assert self.session is not None │ │ │ │ │ + logger.debug('Starting ssh session user=%s, host=%s, private=%s', self.user, self.host, self.private) │ │ │ │ │ + │ │ │ │ │ + basename, colon, portstr = self.host.rpartition(':') │ │ │ │ │ + if colon and portstr.isdigit(): │ │ │ │ │ + host = basename │ │ │ │ │ + port = int(portstr) │ │ │ │ │ + else: │ │ │ │ │ + host = self.host │ │ │ │ │ + port = None │ │ │ │ │ + │ │ │ │ │ + responder = PasswordResponder(self.password) │ │ │ │ │ + options = {"StrictHostKeyChecking": 'yes'} │ │ │ │ │ + │ │ │ │ │ + if self.password is not None: │ │ │ │ │ + options.update(NumberOfPasswordPrompts='1') │ │ │ │ │ + else: │ │ │ │ │ + options.update(PasswordAuthentication="no", KbdInteractiveAuthentication="no") │ │ │ │ │ + │ │ │ │ │ + try: │ │ │ │ │ + await self.session.connect(host, login_name=self.user, port=port, │ │ │ │ │ + handle_host_key=self.private, options=options, │ │ │ │ │ + interaction_responder=responder) │ │ │ │ │ + except (OSError, socket.gaierror) as exc: │ │ │ │ │ + logger.debug('connecting to host %s failed: %s', host, exc) │ │ │ │ │ + raise PeerError('no-host', error='no-host', message=str(exc)) from exc │ │ │ │ │ + │ │ │ │ │ + except ferny.SshHostKeyError as exc: │ │ │ │ │ + if responder.hostkeys_seen: │ │ │ │ │ + # If we saw a hostkey then we can issue a detailed error message │ │ │ │ │ + # containing the key that would need to be accepted. That will │ │ │ │ │ + # cause the front-end to present a dialog. │ │ │ │ │ + _reason, host, algorithm, key, fingerprint = responder.hostkeys_seen[0] │ │ │ │ │ + error_args = {'host-key': f'{host} {algorithm} {key}', 'host-fingerprint': fingerprint} │ │ │ │ │ + else: │ │ │ │ │ + error_args = {} │ │ │ │ │ + │ │ │ │ │ + if isinstance(exc, ferny.SshChangedHostKeyError): │ │ │ │ │ + error = 'invalid-hostkey' │ │ │ │ │ + elif self.private: │ │ │ │ │ + error = 'unknown-hostkey' │ │ │ │ │ + else: │ │ │ │ │ + # non-private session case. throw a generic error. │ │ │ │ │ + error = 'unknown-host' │ │ │ │ │ + │ │ │ │ │ + logger.debug('SshPeer got a %s %s; private %s, seen hostkeys %r; raising %s with extra args %r', │ │ │ │ │ + type(exc), exc, self.private, responder.hostkeys_seen, error, error_args) │ │ │ │ │ + raise PeerError(error, error_args, error=error, auth_method_results={}) from exc │ │ │ │ │ + │ │ │ │ │ + except ferny.SshAuthenticationError as exc: │ │ │ │ │ + logger.debug('authentication to host %s failed: %s', host, exc) │ │ │ │ │ + │ │ │ │ │ + results = {method: 'not-provided' for method in exc.methods} │ │ │ │ │ + if 'password' in results and self.password is not None: │ │ │ │ │ + if responder.password_attempts == 0: │ │ │ │ │ + results['password'] = 'not-tried' │ │ │ │ │ + else: │ │ │ │ │ + results['password'] = 'denied' │ │ │ │ │ + │ │ │ │ │ + raise PeerError('authentication-failed', │ │ │ │ │ + error=responder.error_message or 'authentication-failed', │ │ │ │ │ + auth_method_results=results) from exc │ │ │ │ │ + │ │ │ │ │ + except ferny.SshError as exc: │ │ │ │ │ + logger.debug('unknown failure connecting to host %s: %s', host, exc) │ │ │ │ │ + raise PeerError('internal-error', message=str(exc)) from exc │ │ │ │ │ + │ │ │ │ │ + args = self.session.wrap_subprocess_args(['cockpit-bridge']) │ │ │ │ │ + await self.spawn(args, []) │ │ │ │ │ + │ │ │ │ │ + def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None: │ │ │ │ │ + if host == self.host: │ │ │ │ │ + self.close() │ │ │ │ │ + elif host is None: │ │ │ │ │ + super().do_kill(host, group, message) │ │ │ │ │ + │ │ │ │ │ + def do_authorize(self, message: JsonObject) -> None: │ │ │ │ │ + if get_str(message, 'challenge').startswith('plain1:'): │ │ │ │ │ + cookie = get_str(message, 'cookie') │ │ │ │ │ + self.write_control(command='authorize', cookie=cookie, response=self.password or '') │ │ │ │ │ + self.password = None # once is enough... │ │ │ │ │ + │ │ │ │ │ + def do_superuser_init_done(self) -> None: │ │ │ │ │ + self.password = None │ │ │ │ │ + │ │ │ │ │ + def __init__(self, router: Router, host: str, user: Optional[str], options: JsonObject, *, private: bool) -> None: │ │ │ │ │ + super().__init__(router) │ │ │ │ │ + self.host = host │ │ │ │ │ + self.user = user │ │ │ │ │ + self.password = get_str(options, 'password', None) │ │ │ │ │ + self.private = private │ │ │ │ │ + │ │ │ │ │ + self.session = ferny.Session() │ │ │ │ │ + │ │ │ │ │ + superuser: JsonValue │ │ │ │ │ + init_superuser = get_str_or_none(options, 'init-superuser', None) │ │ │ │ │ + if init_superuser in (None, 'none'): │ │ │ │ │ + superuser = False │ │ │ │ │ + else: │ │ │ │ │ + superuser = {'id': init_superuser} │ │ │ │ │ + │ │ │ │ │ + self.start_in_background(init_host=host, superuser=superuser) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class HostRoutingRule(RoutingRule): │ │ │ │ │ + remotes: Dict[Tuple[str, Optional[str], Optional[str]], Peer] │ │ │ │ │ + │ │ │ │ │ + def __init__(self, router): │ │ │ │ │ + super().__init__(router) │ │ │ │ │ + self.remotes = {} │ │ │ │ │ + │ │ │ │ │ + def apply_rule(self, options: JsonObject) -> Optional[Peer]: │ │ │ │ │ + assert self.router is not None │ │ │ │ │ + assert self.router.init_host is not None │ │ │ │ │ + │ │ │ │ │ + host = get_str(options, 'host', self.router.init_host) │ │ │ │ │ + if host == self.router.init_host: │ │ │ │ │ + return None │ │ │ │ │ + │ │ │ │ │ + user = get_str(options, 'user', None) │ │ │ │ │ + # HACK: the front-end relies on this for tracking connections without an explicit user name; │ │ │ │ │ + # the user will then be determined by SSH (`User` in the config or the current user) │ │ │ │ │ + # See cockpit_router_normalize_host_params() in src/bridge/cockpitrouter.c │ │ │ │ │ + if user == getpass.getuser(): │ │ │ │ │ + user = None │ │ │ │ │ + if not user: │ │ │ │ │ + user_from_host, _, _ = host.rpartition('@') │ │ │ │ │ + user = user_from_host or None # avoid '' │ │ │ │ │ + │ │ │ │ │ + if get_str(options, 'session', None) == 'private': │ │ │ │ │ + nonce = get_str(options, 'channel') │ │ │ │ │ + else: │ │ │ │ │ + nonce = None │ │ │ │ │ + │ │ │ │ │ + assert isinstance(host, str) │ │ │ │ │ + assert user is None or isinstance(user, str) │ │ │ │ │ + assert nonce is None or isinstance(nonce, str) │ │ │ │ │ + │ │ │ │ │ + key = host, user, nonce │ │ │ │ │ + │ │ │ │ │ + logger.debug('Request for channel %s is remote.', options) │ │ │ │ │ + logger.debug('key=%s', key) │ │ │ │ │ + │ │ │ │ │ + if key not in self.remotes: │ │ │ │ │ + logger.debug('%s is not among the existing remotes %s. Opening a new connection.', key, self.remotes) │ │ │ │ │ + peer = SshPeer(self.router, host, user, options, private=nonce is not None) │ │ │ │ │ + peer.add_done_callback(lambda: self.remotes.__delitem__(key)) │ │ │ │ │ + self.remotes[key] = peer │ │ │ │ │ + │ │ │ │ │ + return self.remotes[key] │ │ │ │ │ + │ │ │ │ │ + def shutdown(self): │ │ │ │ │ + for peer in set(self.remotes.values()): │ │ │ │ │ + peer.close() │ │ │ │ │ +'''.encode('utf-8'), │ │ │ │ │ + 'cockpit/_vendor/__init__.py': br'''''', │ │ │ │ │ + 'cockpit/_vendor/ferny/session.py': r'''# ferny - asyncio SSH client library, using ssh(1) │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ +# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ - │ │ │ │ │ -# This file is responsible for creating functions to (de)serialize Python │ │ │ │ │ -# objects into and out of BusMessage objects. │ │ │ │ │ -# │ │ │ │ │ -# Each Type corresponds to a (possibly complex) D-Bus type. It has a .reader │ │ │ │ │ -# and a .writer property. The readers take a message and deserialize a single │ │ │ │ │ -# value from it, returning the value: │ │ │ │ │ -# │ │ │ │ │ -# def reader(message: BusMessage) -> object: │ │ │ │ │ -# │ │ │ │ │ -# The writers take a message and a value, and append the value to the message. │ │ │ │ │ -# │ │ │ │ │ -# def writer(message: BusMessage, value: object) -> None: │ │ │ │ │ -# │ │ │ │ │ -# The necessary information for the specific type of object to be handled is │ │ │ │ │ -# part of the function. No additional information needs to be provided. │ │ │ │ │ - │ │ │ │ │ -import binascii │ │ │ │ │ +import asyncio │ │ │ │ │ import ctypes │ │ │ │ │ import functools │ │ │ │ │ -import inspect │ │ │ │ │ -import json │ │ │ │ │ -import re │ │ │ │ │ -from enum import Enum │ │ │ │ │ -from typing import Any, Callable, ClassVar, Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union │ │ │ │ │ - │ │ │ │ │ -from . import libsystemd, typing │ │ │ │ │ -from .typing import Annotated, TypeGuard │ │ │ │ │ - │ │ │ │ │ -_object_path_re = re.compile(r'/|(/[A-Za-z0-9_]+)+') │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def is_object_path(candidate: str) -> TypeGuard['BusType.objectpath']: │ │ │ │ │ - return _object_path_re.fullmatch(candidate) is not None │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -def is_signature(candidate: str) -> TypeGuard['BusType.signature']: │ │ │ │ │ - offset = 0 │ │ │ │ │ +import logging │ │ │ │ │ +import os │ │ │ │ │ +import shlex │ │ │ │ │ +import signal │ │ │ │ │ +import subprocess │ │ │ │ │ +import tempfile │ │ │ │ │ +from typing import Mapping, Sequence │ │ │ │ │ │ │ │ │ │ - def maybe_pop(acceptable: str) -> Optional[str]: │ │ │ │ │ - nonlocal offset │ │ │ │ │ - char = candidate[offset] │ │ │ │ │ - if char in acceptable: │ │ │ │ │ - offset += 1 │ │ │ │ │ - return char │ │ │ │ │ - else: │ │ │ │ │ - return None │ │ │ │ │ +from . import ssh_errors │ │ │ │ │ +from .interaction_agent import InteractionAgent, InteractionError, InteractionHandler, write_askpass_to_tmpdir │ │ │ │ │ │ │ │ │ │ - def pop(acceptable: str) -> str: │ │ │ │ │ - char = maybe_pop(acceptable) │ │ │ │ │ - assert char is not None │ │ │ │ │ - return char │ │ │ │ │ +prctl = ctypes.cdll.LoadLibrary('libc.so.6').prctl │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ +PR_SET_PDEATHSIG = 1 │ │ │ │ │ │ │ │ │ │ - def find_next() -> None: │ │ │ │ │ - first = pop('ybnqiuxtsogdva(') # valid first characters │ │ │ │ │ - if first == 'a': │ │ │ │ │ - if maybe_pop('{'): # dict │ │ │ │ │ - pop('ybnqiuxtsogd') # key │ │ │ │ │ - find_next() # value │ │ │ │ │ - pop('}') │ │ │ │ │ - else: # array │ │ │ │ │ - find_next() # item │ │ │ │ │ - elif first == '(': # structure │ │ │ │ │ - find_next() # at least one item │ │ │ │ │ - while not maybe_pop(')'): │ │ │ │ │ - find_next() # and possibly more │ │ │ │ │ │ │ │ │ │ +@functools.lru_cache() │ │ │ │ │ +def has_feature(feature: str, teststr: str = 'x') -> bool: │ │ │ │ │ try: │ │ │ │ │ - while offset < len(candidate): │ │ │ │ │ - find_next() │ │ │ │ │ + subprocess.check_output(['ssh', f'-o{feature} {teststr}', '-G', 'nonexisting'], stderr=subprocess.DEVNULL) │ │ │ │ │ return True │ │ │ │ │ - except (AssertionError, IndexError): │ │ │ │ │ + except subprocess.CalledProcessError: │ │ │ │ │ return False │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -def yield_base_helpers() -> Iterable[Tuple[str, object]]: │ │ │ │ │ - for method in ['enter_container', 'exit_container', 'open_container', 'close_container', │ │ │ │ │ - 'append_basic', 'read_basic', 'append_array', 'read_array']: │ │ │ │ │ - yield method, libsystemd.libsystemd[f'sd_bus_message_{method}'] │ │ │ │ │ +class SubprocessContext: │ │ │ │ │ + def wrap_subprocess_args(self, args: Sequence[str]) -> Sequence[str]: │ │ │ │ │ + """Return the args required to launch a process in the given context. │ │ │ │ │ │ │ │ │ │ - for name in ['size_t', 'char_p']: │ │ │ │ │ - instance = getattr(ctypes, f'c_{name}')() │ │ │ │ │ - yield f'{name}', instance │ │ │ │ │ - yield f'{name}_ref', ctypes.byref(instance) │ │ │ │ │ - yield f'{name}_setter', instance.__class__.value.__set__ │ │ │ │ │ + For example, this might return a vector with │ │ │ │ │ + ["sudo"] │ │ │ │ │ + or │ │ │ │ │ + ["flatpak-spawn", "--host"] │ │ │ │ │ + prepended. │ │ │ │ │ │ │ │ │ │ - for char in 'aervy': │ │ │ │ │ - yield char, ctypes.c_char(ord(char)) │ │ │ │ │ + It is also possible that more substantial changes may be performed. │ │ │ │ │ │ │ │ │ │ - # https://docs.python.org/3/c-api/unicode.html#c.PyUnicode_FromString │ │ │ │ │ - to_bytes = ctypes.pythonapi.PyBytes_FromStringAndSize │ │ │ │ │ - to_bytes.restype = ctypes.py_object │ │ │ │ │ - yield 'to_bytes', to_bytes │ │ │ │ │ + This function is not permitted to modify its argument, although it may │ │ │ │ │ + (optionally) return it unmodified, if no changes are required. │ │ │ │ │ + """ │ │ │ │ │ + return args │ │ │ │ │ │ │ │ │ │ + def wrap_subprocess_env(self, env: Mapping[str, str]) -> Mapping[str, str]: │ │ │ │ │ + """Return the envp required to launch a process in the given context. │ │ │ │ │ │ │ │ │ │ -_base_helpers = dict(yield_base_helpers()) │ │ │ │ │ + For example, this might set the "SUDO_ASKPASS" environment variable, if │ │ │ │ │ + needed. │ │ │ │ │ │ │ │ │ │ -T = TypeVar('T') │ │ │ │ │ + As with wrap_subprocess_args(), this function is not permitted to │ │ │ │ │ + modify its argument, although it may (optionally) return it unmodified │ │ │ │ │ + if no changes are required. │ │ │ │ │ + """ │ │ │ │ │ + return env │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -def call_with_kwargs(func: Callable[..., T], kwargs: Dict[str, Any]) -> T: │ │ │ │ │ - parameters = set(inspect.signature(func).parameters) │ │ │ │ │ - return func(**{key: value for key, value in kwargs.items() if key in parameters}) │ │ │ │ │ +class Session(SubprocessContext, InteractionHandler): │ │ │ │ │ + # Set after .connect() called, even if failed │ │ │ │ │ + _controldir: 'tempfile.TemporaryDirectory | None' = None │ │ │ │ │ + _controlsock: 'str | None' = None │ │ │ │ │ │ │ │ │ │ + # Set if connected, else None │ │ │ │ │ + _process: 'asyncio.subprocess.Process | None' = None │ │ │ │ │ │ │ │ │ │ -class Type: │ │ │ │ │ - _cache: ClassVar[Dict[Tuple[type, Tuple[object, ...]], 'Type']] = {} │ │ │ │ │ + async def connect(self, │ │ │ │ │ + destination: str, │ │ │ │ │ + handle_host_key: bool = False, │ │ │ │ │ + configfile: 'str | None' = None, │ │ │ │ │ + identity_file: 'str | None' = None, │ │ │ │ │ + login_name: 'str | None' = None, │ │ │ │ │ + options: 'Mapping[str, str] | None' = None, │ │ │ │ │ + pkcs11: 'str | None' = None, │ │ │ │ │ + port: 'int | None' = None, │ │ │ │ │ + interaction_responder: 'InteractionHandler | None' = None) -> None: │ │ │ │ │ + rundir = os.path.join(os.environ.get('XDG_RUNTIME_DIR', '/run'), 'ferny') │ │ │ │ │ + os.makedirs(rundir, exist_ok=True) │ │ │ │ │ + self._controldir = tempfile.TemporaryDirectory(dir=rundir) │ │ │ │ │ + self._controlsock = f'{self._controldir.name}/socket' │ │ │ │ │ │ │ │ │ │ - __slots__ = 'typestring', 'bytes_typestring', 'writer', 'reader' │ │ │ │ │ - typestring: str │ │ │ │ │ - bytes_typestring: bytes │ │ │ │ │ - reader: Callable[[libsystemd.sd_bus_message], object] │ │ │ │ │ - writer: Callable[[libsystemd.sd_bus_message, object], None] │ │ │ │ │ + # In general, we can't guarantee an accessible and executable version │ │ │ │ │ + # of this file, but since it's small and we're making a temporary │ │ │ │ │ + # directory anyway, let's just copy it into place and use it from │ │ │ │ │ + # there. │ │ │ │ │ + askpass_path = write_askpass_to_tmpdir(self._controldir.name) │ │ │ │ │ │ │ │ │ │ - def __new__(cls, *args: Any) -> 'Type': │ │ │ │ │ - instance = Type._cache.get((cls, args)) │ │ │ │ │ - if instance is None: │ │ │ │ │ - instance = object.__new__(cls) │ │ │ │ │ - Type._cache[(cls, args)] = instance │ │ │ │ │ - return instance │ │ │ │ │ + env = dict(os.environ) │ │ │ │ │ + env['SSH_ASKPASS'] = askpass_path │ │ │ │ │ + env['SSH_ASKPASS_REQUIRE'] = 'force' │ │ │ │ │ + # old SSH doesn't understand SSH_ASKPASS_REQUIRE and guesses based on DISPLAY instead │ │ │ │ │ + env['DISPLAY'] = '-' │ │ │ │ │ │ │ │ │ │ - def __init__(self, typestring: str, **kwargs: Any): │ │ │ │ │ - self.typestring = typestring │ │ │ │ │ - self.bytes_typestring = typestring.encode('ascii') │ │ │ │ │ + args = [ │ │ │ │ │ + '-M', │ │ │ │ │ + '-N', │ │ │ │ │ + '-S', self._controlsock, │ │ │ │ │ + '-o', 'PermitLocalCommand=yes', │ │ │ │ │ + '-o', f'LocalCommand={askpass_path}', │ │ │ │ │ + ] │ │ │ │ │ │ │ │ │ │ - kwargs = dict(_base_helpers, **kwargs) │ │ │ │ │ - self.writer = call_with_kwargs(self.get_writer, kwargs) │ │ │ │ │ - self.reader = call_with_kwargs(self.get_reader, kwargs) │ │ │ │ │ + if configfile is not None: │ │ │ │ │ + args.append(f'-F{configfile}') │ │ │ │ │ │ │ │ │ │ - def __repr__(self) -> str: │ │ │ │ │ - return f"{self.__class__.__name__}('{self.typestring}')" │ │ │ │ │ + if identity_file is not None: │ │ │ │ │ + args.append(f'-i{identity_file}') │ │ │ │ │ │ │ │ │ │ - def get_writer(self, **kwargs: object) -> Callable[[object, object], None]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + if options is not None: │ │ │ │ │ + for key in options: # Note: Mapping may not have .items() │ │ │ │ │ + args.append(f'-o{key} {options[key]}') │ │ │ │ │ │ │ │ │ │ - def get_reader(self, **kwargs: object) -> Callable[[object], object]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + if pkcs11 is not None: │ │ │ │ │ + args.append(f'-I{pkcs11}') │ │ │ │ │ │ │ │ │ │ + if port is not None: │ │ │ │ │ + args.append(f'-p{port}') │ │ │ │ │ │ │ │ │ │ -class BasicType(Type): │ │ │ │ │ - __slots__ = () │ │ │ │ │ + if login_name is not None: │ │ │ │ │ + args.append(f'-l{login_name}') │ │ │ │ │ │ │ │ │ │ - def __init__(self, typestring: str, ctype, get_wrapper=None, **kwargs): │ │ │ │ │ - variable = ctype() # NB: not thread-safe │ │ │ │ │ - super().__init__(typestring, ctype=ctype, type_constant=ctypes.c_char(ord(typestring)), │ │ │ │ │ - getter=get_wrapper or ctype.value.__get__, setter=ctype.value.__set__, │ │ │ │ │ - variable=variable, reference=ctypes.byref(variable), **kwargs) │ │ │ │ │ + if handle_host_key and has_feature('KnownHostsCommand'): │ │ │ │ │ + args.extend([ │ │ │ │ │ + '-o', f'KnownHostsCommand={askpass_path} %I %H %t %K %f', │ │ │ │ │ + '-o', 'StrictHostKeyChecking=yes', │ │ │ │ │ + ]) │ │ │ │ │ │ │ │ │ │ - def get_reader(self, read_basic, type_constant, variable, reference, getter): │ │ │ │ │ - def basic_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ - if read_basic(message, type_constant, reference) <= 0: │ │ │ │ │ - raise StopIteration │ │ │ │ │ - return getter(variable) │ │ │ │ │ - return basic_reader │ │ │ │ │ + agent = InteractionAgent([interaction_responder] if interaction_responder is not None else []) │ │ │ │ │ │ │ │ │ │ + # SSH_ASKPASS_REQUIRE is not generally available, so use setsid │ │ │ │ │ + process = await asyncio.create_subprocess_exec( │ │ │ │ │ + *('/usr/bin/ssh', *args, destination), env=env, │ │ │ │ │ + start_new_session=True, stdin=asyncio.subprocess.DEVNULL, │ │ │ │ │ + stdout=asyncio.subprocess.DEVNULL, stderr=agent, # type: ignore │ │ │ │ │ + preexec_fn=lambda: prctl(PR_SET_PDEATHSIG, signal.SIGKILL)) │ │ │ │ │ │ │ │ │ │ -class FixedType(BasicType): │ │ │ │ │ - __slots__ = () │ │ │ │ │ + # This is tricky: we need to clean up the subprocess, but only in case │ │ │ │ │ + # if failure. Otherwise, we keep it around. │ │ │ │ │ + try: │ │ │ │ │ + await agent.communicate() │ │ │ │ │ + assert os.path.exists(self._controlsock) │ │ │ │ │ + self._process = process │ │ │ │ │ + except InteractionError as exc: │ │ │ │ │ + await process.wait() │ │ │ │ │ + raise ssh_errors.get_exception_for_ssh_stderr(str(exc)) from None │ │ │ │ │ + except BaseException: │ │ │ │ │ + # If we get here because the InteractionHandler raised an │ │ │ │ │ + # exception then SSH might still be running, and may even attempt │ │ │ │ │ + # further interactions (ie: 2nd attempt for password). We already │ │ │ │ │ + # have our exception and don't need any more info. Kill it. │ │ │ │ │ + try: │ │ │ │ │ + process.kill() │ │ │ │ │ + except ProcessLookupError: │ │ │ │ │ + pass # already exited? good. │ │ │ │ │ + await process.wait() │ │ │ │ │ + raise │ │ │ │ │ │ │ │ │ │ - def get_writer(self, append_basic, type_constant, variable, reference, setter, getter): │ │ │ │ │ - def fixed_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ - setter(variable, value) │ │ │ │ │ - if getter(variable) != value: │ │ │ │ │ - raise TypeError(f"Cannot represent value {value} with type '{self.typestring}'") │ │ │ │ │ - append_basic(message, type_constant, reference) │ │ │ │ │ - return fixed_writer │ │ │ │ │ + def is_connected(self) -> bool: │ │ │ │ │ + return self._process is not None │ │ │ │ │ │ │ │ │ │ + async def wait(self) -> None: │ │ │ │ │ + assert self._process is not None │ │ │ │ │ + await self._process.wait() │ │ │ │ │ │ │ │ │ │ -class StringLikeType(BasicType): │ │ │ │ │ - __slots__ = () │ │ │ │ │ + def exit(self) -> None: │ │ │ │ │ + assert self._process is not None │ │ │ │ │ + self._process.terminate() │ │ │ │ │ │ │ │ │ │ - @staticmethod │ │ │ │ │ - def get_guarded_conversion(typestring: str, guard: Callable[[str], bool]) -> Callable[[object], bytes]: │ │ │ │ │ - def convert(candidate: object) -> bytes: │ │ │ │ │ - if not isinstance(candidate, str): │ │ │ │ │ - raise TypeError(f"'{typestring}' encodes 'str', not '{candidate.__class__.__name__}'") │ │ │ │ │ - if not guard(candidate): │ │ │ │ │ - raise ValueError(f"Invalid value provided for type '{typestring}'") │ │ │ │ │ - return str.encode(candidate) │ │ │ │ │ - return convert │ │ │ │ │ + async def disconnect(self) -> None: │ │ │ │ │ + self.exit() │ │ │ │ │ + await self.wait() │ │ │ │ │ │ │ │ │ │ - def __init__(self, typestring: str, guard: Optional[Callable[[str], bool]] = None): │ │ │ │ │ - # https://docs.python.org/3/c-api/unicode.html#c.PyUnicode_FromString │ │ │ │ │ - to_unicode = ctypes.pythonapi.PyUnicode_FromString │ │ │ │ │ - to_unicode.restype = ctypes.py_object │ │ │ │ │ + # Launching of processes │ │ │ │ │ + def wrap_subprocess_args(self, args: Sequence[str]) -> Sequence[str]: │ │ │ │ │ + assert self._controlsock is not None │ │ │ │ │ + # 1. We specify the hostname as the empty string: it will be ignored │ │ │ │ │ + # when ssh is trying to use the control socket, but in case the │ │ │ │ │ + # socket has stopped working, ssh will try to fall back to directly │ │ │ │ │ + # connecting, in which case an empty hostname will prevent that. │ │ │ │ │ + # 2. We need to quote the arguments — ssh will paste them together │ │ │ │ │ + # using only spaces, executing the result using the user's shell. │ │ │ │ │ + return ('ssh', '-S', self._controlsock, '', *map(shlex.quote, args)) │ │ │ │ │ +'''.encode('utf-8'), │ │ │ │ │ + 'cockpit/_vendor/ferny/askpass.py': br'''from .interaction_client import main │ │ │ │ │ │ │ │ │ │ - if guard is not None: │ │ │ │ │ - convert = StringLikeType.get_guarded_conversion(typestring, guard) │ │ │ │ │ - else: │ │ │ │ │ - convert = str.encode # type: ignore[assignment] # can throw TypeError on call │ │ │ │ │ +if __name__ == '__main__': │ │ │ │ │ + main() │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/ferny/py.typed': br'''''', │ │ │ │ │ + 'cockpit/_vendor/ferny/ssh_askpass.py': br'''import logging │ │ │ │ │ +import re │ │ │ │ │ +from typing import ClassVar, Match, Sequence │ │ │ │ │ │ │ │ │ │ - super().__init__(typestring, ctypes.c_char_p, to_unicode, convert=convert) │ │ │ │ │ +from .interaction_agent import AskpassHandler │ │ │ │ │ │ │ │ │ │ - def get_writer(self, append_basic, type_constant, convert): │ │ │ │ │ - def string_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ - append_basic(message, type_constant, convert(value)) │ │ │ │ │ - return string_writer │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class BytestringType(Type): │ │ │ │ │ - __slots__ = () │ │ │ │ │ +class AskpassPrompt: │ │ │ │ │ + """An askpass prompt resulting from a call to ferny-askpass. │ │ │ │ │ │ │ │ │ │ - def get_writer(self, append_array, y, size_t_setter, size_t): │ │ │ │ │ - def bytes_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ - if not isinstance(value, bytes): │ │ │ │ │ - if isinstance(value, str): │ │ │ │ │ - try: │ │ │ │ │ - value = binascii.a2b_base64(value.encode('ascii')) # or decode base64 │ │ │ │ │ - except binascii.Error as exc: │ │ │ │ │ - raise ValueError("'ay' cannot encode invalid base64 string") from exc │ │ │ │ │ - elif isinstance(value, (memoryview, bytearray)): │ │ │ │ │ - value = bytes(value) │ │ │ │ │ - else: │ │ │ │ │ - raise TypeError("'ay' can only encode bytes-like or base64 string objects, " │ │ │ │ │ - f"not '{value.__class__.__name__}'.") │ │ │ │ │ - size_t_setter(size_t, len(value)) │ │ │ │ │ - append_array(message, y, value, size_t) │ │ │ │ │ - return bytes_writer │ │ │ │ │ + stderr: the contents of stderr from before ferny-askpass was called. │ │ │ │ │ + Likely related to previous failed operations. │ │ │ │ │ + messages: all but the last line of the prompt as handed to ferny-askpass. │ │ │ │ │ + Usually contains context about the question. │ │ │ │ │ + prompt: the last line handed to ferny-askpass. The prompt itself. │ │ │ │ │ + """ │ │ │ │ │ + stderr: str │ │ │ │ │ + messages: str │ │ │ │ │ + prompt: str │ │ │ │ │ │ │ │ │ │ - def get_reader(self, read_array, y, to_bytes, char_p, char_p_ref, size_t, size_t_ref): │ │ │ │ │ - def bytes_reader(message): │ │ │ │ │ - if read_array(message, y, char_p_ref, size_t_ref) <= 0: │ │ │ │ │ - raise StopIteration │ │ │ │ │ - return to_bytes(char_p, size_t) │ │ │ │ │ - return bytes_reader │ │ │ │ │ + def __init__(self, prompt: str, messages: str, stderr: str) -> None: │ │ │ │ │ + self.stderr = stderr │ │ │ │ │ + self.messages = messages │ │ │ │ │ + self.prompt = prompt │ │ │ │ │ │ │ │ │ │ + def reply(self, response: str) -> None: │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ -class ContainerType(Type): │ │ │ │ │ - _typestring_template: ClassVar[str] │ │ │ │ │ - __slots__ = 'item_types' │ │ │ │ │ - item_types: Sequence[Type] │ │ │ │ │ + def close(self) -> None: │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ - def __init__(self, *item_types: Type, **kwargs: Any): │ │ │ │ │ - assert len(item_types) > 0 │ │ │ │ │ - item_typestrings = ''.join(item.typestring for item in item_types) │ │ │ │ │ - self.item_types = item_types │ │ │ │ │ - super().__init__(self._typestring_template.replace('_', item_typestrings), │ │ │ │ │ - type_contents=ctypes.c_char_p(item_typestrings.encode('ascii')), │ │ │ │ │ - **kwargs) │ │ │ │ │ + async def handle_via(self, responder: 'SshAskpassResponder') -> None: │ │ │ │ │ + try: │ │ │ │ │ + response = await self.dispatch(responder) │ │ │ │ │ + if response is not None: │ │ │ │ │ + self.reply(response) │ │ │ │ │ + finally: │ │ │ │ │ + self.close() │ │ │ │ │ │ │ │ │ │ + async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ + return await responder.do_prompt(self) │ │ │ │ │ │ │ │ │ │ -class ArrayType(ContainerType): │ │ │ │ │ - _typestring_template = 'a_' │ │ │ │ │ - __slots__ = () │ │ │ │ │ │ │ │ │ │ - def __init__(self, item_type: Type): │ │ │ │ │ - super().__init__(item_type, │ │ │ │ │ - item_writer=item_type.writer, │ │ │ │ │ - item_reader=item_type.reader, │ │ │ │ │ - list_append=list.append) │ │ │ │ │ +class SSHAskpassPrompt(AskpassPrompt): │ │ │ │ │ + # The valid answers to prompts of this type. If this is None then any │ │ │ │ │ + # answer is permitted. If it's a sequence then only answers from the │ │ │ │ │ + # sequence are permitted. If it's an empty sequence, then no answer is │ │ │ │ │ + # permitted (ie: the askpass callback should never return). │ │ │ │ │ + answers: 'ClassVar[Sequence[str] | None]' = None │ │ │ │ │ │ │ │ │ │ - def get_reader(self, enter_container, exit_container, list_append, item_reader): │ │ │ │ │ - def array_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ - if enter_container(message, 0, None) <= 0: │ │ │ │ │ - raise StopIteration │ │ │ │ │ - result: List[object] = [] │ │ │ │ │ - try: │ │ │ │ │ - while True: │ │ │ │ │ - list_append(result, item_reader(message)) │ │ │ │ │ - except StopIteration: │ │ │ │ │ - return result │ │ │ │ │ - finally: │ │ │ │ │ - exit_container(message) │ │ │ │ │ - return array_reader │ │ │ │ │ + # Patterns to capture. `_pattern` *must* match. │ │ │ │ │ + _pattern: ClassVar[str] │ │ │ │ │ + # `_extra_patterns` can fill in extra class attributes if they match. │ │ │ │ │ + _extra_patterns: ClassVar[Sequence[str]] = () │ │ │ │ │ │ │ │ │ │ - def get_writer(self, a, type_contents, open_container, close_container, item_writer): │ │ │ │ │ - def array_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ - open_container(message, a, type_contents) │ │ │ │ │ - for item in value: # type: ignore[attr-defined] # can throw TypeError │ │ │ │ │ - item_writer(message, item) │ │ │ │ │ - close_container(message) │ │ │ │ │ - return array_writer │ │ │ │ │ + def __init__(self, prompt: str, messages: str, stderr: str, match: Match) -> None: │ │ │ │ │ + super().__init__(prompt, messages, stderr) │ │ │ │ │ + self.__dict__.update(match.groupdict()) │ │ │ │ │ │ │ │ │ │ + for pattern in self._extra_patterns: │ │ │ │ │ + extra_match = re.search(with_helpers(pattern), messages, re.M) │ │ │ │ │ + if extra_match is not None: │ │ │ │ │ + self.__dict__.update(extra_match.groupdict()) │ │ │ │ │ │ │ │ │ │ -class StructType(ContainerType): │ │ │ │ │ - _typestring_template = '(_)' │ │ │ │ │ - __slots__ = () │ │ │ │ │ │ │ │ │ │ - def get_reader(self, enter_container, exit_container): │ │ │ │ │ - item_readers = tuple(item_type.reader for item_type in self.item_types) │ │ │ │ │ +# Specific prompts │ │ │ │ │ +HELPERS = { │ │ │ │ │ + "%{algorithm}": r"(?P\b[-\w]+\b)", │ │ │ │ │ + "%{filename}": r"(?P.+)", │ │ │ │ │ + "%{fingerprint}": r"(?PSHA256:[0-9A-Za-z+/]{43})", │ │ │ │ │ + "%{hostname}": r"(?P[^ @']+)", │ │ │ │ │ + "%{pkcs11_id}": r"(?P.+)", │ │ │ │ │ + "%{username}": r"(?P[^ @']+)", │ │ │ │ │ +} │ │ │ │ │ │ │ │ │ │ - def array_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ - if enter_container(message, 0, None) <= 0: │ │ │ │ │ - raise StopIteration │ │ │ │ │ - result = tuple(item_reader(message) for item_reader in item_readers) │ │ │ │ │ - exit_container(message) │ │ │ │ │ - return result │ │ │ │ │ - return array_reader │ │ │ │ │ │ │ │ │ │ - def get_writer(self, r, type_contents, open_container, close_container): │ │ │ │ │ - item_writers = tuple(item_type.writer for item_type in self.item_types) │ │ │ │ │ +class SshPasswordPrompt(SSHAskpassPrompt): │ │ │ │ │ + _pattern = r"%{username}@%{hostname}'s password: " │ │ │ │ │ + username: 'str | None' = None │ │ │ │ │ + hostname: 'str | None' = None │ │ │ │ │ │ │ │ │ │ - def struct_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ - n_items = len(value) # type: ignore[arg-type] # can throw TypeError │ │ │ │ │ - if n_items != len(item_writers): │ │ │ │ │ - raise TypeError(f"Wrong numbers of items ({n_items}) for structure type '{self.typestring}'") │ │ │ │ │ - open_container(message, r, type_contents) │ │ │ │ │ - for item_writer, item in zip(item_writers, value): # type: ignore[call-overload] # can throw TypeError │ │ │ │ │ - item_writer(message, item) │ │ │ │ │ - close_container(message) │ │ │ │ │ - return struct_writer │ │ │ │ │ + async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ + return await responder.do_password_prompt(self) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class DictionaryType(ContainerType): │ │ │ │ │ - _typestring_template = 'a{_}' │ │ │ │ │ - __slots__ = () │ │ │ │ │ +class SshPassphrasePrompt(SSHAskpassPrompt): │ │ │ │ │ + _pattern = r"Enter passphrase for key '%{filename}': " │ │ │ │ │ + filename: str │ │ │ │ │ │ │ │ │ │ - def __init__(self, key_type: Type, value_type: Type): │ │ │ │ │ - assert isinstance(key_type, BasicType) │ │ │ │ │ - item_type = '{' + key_type.typestring + value_type.typestring + '}' │ │ │ │ │ - super().__init__(key_type, value_type, │ │ │ │ │ - key_reader=key_type.reader, key_writer=key_type.writer, │ │ │ │ │ - value_reader=value_type.reader, value_writer=value_type.writer, │ │ │ │ │ - item_type=ctypes.c_char_p(item_type.encode('ascii'))) │ │ │ │ │ + async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ + return await responder.do_passphrase_prompt(self) │ │ │ │ │ │ │ │ │ │ - def get_reader(self, enter_container, exit_container, key_reader, value_reader): │ │ │ │ │ - def dict_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ - if enter_container(message, 0, None) <= 0: # array │ │ │ │ │ - raise StopIteration │ │ │ │ │ - result = {} │ │ │ │ │ - while enter_container(message, 0, None) > 0: # entry │ │ │ │ │ - key = key_reader(message) │ │ │ │ │ - value = value_reader(message) │ │ │ │ │ - result[key] = value │ │ │ │ │ - exit_container(message) │ │ │ │ │ - exit_container(message) │ │ │ │ │ - return result │ │ │ │ │ - return dict_reader │ │ │ │ │ │ │ │ │ │ - def get_writer(self, a, item_type, e, type_contents, open_container, close_container, key_writer, value_writer): │ │ │ │ │ - def dict_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ - open_container(message, a, item_type) # array │ │ │ │ │ - for key, val in value.items(): # type: ignore[attr-defined] # can raise AttributeError │ │ │ │ │ - open_container(message, e, type_contents) # entry │ │ │ │ │ - key_writer(message, key) # key │ │ │ │ │ - value_writer(message, val) # value │ │ │ │ │ - close_container(message) # end entry │ │ │ │ │ - close_container(message) # end array │ │ │ │ │ - return dict_writer │ │ │ │ │ +class SshFIDOPINPrompt(SSHAskpassPrompt): │ │ │ │ │ + _pattern = r"Enter PIN for %{algorithm} key %{filename}: " │ │ │ │ │ + algorithm: str │ │ │ │ │ + filename: str │ │ │ │ │ │ │ │ │ │ + async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ + return await responder.do_fido_pin_prompt(self) │ │ │ │ │ │ │ │ │ │ -class VariantType(Type): │ │ │ │ │ - __slots__ = () │ │ │ │ │ │ │ │ │ │ - def get_reader(self, enter_container, exit_container): │ │ │ │ │ - def variant_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ - if enter_container(message, 0, None) <= 0: │ │ │ │ │ - raise StopIteration │ │ │ │ │ - typestring = message.get_signature(False) │ │ │ │ │ - type_, = from_signature(typestring) │ │ │ │ │ - value = type_.reader(message) │ │ │ │ │ - exit_container(message) │ │ │ │ │ - return Variant(value, type_) │ │ │ │ │ - return variant_reader │ │ │ │ │ +class SshFIDOUserPresencePrompt(SSHAskpassPrompt): │ │ │ │ │ + _pattern = r"Confirm user presence for key %{algorithm} %{fingerprint}" │ │ │ │ │ + answers = () │ │ │ │ │ + algorithm: str │ │ │ │ │ + fingerprint: str │ │ │ │ │ │ │ │ │ │ - def get_writer(self, open_container, close_container, v): │ │ │ │ │ - def variant_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ - if isinstance(value, Variant): │ │ │ │ │ - type_ = value.type │ │ │ │ │ - contents = value.value │ │ │ │ │ - else: │ │ │ │ │ - try: │ │ │ │ │ - type_, = from_signature(value['t']) # type: ignore[index] # can throw TypeError │ │ │ │ │ - contents = value['v'] # type: ignore[index] # can throw TypeError │ │ │ │ │ - except KeyError as exc: │ │ │ │ │ - raise TypeError("'v' can encode Variant objects, or mappings with 't' and 'v' keys") from exc │ │ │ │ │ + async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ + return await responder.do_fido_user_presence_prompt(self) │ │ │ │ │ │ │ │ │ │ - open_container(message, v, type_.bytes_typestring) │ │ │ │ │ - type_.writer(message, contents) │ │ │ │ │ - close_container(message) │ │ │ │ │ - return variant_writer │ │ │ │ │ │ │ │ │ │ +class SshPKCS11PINPrompt(SSHAskpassPrompt): │ │ │ │ │ + _pattern = r"Enter PIN for '%{pkcs11_id}': " │ │ │ │ │ + pkcs11_id: str │ │ │ │ │ │ │ │ │ │ -class Variant: │ │ │ │ │ - __slots__ = 'type', 'value' │ │ │ │ │ - type: Type │ │ │ │ │ - value: object │ │ │ │ │ + async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ + return await responder.do_pkcs11_pin_prompt(self) │ │ │ │ │ │ │ │ │ │ - def __init__(self, value: object, hint: object = None): │ │ │ │ │ - if isinstance(hint, Type): │ │ │ │ │ - self.type = hint │ │ │ │ │ - elif isinstance(hint, str): │ │ │ │ │ - self.type, = from_signature(hint) │ │ │ │ │ - else: │ │ │ │ │ - self.type = from_annotation(hint or value.__class__) │ │ │ │ │ - self.value = value │ │ │ │ │ │ │ │ │ │ - def __repr__(self) -> str: │ │ │ │ │ - return f"systemd_ctypes.Variant({self.value}, '{self.type.typestring}')" │ │ │ │ │ +class SshHostKeyPrompt(SSHAskpassPrompt): │ │ │ │ │ + _pattern = r"Are you sure you want to continue connecting \(yes/no(/\[fingerprint\])?\)\? " │ │ │ │ │ + _extra_patterns = [ │ │ │ │ │ + r"%{fingerprint}[.]$", │ │ │ │ │ + r"^%{algorithm} key fingerprint is", │ │ │ │ │ + r"^The fingerprint for the %{algorithm} key sent by the remote host is$" │ │ │ │ │ + ] │ │ │ │ │ + answers = ('yes', 'no') │ │ │ │ │ + algorithm: str │ │ │ │ │ + fingerprint: str │ │ │ │ │ │ │ │ │ │ - def __eq__(self, other: object) -> bool: │ │ │ │ │ - if isinstance(other, Variant): │ │ │ │ │ - return self.type == other.type and self.value == other.value │ │ │ │ │ - elif isinstance(other, dict): │ │ │ │ │ - return (self.type,) == from_signature(other['t']) and self.value == other['v'] │ │ │ │ │ - else: │ │ │ │ │ - return False │ │ │ │ │ + async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ + return await responder.do_host_key_prompt(self) │ │ │ │ │ │ │ │ │ │ - def __hash__(self) -> int: │ │ │ │ │ - return hash(self.type) ^ hash(self.value) │ │ │ │ │ │ │ │ │ │ +def with_helpers(pattern: str) -> str: │ │ │ │ │ + for name, helper in HELPERS.items(): │ │ │ │ │ + pattern = pattern.replace(name, helper) │ │ │ │ │ │ │ │ │ │ -class BusType(Enum): │ │ │ │ │ - boolean = Annotated[bool, FixedType('b', ctypes.c_int, ctypes.c_int.__bool__)] │ │ │ │ │ - byte = Annotated[int, FixedType('y', ctypes.c_uint8)] │ │ │ │ │ - int16 = Annotated[int, FixedType('n', ctypes.c_int16)] │ │ │ │ │ - uint16 = Annotated[int, FixedType('q', ctypes.c_uint16)] │ │ │ │ │ - int32 = Annotated[int, FixedType('i', ctypes.c_int32)] │ │ │ │ │ - uint32 = Annotated[int, FixedType('u', ctypes.c_uint32)] │ │ │ │ │ - int64 = Annotated[int, FixedType('x', ctypes.c_int64)] │ │ │ │ │ - uint64 = Annotated[int, FixedType('t', ctypes.c_uint64)] │ │ │ │ │ - double = Annotated[float, FixedType('d', ctypes.c_double)] │ │ │ │ │ - string = Annotated[str, StringLikeType('s')] │ │ │ │ │ - objectpath = Annotated[str, StringLikeType('o', is_object_path)] │ │ │ │ │ - signature = Annotated[str, StringLikeType('g', is_signature)] │ │ │ │ │ - bytestring = Annotated[bytes, BytestringType('ay')] │ │ │ │ │ - variant = Annotated[dict, VariantType('v')] │ │ │ │ │ + assert '%{' not in pattern │ │ │ │ │ + return pattern │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -# mypy gets confused by enums, so just use Any │ │ │ │ │ -_base_equivalence_map: Dict[type, Any] = { │ │ │ │ │ - bool: BusType.boolean, │ │ │ │ │ - bytes: BusType.bytestring, │ │ │ │ │ - int: BusType.int32, │ │ │ │ │ - str: BusType.string, │ │ │ │ │ - Variant: BusType.variant, │ │ │ │ │ -} │ │ │ │ │ +def categorize_ssh_prompt(string: str, stderr: str) -> AskpassPrompt: │ │ │ │ │ + classes = [ │ │ │ │ │ + SshFIDOPINPrompt, │ │ │ │ │ + SshFIDOUserPresencePrompt, │ │ │ │ │ + SshHostKeyPrompt, │ │ │ │ │ + SshPKCS11PINPrompt, │ │ │ │ │ + SshPassphrasePrompt, │ │ │ │ │ + SshPasswordPrompt, │ │ │ │ │ + ] │ │ │ │ │ │ │ │ │ │ -_factory_map: Dict[object, Callable[..., Type]] = { │ │ │ │ │ - dict: DictionaryType, Dict: DictionaryType, │ │ │ │ │ - list: ArrayType, List: ArrayType, │ │ │ │ │ - tuple: StructType, Tuple: StructType, │ │ │ │ │ -} │ │ │ │ │ + # The last line is the line after the last newline character, excluding the │ │ │ │ │ + # optional final newline character. eg: "x\ny\nLAST\n" or "x\ny\nLAST" │ │ │ │ │ + second_last_newline = string.rfind('\n', 0, -1) │ │ │ │ │ + if second_last_newline >= 0: │ │ │ │ │ + last_line = string[second_last_newline + 1:] │ │ │ │ │ + extras = string[:second_last_newline + 1] │ │ │ │ │ + else: │ │ │ │ │ + last_line = string │ │ │ │ │ + extras = '' │ │ │ │ │ │ │ │ │ │ + for cls in classes: │ │ │ │ │ + pattern = with_helpers(cls._pattern) │ │ │ │ │ + match = re.fullmatch(pattern, last_line) │ │ │ │ │ + if match is not None: │ │ │ │ │ + return cls(last_line, extras, stderr, match) │ │ │ │ │ │ │ │ │ │ -@functools.lru_cache() │ │ │ │ │ -def from_annotation(annotation: Union[str, type, BusType]) -> Type: │ │ │ │ │ - # Simple Python types │ │ │ │ │ - if isinstance(annotation, str): │ │ │ │ │ - types = from_signature(annotation) │ │ │ │ │ - if len(types) != 1: │ │ │ │ │ - raise TypeError(f"Signature '{annotation}' invalid as a type string " │ │ │ │ │ - f"because it describes {len(types)} types, not one.") │ │ │ │ │ - return types[0] │ │ │ │ │ + return AskpassPrompt(last_line, extras, stderr) │ │ │ │ │ │ │ │ │ │ - if isinstance(annotation, type): │ │ │ │ │ - annotation = _base_equivalence_map.get(annotation, annotation) │ │ │ │ │ │ │ │ │ │ - # Our own BusType types │ │ │ │ │ - if isinstance(annotation, BusType): │ │ │ │ │ - bus_type = typing.get_args(annotation.value)[1] │ │ │ │ │ - assert isinstance(bus_type, Type) │ │ │ │ │ - return bus_type │ │ │ │ │ +class SshAskpassResponder(AskpassHandler): │ │ │ │ │ + async def do_askpass(self, stderr: str, prompt: str, hint: str) -> 'str | None': │ │ │ │ │ + return await categorize_ssh_prompt(prompt, stderr).dispatch(self) │ │ │ │ │ │ │ │ │ │ - # Container types │ │ │ │ │ - try: │ │ │ │ │ - factory = _factory_map[typing.get_origin(annotation)] │ │ │ │ │ - args = [from_annotation(arg) for arg in typing.get_args(annotation)] │ │ │ │ │ - return factory(*args) │ │ │ │ │ - except (AssertionError, AttributeError, KeyError, TypeError): │ │ │ │ │ - raise TypeError(f"Cannot interpret {annotation} as a dbus type") from None │ │ │ │ │ + async def do_prompt(self, prompt: AskpassPrompt) -> 'str | None': │ │ │ │ │ + # Default fallback for unrecognised message types: unimplemented │ │ │ │ │ + return None │ │ │ │ │ │ │ │ │ │ + async def do_fido_pin_prompt(self, prompt: SshFIDOPINPrompt) -> 'str | None': │ │ │ │ │ + return await self.do_prompt(prompt) │ │ │ │ │ │ │ │ │ │ -_base_typestring_map: Dict[str, Type] = { │ │ │ │ │ - bustype.typestring: bustype for bustype in (from_annotation(entry) for entry in BusType) │ │ │ │ │ -} │ │ │ │ │ + async def do_fido_user_presence_prompt(self, prompt: SshFIDOUserPresencePrompt) -> 'str | None': │ │ │ │ │ + return await self.do_prompt(prompt) │ │ │ │ │ │ │ │ │ │ + async def do_host_key_prompt(self, prompt: SshHostKeyPrompt) -> 'str | None': │ │ │ │ │ + return await self.do_prompt(prompt) │ │ │ │ │ │ │ │ │ │ -@functools.lru_cache() │ │ │ │ │ -def from_signature(signature: str) -> Tuple[Type, ...]: │ │ │ │ │ - stack = list(reversed(signature)) │ │ │ │ │ + async def do_pkcs11_pin_prompt(self, prompt: SshPKCS11PINPrompt) -> 'str | None': │ │ │ │ │ + return await self.do_prompt(prompt) │ │ │ │ │ │ │ │ │ │ - def get_one() -> Type: │ │ │ │ │ - first = stack.pop() │ │ │ │ │ - if first == 'a': │ │ │ │ │ - if stack[-1] == 'y': │ │ │ │ │ - first += stack.pop() │ │ │ │ │ - elif stack[-1] == '{': │ │ │ │ │ - stack.pop() │ │ │ │ │ - return DictionaryType(*get_several('}')) │ │ │ │ │ - else: │ │ │ │ │ - return ArrayType(get_one()) │ │ │ │ │ - elif first == '(': │ │ │ │ │ - return StructType(*get_several(')')) │ │ │ │ │ + async def do_passphrase_prompt(self, prompt: SshPassphrasePrompt) -> 'str | None': │ │ │ │ │ + return await self.do_prompt(prompt) │ │ │ │ │ │ │ │ │ │ - return _base_typestring_map[first] │ │ │ │ │ + async def do_password_prompt(self, prompt: SshPasswordPrompt) -> 'str | None': │ │ │ │ │ + return await self.do_prompt(prompt) │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/ferny/interaction_client.py': br'''#!/usr/bin/python3 │ │ │ │ │ │ │ │ │ │ - def get_several(end: str) -> Iterable[Type]: │ │ │ │ │ - yield get_one() │ │ │ │ │ - while stack[-1] != end: │ │ │ │ │ - yield get_one() │ │ │ │ │ - stack.pop() │ │ │ │ │ +import array │ │ │ │ │ +import io │ │ │ │ │ +import os │ │ │ │ │ +import socket │ │ │ │ │ +import sys │ │ │ │ │ +from typing import Sequence │ │ │ │ │ │ │ │ │ │ - def get_all() -> Iterable[Type]: │ │ │ │ │ - while stack: │ │ │ │ │ - yield get_one() │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - return tuple(get_all()) │ │ │ │ │ - except (AssertionError, IndexError, KeyError) as exc: │ │ │ │ │ - raise TypeError(f"Invalid type signature '{signature}'") from exc │ │ │ │ │ +def command(stderr_fd: int, command: str, *args: object, fds: Sequence[int] = ()) -> None: │ │ │ │ │ + cmd_read, cmd_write = [io.open(*end) for end in zip(os.pipe(), 'rw')] │ │ │ │ │ │ │ │ │ │ + with cmd_write: │ │ │ │ │ + with cmd_read: │ │ │ │ │ + with socket.fromfd(stderr_fd, socket.AF_UNIX, socket.SOCK_STREAM) as sock: │ │ │ │ │ + fd_array = array.array('i', (cmd_read.fileno(), *fds)) │ │ │ │ │ + sock.sendmsg([b'\0'], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fd_array)]) │ │ │ │ │ │ │ │ │ │ -class MessageType: │ │ │ │ │ - item_types: Sequence[Type] │ │ │ │ │ - typestrings: List[str] │ │ │ │ │ - signature: str │ │ │ │ │ + cmd_write.write(repr((command, args))) │ │ │ │ │ │ │ │ │ │ - def __init__(self, item_types: Sequence[Union[str, type, BusType]]): │ │ │ │ │ - self.item_types = [from_annotation(item_type) for item_type in item_types] │ │ │ │ │ - self.typestrings = [item_type.typestring for item_type in self.item_types] │ │ │ │ │ - self.signature = ''.join(self.typestrings) │ │ │ │ │ │ │ │ │ │ - def write(self, message: libsystemd.sd_bus_message, *items: object) -> None: │ │ │ │ │ - assert len(items) == len(self.item_types) │ │ │ │ │ - for item_type, item in zip(self.item_types, items): │ │ │ │ │ - item_type.writer(message, item) │ │ │ │ │ +def askpass(stderr_fd: int, stdout_fd: int, args: 'list[str]', env: 'dict[str, str]') -> int: │ │ │ │ │ + ours, theirs = socket.socketpair() │ │ │ │ │ │ │ │ │ │ - def read(self, message: libsystemd.sd_bus_message) -> Optional[Tuple[object, ...]]: │ │ │ │ │ - if not message.has_signature(self.signature): │ │ │ │ │ - return None │ │ │ │ │ - return tuple(item_type.reader(message) for item_type in self.item_types) │ │ │ │ │ + with theirs: │ │ │ │ │ + command(stderr_fd, 'ferny.askpass', args, env, fds=(theirs.fileno(), stdout_fd)) │ │ │ │ │ │ │ │ │ │ - def __len__(self) -> int: │ │ │ │ │ - return len(self.item_types) │ │ │ │ │ + with ours: │ │ │ │ │ + return int(ours.recv(16) or b'1') │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class JSONEncoder(json.JSONEncoder): │ │ │ │ │ - def default(self, obj: object) -> object: │ │ │ │ │ - if isinstance(obj, Variant): │ │ │ │ │ - return {"t": obj.type.typestring, "v": obj.value} │ │ │ │ │ - elif isinstance(obj, bytes): │ │ │ │ │ - return binascii.b2a_base64(obj, newline=False).decode('ascii') │ │ │ │ │ - return super().default(obj) │ │ │ │ │ +def main() -> None: │ │ │ │ │ + if len(sys.argv) == 1: │ │ │ │ │ + command(2, 'ferny.end', []) │ │ │ │ │ + else: │ │ │ │ │ + sys.exit(askpass(2, 1, sys.argv, dict(os.environ))) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +if __name__ == '__main__': │ │ │ │ │ + main() │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/introspection.py': br'''# systemd_ctypes │ │ │ │ │ + 'cockpit/_vendor/ferny/transport.py': br'''# ferny - asyncio SSH client library, using ssh(1) │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import xml.etree.ElementTree as ET │ │ │ │ │ +import asyncio │ │ │ │ │ +import contextlib │ │ │ │ │ +import logging │ │ │ │ │ +import typing │ │ │ │ │ +from typing import Any, Callable, Iterable, Sequence, TypeVar │ │ │ │ │ │ │ │ │ │ +from .interaction_agent import InteractionAgent, InteractionHandler, get_running_loop │ │ │ │ │ +from .ssh_errors import get_exception_for_ssh_stderr │ │ │ │ │ │ │ │ │ │ -def parse_method(method): │ │ │ │ │ - return { │ │ │ │ │ - "in": [tag.attrib['type'] for tag in method.findall("arg") if tag.get('direction', 'in') == 'in'], │ │ │ │ │ - "out": [tag.attrib['type'] for tag in method.findall("arg[@direction='out']")] │ │ │ │ │ - } │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ +P = TypeVar('P', bound=asyncio.Protocol) │ │ │ │ │ │ │ │ │ │ -def parse_property(prop): │ │ │ │ │ - return { │ │ │ │ │ - "flags": 'w' if prop.attrib.get('access') == 'write' else 'r', │ │ │ │ │ - "type": prop.attrib['type'] │ │ │ │ │ - } │ │ │ │ │ │ │ │ │ │ +class SubprocessError(Exception): │ │ │ │ │ + returncode: int │ │ │ │ │ + stderr: str │ │ │ │ │ │ │ │ │ │ -def parse_signal(signal): │ │ │ │ │ - return {"in": [tag.attrib['type'] for tag in signal.findall("arg")]} │ │ │ │ │ + def __init__(self, returncode: int, stderr: str) -> None: │ │ │ │ │ + super().__init__(returncode, stderr) │ │ │ │ │ + self.returncode = returncode │ │ │ │ │ + self.stderr = stderr │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -def parse_interface(interface): │ │ │ │ │ - return { │ │ │ │ │ - "methods": {tag.attrib['name']: parse_method(tag) for tag in interface.findall('method')}, │ │ │ │ │ - "properties": {tag.attrib['name']: parse_property(tag) for tag in interface.findall('property')}, │ │ │ │ │ - "signals": {tag.attrib['name']: parse_signal(tag) for tag in interface.findall('signal')} │ │ │ │ │ - } │ │ │ │ │ +class FernyTransport(asyncio.Transport, asyncio.SubprocessProtocol): │ │ │ │ │ + _agent: InteractionAgent │ │ │ │ │ + _exec_task: 'asyncio.Task[tuple[asyncio.SubprocessTransport, FernyTransport]]' │ │ │ │ │ + _is_ssh: bool │ │ │ │ │ + _protocol: asyncio.Protocol │ │ │ │ │ + _protocol_disconnected: bool = False │ │ │ │ │ │ │ │ │ │ + # These get initialized in connection_made() and once set, never get unset. │ │ │ │ │ + _subprocess_transport: 'asyncio.SubprocessTransport | None' = None │ │ │ │ │ + _stdin_transport: 'asyncio.WriteTransport | None' = None │ │ │ │ │ + _stdout_transport: 'asyncio.ReadTransport | None' = None │ │ │ │ │ │ │ │ │ │ -def parse_xml(xml): │ │ │ │ │ - et = ET.fromstring(xml) │ │ │ │ │ - return {tag.attrib['name']: parse_interface(tag) for tag in et.findall('interface')} │ │ │ │ │ + # We record events that might build towards a connection termination here │ │ │ │ │ + # and consider them from _consider_disconnect() in order to try to get the │ │ │ │ │ + # best possible Exception for the protocol, rather than just taking the │ │ │ │ │ + # first one (which is likely to be somewhat random). │ │ │ │ │ + _exception: 'Exception | None' = None │ │ │ │ │ + _stderr_output: 'str | None' = None │ │ │ │ │ + _returncode: 'int | None' = None │ │ │ │ │ + _transport_disconnected: bool = False │ │ │ │ │ + _closed: bool = False │ │ │ │ │ │ │ │ │ │ + @classmethod │ │ │ │ │ + def spawn( │ │ │ │ │ + cls: 'type[typing.Self]', │ │ │ │ │ + protocol_factory: Callable[[], P], │ │ │ │ │ + args: Sequence[str], │ │ │ │ │ + loop: 'asyncio.AbstractEventLoop | None' = None, │ │ │ │ │ + interaction_handlers: Sequence[InteractionHandler] = (), │ │ │ │ │ + is_ssh: bool = True, │ │ │ │ │ + **kwargs: Any │ │ │ │ │ + ) -> 'tuple[typing.Self, P]': │ │ │ │ │ + """Connects a FernyTransport to a protocol, using the given command. │ │ │ │ │ │ │ │ │ │ -# Pretend like this is a little bit functional │ │ │ │ │ -def element(tag, children=(), **kwargs): │ │ │ │ │ - tag = ET.Element(tag, kwargs) │ │ │ │ │ - tag.extend(children) │ │ │ │ │ - return tag │ │ │ │ │ + This spawns an external command and connects the stdin and stdout of │ │ │ │ │ + the command to the protocol returned by the factory. │ │ │ │ │ │ │ │ │ │ + An instance of ferny.InteractionAgent is created and attached to the │ │ │ │ │ + stderr of the spawned process, using the provided handlers. It is the │ │ │ │ │ + responsibility of the caller to ensure that: │ │ │ │ │ + - a `ferny-askpass` client program is installed somewhere; and │ │ │ │ │ + - any relevant command-line arguments or environment variables are │ │ │ │ │ + passed correctly to the program to be spawned │ │ │ │ │ │ │ │ │ │ -def method_to_xml(name, method_info): │ │ │ │ │ - return element('method', name=name, │ │ │ │ │ - children=[ │ │ │ │ │ - element('arg', type=arg_type, direction=direction) │ │ │ │ │ - for direction in ['in', 'out'] │ │ │ │ │ - for arg_type in method_info[direction] │ │ │ │ │ - ]) │ │ │ │ │ + This function returns immediately and never raises exceptions, assuming │ │ │ │ │ + all preconditions are met. │ │ │ │ │ │ │ │ │ │ + If spawning the process fails then connection_lost() will be │ │ │ │ │ + called with the relevant OSError, even before connection_made() is │ │ │ │ │ + called. This is somewhat non-standard behaviour, but is the easiest │ │ │ │ │ + way to report these errors without making this function async. │ │ │ │ │ │ │ │ │ │ -def property_to_xml(name, property_info): │ │ │ │ │ - return element('property', name=name, │ │ │ │ │ - access='write' if property_info['flags'] == 'w' else 'read', │ │ │ │ │ - type=property_info['type']) │ │ │ │ │ + Once the process is successfully executed, connection_made() will be │ │ │ │ │ + called and the transport can be used as normal. connection_lost() will │ │ │ │ │ + be called if the process exits or another error occurs. │ │ │ │ │ │ │ │ │ │ + The return value of this function is the transport, but it exists in a │ │ │ │ │ + semi-initialized state. You can call .close() on it, but nothing else. │ │ │ │ │ + Once .connection_made() is called, you can call all the other │ │ │ │ │ + functions. │ │ │ │ │ │ │ │ │ │ -def signal_to_xml(name, signal_info): │ │ │ │ │ - return element('signal', name=name, │ │ │ │ │ - children=[ │ │ │ │ │ - element('arg', type=arg_type) for arg_type in signal_info['in'] │ │ │ │ │ - ]) │ │ │ │ │ + After you call this function, `.connection_lost()` will be called on │ │ │ │ │ + your Protocol, exactly once, no matter what. Until that happens, you │ │ │ │ │ + are responsible for holding a reference to the returned transport. │ │ │ │ │ │ │ │ │ │ + :param args: the full argv of the command to spawn │ │ │ │ │ + :param loop: the event loop to use. If none is provided, we use the │ │ │ │ │ + one which is (read: must be) currently running. │ │ │ │ │ + :param interaction_handlers: the handlers passed to the │ │ │ │ │ + InteractionAgent │ │ │ │ │ + :param is_ssh: whether we should attempt to interpret stderr as ssh │ │ │ │ │ + error messages │ │ │ │ │ + :param kwargs: anything else is passed through to `subprocess_exec()` │ │ │ │ │ + :returns: the usual `(Transport, Protocol)` pair │ │ │ │ │ + """ │ │ │ │ │ + logger.debug('spawn(%r, %r, %r)', cls, protocol_factory, args) │ │ │ │ │ │ │ │ │ │ -def interface_to_xml(name, interface_info): │ │ │ │ │ - return element('interface', name=name, │ │ │ │ │ - children=[ │ │ │ │ │ - *(method_to_xml(name, info) for name, info in interface_info['methods'].items()), │ │ │ │ │ - *(property_to_xml(name, info) for name, info in interface_info['properties'].items()), │ │ │ │ │ - *(signal_to_xml(name, info) for name, info in interface_info['signals'].items()), │ │ │ │ │ - ]) │ │ │ │ │ + protocol = protocol_factory() │ │ │ │ │ + self = cls(protocol) │ │ │ │ │ + self._is_ssh = is_ssh │ │ │ │ │ │ │ │ │ │ + if loop is None: │ │ │ │ │ + loop = get_running_loop() │ │ │ │ │ │ │ │ │ │ -def to_xml(interfaces): │ │ │ │ │ - node = element('node', children=(interface_to_xml(name, members) for name, members in interfaces.items())) │ │ │ │ │ - return ET.tostring(node, encoding='unicode') │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/__init__.py': br'''# systemd_ctypes │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ + self._agent = InteractionAgent(interaction_handlers, loop, self._interaction_completed) │ │ │ │ │ + kwargs.setdefault('stderr', self._agent.fileno()) │ │ │ │ │ │ │ │ │ │ -"""systemd_ctypes""" │ │ │ │ │ + # As of Python 3.12 this isn't really asynchronous (since it uses the │ │ │ │ │ + # subprocess module, which blocks while waiting for the exec() to │ │ │ │ │ + # complete in the child), but we have to deal with the complication of │ │ │ │ │ + # the async interface anyway. Since we, ourselves, want to export a │ │ │ │ │ + # non-async interface, that means that we need a task here and a │ │ │ │ │ + # bottom-half handler below. │ │ │ │ │ + self._exec_task = loop.create_task(loop.subprocess_exec(lambda: self, *args, **kwargs)) │ │ │ │ │ │ │ │ │ │ -__version__ = "0" │ │ │ │ │ + def exec_completed(task: asyncio.Task) -> None: │ │ │ │ │ + logger.debug('exec_completed(%r, %r)', self, task) │ │ │ │ │ + assert task is self._exec_task │ │ │ │ │ + try: │ │ │ │ │ + transport, me = task.result() │ │ │ │ │ + assert me is self │ │ │ │ │ + logger.debug(' success.') │ │ │ │ │ + except asyncio.CancelledError: │ │ │ │ │ + return # in that case, do nothing │ │ │ │ │ + except OSError as exc: │ │ │ │ │ + logger.debug(' OSError %r', exc) │ │ │ │ │ + self.close(exc) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ -from .bus import Bus, BusError, BusMessage │ │ │ │ │ -from .bustypes import BusType, JSONEncoder, Variant │ │ │ │ │ -from .event import Event, EventLoopPolicy, run_async │ │ │ │ │ -from .pathwatch import Handle, PathWatch │ │ │ │ │ + # Our own .connection_made() handler should have gotten called by │ │ │ │ │ + # now. Make sure everything got filled in properly. │ │ │ │ │ + assert self._subprocess_transport is transport │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + assert self._stdout_transport is not None │ │ │ │ │ + │ │ │ │ │ + # Ask the InteractionAgent to start processing stderr. │ │ │ │ │ + self._agent.start() │ │ │ │ │ + │ │ │ │ │ + self._exec_task.add_done_callback(exec_completed) │ │ │ │ │ + │ │ │ │ │ + return self, protocol │ │ │ │ │ + │ │ │ │ │ + def __init__(self, protocol: asyncio.Protocol) -> None: │ │ │ │ │ + self._protocol = protocol │ │ │ │ │ + │ │ │ │ │ + def _consider_disconnect(self) -> None: │ │ │ │ │ + logger.debug('_consider_disconnect(%r)', self) │ │ │ │ │ + # We cannot disconnect as long as any of these three things are happening │ │ │ │ │ + if not self._exec_task.done(): │ │ │ │ │ + logger.debug(' exec_task still running %r', self._exec_task) │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + if self._subprocess_transport is not None and not self._transport_disconnected: │ │ │ │ │ + logger.debug(' transport still connected %r', self._subprocess_transport) │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + if self._stderr_output is None: │ │ │ │ │ + logger.debug(' agent still running') │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + # All conditions for disconnection are satisfied. │ │ │ │ │ + if self._protocol_disconnected: │ │ │ │ │ + logger.debug(' already disconnected') │ │ │ │ │ + return │ │ │ │ │ + self._protocol_disconnected = True │ │ │ │ │ + │ │ │ │ │ + # Now we just need to determine what we report to the protocol... │ │ │ │ │ + if self._exception is not None: │ │ │ │ │ + # If we got an exception reported, that's our reason for closing. │ │ │ │ │ + logger.debug(' disconnect with exception %r', self._exception) │ │ │ │ │ + self._protocol.connection_lost(self._exception) │ │ │ │ │ + elif self._returncode == 0 or self._closed: │ │ │ │ │ + # If we called close() or have a zero return status, that's a clean │ │ │ │ │ + # exit, regardless of noise that might have landed in stderr. │ │ │ │ │ + logger.debug(' clean disconnect') │ │ │ │ │ + self._protocol.connection_lost(None) │ │ │ │ │ + elif self._is_ssh and self._returncode == 255: │ │ │ │ │ + # This is an error code due to an SSH failure. Try to interpret it. │ │ │ │ │ + logger.debug(' disconnect with ssh error %r', self._stderr_output) │ │ │ │ │ + self._protocol.connection_lost(get_exception_for_ssh_stderr(self._stderr_output)) │ │ │ │ │ + else: │ │ │ │ │ + # Otherwise, report the stderr text and return code. │ │ │ │ │ + logger.debug(' disconnect with exit code %r, stderr %r', self._returncode, self._stderr_output) │ │ │ │ │ + # We surely have _returncode set here, since otherwise: │ │ │ │ │ + # - exec_task failed with an exception (which we handle above); or │ │ │ │ │ + # - we're still connected... │ │ │ │ │ + assert self._returncode is not None │ │ │ │ │ + self._protocol.connection_lost(SubprocessError(self._returncode, self._stderr_output)) │ │ │ │ │ + │ │ │ │ │ + def _interaction_completed(self, future: 'asyncio.Future[str]') -> None: │ │ │ │ │ + logger.debug('_interaction_completed(%r, %r)', self, future) │ │ │ │ │ + try: │ │ │ │ │ + self._stderr_output = future.result() │ │ │ │ │ + logger.debug(' stderr: %r', self._stderr_output) │ │ │ │ │ + except Exception as exc: │ │ │ │ │ + logger.debug(' exception: %r', exc) │ │ │ │ │ + self._stderr_output = '' # we need to set this in order to complete │ │ │ │ │ + self.close(exc) │ │ │ │ │ + │ │ │ │ │ + self._consider_disconnect() │ │ │ │ │ + │ │ │ │ │ + # BaseProtocol implementation │ │ │ │ │ + def connection_made(self, transport: asyncio.BaseTransport) -> None: │ │ │ │ │ + logger.debug('connection_made(%r, %r)', self, transport) │ │ │ │ │ + assert isinstance(transport, asyncio.SubprocessTransport) │ │ │ │ │ + self._subprocess_transport = transport │ │ │ │ │ + │ │ │ │ │ + stdin_transport = transport.get_pipe_transport(0) │ │ │ │ │ + assert isinstance(stdin_transport, asyncio.WriteTransport) │ │ │ │ │ + self._stdin_transport = stdin_transport │ │ │ │ │ + │ │ │ │ │ + stdout_transport = transport.get_pipe_transport(1) │ │ │ │ │ + assert isinstance(stdout_transport, asyncio.ReadTransport) │ │ │ │ │ + self._stdout_transport = stdout_transport │ │ │ │ │ + │ │ │ │ │ + stderr_transport = transport.get_pipe_transport(2) │ │ │ │ │ + assert stderr_transport is None │ │ │ │ │ + │ │ │ │ │ + logger.debug('calling connection_made(%r, %r)', self, self._protocol) │ │ │ │ │ + self._protocol.connection_made(self) │ │ │ │ │ + │ │ │ │ │ + def connection_lost(self, exc: 'Exception | None') -> None: │ │ │ │ │ + logger.debug('connection_lost(%r, %r)', self, exc) │ │ │ │ │ + if self._exception is None: │ │ │ │ │ + self._exception = exc │ │ │ │ │ + self._transport_disconnected = True │ │ │ │ │ + self._consider_disconnect() │ │ │ │ │ + │ │ │ │ │ + # SubprocessProtocol implementation │ │ │ │ │ + def pipe_data_received(self, fd: int, data: bytes) -> None: │ │ │ │ │ + logger.debug('pipe_data_received(%r, %r, %r)', self, fd, len(data)) │ │ │ │ │ + assert fd == 1 # stderr is handled separately │ │ │ │ │ + self._protocol.data_received(data) │ │ │ │ │ + │ │ │ │ │ + def pipe_connection_lost(self, fd: int, exc: 'Exception | None') -> None: │ │ │ │ │ + logger.debug('pipe_connection_lost(%r, %r, %r)', self, fd, exc) │ │ │ │ │ + assert fd in (0, 1) # stderr is handled separately │ │ │ │ │ + │ │ │ │ │ + # We treat this as a clean close │ │ │ │ │ + if isinstance(exc, BrokenPipeError): │ │ │ │ │ + exc = None │ │ │ │ │ + │ │ │ │ │ + # Record serious errors to propagate them to the protocol │ │ │ │ │ + # If this is a clean exit on stdout, report an EOF │ │ │ │ │ + if exc is not None: │ │ │ │ │ + self.close(exc) │ │ │ │ │ + elif fd == 1 and not self._closed: │ │ │ │ │ + if not self._protocol.eof_received(): │ │ │ │ │ + self.close() │ │ │ │ │ + │ │ │ │ │ + def process_exited(self) -> None: │ │ │ │ │ + logger.debug('process_exited(%r)', self) │ │ │ │ │ + assert self._subprocess_transport is not None │ │ │ │ │ + self._returncode = self._subprocess_transport.get_returncode() │ │ │ │ │ + logger.debug(' ._returncode = %r', self._returncode) │ │ │ │ │ + self._agent.force_completion() │ │ │ │ │ + │ │ │ │ │ + def pause_writing(self) -> None: │ │ │ │ │ + logger.debug('pause_writing(%r)', self) │ │ │ │ │ + self._protocol.pause_writing() │ │ │ │ │ + │ │ │ │ │ + def resume_writing(self) -> None: │ │ │ │ │ + logger.debug('resume_writing(%r)', self) │ │ │ │ │ + self._protocol.resume_writing() │ │ │ │ │ + │ │ │ │ │ + # Transport implementation. Most of this is straight delegation. │ │ │ │ │ + def close(self, exc: 'Exception | None' = None) -> None: │ │ │ │ │ + logger.debug('close(%r, %r)', self, exc) │ │ │ │ │ + self._closed = True │ │ │ │ │ + if self._exception is None: │ │ │ │ │ + logger.debug(' setting exception %r', exc) │ │ │ │ │ + self._exception = exc │ │ │ │ │ + if not self._exec_task.done(): │ │ │ │ │ + logger.debug(' cancelling _exec_task') │ │ │ │ │ + self._exec_task.cancel() │ │ │ │ │ + if self._subprocess_transport is not None: │ │ │ │ │ + logger.debug(' closing _subprocess_transport') │ │ │ │ │ + # https://github.com/python/cpython/issues/112800 │ │ │ │ │ + with contextlib.suppress(PermissionError): │ │ │ │ │ + self._subprocess_transport.close() │ │ │ │ │ + self._agent.force_completion() │ │ │ │ │ + │ │ │ │ │ + def is_closing(self) -> bool: │ │ │ │ │ + assert self._subprocess_transport is not None │ │ │ │ │ + return self._subprocess_transport.is_closing() │ │ │ │ │ + │ │ │ │ │ + def get_extra_info(self, name: str, default: object = None) -> object: │ │ │ │ │ + assert self._subprocess_transport is not None │ │ │ │ │ + return self._subprocess_transport.get_extra_info(name, default) │ │ │ │ │ + │ │ │ │ │ + def set_protocol(self, protocol: asyncio.BaseProtocol) -> None: │ │ │ │ │ + assert isinstance(protocol, asyncio.Protocol) │ │ │ │ │ + self._protocol = protocol │ │ │ │ │ + │ │ │ │ │ + def get_protocol(self) -> asyncio.Protocol: │ │ │ │ │ + return self._protocol │ │ │ │ │ + │ │ │ │ │ + def is_reading(self) -> bool: │ │ │ │ │ + assert self._stdout_transport is not None │ │ │ │ │ + try: │ │ │ │ │ + return self._stdout_transport.is_reading() │ │ │ │ │ + except NotImplementedError: │ │ │ │ │ + # This is (incorrectly) unimplemented before Python 3.11 │ │ │ │ │ + return not self._stdout_transport._paused # type:ignore[attr-defined] │ │ │ │ │ + except AttributeError: │ │ │ │ │ + # ...and in Python 3.6 it's even worse │ │ │ │ │ + try: │ │ │ │ │ + selector = self._stdout_transport._loop._selector # type:ignore[attr-defined] │ │ │ │ │ + selector.get_key(self._stdout_transport._fileno) # type:ignore[attr-defined] │ │ │ │ │ + return True │ │ │ │ │ + except KeyError: │ │ │ │ │ + return False │ │ │ │ │ + │ │ │ │ │ + def pause_reading(self) -> None: │ │ │ │ │ + assert self._stdout_transport is not None │ │ │ │ │ + self._stdout_transport.pause_reading() │ │ │ │ │ + │ │ │ │ │ + def resume_reading(self) -> None: │ │ │ │ │ + assert self._stdout_transport is not None │ │ │ │ │ + self._stdout_transport.resume_reading() │ │ │ │ │ + │ │ │ │ │ + def abort(self) -> None: │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + assert self._subprocess_transport is not None │ │ │ │ │ + self._stdin_transport.abort() │ │ │ │ │ + self._subprocess_transport.kill() │ │ │ │ │ + │ │ │ │ │ + def can_write_eof(self) -> bool: │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + return self._stdin_transport.can_write_eof() # will always be True │ │ │ │ │ + │ │ │ │ │ + def get_write_buffer_size(self) -> int: │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + return self._stdin_transport.get_write_buffer_size() │ │ │ │ │ + │ │ │ │ │ + def get_write_buffer_limits(self) -> 'tuple[int, int]': │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + return self._stdin_transport.get_write_buffer_limits() │ │ │ │ │ + │ │ │ │ │ + def set_write_buffer_limits(self, high: 'int | None' = None, low: 'int | None' = None) -> None: │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + return self._stdin_transport.set_write_buffer_limits(high, low) │ │ │ │ │ + │ │ │ │ │ + def write(self, data: bytes) -> None: │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + return self._stdin_transport.write(data) │ │ │ │ │ + │ │ │ │ │ + def writelines(self, list_of_data: Iterable[bytes]) -> None: │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + return self._stdin_transport.writelines(list_of_data) │ │ │ │ │ + │ │ │ │ │ + def write_eof(self) -> None: │ │ │ │ │ + assert self._stdin_transport is not None │ │ │ │ │ + return self._stdin_transport.write_eof() │ │ │ │ │ + │ │ │ │ │ + # We don't really implement SubprocessTransport, but provide these as │ │ │ │ │ + # "extras" to our user. │ │ │ │ │ + def get_pid(self) -> int: │ │ │ │ │ + assert self._subprocess_transport is not None │ │ │ │ │ + return self._subprocess_transport.get_pid() │ │ │ │ │ + │ │ │ │ │ + def get_returncode(self) -> 'int | None': │ │ │ │ │ + return self._returncode │ │ │ │ │ + │ │ │ │ │ + def kill(self) -> None: │ │ │ │ │ + assert self._subprocess_transport is not None │ │ │ │ │ + self._subprocess_transport.kill() │ │ │ │ │ + │ │ │ │ │ + def send_signal(self, number: int) -> None: │ │ │ │ │ + assert self._subprocess_transport is not None │ │ │ │ │ + self._subprocess_transport.send_signal(number) │ │ │ │ │ + │ │ │ │ │ + def terminate(self) -> None: │ │ │ │ │ + assert self._subprocess_transport is not None │ │ │ │ │ + self._subprocess_transport.terminate() │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/ferny/__init__.py': br'''from .interaction_agent import ( │ │ │ │ │ + BEIBOOT_GADGETS, │ │ │ │ │ + COMMAND_TEMPLATE, │ │ │ │ │ + AskpassHandler, │ │ │ │ │ + InteractionAgent, │ │ │ │ │ + InteractionError, │ │ │ │ │ + InteractionHandler, │ │ │ │ │ + temporary_askpass, │ │ │ │ │ + write_askpass_to_tmpdir, │ │ │ │ │ +) │ │ │ │ │ +from .session import Session │ │ │ │ │ +from .ssh_askpass import ( │ │ │ │ │ + AskpassPrompt, │ │ │ │ │ + SshAskpassResponder, │ │ │ │ │ + SshFIDOPINPrompt, │ │ │ │ │ + SshFIDOUserPresencePrompt, │ │ │ │ │ + SshHostKeyPrompt, │ │ │ │ │ + SshPassphrasePrompt, │ │ │ │ │ + SshPasswordPrompt, │ │ │ │ │ + SshPKCS11PINPrompt, │ │ │ │ │ +) │ │ │ │ │ +from .ssh_errors import ( │ │ │ │ │ + SshAuthenticationError, │ │ │ │ │ + SshChangedHostKeyError, │ │ │ │ │ + SshError, │ │ │ │ │ + SshHostKeyError, │ │ │ │ │ + SshUnknownHostKeyError, │ │ │ │ │ +) │ │ │ │ │ +from .transport import FernyTransport, SubprocessError │ │ │ │ │ │ │ │ │ │ __all__ = [ │ │ │ │ │ - "Bus", │ │ │ │ │ - "BusError", │ │ │ │ │ - "BusMessage", │ │ │ │ │ - "BusType", │ │ │ │ │ - "Event", │ │ │ │ │ - "EventLoopPolicy", │ │ │ │ │ - "Handle", │ │ │ │ │ - "JSONEncoder", │ │ │ │ │ - "PathWatch", │ │ │ │ │ - "Variant", │ │ │ │ │ - "run_async", │ │ │ │ │ + 'AskpassHandler', │ │ │ │ │ + 'AskpassPrompt', │ │ │ │ │ + 'AuthenticationError', │ │ │ │ │ + 'BEIBOOT_GADGETS', │ │ │ │ │ + 'COMMAND_TEMPLATE', │ │ │ │ │ + 'ChangedHostKeyError', │ │ │ │ │ + 'FernyTransport', │ │ │ │ │ + 'HostKeyError', │ │ │ │ │ + 'InteractionAgent', │ │ │ │ │ + 'InteractionError', │ │ │ │ │ + 'InteractionHandler', │ │ │ │ │ + 'Session', │ │ │ │ │ + 'SshAskpassResponder', │ │ │ │ │ + 'SshAuthenticationError', │ │ │ │ │ + 'SshChangedHostKeyError', │ │ │ │ │ + 'SshError', │ │ │ │ │ + 'SshFIDOPINPrompt', │ │ │ │ │ + 'SshFIDOUserPresencePrompt', │ │ │ │ │ + 'SshHostKeyError', │ │ │ │ │ + 'SshHostKeyPrompt', │ │ │ │ │ + 'SshPKCS11PINPrompt', │ │ │ │ │ + 'SshPassphrasePrompt', │ │ │ │ │ + 'SshPasswordPrompt', │ │ │ │ │ + 'SshUnknownHostKeyError', │ │ │ │ │ + 'SubprocessError', │ │ │ │ │ + 'temporary_askpass', │ │ │ │ │ + 'write_askpass_to_tmpdir', │ │ │ │ │ ] │ │ │ │ │ + │ │ │ │ │ +__version__ = '0' │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/py.typed': br'''''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/pathwatch.py': br'''# systemd_ctypes │ │ │ │ │ + 'cockpit/_vendor/ferny/interaction_agent.py': r'''# ferny - asyncio SSH client library, using ssh(1) │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import errno │ │ │ │ │ +import array │ │ │ │ │ +import ast │ │ │ │ │ +import asyncio │ │ │ │ │ +import contextlib │ │ │ │ │ import logging │ │ │ │ │ import os │ │ │ │ │ -import stat │ │ │ │ │ -from typing import Any, List, Optional │ │ │ │ │ +import re │ │ │ │ │ +import socket │ │ │ │ │ +import tempfile │ │ │ │ │ +from typing import Any, Callable, ClassVar, Generator, Sequence │ │ │ │ │ │ │ │ │ │ -from .event import Event │ │ │ │ │ -from .inotify import Event as IN │ │ │ │ │ +from . import interaction_client │ │ │ │ │ │ │ │ │ │ logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -# inotify hard facts: │ │ │ │ │ -# │ │ │ │ │ -# DELETE_SELF doesn't get called until all references to an inode are gone │ │ │ │ │ -# - including open fds │ │ │ │ │ -# - including on directories │ │ │ │ │ -# │ │ │ │ │ -# ATTRIB gets called when unlinking files (because the link count changes) but │ │ │ │ │ -# not on directories. When unlinking an open directory, no events at all │ │ │ │ │ -# happen on the directory. ATTRIB also collects child events, which means we │ │ │ │ │ -# get a lot of unwanted noise. │ │ │ │ │ -# │ │ │ │ │ -# There's nothing like UNLINK_SELF, unfortunately. │ │ │ │ │ -# │ │ │ │ │ -# Even if it was possible to take this approach, it might not work: after │ │ │ │ │ -# you've opened the fd, it might get deleted before you can establish the watch │ │ │ │ │ -# on it. │ │ │ │ │ -# │ │ │ │ │ -# Additionally, systemd makes it impossible to register those events on │ │ │ │ │ -# symlinks (because it removes IN_DONT_FOLLOW in order to watch via │ │ │ │ │ -# /proc/self/fd). │ │ │ │ │ -# │ │ │ │ │ -# For all of these reasons, unfortunately, the best way seems to be to watch │ │ │ │ │ -# for CREATE|DELETE|MOVE events on each intermediate directory. │ │ │ │ │ -# │ │ │ │ │ -# Unfortunately there is no way to filter to only the name we're interested in, │ │ │ │ │ -# so we're gonna get a lot of unnecessary wakeups. │ │ │ │ │ -# │ │ │ │ │ -# Also: due to the above-mentioned race about watching after opening the fd, │ │ │ │ │ -# let's just always watch for both create and delete events *before* trying to │ │ │ │ │ -# open the fd. We could try to reduce the mask after the fact, but meh... │ │ │ │ │ -# │ │ │ │ │ -# We use a WatchInvalidator utility class to fill the role of "Tell me when an │ │ │ │ │ -# event happened on this (directory) fd which impacted the name file". We │ │ │ │ │ -# build a series of these when setting up a watch in order to find out if any │ │ │ │ │ -# part of the path leading to the monitored file changed. │ │ │ │ │ +COMMAND_RE = re.compile(b'\0ferny\0([^\n]*)\0\0\n') │ │ │ │ │ +COMMAND_TEMPLATE = '\0ferny\0{(command, args)!r}\0\0\n' │ │ │ │ │ │ │ │ │ │ +BEIBOOT_GADGETS = { │ │ │ │ │ + "command": fr""" │ │ │ │ │ + import sys │ │ │ │ │ + def command(command, *args): │ │ │ │ │ + sys.stderr.write(f{COMMAND_TEMPLATE!r}) │ │ │ │ │ + sys.stderr.flush() │ │ │ │ │ + """, │ │ │ │ │ + "end": r""" │ │ │ │ │ + def end(): │ │ │ │ │ + command('ferny.end') │ │ │ │ │ + """, │ │ │ │ │ +} │ │ │ │ │ │ │ │ │ │ -class Handle(int): │ │ │ │ │ - """An integer subclass that makes it easier to work with file descriptors""" │ │ │ │ │ │ │ │ │ │ - def __new__(cls, fd: int = -1) -> 'Handle': │ │ │ │ │ - return super(Handle, cls).__new__(cls, fd) │ │ │ │ │ +class InteractionError(Exception): │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ - # separate __init__() to set _needs_close mostly to keep pylint quiet │ │ │ │ │ - def __init__(self, fd: int = -1): │ │ │ │ │ - super().__init__() │ │ │ │ │ - self._needs_close = fd != -1 │ │ │ │ │ │ │ │ │ │ - def __bool__(self) -> bool: │ │ │ │ │ - return self != -1 │ │ │ │ │ +try: │ │ │ │ │ + recv_fds = socket.recv_fds │ │ │ │ │ +except AttributeError: │ │ │ │ │ + # Python < 3.9 │ │ │ │ │ │ │ │ │ │ - def close(self) -> None: │ │ │ │ │ - if self._needs_close: │ │ │ │ │ - self._needs_close = False │ │ │ │ │ - os.close(self) │ │ │ │ │ + def recv_fds( │ │ │ │ │ + sock: socket.socket, bufsize: int, maxfds: int, flags: int = 0 │ │ │ │ │ + ) -> 'tuple[bytes, list[int], int, None]': │ │ │ │ │ + fds = array.array("i") │ │ │ │ │ + msg, ancdata, flags, addr = sock.recvmsg(bufsize, socket.CMSG_LEN(maxfds * fds.itemsize)) │ │ │ │ │ + for cmsg_level, cmsg_type, cmsg_data in ancdata: │ │ │ │ │ + if (cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS): │ │ │ │ │ + fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) │ │ │ │ │ + return msg, list(fds), flags, addr │ │ │ │ │ │ │ │ │ │ - def __eq__(self, value: object) -> bool: │ │ │ │ │ - if int.__eq__(self, value): # also handles both == -1 │ │ │ │ │ - return True │ │ │ │ │ │ │ │ │ │ - if not isinstance(value, int): # other object is not an int │ │ │ │ │ - return False │ │ │ │ │ +def get_running_loop() -> asyncio.AbstractEventLoop: │ │ │ │ │ + try: │ │ │ │ │ + return asyncio.get_running_loop() │ │ │ │ │ + except AttributeError: │ │ │ │ │ + # Python 3.6 │ │ │ │ │ + return asyncio.get_event_loop() │ │ │ │ │ │ │ │ │ │ - if not self or not value: # when only one == -1 │ │ │ │ │ - return False │ │ │ │ │ │ │ │ │ │ - return os.path.sameopenfile(self, value) │ │ │ │ │ +class InteractionHandler: │ │ │ │ │ + commands: ClassVar[Sequence[str]] │ │ │ │ │ │ │ │ │ │ - def __del__(self) -> None: │ │ │ │ │ - if self._needs_close: │ │ │ │ │ - self.close() │ │ │ │ │ + async def run_command(self, command: str, args: 'tuple[object, ...]', fds: 'list[int]', stderr: str) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - def __enter__(self) -> 'Handle': │ │ │ │ │ - return self │ │ │ │ │ │ │ │ │ │ - def __exit__(self, _type: type, _value: object, _traceback: object) -> None: │ │ │ │ │ - self.close() │ │ │ │ │ +class AskpassHandler(InteractionHandler): │ │ │ │ │ + commands: ClassVar[Sequence[str]] = ('ferny.askpass',) │ │ │ │ │ │ │ │ │ │ - @classmethod │ │ │ │ │ - def open(cls, *args: Any, **kwargs: Any) -> 'Handle': │ │ │ │ │ - return cls(os.open(*args, **kwargs)) │ │ │ │ │ + async def do_askpass(self, messages: str, prompt: str, hint: str) -> 'str | None': │ │ │ │ │ + """Prompt the user for an authentication or confirmation interaction. │ │ │ │ │ │ │ │ │ │ - def steal(self) -> 'Handle': │ │ │ │ │ - self._needs_close = False │ │ │ │ │ - return self.__class__(int(self)) │ │ │ │ │ + 'messages' is data that was sent to stderr before the interaction was requested. │ │ │ │ │ + 'prompt' is the interaction prompt. │ │ │ │ │ │ │ │ │ │ + The expected response type depends on hint: │ │ │ │ │ │ │ │ │ │ -class WatchInvalidator: │ │ │ │ │ - _name: bytes │ │ │ │ │ - _source: Optional[Event.Source] │ │ │ │ │ - _watch: Optional['PathWatch'] │ │ │ │ │ + - "confirm": ask for permission, returning "yes" if accepted │ │ │ │ │ + - example: authorizing agent operation │ │ │ │ │ │ │ │ │ │ - def event(self, mask: IN, _cookie: int, name: Optional[bytes]) -> None: │ │ │ │ │ - logger.debug('invalidator event %s %s', mask, name) │ │ │ │ │ - if self._watch is not None: │ │ │ │ │ - # If this node itself disappeared, that's definitely an │ │ │ │ │ - # invalidation. Otherwise, the name needs to match. │ │ │ │ │ - if IN.IGNORED in mask or self._name == name: │ │ │ │ │ - logger.debug('Invalidating!') │ │ │ │ │ - self._watch.invalidate() │ │ │ │ │ + - "none": show a request without need for a response │ │ │ │ │ + - example: please touch your authentication token │ │ │ │ │ │ │ │ │ │ - def __init__(self, watch: 'PathWatch', event: Event, dirfd: int, name: str): │ │ │ │ │ - self._watch = watch │ │ │ │ │ - self._name = name.encode('utf-8') │ │ │ │ │ + - otherwise: return a password or other form of text token │ │ │ │ │ + - examples: enter password, unlock private key │ │ │ │ │ │ │ │ │ │ - # establishing invalidation watches is best-effort and can fail for a │ │ │ │ │ - # number of reasons, including search (+x) but not read (+r) permission │ │ │ │ │ - # on a particular path component, or exceeding limits on watches │ │ │ │ │ + In any case, the function should properly handle cancellation. For the │ │ │ │ │ + "none" case, this will be the normal way to dismiss the dialog. │ │ │ │ │ + """ │ │ │ │ │ + return None │ │ │ │ │ + │ │ │ │ │ + async def do_hostkey(self, reason: str, host: str, algorithm: str, key: str, fingerprint: str) -> bool: │ │ │ │ │ + """Prompt the user for a decision regarding acceptance of a host key. │ │ │ │ │ + │ │ │ │ │ + The "reason" will be either "HOSTNAME" or "ADDRESS" (if `CheckHostIP` is enabled). │ │ │ │ │ + │ │ │ │ │ + The host, algorithm, and key parameters are the values in the form that │ │ │ │ │ + they would appear one a single line in the known hosts file. The │ │ │ │ │ + fingerprint is the key fingerprint in the format that ssh would │ │ │ │ │ + normally present it to the user. │ │ │ │ │ + │ │ │ │ │ + In case the host key should be accepted, this function needs to return │ │ │ │ │ + True. Returning False means that ssh implements its default logic. To │ │ │ │ │ + interrupt the connection, raise an exception. │ │ │ │ │ + """ │ │ │ │ │ + return False │ │ │ │ │ + │ │ │ │ │ + async def do_custom_command( │ │ │ │ │ + self, command: str, args: 'tuple[object, ...]', fds: 'list[int]', stderr: str │ │ │ │ │ + ) -> None: │ │ │ │ │ + """Handle a custom command. │ │ │ │ │ + │ │ │ │ │ + The command name, its arguments, the passed fds, and the stderr leading │ │ │ │ │ + up to the command invocation are all provided. │ │ │ │ │ + │ │ │ │ │ + See doc/interaction-protocol.md │ │ │ │ │ + """ │ │ │ │ │ + │ │ │ │ │ + async def _askpass_command(self, args: 'tuple[object, ...]', fds: 'list[int]', stderr: str) -> None: │ │ │ │ │ + logger.debug('_askpass_command(%s, %s, %s)', args, fds, stderr) │ │ │ │ │ try: │ │ │ │ │ - mask = IN.CREATE | IN.DELETE | IN.MOVE | IN.DELETE_SELF | IN.IGNORED │ │ │ │ │ - self._source = event.add_inotify_fd(dirfd, mask, self.event) │ │ │ │ │ - except OSError: │ │ │ │ │ - self._source = None │ │ │ │ │ + argv, env = args │ │ │ │ │ + assert isinstance(argv, list) │ │ │ │ │ + assert all(isinstance(arg, str) for arg in argv) │ │ │ │ │ + assert isinstance(env, dict) │ │ │ │ │ + assert all(isinstance(key, str) and isinstance(val, str) for key, val in env.items()) │ │ │ │ │ + assert len(fds) == 2 │ │ │ │ │ + except (ValueError, TypeError, AssertionError) as exc: │ │ │ │ │ + logger.error('Invalid arguments to askpass interaction: %s, %s: %s', args, fds, exc) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - def close(self) -> None: │ │ │ │ │ - # This is a little bit tricky: systemd doesn't have a specific close │ │ │ │ │ - # API outside of unref, so let's make it as explicit as possible. │ │ │ │ │ - self._watch = None │ │ │ │ │ - self._source = None │ │ │ │ │ + with open(fds.pop(0), 'w') as status, open(fds.pop(0), 'w') as stdout: │ │ │ │ │ + try: │ │ │ │ │ + loop = get_running_loop() │ │ │ │ │ + try: │ │ │ │ │ + task = asyncio.current_task() │ │ │ │ │ + except AttributeError: │ │ │ │ │ + task = asyncio.Task.current_task() # type:ignore[attr-defined] # (Python 3.6) │ │ │ │ │ + assert task is not None │ │ │ │ │ + loop.add_reader(status, task.cancel) │ │ │ │ │ │ │ │ │ │ + if len(argv) == 2: │ │ │ │ │ + # normal askpass │ │ │ │ │ + prompt = argv[1] │ │ │ │ │ + hint = env.get('SSH_ASKPASS_PROMPT', '') │ │ │ │ │ + logger.debug('do_askpass(%r, %r, %r)', stderr, prompt, hint) │ │ │ │ │ + answer = await self.do_askpass(stderr, prompt, hint) │ │ │ │ │ + logger.debug('do_askpass answer %r', answer) │ │ │ │ │ + if answer is not None: │ │ │ │ │ + print(answer, file=stdout) │ │ │ │ │ + print(0, file=status) │ │ │ │ │ │ │ │ │ │ -class PathStack(List[str]): │ │ │ │ │ - def add_path(self, pathname: str) -> None: │ │ │ │ │ - # TO DO: consider doing something reasonable with trailing slashes │ │ │ │ │ - # this is a stack, popped from the end: push components in reverse │ │ │ │ │ - self.extend(item for item in reversed(pathname.split('/')) if item) │ │ │ │ │ - if pathname.startswith('/'): │ │ │ │ │ - self.append('/') │ │ │ │ │ + elif len(argv) == 6: │ │ │ │ │ + # KnownHostsCommand │ │ │ │ │ + argv0, reason, host, algorithm, key, fingerprint = argv │ │ │ │ │ + if reason in ['ADDRESS', 'HOSTNAME']: │ │ │ │ │ + logger.debug('do_hostkey(%r, %r, %r, %r, %r)', reason, host, algorithm, key, fingerprint) │ │ │ │ │ + if await self.do_hostkey(reason, host, algorithm, key, fingerprint): │ │ │ │ │ + print(host, algorithm, key, file=stdout) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug('ignoring KnownHostsCommand reason %r', reason) │ │ │ │ │ │ │ │ │ │ - def __init__(self, path: str): │ │ │ │ │ - super().__init__() │ │ │ │ │ - self.add_path(path) │ │ │ │ │ + print(0, file=status) │ │ │ │ │ │ │ │ │ │ + else: │ │ │ │ │ + logger.error('Incorrect number of command-line arguments to ferny-askpass: %s', argv) │ │ │ │ │ + finally: │ │ │ │ │ + loop.remove_reader(status) │ │ │ │ │ │ │ │ │ │ -class Listener: │ │ │ │ │ - def do_inotify_event(self, mask: IN, cookie: int, name: Optional[bytes]) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + async def run_command(self, command: str, args: 'tuple[object, ...]', fds: 'list[int]', stderr: str) -> None: │ │ │ │ │ + logger.debug('run_command(%s, %s, %s, %s)', command, args, fds, stderr) │ │ │ │ │ + if command == 'ferny.askpass': │ │ │ │ │ + await self._askpass_command(args, fds, stderr) │ │ │ │ │ + else: │ │ │ │ │ + await self.do_custom_command(command, args, fds, stderr) │ │ │ │ │ │ │ │ │ │ - def do_identity_changed(self, fd: Optional[Handle], errno: Optional[int]) -> None: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ │ │ │ │ │ +class InteractionAgent: │ │ │ │ │ + _handlers: 'dict[str, InteractionHandler]' │ │ │ │ │ │ │ │ │ │ -class PathWatch: │ │ │ │ │ - _event: Event │ │ │ │ │ - _listener: Listener │ │ │ │ │ - _path: str │ │ │ │ │ - _invalidators: List[WatchInvalidator] │ │ │ │ │ - _errno: Optional[int] │ │ │ │ │ - _source: Optional[Event.Source] │ │ │ │ │ - _tag: Optional[None] │ │ │ │ │ - _fd: Handle │ │ │ │ │ + _loop: asyncio.AbstractEventLoop │ │ │ │ │ │ │ │ │ │ - def __init__(self, path: str, listener: Listener, event: Optional[Event] = None): │ │ │ │ │ - self._event = event or Event.default() │ │ │ │ │ - self._path = path │ │ │ │ │ - self._listener = listener │ │ │ │ │ + _tasks: 'set[asyncio.Task]' │ │ │ │ │ │ │ │ │ │ - self._invalidators = [] │ │ │ │ │ - self._errno = None │ │ │ │ │ - self._source = None │ │ │ │ │ - self._tag = None │ │ │ │ │ - self._fd = Handle() │ │ │ │ │ + _buffer: bytearray │ │ │ │ │ + _ours: socket.socket │ │ │ │ │ + _theirs: socket.socket │ │ │ │ │ │ │ │ │ │ - self.invalidate() │ │ │ │ │ + _completion_future: 'asyncio.Future[str]' │ │ │ │ │ + _pending_result: 'None | str | Exception' = None │ │ │ │ │ + _end: bool = False │ │ │ │ │ │ │ │ │ │ - def got_event(self, mask: IN, cookie: int, name: Optional[bytes]) -> None: │ │ │ │ │ - logger.debug('target event %s: %s %s %s', self._path, mask, cookie, name) │ │ │ │ │ - self._listener.do_inotify_event(mask, cookie, name) │ │ │ │ │ + def _consider_completion(self) -> None: │ │ │ │ │ + logger.debug('_consider_completion(%r)', self) │ │ │ │ │ │ │ │ │ │ - def invalidate(self) -> None: │ │ │ │ │ - for invalidator in self._invalidators: │ │ │ │ │ - invalidator.close() │ │ │ │ │ - self._invalidators = [] │ │ │ │ │ + if self._pending_result is None or self._tasks: │ │ │ │ │ + logger.debug(' but not ready yet') │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - fd = self.walk() │ │ │ │ │ - except OSError as error: │ │ │ │ │ - logger.debug('walk ended in error %d', error.errno) │ │ │ │ │ + elif self._completion_future.done(): │ │ │ │ │ + logger.debug(' but already complete') │ │ │ │ │ │ │ │ │ │ - if self._source or self._fd or self._errno != error.errno: │ │ │ │ │ - logger.debug('Ending existing watches.') │ │ │ │ │ - self._source = None │ │ │ │ │ - self._fd.close() │ │ │ │ │ - self._fd = Handle() │ │ │ │ │ - self._errno = error.errno │ │ │ │ │ + elif isinstance(self._pending_result, str): │ │ │ │ │ + logger.debug(' submitting stderr (%r) to completion_future', self._pending_result) │ │ │ │ │ + self._completion_future.set_result(self._pending_result) │ │ │ │ │ │ │ │ │ │ - logger.debug('Notifying of new error state %d', self._errno) │ │ │ │ │ - self._listener.do_identity_changed(None, self._errno) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug(' submitting exception (%r) to completion_future') │ │ │ │ │ + self._completion_future.set_exception(self._pending_result) │ │ │ │ │ + │ │ │ │ │ + def _result(self, result: 'str | Exception') -> None: │ │ │ │ │ + logger.debug('_result(%r, %r)', self, result) │ │ │ │ │ + │ │ │ │ │ + if self._pending_result is None: │ │ │ │ │ + self._pending_result = result │ │ │ │ │ + │ │ │ │ │ + if self._ours.fileno() != -1: │ │ │ │ │ + logger.debug(' remove_reader(%r)', self._ours) │ │ │ │ │ + self._loop.remove_reader(self._ours.fileno()) │ │ │ │ │ + │ │ │ │ │ + for task in self._tasks: │ │ │ │ │ + logger.debug(' cancel(%r)', task) │ │ │ │ │ + task.cancel() │ │ │ │ │ │ │ │ │ │ + logger.debug(' closing sockets') │ │ │ │ │ + self._theirs.close() # idempotent │ │ │ │ │ + self._ours.close() │ │ │ │ │ + │ │ │ │ │ + self._consider_completion() │ │ │ │ │ + │ │ │ │ │ + def _invoke_command(self, stderr: bytes, command_blob: bytes, fds: 'list[int]') -> None: │ │ │ │ │ + logger.debug('_invoke_command(%r, %r, %r)', stderr, command_blob, fds) │ │ │ │ │ + try: │ │ │ │ │ + command, args = ast.literal_eval(command_blob.decode()) │ │ │ │ │ + if not isinstance(command, str) or not isinstance(args, tuple): │ │ │ │ │ + raise TypeError('Invalid argument types') │ │ │ │ │ + except (UnicodeDecodeError, SyntaxError, ValueError, TypeError) as exc: │ │ │ │ │ + logger.error('Received invalid ferny command: %s: %s', command_blob, exc) │ │ │ │ │ return │ │ │ │ │ │ │ │ │ │ - with fd: │ │ │ │ │ - logger.debug('walk successful. Got fd %d', fd) │ │ │ │ │ - if fd == self._fd: │ │ │ │ │ - logger.debug('fd seems to refer to same file. Doing nothing.') │ │ │ │ │ - return │ │ │ │ │ + if command == 'ferny.end': │ │ │ │ │ + self._end = True │ │ │ │ │ + self._result(self._buffer.decode(errors='replace')) │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ - logger.debug('This file is new for us. Removing old watch.') │ │ │ │ │ - self._source = None │ │ │ │ │ - self._fd.close() │ │ │ │ │ - self._fd = fd.steal() │ │ │ │ │ + try: │ │ │ │ │ + handler = self._handlers[command] │ │ │ │ │ + except KeyError: │ │ │ │ │ + logger.error('Received unhandled ferny command: %s', command) │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + # The task is responsible for the list of fds and removing itself │ │ │ │ │ + # from the set. │ │ │ │ │ + task_fds = list(fds) │ │ │ │ │ + task = self._loop.create_task(handler.run_command(command, args, task_fds, stderr.decode())) │ │ │ │ │ + │ │ │ │ │ + def bottom_half(completed_task: asyncio.Task) -> None: │ │ │ │ │ + assert completed_task is task │ │ │ │ │ + while task_fds: │ │ │ │ │ + os.close(task_fds.pop()) │ │ │ │ │ + self._tasks.remove(task) │ │ │ │ │ │ │ │ │ │ try: │ │ │ │ │ - logger.debug('Establishing a new watch.') │ │ │ │ │ - self._source = self._event.add_inotify_fd(self._fd, IN.CHANGED, self.got_event) │ │ │ │ │ - logger.debug('Watching successfully. Notifying of new identity.') │ │ │ │ │ - self._listener.do_identity_changed(self._fd, None) │ │ │ │ │ - except OSError as error: │ │ │ │ │ - logger.debug('Watching failed (%d). Notifying of new identity.', error.errno) │ │ │ │ │ - self._listener.do_identity_changed(self._fd, error.errno) │ │ │ │ │ + task.result() │ │ │ │ │ + logger.debug('%r completed cleanly', handler) │ │ │ │ │ + except asyncio.CancelledError: │ │ │ │ │ + # this is not an error — it just means ferny-askpass exited via signal │ │ │ │ │ + logger.debug('%r was cancelled', handler) │ │ │ │ │ + except Exception as exc: │ │ │ │ │ + logger.debug('%r raised %r', handler, exc) │ │ │ │ │ + self._result(exc) │ │ │ │ │ │ │ │ │ │ - def walk(self) -> Handle: │ │ │ │ │ - remaining_symlink_lookups = 40 │ │ │ │ │ - remaining_components = PathStack(self._path) │ │ │ │ │ - dirfd = Handle() │ │ │ │ │ + self._consider_completion() │ │ │ │ │ │ │ │ │ │ + task.add_done_callback(bottom_half) │ │ │ │ │ + self._tasks.add(task) │ │ │ │ │ + fds[:] = [] │ │ │ │ │ + │ │ │ │ │ + def _got_data(self, data: bytes, fds: 'list[int]') -> None: │ │ │ │ │ + logger.debug('_got_data(%r, %r)', data, fds) │ │ │ │ │ + │ │ │ │ │ + if data == b'': │ │ │ │ │ + self._result(self._buffer.decode(errors='replace')) │ │ │ │ │ + return │ │ │ │ │ + │ │ │ │ │ + self._buffer.extend(data) │ │ │ │ │ + │ │ │ │ │ + # Read zero or more "remote" messages │ │ │ │ │ + chunks = COMMAND_RE.split(self._buffer) │ │ │ │ │ + self._buffer = bytearray(chunks.pop()) │ │ │ │ │ + while len(chunks) > 1: │ │ │ │ │ + self._invoke_command(chunks[0], chunks[1], []) │ │ │ │ │ + chunks = chunks[2:] │ │ │ │ │ + │ │ │ │ │ + # Maybe read one "local" message │ │ │ │ │ + if fds: │ │ │ │ │ + assert self._buffer.endswith(b'\0'), self._buffer │ │ │ │ │ + stderr = self._buffer[:-1] │ │ │ │ │ + self._buffer = bytearray(b'') │ │ │ │ │ + with open(fds.pop(0), 'rb') as command_channel: │ │ │ │ │ + command = command_channel.read() │ │ │ │ │ + self._invoke_command(stderr, command, fds) │ │ │ │ │ + │ │ │ │ │ + def _read_ready(self) -> None: │ │ │ │ │ try: │ │ │ │ │ - logger.debug('Starting path walk') │ │ │ │ │ + data, fds, _flags, _addr = recv_fds(self._ours, 4096, 10, flags=socket.MSG_DONTWAIT) │ │ │ │ │ + except BlockingIOError: │ │ │ │ │ + return │ │ │ │ │ + except OSError as exc: │ │ │ │ │ + self._result(exc) │ │ │ │ │ + else: │ │ │ │ │ + self._got_data(data, fds) │ │ │ │ │ + finally: │ │ │ │ │ + while fds: │ │ │ │ │ + os.close(fds.pop()) │ │ │ │ │ │ │ │ │ │ - while remaining_components: │ │ │ │ │ - logger.debug('r=%s dfd=%s', remaining_components, dirfd) │ │ │ │ │ + def __init__( │ │ │ │ │ + self, │ │ │ │ │ + handlers: Sequence[InteractionHandler], │ │ │ │ │ + loop: 'asyncio.AbstractEventLoop | None' = None, │ │ │ │ │ + done_callback: 'Callable[[asyncio.Future[str]], None] | None' = None, │ │ │ │ │ + ) -> None: │ │ │ │ │ + self._loop = loop or get_running_loop() │ │ │ │ │ + self._completion_future = self._loop.create_future() │ │ │ │ │ + self._tasks = set() │ │ │ │ │ + self._handlers = {} │ │ │ │ │ │ │ │ │ │ - name = remaining_components.pop() │ │ │ │ │ + for handler in handlers: │ │ │ │ │ + for command in handler.commands: │ │ │ │ │ + self._handlers[command] = handler │ │ │ │ │ │ │ │ │ │ - if dirfd and name != '/': │ │ │ │ │ - self._invalidators.append(WatchInvalidator(self, self._event, dirfd, name)) │ │ │ │ │ + if done_callback is not None: │ │ │ │ │ + self._completion_future.add_done_callback(done_callback) │ │ │ │ │ │ │ │ │ │ - with Handle.open(name, os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=dirfd) as fd: │ │ │ │ │ - mode = os.fstat(fd).st_mode │ │ │ │ │ + self._theirs, self._ours = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) │ │ │ │ │ + self._buffer = bytearray() │ │ │ │ │ │ │ │ │ │ - if stat.S_ISLNK(mode): │ │ │ │ │ - if remaining_symlink_lookups == 0: │ │ │ │ │ - raise OSError(errno.ELOOP, os.strerror(errno.ELOOP)) │ │ │ │ │ - remaining_symlink_lookups -= 1 │ │ │ │ │ - linkpath = os.readlink('', dir_fd=fd) │ │ │ │ │ - logger.debug('%s is a symlink. adding %s to components', name, linkpath) │ │ │ │ │ - remaining_components.add_path(linkpath) │ │ │ │ │ + def fileno(self) -> int: │ │ │ │ │ + return self._theirs.fileno() │ │ │ │ │ │ │ │ │ │ - else: │ │ │ │ │ - dirfd.close() │ │ │ │ │ - dirfd = fd.steal() │ │ │ │ │ + def start(self) -> None: │ │ │ │ │ + logger.debug('start(%r)', self) │ │ │ │ │ + if self._ours.fileno() != -1: │ │ │ │ │ + logger.debug(' add_reader(%r)', self._ours) │ │ │ │ │ + self._loop.add_reader(self._ours.fileno(), self._read_ready) │ │ │ │ │ + else: │ │ │ │ │ + logger.debug(' ...but agent is already finished.') │ │ │ │ │ │ │ │ │ │ - return dirfd.steal() │ │ │ │ │ + logger.debug(' close(%r)', self._theirs) │ │ │ │ │ + self._theirs.close() │ │ │ │ │ │ │ │ │ │ + def force_completion(self) -> None: │ │ │ │ │ + logger.debug('force_completion(%r)', self) │ │ │ │ │ + │ │ │ │ │ + # read any residual data on stderr, but don't process commands, and │ │ │ │ │ + # don't block │ │ │ │ │ + try: │ │ │ │ │ + if self._ours.fileno() != -1: │ │ │ │ │ + logger.debug(' draining pending stderr data (non-blocking)') │ │ │ │ │ + with contextlib.suppress(BlockingIOError): │ │ │ │ │ + while True: │ │ │ │ │ + data = self._ours.recv(4096, socket.MSG_DONTWAIT) │ │ │ │ │ + logger.debug(' got %d bytes', len(data)) │ │ │ │ │ + if not data: │ │ │ │ │ + break │ │ │ │ │ + self._buffer.extend(data) │ │ │ │ │ + except OSError as exc: │ │ │ │ │ + self._result(exc) │ │ │ │ │ + else: │ │ │ │ │ + self._result(self._buffer.decode(errors='replace')) │ │ │ │ │ + │ │ │ │ │ + async def communicate(self) -> None: │ │ │ │ │ + logger.debug('_communicate(%r)', self) │ │ │ │ │ + try: │ │ │ │ │ + self.start() │ │ │ │ │ + # We assume that we are the only ones to write to │ │ │ │ │ + # self._completion_future. If we directly await it, though, it can │ │ │ │ │ + # also have a asyncio.CancelledError posted to it from outside. │ │ │ │ │ + # Shield it to prevent that from happening. │ │ │ │ │ + stderr = await asyncio.shield(self._completion_future) │ │ │ │ │ + logger.debug('_communicate(%r) stderr result is %r', self, stderr) │ │ │ │ │ finally: │ │ │ │ │ - dirfd.close() │ │ │ │ │ + logger.debug('_communicate finished. Ensuring completion.') │ │ │ │ │ + self.force_completion() │ │ │ │ │ + if not self._end: │ │ │ │ │ + logger.debug('_communicate never saw ferny.end. raising InteractionError.') │ │ │ │ │ + raise InteractionError(stderr.strip()) │ │ │ │ │ │ │ │ │ │ - def close(self) -> None: │ │ │ │ │ - for invalidator in self._invalidators: │ │ │ │ │ - invalidator.close() │ │ │ │ │ - self._invalidators = [] │ │ │ │ │ - self._source = None │ │ │ │ │ - self._fd.close() │ │ │ │ │ + │ │ │ │ │ +def write_askpass_to_tmpdir(tmpdir: str) -> str: │ │ │ │ │ + askpass_path = os.path.join(tmpdir, 'ferny-askpass') │ │ │ │ │ + fd = os.open(askpass_path, os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC | os.O_EXCL | os.O_NOFOLLOW, 0o777) │ │ │ │ │ + try: │ │ │ │ │ + os.write(fd, __loader__.get_data(interaction_client.__file__)) # type: ignore │ │ │ │ │ + finally: │ │ │ │ │ + os.close(fd) │ │ │ │ │ + return askpass_path │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +@contextlib.contextmanager │ │ │ │ │ +def temporary_askpass(**kwargs: Any) -> Generator[str, None, None]: │ │ │ │ │ + with tempfile.TemporaryDirectory(**kwargs) as directory: │ │ │ │ │ + yield write_askpass_to_tmpdir(directory) │ │ │ │ │ +'''.encode('utf-8'), │ │ │ │ │ + 'cockpit/_vendor/ferny/ssh_errors.py': br'''# ferny - asyncio SSH client library, using ssh(1) │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ + │ │ │ │ │ +import ctypes │ │ │ │ │ +import errno │ │ │ │ │ +import os │ │ │ │ │ +import re │ │ │ │ │ +import socket │ │ │ │ │ +from typing import ClassVar, Iterable, Match, Pattern │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class SshError(Exception): │ │ │ │ │ + PATTERN: ClassVar[Pattern] │ │ │ │ │ + │ │ │ │ │ + def __init__(self, match: 'Match | None', stderr: str) -> None: │ │ │ │ │ + super().__init__(match.group(0) if match is not None else stderr) │ │ │ │ │ + self.stderr = stderr │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class SshAuthenticationError(SshError): │ │ │ │ │ + PATTERN = re.compile(r'^([^:]+): Permission denied \(([^()]+)\)\.$', re.M) │ │ │ │ │ + │ │ │ │ │ + def __init__(self, match: Match, stderr: str) -> None: │ │ │ │ │ + super().__init__(match, stderr) │ │ │ │ │ + self.destination = match.group(1) │ │ │ │ │ + self.methods = match.group(2).split(',') │ │ │ │ │ + self.message = match.group(0) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +# generic host key error for OSes without KnownHostsCommand support │ │ │ │ │ +class SshHostKeyError(SshError): │ │ │ │ │ + PATTERN = re.compile(r'^Host key verification failed.$', re.M) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +# specific errors for OSes with KnownHostsCommand │ │ │ │ │ +class SshUnknownHostKeyError(SshHostKeyError): │ │ │ │ │ + PATTERN = re.compile(r'^No .* host key is known.*Host key verification failed.$', re.S | re.M) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class SshChangedHostKeyError(SshHostKeyError): │ │ │ │ │ + PATTERN = re.compile(r'warning.*remote host identification has changed', re.I) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +# Functionality for mapping getaddrinfo()-family error messages to their │ │ │ │ │ +# equivalent Python exceptions. │ │ │ │ │ +def make_gaierror_map() -> 'Iterable[tuple[str, int]]': │ │ │ │ │ + libc = ctypes.CDLL(None) │ │ │ │ │ + libc.gai_strerror.restype = ctypes.c_char_p │ │ │ │ │ + │ │ │ │ │ + for key in dir(socket): │ │ │ │ │ + if key.startswith('EAI_'): │ │ │ │ │ + errnum = getattr(socket, key) │ │ │ │ │ + yield libc.gai_strerror(errnum).decode('utf-8'), errnum │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +gaierror_map = dict(make_gaierror_map()) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +# Functionality for passing strerror() error messages to their equivalent │ │ │ │ │ +# Python exceptions. │ │ │ │ │ +# There doesn't seem to be an official API for turning an errno into the │ │ │ │ │ +# correct subtype of OSError, and the list that cpython uses is hidden fairly │ │ │ │ │ +# deeply inside of the implementation. This is basically copied from the │ │ │ │ │ +# ADD_ERRNO() lines in _PyExc_InitState in cpython/Objects/exceptions.c │ │ │ │ │ +oserror_subclass_map = dict((errnum, cls) for cls, errnum in [ │ │ │ │ │ + (BlockingIOError, errno.EAGAIN), │ │ │ │ │ + (BlockingIOError, errno.EALREADY), │ │ │ │ │ + (BlockingIOError, errno.EINPROGRESS), │ │ │ │ │ + (BlockingIOError, errno.EWOULDBLOCK), │ │ │ │ │ + (BrokenPipeError, errno.EPIPE), │ │ │ │ │ + (BrokenPipeError, errno.ESHUTDOWN), │ │ │ │ │ + (ChildProcessError, errno.ECHILD), │ │ │ │ │ + (ConnectionAbortedError, errno.ECONNABORTED), │ │ │ │ │ + (ConnectionRefusedError, errno.ECONNREFUSED), │ │ │ │ │ + (ConnectionResetError, errno.ECONNRESET), │ │ │ │ │ + (FileExistsError, errno.EEXIST), │ │ │ │ │ + (FileNotFoundError, errno.ENOENT), │ │ │ │ │ + (IsADirectoryError, errno.EISDIR), │ │ │ │ │ + (NotADirectoryError, errno.ENOTDIR), │ │ │ │ │ + (InterruptedError, errno.EINTR), │ │ │ │ │ + (PermissionError, errno.EACCES), │ │ │ │ │ + (PermissionError, errno.EPERM), │ │ │ │ │ + (ProcessLookupError, errno.ESRCH), │ │ │ │ │ + (TimeoutError, errno.ETIMEDOUT), │ │ │ │ │ +]) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def get_exception_for_ssh_stderr(stderr: str) -> Exception: │ │ │ │ │ + stderr = stderr.replace('\r\n', '\n') # fix line separators │ │ │ │ │ + │ │ │ │ │ + # check for the specific error messages first, then for generic SshHostKeyError │ │ │ │ │ + for ssh_cls in [SshAuthenticationError, SshChangedHostKeyError, SshUnknownHostKeyError, SshHostKeyError]: │ │ │ │ │ + match = ssh_cls.PATTERN.search(stderr) │ │ │ │ │ + if match is not None: │ │ │ │ │ + return ssh_cls(match, stderr) │ │ │ │ │ + │ │ │ │ │ + before, colon, after = stderr.rpartition(':') │ │ │ │ │ + if colon and after: │ │ │ │ │ + potential_strerror = after.strip() │ │ │ │ │ + │ │ │ │ │ + # DNS lookup errors │ │ │ │ │ + if potential_strerror in gaierror_map: │ │ │ │ │ + errnum = gaierror_map[potential_strerror] │ │ │ │ │ + return socket.gaierror(errnum, stderr) │ │ │ │ │ + │ │ │ │ │ + # Network connect errors │ │ │ │ │ + for errnum in errno.errorcode: │ │ │ │ │ + if os.strerror(errnum) == potential_strerror: │ │ │ │ │ + os_cls = oserror_subclass_map.get(errnum, OSError) │ │ │ │ │ + return os_cls(errnum, stderr) │ │ │ │ │ + │ │ │ │ │ + # No match? Generic. │ │ │ │ │ + return SshError(None, stderr) │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/libsystemd.py': r'''# systemd_ctypes │ │ │ │ │ + 'cockpit/_vendor/bei/tmpfs.py': br'''import os │ │ │ │ │ +import subprocess │ │ │ │ │ +import sys │ │ │ │ │ +import tempfile │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def main(*command: str) -> None: │ │ │ │ │ + with tempfile.TemporaryDirectory() as tmpdir: │ │ │ │ │ + os.chdir(tmpdir) │ │ │ │ │ + │ │ │ │ │ + for key, value in __loader__.get_contents().items(): │ │ │ │ │ + if key.startswith('tmpfs/'): │ │ │ │ │ + subdir = os.path.dirname(key) │ │ │ │ │ + os.makedirs(subdir, exist_ok=True) │ │ │ │ │ + with open(key, 'wb') as fp: │ │ │ │ │ + fp.write(value) │ │ │ │ │ + │ │ │ │ │ + os.chdir('tmpfs') │ │ │ │ │ + │ │ │ │ │ + result = subprocess.run(command, check=False) │ │ │ │ │ + sys.exit(result.returncode) │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/bei/beipack.py': br'''# beipack - Remote bootloader for Python │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ @@ -6872,333 +6385,356 @@ │ │ │ │ │ # 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import ctypes │ │ │ │ │ +import argparse │ │ │ │ │ +import binascii │ │ │ │ │ +import lzma │ │ │ │ │ import os │ │ │ │ │ import sys │ │ │ │ │ -from typing import ClassVar, List, Optional, Tuple, Union │ │ │ │ │ +import tempfile │ │ │ │ │ +import zipfile │ │ │ │ │ +from typing import Dict, Iterable, List, Optional, Set, Tuple │ │ │ │ │ │ │ │ │ │ -from .inotify import inotify_event │ │ │ │ │ -from .librarywrapper import ( │ │ │ │ │ - Callback, │ │ │ │ │ - Errno, │ │ │ │ │ - Reference, │ │ │ │ │ - ReferenceType, │ │ │ │ │ - UserData, │ │ │ │ │ - WeakReference, │ │ │ │ │ - byref, │ │ │ │ │ -) │ │ │ │ │ -from .typing import Annotated │ │ │ │ │ +from .data import read_data_file │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class Trampoline(ReferenceType): │ │ │ │ │ - deferred: 'ClassVar[list[Callback] | None]' = None │ │ │ │ │ - trampoline: Callback │ │ │ │ │ - userdata: UserData = None │ │ │ │ │ +def escape_string(data: str) -> str: │ │ │ │ │ + # Avoid mentioning ' ' ' literally, to make our own packing a bit prettier │ │ │ │ │ + triplequote = "'" * 3 │ │ │ │ │ + if triplequote not in data: │ │ │ │ │ + return "r" + triplequote + data + triplequote │ │ │ │ │ + if '"""' not in data: │ │ │ │ │ + return 'r"""' + data + '"""' │ │ │ │ │ + return repr(data) │ │ │ │ │ │ │ │ │ │ - def cancel(self) -> None: │ │ │ │ │ - self._unref() │ │ │ │ │ - self.value = None │ │ │ │ │ │ │ │ │ │ - def __del__(self) -> None: │ │ │ │ │ - # This might be the currently-dispatching callback — make sure we don't │ │ │ │ │ - # destroy the trampoline before we return. We drop the deferred list │ │ │ │ │ - # from the event loop when we're sure we're not doing any dispatches. │ │ │ │ │ - if Trampoline.deferred is not None: │ │ │ │ │ - Trampoline.deferred.append(self.trampoline) │ │ │ │ │ - if self.value is not None: │ │ │ │ │ - self._unref() │ │ │ │ │ +def ascii_bytes_repr(data: bytes) -> str: │ │ │ │ │ + return 'b' + escape_string(data.decode('ascii')) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class sd_bus_error(ctypes.Structure): │ │ │ │ │ - # This is ABI, so we are safe to assume it doesn't change. │ │ │ │ │ - # Unfortunately, we lack anything like sd_bus_error_new(). │ │ │ │ │ - _fields_ = ( │ │ │ │ │ - ("name", ctypes.c_char_p), │ │ │ │ │ - ("message", ctypes.c_char_p), │ │ │ │ │ - ("_need_free", ctypes.c_int), │ │ │ │ │ - ) │ │ │ │ │ +def utf8_bytes_repr(data: bytes) -> str: │ │ │ │ │ + return escape_string(data.decode('utf-8')) + ".encode('utf-8')" │ │ │ │ │ │ │ │ │ │ - def get(self) -> Tuple[str, str]: │ │ │ │ │ - return self.name.decode(), self.message.decode() │ │ │ │ │ │ │ │ │ │ - def set(self, name: str, message: str) -> None: │ │ │ │ │ - result = libsystemd.sd_bus_error_set(byref(self), name, message) │ │ │ │ │ - if result < 0: │ │ │ │ │ - raise OSError(-result, f"sd_bus_error_set: {os.strerror(-result)}") │ │ │ │ │ +def base64_bytes_repr(data: bytes, imports: Set[str]) -> str: │ │ │ │ │ + # base85 is smaller, but base64 is in C, and ~20x faster. │ │ │ │ │ + # when compressing with `xz -e` the size difference is marginal. │ │ │ │ │ + imports.add('from binascii import a2b_base64') │ │ │ │ │ + encoded = binascii.b2a_base64(data).decode('ascii').strip() │ │ │ │ │ + return f'a2b_base64("{encoded}")' │ │ │ │ │ │ │ │ │ │ - def __del__(self) -> None: │ │ │ │ │ - if self._b_needsfree_: │ │ │ │ │ - libsystemd.sd_bus_error_free(byref(self)) │ │ │ │ │ │ │ │ │ │ +def bytes_repr(data: bytes, imports: Set[str]) -> str: │ │ │ │ │ + # Strategy: │ │ │ │ │ + # if the file is ascii, encode it directly as bytes │ │ │ │ │ + # otherwise, if it's UTF-8, use a unicode string and encode │ │ │ │ │ + # otherwise, base64 │ │ │ │ │ │ │ │ │ │ -class sd_id128(ctypes.Structure): │ │ │ │ │ - # HACK: Pass-by-value of array-containing-structs is broken on Python │ │ │ │ │ - # 3.6. See https://bugs.python.org/issue22273 │ │ │ │ │ - _fields_: List[Tuple[str, type]] = ( │ │ │ │ │ - [("bytes", ctypes.c_uint8 * 16)] │ │ │ │ │ - if sys.version_info >= (3, 7, 0) │ │ │ │ │ - else [("one", ctypes.c_uint64), ("two", ctypes.c_uint64)] │ │ │ │ │ - ) │ │ │ │ │ + try: │ │ │ │ │ + return ascii_bytes_repr(data) │ │ │ │ │ + except UnicodeDecodeError: │ │ │ │ │ + # it's not ascii │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ + # utf-8 │ │ │ │ │ + try: │ │ │ │ │ + return utf8_bytes_repr(data) │ │ │ │ │ + except UnicodeDecodeError: │ │ │ │ │ + # it's not utf-8 │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ -class sd_event_source(Trampoline): │ │ │ │ │ - ... │ │ │ │ │ + return base64_bytes_repr(data, imports) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class sd_event(ReferenceType): │ │ │ │ │ - def _add_inotify( │ │ │ │ │ - self: 'sd_event', │ │ │ │ │ - source: Reference[sd_event_source], │ │ │ │ │ - path: str, │ │ │ │ │ - event: int, │ │ │ │ │ - callback: Callback, │ │ │ │ │ - user_data: UserData, │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ +def dict_repr(contents: Dict[str, bytes], imports: Set[str]) -> str: │ │ │ │ │ + return ('{\n' + │ │ │ │ │ + ''.join(f' {repr(k)}: {bytes_repr(v, imports)},\n' │ │ │ │ │ + for k, v in contents.items()) + │ │ │ │ │ + '}') │ │ │ │ │ │ │ │ │ │ - def dispatch(self: 'sd_event') -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ │ │ │ │ │ - def get_fd(self: 'sd_event') -> Union[int, Errno]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ +def pack(contents: Dict[str, bytes], │ │ │ │ │ + entrypoint: Optional[str] = None, │ │ │ │ │ + args: str = '') -> str: │ │ │ │ │ + """Creates a beipack with the given `contents`. │ │ │ │ │ │ │ │ │ │ - def get_state(self: 'sd_event') -> Union[int, Errno]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + If `entrypoint` is given, it should be an entry point which is run as the │ │ │ │ │ + "main" function. It is given in the `package.module:func format` such that │ │ │ │ │ + the following code is emitted: │ │ │ │ │ │ │ │ │ │ - def loop(self: 'sd_event') -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + from package.module import func as main │ │ │ │ │ + main() │ │ │ │ │ │ │ │ │ │ - def prepare(self: 'sd_event') -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + Additionally, if `args` is given, it is written verbatim between the parens │ │ │ │ │ + of the call to main (ie: it should already be in Python syntax). │ │ │ │ │ + """ │ │ │ │ │ │ │ │ │ │ - def wait( │ │ │ │ │ - self: 'sd_event', timeout: Annotated[int, ctypes.c_uint64] │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + loader = read_data_file('beipack_loader.py') │ │ │ │ │ + lines = [line for line in loader.splitlines() if line] │ │ │ │ │ + lines.append('') │ │ │ │ │ │ │ │ │ │ - @staticmethod │ │ │ │ │ - def _default(ret: Reference['sd_event']) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + imports = {'import sys'} │ │ │ │ │ + contents_txt = dict_repr(contents, imports) │ │ │ │ │ + lines.extend(imports) │ │ │ │ │ + lines.append(f'sys.meta_path.insert(0, BeipackLoader({contents_txt}))') │ │ │ │ │ │ │ │ │ │ + if entrypoint: │ │ │ │ │ + package, main = entrypoint.split(':') │ │ │ │ │ + lines.append(f'from {package} import {main} as main') │ │ │ │ │ + lines.append(f'main({args})') │ │ │ │ │ │ │ │ │ │ -class sd_bus_slot(Trampoline): │ │ │ │ │ - ... │ │ │ │ │ + return ''.join(f'{line}\n' for line in lines) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class sd_bus_message(ReferenceType): │ │ │ │ │ - def rewind(self: 'sd_bus_message', complete: bool) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ +def collect_contents(filenames: List[str], │ │ │ │ │ + relative_to: Optional[str] = None) -> Dict[str, bytes]: │ │ │ │ │ + contents: Dict[str, bytes] = {} │ │ │ │ │ │ │ │ │ │ - def _get_error(self: 'sd_bus_message') -> Reference[sd_bus_error]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + for filename in filenames: │ │ │ │ │ + with open(filename, 'rb') as file: │ │ │ │ │ + contents[os.path.relpath(filename, start=relative_to)] = file.read() │ │ │ │ │ │ │ │ │ │ - def has_signature(self: 'sd_bus_message', signature: str) -> Union[bool, Errno]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + return contents │ │ │ │ │ │ │ │ │ │ - def is_method_error(self: 'sd_bus_message', name: str) -> Union[bool, Errno]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - def _new_method_errnof( │ │ │ │ │ - self: 'sd_bus_message', │ │ │ │ │ - message: Reference['sd_bus_message'], │ │ │ │ │ - error: int, │ │ │ │ │ - format_str: str, │ │ │ │ │ - first_arg: str │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ +def collect_module(name: str, *, recursive: bool) -> Dict[str, bytes]: │ │ │ │ │ + import importlib.resources │ │ │ │ │ + from importlib.resources.abc import Traversable │ │ │ │ │ │ │ │ │ │ - def _new_method_errorf( │ │ │ │ │ - self: 'sd_bus_message', │ │ │ │ │ - m: Reference['sd_bus_message'], │ │ │ │ │ - name: str, │ │ │ │ │ - format_str: str, │ │ │ │ │ - first_arg: str │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + def walk(path: str, entry: Traversable) -> Iterable[Tuple[str, bytes]]: │ │ │ │ │ + for item in entry.iterdir(): │ │ │ │ │ + itemname = f'{path}/{item.name}' │ │ │ │ │ + if item.is_file(): │ │ │ │ │ + yield itemname, item.read_bytes() │ │ │ │ │ + elif recursive and item.name != '__pycache__': │ │ │ │ │ + yield from walk(itemname, item) │ │ │ │ │ │ │ │ │ │ - def _new_method_return( │ │ │ │ │ - self: 'sd_bus_message', m: Reference['sd_bus_message'] │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + return dict(walk(name.replace('.', '/'), importlib.resources.files(name))) │ │ │ │ │ │ │ │ │ │ - def seal( │ │ │ │ │ - self: 'sd_bus_message', │ │ │ │ │ - cookie: Annotated[int, ctypes.c_uint64], │ │ │ │ │ - timeout: Annotated[int, ctypes.c_uint64], │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ │ │ │ │ │ - def _get_bus(self: 'sd_bus_message') -> WeakReference: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ +def collect_zip(filename: str) -> Dict[str, bytes]: │ │ │ │ │ + contents = {} │ │ │ │ │ │ │ │ │ │ - def get_destination(self: 'sd_bus_message') -> str: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + with zipfile.ZipFile(filename) as file: │ │ │ │ │ + for entry in file.filelist: │ │ │ │ │ + if '.dist-info/' in entry.filename: │ │ │ │ │ + continue │ │ │ │ │ + contents[entry.filename] = file.read(entry) │ │ │ │ │ │ │ │ │ │ - def get_interface(self: 'sd_bus_message') -> str: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ + return contents │ │ │ │ │ │ │ │ │ │ - def get_member(self: 'sd_bus_message') -> str: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - def get_path(self: 'sd_bus_message') -> str: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ +def collect_pep517(path: str) -> Dict[str, bytes]: │ │ │ │ │ + with tempfile.TemporaryDirectory() as tmpdir: │ │ │ │ │ + import build │ │ │ │ │ + builder = build.ProjectBuilder(path) │ │ │ │ │ + wheel = builder.build('wheel', tmpdir) │ │ │ │ │ + return collect_zip(wheel) │ │ │ │ │ │ │ │ │ │ - def get_sender(self: 'sd_bus_message') -> Optional[str]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - def get_signature(self: 'sd_bus_message', complete: bool) -> str: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ +def main() -> None: │ │ │ │ │ + parser = argparse.ArgumentParser() │ │ │ │ │ + parser.add_argument('--python', '-p', │ │ │ │ │ + help="add a #!python3 interpreter line using the given path") │ │ │ │ │ + parser.add_argument('--xz', '-J', action='store_true', │ │ │ │ │ + help="compress the output with `xz`") │ │ │ │ │ + parser.add_argument('--topdir', │ │ │ │ │ + help="toplevel directory (paths are stored relative to this)") │ │ │ │ │ + parser.add_argument('--output', '-o', │ │ │ │ │ + help="write output to a file (default: stdout)") │ │ │ │ │ + parser.add_argument('--main', '-m', metavar='MODULE:FUNC', │ │ │ │ │ + help="use FUNC from MODULE as the main function") │ │ │ │ │ + parser.add_argument('--main-args', metavar='ARGS', │ │ │ │ │ + help="arguments to main() in Python syntax", default='') │ │ │ │ │ + parser.add_argument('--module', action='append', default=[], │ │ │ │ │ + help="collect installed modules (recursively)") │ │ │ │ │ + parser.add_argument('--zip', '-z', action='append', default=[], │ │ │ │ │ + help="include files from a zipfile (or wheel)") │ │ │ │ │ + parser.add_argument('--build', metavar='DIR', action='append', default=[], │ │ │ │ │ + help="PEP-517 from a given source directory") │ │ │ │ │ + parser.add_argument('files', nargs='*', │ │ │ │ │ + help="files to include in the beipack") │ │ │ │ │ + args = parser.parse_args() │ │ │ │ │ │ │ │ │ │ + contents = collect_contents(args.files, relative_to=args.topdir) │ │ │ │ │ │ │ │ │ │ -class sd_bus(ReferenceType): │ │ │ │ │ - def _add_match( │ │ │ │ │ - self: 'sd_bus', │ │ │ │ │ - slot: Reference[sd_bus_slot], │ │ │ │ │ - match: str, │ │ │ │ │ - handler: Callback, │ │ │ │ │ - user_data: UserData, │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + for file in args.zip: │ │ │ │ │ + contents.update(collect_zip(file)) │ │ │ │ │ │ │ │ │ │ - def _add_match_async( │ │ │ │ │ - self: 'sd_bus', │ │ │ │ │ - slot: Reference[sd_bus_slot], │ │ │ │ │ - match: str, │ │ │ │ │ - callback: Callback, │ │ │ │ │ - install_callback: Callback, │ │ │ │ │ - user_data: UserData, │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + for name in args.module: │ │ │ │ │ + contents.update(collect_module(name, recursive=True)) │ │ │ │ │ │ │ │ │ │ - def _add_object( │ │ │ │ │ - self: 'sd_bus', │ │ │ │ │ - slot: Reference[sd_bus_slot], │ │ │ │ │ - path: str, │ │ │ │ │ - callback: Callback, │ │ │ │ │ - user_data: UserData, │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + for path in args.build: │ │ │ │ │ + contents.update(collect_pep517(path)) │ │ │ │ │ │ │ │ │ │ - def attach_event( │ │ │ │ │ - self: 'sd_bus', event: Optional[sd_event], priority: int │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + result = pack(contents, args.main, args.main_args).encode('utf-8') │ │ │ │ │ │ │ │ │ │ - def _call( │ │ │ │ │ - self: 'sd_bus', │ │ │ │ │ - message: sd_bus_message, │ │ │ │ │ - timeout: Annotated[int, ctypes.c_uint64], │ │ │ │ │ - ret_error: Reference[sd_bus_error], │ │ │ │ │ - reply: Reference[sd_bus_message], │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + if args.python: │ │ │ │ │ + result = b'#!' + args.python.encode('ascii') + b'\n' + result │ │ │ │ │ │ │ │ │ │ - def _call_async( │ │ │ │ │ - self: 'sd_bus', │ │ │ │ │ - slot: Reference[sd_bus_slot], │ │ │ │ │ - message: sd_bus_message, │ │ │ │ │ - callback: Callback, │ │ │ │ │ - user_data: UserData, │ │ │ │ │ - timeout_usec: Annotated[int, ctypes.c_uint64], │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + if args.xz: │ │ │ │ │ + result = lzma.compress(result, preset=lzma.PRESET_EXTREME) │ │ │ │ │ + │ │ │ │ │ + if args.output: │ │ │ │ │ + with open(args.output, 'wb') as file: │ │ │ │ │ + file.write(result) │ │ │ │ │ + else: │ │ │ │ │ + if args.xz and os.isatty(1): │ │ │ │ │ + sys.exit('refusing to write compressed output to a terminal') │ │ │ │ │ + sys.stdout.buffer.write(result) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +if __name__ == '__main__': │ │ │ │ │ + main() │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/bei/bootloader.py': br'''# beiboot - Remote bootloader for Python │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ + │ │ │ │ │ +import textwrap │ │ │ │ │ +from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple │ │ │ │ │ + │ │ │ │ │ +GADGETS = { │ │ │ │ │ + "_frame": r""" │ │ │ │ │ + import sys │ │ │ │ │ + import traceback │ │ │ │ │ + try: │ │ │ │ │ + ... │ │ │ │ │ + except SystemExit: │ │ │ │ │ + raise │ │ │ │ │ + except BaseException: │ │ │ │ │ + command('beiboot.exc', traceback.format_exc()) │ │ │ │ │ + sys.exit(37) │ │ │ │ │ + """, │ │ │ │ │ + "try_exec": r""" │ │ │ │ │ + import contextlib │ │ │ │ │ + import os │ │ │ │ │ + def try_exec(argv): │ │ │ │ │ + with contextlib.suppress(OSError): │ │ │ │ │ + os.execvp(argv[0], argv) │ │ │ │ │ + """, │ │ │ │ │ + "boot_xz": r""" │ │ │ │ │ + import lzma │ │ │ │ │ + import sys │ │ │ │ │ + def boot_xz(filename, size, args=[], send_end=False): │ │ │ │ │ + command('beiboot.provide', size) │ │ │ │ │ + src_xz = sys.stdin.buffer.read(size) │ │ │ │ │ + src = lzma.decompress(src_xz) │ │ │ │ │ + sys.argv = [filename, *args] │ │ │ │ │ + if send_end: │ │ │ │ │ + end() │ │ │ │ │ + exec(src, { │ │ │ │ │ + '__name__': '__main__', │ │ │ │ │ + '__self_source__': src_xz, │ │ │ │ │ + '__file__': filename}) │ │ │ │ │ + sys.exit() │ │ │ │ │ + """, │ │ │ │ │ +} │ │ │ │ │ │ │ │ │ │ - def flush(self: 'sd_bus') -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ │ │ │ │ │ - def get_fd(self: 'sd_bus') -> Union[int, Errno]: │ │ │ │ │ - raise NotImplementedError │ │ │ │ │ +def split_code(code: str, imports: Set[str]) -> Iterable[Tuple[str, str]]: │ │ │ │ │ + for line in textwrap.dedent(code).splitlines(): │ │ │ │ │ + text = line.lstrip(" ") │ │ │ │ │ + if text.startswith("import "): │ │ │ │ │ + imports.add(text) │ │ │ │ │ + elif text: │ │ │ │ │ + spaces = len(line) - len(text) │ │ │ │ │ + assert (spaces % 4) == 0 │ │ │ │ │ + yield "\t" * (spaces // 4), text │ │ │ │ │ │ │ │ │ │ - def _message_new_method_call( │ │ │ │ │ - self: 'sd_bus', │ │ │ │ │ - message: Reference[sd_bus_message], │ │ │ │ │ - destination: Optional[str], │ │ │ │ │ - path: str, │ │ │ │ │ - interface: str, │ │ │ │ │ - member: str, │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ │ │ │ │ │ - def _message_new_signal( │ │ │ │ │ - self: 'sd_bus', │ │ │ │ │ - message: Reference[sd_bus_message], │ │ │ │ │ - path: str, │ │ │ │ │ - interface: str, │ │ │ │ │ - member: str, │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ +def yield_body(user_gadgets: Dict[str, str], │ │ │ │ │ + steps: Sequence[Tuple[str, Sequence[object]]], │ │ │ │ │ + imports: Set[str]) -> Iterable[Tuple[str, str]]: │ │ │ │ │ + # Allow the caller to override our gadgets, but keep the original │ │ │ │ │ + # variable for use in the next step. │ │ │ │ │ + gadgets = dict(GADGETS, **user_gadgets) │ │ │ │ │ │ │ │ │ │ - def release_name(self: 'sd_bus', name: str) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + # First emit the gadgets. Emit all gadgets provided by the caller, │ │ │ │ │ + # plus any referred to by the caller's list of steps. │ │ │ │ │ + provided_gadgets = set(user_gadgets) │ │ │ │ │ + step_gadgets = {name for name, _args in steps} │ │ │ │ │ + for name in provided_gadgets | step_gadgets: │ │ │ │ │ + yield from split_code(gadgets[name], imports) │ │ │ │ │ │ │ │ │ │ - def request_name( │ │ │ │ │ - self: 'sd_bus', name: str, flags: Annotated[int, ctypes.c_uint64] │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + # Yield functions mentioned in steps from the caller │ │ │ │ │ + for name, args in steps: │ │ │ │ │ + yield '', name + repr(tuple(args)) │ │ │ │ │ │ │ │ │ │ - def set_address(self: 'sd_bus', address: str) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ │ │ │ │ │ - def set_bus_client(self: 'sd_bus', b: bool) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ +def make_bootloader(steps: Sequence[Tuple[str, Sequence[object]]], │ │ │ │ │ + gadgets: Optional[Dict[str, str]] = None) -> str: │ │ │ │ │ + imports: Set[str] = set() │ │ │ │ │ + lines: List[str] = [] │ │ │ │ │ │ │ │ │ │ - def set_fd(self: 'sd_bus', input_fd: int, output_fd: int) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + for frame_spaces, frame_text in split_code(GADGETS["_frame"], imports): │ │ │ │ │ + if frame_text == "...": │ │ │ │ │ + for spaces, text in yield_body(gadgets or {}, steps, imports): │ │ │ │ │ + lines.append(frame_spaces + spaces + text) │ │ │ │ │ + else: │ │ │ │ │ + lines.append(frame_spaces + frame_text) │ │ │ │ │ │ │ │ │ │ - def set_server(self: 'sd_bus', b: bool, bus_d: sd_id128) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + return "".join(f"{line}\n" for line in [*imports, *lines]) + "\n" │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/bei/spawn.py': br'''"""Helper to create a beipack to spawn a command with files in a tmpdir""" │ │ │ │ │ │ │ │ │ │ - def start(self: 'sd_bus') -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ +import argparse │ │ │ │ │ +import os │ │ │ │ │ +import sys │ │ │ │ │ │ │ │ │ │ - def wait( │ │ │ │ │ - self: 'sd_bus', timeout_usec: Annotated[int, ctypes.c_uint64] │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ +from . import pack, tmpfs │ │ │ │ │ │ │ │ │ │ - def send( │ │ │ │ │ - self: 'sd_bus', message: sd_bus_message, cookie: Optional[Reference[ctypes.c_uint64]] │ │ │ │ │ - ) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ │ │ │ │ │ - @staticmethod │ │ │ │ │ - def _default_system(ret: Reference['sd_bus']) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ +def main() -> None: │ │ │ │ │ + parser = argparse.ArgumentParser() │ │ │ │ │ + parser.add_argument('--file', '-f', action='append') │ │ │ │ │ + parser.add_argument('command', nargs='+', help='The command to execute') │ │ │ │ │ + args = parser.parse_args() │ │ │ │ │ │ │ │ │ │ - @staticmethod │ │ │ │ │ - def _default_user(ret: Reference['sd_bus']) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + contents = { │ │ │ │ │ + '_beitmpfs.py': tmpfs.__spec__.loader.get_data(tmpfs.__spec__.origin) │ │ │ │ │ + } │ │ │ │ │ │ │ │ │ │ - @staticmethod │ │ │ │ │ - def _new(ret: Reference['sd_bus']) -> Union[None, Errno]: │ │ │ │ │ - ... │ │ │ │ │ + if args.file is not None: │ │ │ │ │ + files = args.file │ │ │ │ │ + else: │ │ │ │ │ + file = args.command[-1] │ │ │ │ │ + files = [file] │ │ │ │ │ + args.command[-1] = './' + os.path.basename(file) │ │ │ │ │ │ │ │ │ │ + for filename in files: │ │ │ │ │ + with open(filename, 'rb') as file: │ │ │ │ │ + basename = os.path.basename(filename) │ │ │ │ │ + contents[f'tmpfs/{basename}'] = file.read() │ │ │ │ │ │ │ │ │ │ -sd_bus_message_handler_t = ctypes.CFUNCTYPE( │ │ │ │ │ - ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(sd_bus_error)) │ │ │ │ │ -sd_event_inotify_handler_t = ctypes.CFUNCTYPE( │ │ │ │ │ - ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(inotify_event), ctypes.c_void_p) │ │ │ │ │ + script = pack.pack(contents, '_beitmpfs:main', '*' + repr(args.command)) │ │ │ │ │ + sys.stdout.write(script) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -libsystemd = ctypes.CDLL("libsystemd.so.0") │ │ │ │ │ -for cls in { │ │ │ │ │ - sd_bus, │ │ │ │ │ - sd_bus_message, │ │ │ │ │ - sd_bus_slot, │ │ │ │ │ - sd_event, │ │ │ │ │ - sd_event_source, │ │ │ │ │ -}: │ │ │ │ │ - cls._install_cfuncs(libsystemd) │ │ │ │ │ -'''.encode('utf-8'), │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/inotify.py': br'''# systemd_ctypes │ │ │ │ │ +if __name__ == '__main__': │ │ │ │ │ + main() │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/bei/beiboot.py': br"""# beiboot - Remote bootloader for Python │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ @@ -7207,130 +6743,258 @@ │ │ │ │ │ # 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import ctypes │ │ │ │ │ -from enum import IntFlag, auto │ │ │ │ │ -from typing import Optional │ │ │ │ │ +import argparse │ │ │ │ │ +import asyncio │ │ │ │ │ +import os │ │ │ │ │ +import shlex │ │ │ │ │ +import subprocess │ │ │ │ │ +import sys │ │ │ │ │ +import threading │ │ │ │ │ +from typing import IO, List, Sequence, Tuple │ │ │ │ │ │ │ │ │ │ +from .bootloader import make_bootloader │ │ │ │ │ │ │ │ │ │ -class inotify_event(ctypes.Structure): │ │ │ │ │ - _fields_ = ( │ │ │ │ │ - ('wd', ctypes.c_int32), │ │ │ │ │ - ('mask', ctypes.c_uint32), │ │ │ │ │ - ('cookie', ctypes.c_uint32), │ │ │ │ │ - ('len', ctypes.c_uint32), │ │ │ │ │ - ) │ │ │ │ │ │ │ │ │ │ - @property │ │ │ │ │ - def name(self) -> Optional[bytes]: │ │ │ │ │ - if self.len == 0: │ │ │ │ │ - return None │ │ │ │ │ +def get_python_command(local: bool = False, │ │ │ │ │ + tty: bool = False, │ │ │ │ │ + sh: bool = False) -> Sequence[str]: │ │ │ │ │ + interpreter = sys.executable if local else 'python3' │ │ │ │ │ + command: Sequence[str] │ │ │ │ │ │ │ │ │ │ - class event_with_name(ctypes.Structure): │ │ │ │ │ - _fields_ = (*inotify_event._fields_, ('name', ctypes.c_char * self.len)) │ │ │ │ │ + if tty: │ │ │ │ │ + command = (interpreter, '-iq') │ │ │ │ │ + else: │ │ │ │ │ + command = ( │ │ │ │ │ + interpreter, '-ic', │ │ │ │ │ + # https://github.com/python/cpython/issues/93139 │ │ │ │ │ + '''" - beiboot - "; import sys; sys.ps1 = ''; sys.ps2 = '';''' │ │ │ │ │ + ) │ │ │ │ │ │ │ │ │ │ - name = ctypes.cast(ctypes.addressof(self), ctypes.POINTER(event_with_name)).contents.name │ │ │ │ │ - assert isinstance(name, bytes) │ │ │ │ │ - return name │ │ │ │ │ + if sh: │ │ │ │ │ + command = (' '.join(shlex.quote(arg) for arg in command),) │ │ │ │ │ │ │ │ │ │ + return command │ │ │ │ │ │ │ │ │ │ -class Event(IntFlag): │ │ │ │ │ - ACCESS = auto() │ │ │ │ │ - MODIFY = auto() │ │ │ │ │ - ATTRIB = auto() │ │ │ │ │ - CLOSE_WRITE = auto() │ │ │ │ │ - CLOSE_NOWRITE = auto() │ │ │ │ │ - OPEN = auto() │ │ │ │ │ - MOVED_FROM = auto() │ │ │ │ │ - MOVED_TO = auto() │ │ │ │ │ - CREATE = auto() │ │ │ │ │ - DELETE = auto() │ │ │ │ │ - DELETE_SELF = auto() │ │ │ │ │ - MOVE_SELF = auto() │ │ │ │ │ │ │ │ │ │ - UNMOUNT = 1 << 13 │ │ │ │ │ - Q_OVERFLOW = auto() │ │ │ │ │ - IGNORED = auto() │ │ │ │ │ +def get_ssh_command(*args: str, tty: bool = False) -> Sequence[str]: │ │ │ │ │ + return ('ssh', │ │ │ │ │ + *(['-t'] if tty else ()), │ │ │ │ │ + *args, │ │ │ │ │ + *get_python_command(tty=tty, sh=True)) │ │ │ │ │ │ │ │ │ │ - ONLYDIR = 1 << 24 │ │ │ │ │ - DONT_FOLLOW = auto() │ │ │ │ │ - EXCL_UNLINK = auto() │ │ │ │ │ │ │ │ │ │ - MASK_CREATE = 1 << 28 │ │ │ │ │ - MASK_ADD = auto() │ │ │ │ │ - ISDIR = auto() │ │ │ │ │ - ONESHOT = auto() │ │ │ │ │ +def get_container_command(*args: str, tty: bool = False) -> Sequence[str]: │ │ │ │ │ + return ('podman', 'exec', '--interactive', │ │ │ │ │ + *(['--tty'] if tty else ()), │ │ │ │ │ + *args, │ │ │ │ │ + *get_python_command(tty=tty)) │ │ │ │ │ │ │ │ │ │ - CLOSE = CLOSE_WRITE | CLOSE_NOWRITE │ │ │ │ │ - MOVE = MOVED_FROM | MOVED_TO │ │ │ │ │ - CHANGED = (MODIFY | ATTRIB | CLOSE_WRITE | MOVE | │ │ │ │ │ - CREATE | DELETE | DELETE_SELF | MOVE_SELF) │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/systemd_ctypes/typing.py': br'''import typing │ │ │ │ │ -from typing import TYPE_CHECKING │ │ │ │ │ │ │ │ │ │ -# The goal here is to continue to work on Python 3.6 while pretending to have │ │ │ │ │ -# access to some modern typing features. The shims provided here are only │ │ │ │ │ -# enough for what we need for systemd_ctypes to work at runtime. │ │ │ │ │ +def get_command(*args: str, tty: bool = False, sh: bool = False) -> Sequence[str]: │ │ │ │ │ + return (*args, *get_python_command(local=True, tty=tty, sh=sh)) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -if TYPE_CHECKING: │ │ │ │ │ - # See https://github.com/python/mypy/issues/1153 for why we do this separately │ │ │ │ │ - from typing import Annotated, ForwardRef, TypeGuard, get_args, get_origin │ │ │ │ │ +def splice_in_thread(src: int, dst: IO[bytes]) -> None: │ │ │ │ │ + def _thread() -> None: │ │ │ │ │ + # os.splice() only in Python 3.10 │ │ │ │ │ + with dst: │ │ │ │ │ + block_size = 1 << 20 │ │ │ │ │ + while True: │ │ │ │ │ + data = os.read(src, block_size) │ │ │ │ │ + if not data: │ │ │ │ │ + break │ │ │ │ │ + dst.write(data) │ │ │ │ │ + dst.flush() │ │ │ │ │ + │ │ │ │ │ + threading.Thread(target=_thread, daemon=True).start() │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def send_and_splice(command: Sequence[str], script: bytes) -> None: │ │ │ │ │ + with subprocess.Popen(command, stdin=subprocess.PIPE) as proc: │ │ │ │ │ + assert proc.stdin is not None │ │ │ │ │ + proc.stdin.write(script) │ │ │ │ │ + │ │ │ │ │ + splice_in_thread(0, proc.stdin) │ │ │ │ │ + sys.exit(proc.wait()) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def send_xz_and_splice(command: Sequence[str], script: bytes) -> None: │ │ │ │ │ + import ferny │ │ │ │ │ + │ │ │ │ │ + class Responder(ferny.InteractionResponder): │ │ │ │ │ + async def do_custom_command(self, │ │ │ │ │ + command: str, │ │ │ │ │ + args: Tuple, │ │ │ │ │ + fds: List[int], │ │ │ │ │ + stderr: str) -> None: │ │ │ │ │ + assert proc.stdin is not None │ │ │ │ │ + if command == 'beiboot.provide': │ │ │ │ │ + proc.stdin.write(script) │ │ │ │ │ + proc.stdin.flush() │ │ │ │ │ + │ │ │ │ │ + agent = ferny.InteractionAgent(Responder()) │ │ │ │ │ + with subprocess.Popen(command, stdin=subprocess.PIPE, stderr=agent) as proc: │ │ │ │ │ + assert proc.stdin is not None │ │ │ │ │ + proc.stdin.write(make_bootloader([ │ │ │ │ │ + ('boot_xz', ('script.py.xz', len(script), [], True)), │ │ │ │ │ + ], gadgets=ferny.BEIBOOT_GADGETS).encode()) │ │ │ │ │ + proc.stdin.flush() │ │ │ │ │ + │ │ │ │ │ + asyncio.run(agent.communicate()) │ │ │ │ │ + splice_in_thread(0, proc.stdin) │ │ │ │ │ + sys.exit(proc.wait()) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +def main() -> None: │ │ │ │ │ + parser = argparse.ArgumentParser() │ │ │ │ │ + parser.add_argument('--sh', action='store_true', │ │ │ │ │ + help='Pass Python interpreter command as shell-script') │ │ │ │ │ + parser.add_argument('--xz', help="the xz to run remotely") │ │ │ │ │ + parser.add_argument('--script', │ │ │ │ │ + help="the script to run remotely (must be repl-friendly)") │ │ │ │ │ + parser.add_argument('command', nargs='*') │ │ │ │ │ + │ │ │ │ │ + args = parser.parse_args() │ │ │ │ │ + tty = not args.script and os.isatty(0) │ │ │ │ │ + │ │ │ │ │ + if args.command == []: │ │ │ │ │ + command = get_python_command(tty=tty) │ │ │ │ │ + elif args.command[0] == 'ssh': │ │ │ │ │ + command = get_ssh_command(*args.command[1:], tty=tty) │ │ │ │ │ + elif args.command[0] == 'container': │ │ │ │ │ + command = get_container_command(*args.command[1:], tty=tty) │ │ │ │ │ + else: │ │ │ │ │ + command = get_command(*args.command, tty=tty, sh=args.sh) │ │ │ │ │ + │ │ │ │ │ + if args.script: │ │ │ │ │ + with open(args.script, 'rb') as file: │ │ │ │ │ + script = file.read() │ │ │ │ │ + │ │ │ │ │ + send_and_splice(command, script) │ │ │ │ │ + │ │ │ │ │ + elif args.xz: │ │ │ │ │ + with open(args.xz, 'rb') as file: │ │ │ │ │ + script = file.read() │ │ │ │ │ + │ │ │ │ │ + send_xz_and_splice(command, script) │ │ │ │ │ + │ │ │ │ │ + else: │ │ │ │ │ + # If we're streaming from stdin then this is a lot easier... │ │ │ │ │ + os.execlp(command[0], *command) │ │ │ │ │ + │ │ │ │ │ + # Otherwise, "full strength" │ │ │ │ │ + │ │ │ │ │ +if __name__ == '__main__': │ │ │ │ │ + main() │ │ │ │ │ +""", │ │ │ │ │ + 'cockpit/_vendor/bei/__init__.py': br'''''', │ │ │ │ │ + 'cockpit/_vendor/bei/data/__init__.py': br'''import sys │ │ │ │ │ + │ │ │ │ │ +if sys.version_info >= (3, 9): │ │ │ │ │ + import importlib.abc │ │ │ │ │ + import importlib.resources │ │ │ │ │ │ │ │ │ │ + def read_data_file(filename: str) -> str: │ │ │ │ │ + return (importlib.resources.files(__name__) / filename).read_text() │ │ │ │ │ else: │ │ │ │ │ - # typing.get_args() and .get_origin() appeared in Python 3.8 but Annotated │ │ │ │ │ - # arrived in 3.9. Unfortunately, it's difficult to implement a mocked up │ │ │ │ │ - # version of Annotated which works with the real typing.get_args() and │ │ │ │ │ - # .get_origin() in Python 3.8, so we use our own versions there as well. │ │ │ │ │ - try: │ │ │ │ │ - from typing import Annotated, get_args, get_origin │ │ │ │ │ - except ImportError: │ │ │ │ │ - class AnnotatedMeta(type): │ │ │ │ │ - def __getitem__(cls, params): │ │ │ │ │ - class AnnotatedType: │ │ │ │ │ - __origin__ = Annotated │ │ │ │ │ - __args__ = params │ │ │ │ │ - return AnnotatedType │ │ │ │ │ + def read_data_file(filename: str) -> str: │ │ │ │ │ + loader = __loader__ # type: ignore[name-defined] │ │ │ │ │ + data = loader.get_data(__file__.replace('__init__.py', filename)) │ │ │ │ │ + return data.decode('utf-8') │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/bei/data/beipack_loader.py': br'''# beipack https://github.com/allisonkarlitskaya/beipack │ │ │ │ │ │ │ │ │ │ - class Annotated(metaclass=AnnotatedMeta): │ │ │ │ │ - pass │ │ │ │ │ +import importlib.abc │ │ │ │ │ +import importlib.util │ │ │ │ │ +import io │ │ │ │ │ +import sys │ │ │ │ │ +from types import ModuleType │ │ │ │ │ +from typing import BinaryIO, Dict, Iterator, Optional, Sequence │ │ │ │ │ │ │ │ │ │ - def get_args(annotation: typing.Any) -> typing.Tuple[typing.Any]: │ │ │ │ │ - return getattr(annotation, '__args__', ()) │ │ │ │ │ │ │ │ │ │ - def get_origin(annotation: typing.Any) -> typing.Any: │ │ │ │ │ - return getattr(annotation, '__origin__', None) │ │ │ │ │ +class BeipackLoader(importlib.abc.SourceLoader, importlib.abc.MetaPathFinder): │ │ │ │ │ + if sys.version_info >= (3, 11): │ │ │ │ │ + from importlib.resources.abc import ResourceReader as AbstractResourceReader │ │ │ │ │ + else: │ │ │ │ │ + AbstractResourceReader = object │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - from typing import ForwardRef │ │ │ │ │ - except ImportError: │ │ │ │ │ - from typing import _ForwardRef as ForwardRef │ │ │ │ │ + class ResourceReader(AbstractResourceReader): │ │ │ │ │ + def __init__(self, contents: Dict[str, bytes], filename: str) -> None: │ │ │ │ │ + self._contents = contents │ │ │ │ │ + self._dir = f'{filename}/' │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - from typing import TypeGuard │ │ │ │ │ - except ImportError: │ │ │ │ │ - T = typing.TypeVar('T') │ │ │ │ │ + def is_resource(self, resource: str) -> bool: │ │ │ │ │ + return f'{self._dir}{resource}' in self._contents │ │ │ │ │ │ │ │ │ │ - class TypeGuard(typing.Generic[T]): │ │ │ │ │ + def open_resource(self, resource: str) -> BinaryIO: │ │ │ │ │ + return io.BytesIO(self._contents[f'{self._dir}{resource}']) │ │ │ │ │ + │ │ │ │ │ + def resource_path(self, resource: str) -> str: │ │ │ │ │ + raise FileNotFoundError │ │ │ │ │ + │ │ │ │ │ + def contents(self) -> Iterator[str]: │ │ │ │ │ + dir_length = len(self._dir) │ │ │ │ │ + result = set() │ │ │ │ │ + │ │ │ │ │ + for filename in self._contents: │ │ │ │ │ + if filename.startswith(self._dir): │ │ │ │ │ + try: │ │ │ │ │ + next_slash = filename.index('/', dir_length) │ │ │ │ │ + except ValueError: │ │ │ │ │ + next_slash = None │ │ │ │ │ + result.add(filename[dir_length:next_slash]) │ │ │ │ │ + │ │ │ │ │ + return iter(result) │ │ │ │ │ + │ │ │ │ │ + contents: Dict[str, bytes] │ │ │ │ │ + modules: Dict[str, str] │ │ │ │ │ + │ │ │ │ │ + def __init__(self, contents: Dict[str, bytes]) -> None: │ │ │ │ │ + try: │ │ │ │ │ + contents[__file__] = __self_source__ # type: ignore[name-defined] │ │ │ │ │ + except NameError: │ │ │ │ │ pass │ │ │ │ │ │ │ │ │ │ + self.contents = contents │ │ │ │ │ + self.modules = { │ │ │ │ │ + self.get_fullname(filename): filename │ │ │ │ │ + for filename in contents │ │ │ │ │ + if filename.endswith(".py") │ │ │ │ │ + } │ │ │ │ │ │ │ │ │ │ -__all__ = ( │ │ │ │ │ - 'Annotated', │ │ │ │ │ - 'ForwardRef', │ │ │ │ │ - 'TypeGuard', │ │ │ │ │ - 'get_args', │ │ │ │ │ - 'get_origin', │ │ │ │ │ - 'TYPE_CHECKING', │ │ │ │ │ -) │ │ │ │ │ + def get_fullname(self, filename: str) -> str: │ │ │ │ │ + assert filename.endswith(".py") │ │ │ │ │ + filename = filename[:-3] │ │ │ │ │ + if filename.endswith("/__init__"): │ │ │ │ │ + filename = filename[:-9] │ │ │ │ │ + return filename.replace("/", ".") │ │ │ │ │ + │ │ │ │ │ + def get_resource_reader(self, fullname: str) -> ResourceReader: │ │ │ │ │ + return BeipackLoader.ResourceReader(self.contents, fullname.replace('.', '/')) │ │ │ │ │ + │ │ │ │ │ + def get_data(self, path: str) -> bytes: │ │ │ │ │ + return self.contents[path] │ │ │ │ │ + │ │ │ │ │ + def get_filename(self, fullname: str) -> str: │ │ │ │ │ + return self.modules[fullname] │ │ │ │ │ + │ │ │ │ │ + def find_spec( │ │ │ │ │ + self, │ │ │ │ │ + fullname: str, │ │ │ │ │ + path: Optional[Sequence[str]], │ │ │ │ │ + target: Optional[ModuleType] = None │ │ │ │ │ + ) -> Optional[importlib.machinery.ModuleSpec]: │ │ │ │ │ + if fullname not in self.modules: │ │ │ │ │ + return None │ │ │ │ │ + return importlib.util.spec_from_loader(fullname, self) │ │ │ │ │ ''', │ │ │ │ │ 'cockpit/_vendor/systemd_ctypes/bus.py': br'''# systemd_ctypes │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program is free software: you can redistribute it and/or modify │ │ │ │ │ # it under the terms of the GNU General Public License as published by │ │ │ │ │ @@ -8186,1144 +7850,1076 @@ │ │ │ │ │ try: │ │ │ │ │ method = self._find_member(interface, 'methods', name) │ │ │ │ │ assert isinstance(method, Interface.Method) │ │ │ │ │ return method._invoke(self, message) │ │ │ │ │ except Object.Method.Unhandled: │ │ │ │ │ return False │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/ferny/askpass.py': br'''from .interaction_client import main │ │ │ │ │ - │ │ │ │ │ -if __name__ == '__main__': │ │ │ │ │ - main() │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/ferny/transport.py': br'''# ferny - asyncio SSH client library, using ssh(1) │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/introspection.py': br'''# systemd_ctypes │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ +# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import asyncio │ │ │ │ │ -import contextlib │ │ │ │ │ -import logging │ │ │ │ │ -import typing │ │ │ │ │ -from typing import Any, Callable, Iterable, Sequence, TypeVar │ │ │ │ │ - │ │ │ │ │ -from .interaction_agent import InteractionAgent, InteractionHandler, get_running_loop │ │ │ │ │ -from .ssh_errors import get_exception_for_ssh_stderr │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ -P = TypeVar('P', bound=asyncio.Protocol) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class SubprocessError(Exception): │ │ │ │ │ - returncode: int │ │ │ │ │ - stderr: str │ │ │ │ │ - │ │ │ │ │ - def __init__(self, returncode: int, stderr: str) -> None: │ │ │ │ │ - super().__init__(returncode, stderr) │ │ │ │ │ - self.returncode = returncode │ │ │ │ │ - self.stderr = stderr │ │ │ │ │ +import xml.etree.ElementTree as ET │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class FernyTransport(asyncio.Transport, asyncio.SubprocessProtocol): │ │ │ │ │ - _agent: InteractionAgent │ │ │ │ │ - _exec_task: 'asyncio.Task[tuple[asyncio.SubprocessTransport, FernyTransport]]' │ │ │ │ │ - _is_ssh: bool │ │ │ │ │ - _protocol: asyncio.Protocol │ │ │ │ │ - _protocol_disconnected: bool = False │ │ │ │ │ +def parse_method(method): │ │ │ │ │ + return { │ │ │ │ │ + "in": [tag.attrib['type'] for tag in method.findall("arg") if tag.get('direction', 'in') == 'in'], │ │ │ │ │ + "out": [tag.attrib['type'] for tag in method.findall("arg[@direction='out']")] │ │ │ │ │ + } │ │ │ │ │ │ │ │ │ │ - # These get initialized in connection_made() and once set, never get unset. │ │ │ │ │ - _subprocess_transport: 'asyncio.SubprocessTransport | None' = None │ │ │ │ │ - _stdin_transport: 'asyncio.WriteTransport | None' = None │ │ │ │ │ - _stdout_transport: 'asyncio.ReadTransport | None' = None │ │ │ │ │ │ │ │ │ │ - # We record events that might build towards a connection termination here │ │ │ │ │ - # and consider them from _consider_disconnect() in order to try to get the │ │ │ │ │ - # best possible Exception for the protocol, rather than just taking the │ │ │ │ │ - # first one (which is likely to be somewhat random). │ │ │ │ │ - _exception: 'Exception | None' = None │ │ │ │ │ - _stderr_output: 'str | None' = None │ │ │ │ │ - _returncode: 'int | None' = None │ │ │ │ │ - _transport_disconnected: bool = False │ │ │ │ │ - _closed: bool = False │ │ │ │ │ +def parse_property(prop): │ │ │ │ │ + return { │ │ │ │ │ + "flags": 'w' if prop.attrib.get('access') == 'write' else 'r', │ │ │ │ │ + "type": prop.attrib['type'] │ │ │ │ │ + } │ │ │ │ │ │ │ │ │ │ - @classmethod │ │ │ │ │ - def spawn( │ │ │ │ │ - cls: 'type[typing.Self]', │ │ │ │ │ - protocol_factory: Callable[[], P], │ │ │ │ │ - args: Sequence[str], │ │ │ │ │ - loop: 'asyncio.AbstractEventLoop | None' = None, │ │ │ │ │ - interaction_handlers: Sequence[InteractionHandler] = (), │ │ │ │ │ - is_ssh: bool = True, │ │ │ │ │ - **kwargs: Any │ │ │ │ │ - ) -> 'tuple[typing.Self, P]': │ │ │ │ │ - """Connects a FernyTransport to a protocol, using the given command. │ │ │ │ │ │ │ │ │ │ - This spawns an external command and connects the stdin and stdout of │ │ │ │ │ - the command to the protocol returned by the factory. │ │ │ │ │ +def parse_signal(signal): │ │ │ │ │ + return {"in": [tag.attrib['type'] for tag in signal.findall("arg")]} │ │ │ │ │ │ │ │ │ │ - An instance of ferny.InteractionAgent is created and attached to the │ │ │ │ │ - stderr of the spawned process, using the provided handlers. It is the │ │ │ │ │ - responsibility of the caller to ensure that: │ │ │ │ │ - - a `ferny-askpass` client program is installed somewhere; and │ │ │ │ │ - - any relevant command-line arguments or environment variables are │ │ │ │ │ - passed correctly to the program to be spawned │ │ │ │ │ │ │ │ │ │ - This function returns immediately and never raises exceptions, assuming │ │ │ │ │ - all preconditions are met. │ │ │ │ │ +def parse_interface(interface): │ │ │ │ │ + return { │ │ │ │ │ + "methods": {tag.attrib['name']: parse_method(tag) for tag in interface.findall('method')}, │ │ │ │ │ + "properties": {tag.attrib['name']: parse_property(tag) for tag in interface.findall('property')}, │ │ │ │ │ + "signals": {tag.attrib['name']: parse_signal(tag) for tag in interface.findall('signal')} │ │ │ │ │ + } │ │ │ │ │ │ │ │ │ │ - If spawning the process fails then connection_lost() will be │ │ │ │ │ - called with the relevant OSError, even before connection_made() is │ │ │ │ │ - called. This is somewhat non-standard behaviour, but is the easiest │ │ │ │ │ - way to report these errors without making this function async. │ │ │ │ │ │ │ │ │ │ - Once the process is successfully executed, connection_made() will be │ │ │ │ │ - called and the transport can be used as normal. connection_lost() will │ │ │ │ │ - be called if the process exits or another error occurs. │ │ │ │ │ +def parse_xml(xml): │ │ │ │ │ + et = ET.fromstring(xml) │ │ │ │ │ + return {tag.attrib['name']: parse_interface(tag) for tag in et.findall('interface')} │ │ │ │ │ │ │ │ │ │ - The return value of this function is the transport, but it exists in a │ │ │ │ │ - semi-initialized state. You can call .close() on it, but nothing else. │ │ │ │ │ - Once .connection_made() is called, you can call all the other │ │ │ │ │ - functions. │ │ │ │ │ │ │ │ │ │ - After you call this function, `.connection_lost()` will be called on │ │ │ │ │ - your Protocol, exactly once, no matter what. Until that happens, you │ │ │ │ │ - are responsible for holding a reference to the returned transport. │ │ │ │ │ +# Pretend like this is a little bit functional │ │ │ │ │ +def element(tag, children=(), **kwargs): │ │ │ │ │ + tag = ET.Element(tag, kwargs) │ │ │ │ │ + tag.extend(children) │ │ │ │ │ + return tag │ │ │ │ │ │ │ │ │ │ - :param args: the full argv of the command to spawn │ │ │ │ │ - :param loop: the event loop to use. If none is provided, we use the │ │ │ │ │ - one which is (read: must be) currently running. │ │ │ │ │ - :param interaction_handlers: the handlers passed to the │ │ │ │ │ - InteractionAgent │ │ │ │ │ - :param is_ssh: whether we should attempt to interpret stderr as ssh │ │ │ │ │ - error messages │ │ │ │ │ - :param kwargs: anything else is passed through to `subprocess_exec()` │ │ │ │ │ - :returns: the usual `(Transport, Protocol)` pair │ │ │ │ │ - """ │ │ │ │ │ - logger.debug('spawn(%r, %r, %r)', cls, protocol_factory, args) │ │ │ │ │ │ │ │ │ │ - protocol = protocol_factory() │ │ │ │ │ - self = cls(protocol) │ │ │ │ │ - self._is_ssh = is_ssh │ │ │ │ │ +def method_to_xml(name, method_info): │ │ │ │ │ + return element('method', name=name, │ │ │ │ │ + children=[ │ │ │ │ │ + element('arg', type=arg_type, direction=direction) │ │ │ │ │ + for direction in ['in', 'out'] │ │ │ │ │ + for arg_type in method_info[direction] │ │ │ │ │ + ]) │ │ │ │ │ │ │ │ │ │ - if loop is None: │ │ │ │ │ - loop = get_running_loop() │ │ │ │ │ │ │ │ │ │ - self._agent = InteractionAgent(interaction_handlers, loop, self._interaction_completed) │ │ │ │ │ - kwargs.setdefault('stderr', self._agent.fileno()) │ │ │ │ │ +def property_to_xml(name, property_info): │ │ │ │ │ + return element('property', name=name, │ │ │ │ │ + access='write' if property_info['flags'] == 'w' else 'read', │ │ │ │ │ + type=property_info['type']) │ │ │ │ │ │ │ │ │ │ - # As of Python 3.12 this isn't really asynchronous (since it uses the │ │ │ │ │ - # subprocess module, which blocks while waiting for the exec() to │ │ │ │ │ - # complete in the child), but we have to deal with the complication of │ │ │ │ │ - # the async interface anyway. Since we, ourselves, want to export a │ │ │ │ │ - # non-async interface, that means that we need a task here and a │ │ │ │ │ - # bottom-half handler below. │ │ │ │ │ - self._exec_task = loop.create_task(loop.subprocess_exec(lambda: self, *args, **kwargs)) │ │ │ │ │ │ │ │ │ │ - def exec_completed(task: asyncio.Task) -> None: │ │ │ │ │ - logger.debug('exec_completed(%r, %r)', self, task) │ │ │ │ │ - assert task is self._exec_task │ │ │ │ │ - try: │ │ │ │ │ - transport, me = task.result() │ │ │ │ │ - assert me is self │ │ │ │ │ - logger.debug(' success.') │ │ │ │ │ - except asyncio.CancelledError: │ │ │ │ │ - return # in that case, do nothing │ │ │ │ │ - except OSError as exc: │ │ │ │ │ - logger.debug(' OSError %r', exc) │ │ │ │ │ - self.close(exc) │ │ │ │ │ - return │ │ │ │ │ +def signal_to_xml(name, signal_info): │ │ │ │ │ + return element('signal', name=name, │ │ │ │ │ + children=[ │ │ │ │ │ + element('arg', type=arg_type) for arg_type in signal_info['in'] │ │ │ │ │ + ]) │ │ │ │ │ │ │ │ │ │ - # Our own .connection_made() handler should have gotten called by │ │ │ │ │ - # now. Make sure everything got filled in properly. │ │ │ │ │ - assert self._subprocess_transport is transport │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - assert self._stdout_transport is not None │ │ │ │ │ │ │ │ │ │ - # Ask the InteractionAgent to start processing stderr. │ │ │ │ │ - self._agent.start() │ │ │ │ │ +def interface_to_xml(name, interface_info): │ │ │ │ │ + return element('interface', name=name, │ │ │ │ │ + children=[ │ │ │ │ │ + *(method_to_xml(name, info) for name, info in interface_info['methods'].items()), │ │ │ │ │ + *(property_to_xml(name, info) for name, info in interface_info['properties'].items()), │ │ │ │ │ + *(signal_to_xml(name, info) for name, info in interface_info['signals'].items()), │ │ │ │ │ + ]) │ │ │ │ │ │ │ │ │ │ - self._exec_task.add_done_callback(exec_completed) │ │ │ │ │ │ │ │ │ │ - return self, protocol │ │ │ │ │ +def to_xml(interfaces): │ │ │ │ │ + node = element('node', children=(interface_to_xml(name, members) for name, members in interfaces.items())) │ │ │ │ │ + return ET.tostring(node, encoding='unicode') │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/pathwatch.py': br'''# systemd_ctypes │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ - def __init__(self, protocol: asyncio.Protocol) -> None: │ │ │ │ │ - self._protocol = protocol │ │ │ │ │ +import errno │ │ │ │ │ +import logging │ │ │ │ │ +import os │ │ │ │ │ +import stat │ │ │ │ │ +from typing import Any, List, Optional │ │ │ │ │ │ │ │ │ │ - def _consider_disconnect(self) -> None: │ │ │ │ │ - logger.debug('_consider_disconnect(%r)', self) │ │ │ │ │ - # We cannot disconnect as long as any of these three things are happening │ │ │ │ │ - if not self._exec_task.done(): │ │ │ │ │ - logger.debug(' exec_task still running %r', self._exec_task) │ │ │ │ │ - return │ │ │ │ │ +from .event import Event │ │ │ │ │ +from .inotify import Event as IN │ │ │ │ │ │ │ │ │ │ - if self._subprocess_transport is not None and not self._transport_disconnected: │ │ │ │ │ - logger.debug(' transport still connected %r', self._subprocess_transport) │ │ │ │ │ - return │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ - if self._stderr_output is None: │ │ │ │ │ - logger.debug(' agent still running') │ │ │ │ │ - return │ │ │ │ │ │ │ │ │ │ - # All conditions for disconnection are satisfied. │ │ │ │ │ - if self._protocol_disconnected: │ │ │ │ │ - logger.debug(' already disconnected') │ │ │ │ │ - return │ │ │ │ │ - self._protocol_disconnected = True │ │ │ │ │ +# inotify hard facts: │ │ │ │ │ +# │ │ │ │ │ +# DELETE_SELF doesn't get called until all references to an inode are gone │ │ │ │ │ +# - including open fds │ │ │ │ │ +# - including on directories │ │ │ │ │ +# │ │ │ │ │ +# ATTRIB gets called when unlinking files (because the link count changes) but │ │ │ │ │ +# not on directories. When unlinking an open directory, no events at all │ │ │ │ │ +# happen on the directory. ATTRIB also collects child events, which means we │ │ │ │ │ +# get a lot of unwanted noise. │ │ │ │ │ +# │ │ │ │ │ +# There's nothing like UNLINK_SELF, unfortunately. │ │ │ │ │ +# │ │ │ │ │ +# Even if it was possible to take this approach, it might not work: after │ │ │ │ │ +# you've opened the fd, it might get deleted before you can establish the watch │ │ │ │ │ +# on it. │ │ │ │ │ +# │ │ │ │ │ +# Additionally, systemd makes it impossible to register those events on │ │ │ │ │ +# symlinks (because it removes IN_DONT_FOLLOW in order to watch via │ │ │ │ │ +# /proc/self/fd). │ │ │ │ │ +# │ │ │ │ │ +# For all of these reasons, unfortunately, the best way seems to be to watch │ │ │ │ │ +# for CREATE|DELETE|MOVE events on each intermediate directory. │ │ │ │ │ +# │ │ │ │ │ +# Unfortunately there is no way to filter to only the name we're interested in, │ │ │ │ │ +# so we're gonna get a lot of unnecessary wakeups. │ │ │ │ │ +# │ │ │ │ │ +# Also: due to the above-mentioned race about watching after opening the fd, │ │ │ │ │ +# let's just always watch for both create and delete events *before* trying to │ │ │ │ │ +# open the fd. We could try to reduce the mask after the fact, but meh... │ │ │ │ │ +# │ │ │ │ │ +# We use a WatchInvalidator utility class to fill the role of "Tell me when an │ │ │ │ │ +# event happened on this (directory) fd which impacted the name file". We │ │ │ │ │ +# build a series of these when setting up a watch in order to find out if any │ │ │ │ │ +# part of the path leading to the monitored file changed. │ │ │ │ │ │ │ │ │ │ - # Now we just need to determine what we report to the protocol... │ │ │ │ │ - if self._exception is not None: │ │ │ │ │ - # If we got an exception reported, that's our reason for closing. │ │ │ │ │ - logger.debug(' disconnect with exception %r', self._exception) │ │ │ │ │ - self._protocol.connection_lost(self._exception) │ │ │ │ │ - elif self._returncode == 0 or self._closed: │ │ │ │ │ - # If we called close() or have a zero return status, that's a clean │ │ │ │ │ - # exit, regardless of noise that might have landed in stderr. │ │ │ │ │ - logger.debug(' clean disconnect') │ │ │ │ │ - self._protocol.connection_lost(None) │ │ │ │ │ - elif self._is_ssh and self._returncode == 255: │ │ │ │ │ - # This is an error code due to an SSH failure. Try to interpret it. │ │ │ │ │ - logger.debug(' disconnect with ssh error %r', self._stderr_output) │ │ │ │ │ - self._protocol.connection_lost(get_exception_for_ssh_stderr(self._stderr_output)) │ │ │ │ │ - else: │ │ │ │ │ - # Otherwise, report the stderr text and return code. │ │ │ │ │ - logger.debug(' disconnect with exit code %r, stderr %r', self._returncode, self._stderr_output) │ │ │ │ │ - # We surely have _returncode set here, since otherwise: │ │ │ │ │ - # - exec_task failed with an exception (which we handle above); or │ │ │ │ │ - # - we're still connected... │ │ │ │ │ - assert self._returncode is not None │ │ │ │ │ - self._protocol.connection_lost(SubprocessError(self._returncode, self._stderr_output)) │ │ │ │ │ │ │ │ │ │ - def _interaction_completed(self, future: 'asyncio.Future[str]') -> None: │ │ │ │ │ - logger.debug('_interaction_completed(%r, %r)', self, future) │ │ │ │ │ - try: │ │ │ │ │ - self._stderr_output = future.result() │ │ │ │ │ - logger.debug(' stderr: %r', self._stderr_output) │ │ │ │ │ - except Exception as exc: │ │ │ │ │ - logger.debug(' exception: %r', exc) │ │ │ │ │ - self._stderr_output = '' # we need to set this in order to complete │ │ │ │ │ - self.close(exc) │ │ │ │ │ +class Handle(int): │ │ │ │ │ + """An integer subclass that makes it easier to work with file descriptors""" │ │ │ │ │ │ │ │ │ │ - self._consider_disconnect() │ │ │ │ │ + def __new__(cls, fd: int = -1) -> 'Handle': │ │ │ │ │ + return super(Handle, cls).__new__(cls, fd) │ │ │ │ │ │ │ │ │ │ - # BaseProtocol implementation │ │ │ │ │ - def connection_made(self, transport: asyncio.BaseTransport) -> None: │ │ │ │ │ - logger.debug('connection_made(%r, %r)', self, transport) │ │ │ │ │ - assert isinstance(transport, asyncio.SubprocessTransport) │ │ │ │ │ - self._subprocess_transport = transport │ │ │ │ │ + # separate __init__() to set _needs_close mostly to keep pylint quiet │ │ │ │ │ + def __init__(self, fd: int = -1): │ │ │ │ │ + super().__init__() │ │ │ │ │ + self._needs_close = fd != -1 │ │ │ │ │ │ │ │ │ │ - stdin_transport = transport.get_pipe_transport(0) │ │ │ │ │ - assert isinstance(stdin_transport, asyncio.WriteTransport) │ │ │ │ │ - self._stdin_transport = stdin_transport │ │ │ │ │ + def __bool__(self) -> bool: │ │ │ │ │ + return self != -1 │ │ │ │ │ │ │ │ │ │ - stdout_transport = transport.get_pipe_transport(1) │ │ │ │ │ - assert isinstance(stdout_transport, asyncio.ReadTransport) │ │ │ │ │ - self._stdout_transport = stdout_transport │ │ │ │ │ + def close(self) -> None: │ │ │ │ │ + if self._needs_close: │ │ │ │ │ + self._needs_close = False │ │ │ │ │ + os.close(self) │ │ │ │ │ │ │ │ │ │ - stderr_transport = transport.get_pipe_transport(2) │ │ │ │ │ - assert stderr_transport is None │ │ │ │ │ + def __eq__(self, value: object) -> bool: │ │ │ │ │ + if int.__eq__(self, value): # also handles both == -1 │ │ │ │ │ + return True │ │ │ │ │ │ │ │ │ │ - logger.debug('calling connection_made(%r, %r)', self, self._protocol) │ │ │ │ │ - self._protocol.connection_made(self) │ │ │ │ │ + if not isinstance(value, int): # other object is not an int │ │ │ │ │ + return False │ │ │ │ │ │ │ │ │ │ - def connection_lost(self, exc: 'Exception | None') -> None: │ │ │ │ │ - logger.debug('connection_lost(%r, %r)', self, exc) │ │ │ │ │ - if self._exception is None: │ │ │ │ │ - self._exception = exc │ │ │ │ │ - self._transport_disconnected = True │ │ │ │ │ - self._consider_disconnect() │ │ │ │ │ + if not self or not value: # when only one == -1 │ │ │ │ │ + return False │ │ │ │ │ │ │ │ │ │ - # SubprocessProtocol implementation │ │ │ │ │ - def pipe_data_received(self, fd: int, data: bytes) -> None: │ │ │ │ │ - logger.debug('pipe_data_received(%r, %r, %r)', self, fd, len(data)) │ │ │ │ │ - assert fd == 1 # stderr is handled separately │ │ │ │ │ - self._protocol.data_received(data) │ │ │ │ │ + return os.path.sameopenfile(self, value) │ │ │ │ │ │ │ │ │ │ - def pipe_connection_lost(self, fd: int, exc: 'Exception | None') -> None: │ │ │ │ │ - logger.debug('pipe_connection_lost(%r, %r, %r)', self, fd, exc) │ │ │ │ │ - assert fd in (0, 1) # stderr is handled separately │ │ │ │ │ + def __del__(self) -> None: │ │ │ │ │ + if self._needs_close: │ │ │ │ │ + self.close() │ │ │ │ │ │ │ │ │ │ - # We treat this as a clean close │ │ │ │ │ - if isinstance(exc, BrokenPipeError): │ │ │ │ │ - exc = None │ │ │ │ │ + def __enter__(self) -> 'Handle': │ │ │ │ │ + return self │ │ │ │ │ │ │ │ │ │ - # Record serious errors to propagate them to the protocol │ │ │ │ │ - # If this is a clean exit on stdout, report an EOF │ │ │ │ │ - if exc is not None: │ │ │ │ │ - self.close(exc) │ │ │ │ │ - elif fd == 1 and not self._closed: │ │ │ │ │ - if not self._protocol.eof_received(): │ │ │ │ │ - self.close() │ │ │ │ │ + def __exit__(self, _type: type, _value: object, _traceback: object) -> None: │ │ │ │ │ + self.close() │ │ │ │ │ │ │ │ │ │ - def process_exited(self) -> None: │ │ │ │ │ - logger.debug('process_exited(%r)', self) │ │ │ │ │ - assert self._subprocess_transport is not None │ │ │ │ │ - self._returncode = self._subprocess_transport.get_returncode() │ │ │ │ │ - logger.debug(' ._returncode = %r', self._returncode) │ │ │ │ │ - self._agent.force_completion() │ │ │ │ │ + @classmethod │ │ │ │ │ + def open(cls, *args: Any, **kwargs: Any) -> 'Handle': │ │ │ │ │ + return cls(os.open(*args, **kwargs)) │ │ │ │ │ │ │ │ │ │ - def pause_writing(self) -> None: │ │ │ │ │ - logger.debug('pause_writing(%r)', self) │ │ │ │ │ - self._protocol.pause_writing() │ │ │ │ │ + def steal(self) -> 'Handle': │ │ │ │ │ + self._needs_close = False │ │ │ │ │ + return self.__class__(int(self)) │ │ │ │ │ │ │ │ │ │ - def resume_writing(self) -> None: │ │ │ │ │ - logger.debug('resume_writing(%r)', self) │ │ │ │ │ - self._protocol.resume_writing() │ │ │ │ │ │ │ │ │ │ - # Transport implementation. Most of this is straight delegation. │ │ │ │ │ - def close(self, exc: 'Exception | None' = None) -> None: │ │ │ │ │ - logger.debug('close(%r, %r)', self, exc) │ │ │ │ │ - self._closed = True │ │ │ │ │ - if self._exception is None: │ │ │ │ │ - logger.debug(' setting exception %r', exc) │ │ │ │ │ - self._exception = exc │ │ │ │ │ - if not self._exec_task.done(): │ │ │ │ │ - logger.debug(' cancelling _exec_task') │ │ │ │ │ - self._exec_task.cancel() │ │ │ │ │ - if self._subprocess_transport is not None: │ │ │ │ │ - logger.debug(' closing _subprocess_transport') │ │ │ │ │ - # https://github.com/python/cpython/issues/112800 │ │ │ │ │ - with contextlib.suppress(PermissionError): │ │ │ │ │ - self._subprocess_transport.close() │ │ │ │ │ - self._agent.force_completion() │ │ │ │ │ +class WatchInvalidator: │ │ │ │ │ + _name: bytes │ │ │ │ │ + _source: Optional[Event.Source] │ │ │ │ │ + _watch: Optional['PathWatch'] │ │ │ │ │ │ │ │ │ │ - def is_closing(self) -> bool: │ │ │ │ │ - assert self._subprocess_transport is not None │ │ │ │ │ - return self._subprocess_transport.is_closing() │ │ │ │ │ + def event(self, mask: IN, _cookie: int, name: Optional[bytes]) -> None: │ │ │ │ │ + logger.debug('invalidator event %s %s', mask, name) │ │ │ │ │ + if self._watch is not None: │ │ │ │ │ + # If this node itself disappeared, that's definitely an │ │ │ │ │ + # invalidation. Otherwise, the name needs to match. │ │ │ │ │ + if IN.IGNORED in mask or self._name == name: │ │ │ │ │ + logger.debug('Invalidating!') │ │ │ │ │ + self._watch.invalidate() │ │ │ │ │ │ │ │ │ │ - def get_extra_info(self, name: str, default: object = None) -> object: │ │ │ │ │ - assert self._subprocess_transport is not None │ │ │ │ │ - return self._subprocess_transport.get_extra_info(name, default) │ │ │ │ │ + def __init__(self, watch: 'PathWatch', event: Event, dirfd: int, name: str): │ │ │ │ │ + self._watch = watch │ │ │ │ │ + self._name = name.encode('utf-8') │ │ │ │ │ │ │ │ │ │ - def set_protocol(self, protocol: asyncio.BaseProtocol) -> None: │ │ │ │ │ - assert isinstance(protocol, asyncio.Protocol) │ │ │ │ │ - self._protocol = protocol │ │ │ │ │ + # establishing invalidation watches is best-effort and can fail for a │ │ │ │ │ + # number of reasons, including search (+x) but not read (+r) permission │ │ │ │ │ + # on a particular path component, or exceeding limits on watches │ │ │ │ │ + try: │ │ │ │ │ + mask = IN.CREATE | IN.DELETE | IN.MOVE | IN.DELETE_SELF | IN.IGNORED │ │ │ │ │ + self._source = event.add_inotify_fd(dirfd, mask, self.event) │ │ │ │ │ + except OSError: │ │ │ │ │ + self._source = None │ │ │ │ │ │ │ │ │ │ - def get_protocol(self) -> asyncio.Protocol: │ │ │ │ │ - return self._protocol │ │ │ │ │ + def close(self) -> None: │ │ │ │ │ + # This is a little bit tricky: systemd doesn't have a specific close │ │ │ │ │ + # API outside of unref, so let's make it as explicit as possible. │ │ │ │ │ + self._watch = None │ │ │ │ │ + self._source = None │ │ │ │ │ │ │ │ │ │ - def is_reading(self) -> bool: │ │ │ │ │ - assert self._stdout_transport is not None │ │ │ │ │ - try: │ │ │ │ │ - return self._stdout_transport.is_reading() │ │ │ │ │ - except NotImplementedError: │ │ │ │ │ - # This is (incorrectly) unimplemented before Python 3.11 │ │ │ │ │ - return not self._stdout_transport._paused # type:ignore[attr-defined] │ │ │ │ │ - except AttributeError: │ │ │ │ │ - # ...and in Python 3.6 it's even worse │ │ │ │ │ - try: │ │ │ │ │ - selector = self._stdout_transport._loop._selector # type:ignore[attr-defined] │ │ │ │ │ - selector.get_key(self._stdout_transport._fileno) # type:ignore[attr-defined] │ │ │ │ │ - return True │ │ │ │ │ - except KeyError: │ │ │ │ │ - return False │ │ │ │ │ │ │ │ │ │ - def pause_reading(self) -> None: │ │ │ │ │ - assert self._stdout_transport is not None │ │ │ │ │ - self._stdout_transport.pause_reading() │ │ │ │ │ +class PathStack(List[str]): │ │ │ │ │ + def add_path(self, pathname: str) -> None: │ │ │ │ │ + # TO DO: consider doing something reasonable with trailing slashes │ │ │ │ │ + # this is a stack, popped from the end: push components in reverse │ │ │ │ │ + self.extend(item for item in reversed(pathname.split('/')) if item) │ │ │ │ │ + if pathname.startswith('/'): │ │ │ │ │ + self.append('/') │ │ │ │ │ │ │ │ │ │ - def resume_reading(self) -> None: │ │ │ │ │ - assert self._stdout_transport is not None │ │ │ │ │ - self._stdout_transport.resume_reading() │ │ │ │ │ + def __init__(self, path: str): │ │ │ │ │ + super().__init__() │ │ │ │ │ + self.add_path(path) │ │ │ │ │ │ │ │ │ │ - def abort(self) -> None: │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - assert self._subprocess_transport is not None │ │ │ │ │ - self._stdin_transport.abort() │ │ │ │ │ - self._subprocess_transport.kill() │ │ │ │ │ │ │ │ │ │ - def can_write_eof(self) -> bool: │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - return self._stdin_transport.can_write_eof() # will always be True │ │ │ │ │ +class Listener: │ │ │ │ │ + def do_inotify_event(self, mask: IN, cookie: int, name: Optional[bytes]) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - def get_write_buffer_size(self) -> int: │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - return self._stdin_transport.get_write_buffer_size() │ │ │ │ │ + def do_identity_changed(self, fd: Optional[Handle], errno: Optional[int]) -> None: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - def get_write_buffer_limits(self) -> 'tuple[int, int]': │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - return self._stdin_transport.get_write_buffer_limits() │ │ │ │ │ │ │ │ │ │ - def set_write_buffer_limits(self, high: 'int | None' = None, low: 'int | None' = None) -> None: │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - return self._stdin_transport.set_write_buffer_limits(high, low) │ │ │ │ │ +class PathWatch: │ │ │ │ │ + _event: Event │ │ │ │ │ + _listener: Listener │ │ │ │ │ + _path: str │ │ │ │ │ + _invalidators: List[WatchInvalidator] │ │ │ │ │ + _errno: Optional[int] │ │ │ │ │ + _source: Optional[Event.Source] │ │ │ │ │ + _tag: Optional[None] │ │ │ │ │ + _fd: Handle │ │ │ │ │ │ │ │ │ │ - def write(self, data: bytes) -> None: │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - return self._stdin_transport.write(data) │ │ │ │ │ + def __init__(self, path: str, listener: Listener, event: Optional[Event] = None): │ │ │ │ │ + self._event = event or Event.default() │ │ │ │ │ + self._path = path │ │ │ │ │ + self._listener = listener │ │ │ │ │ │ │ │ │ │ - def writelines(self, list_of_data: Iterable[bytes]) -> None: │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - return self._stdin_transport.writelines(list_of_data) │ │ │ │ │ + self._invalidators = [] │ │ │ │ │ + self._errno = None │ │ │ │ │ + self._source = None │ │ │ │ │ + self._tag = None │ │ │ │ │ + self._fd = Handle() │ │ │ │ │ │ │ │ │ │ - def write_eof(self) -> None: │ │ │ │ │ - assert self._stdin_transport is not None │ │ │ │ │ - return self._stdin_transport.write_eof() │ │ │ │ │ + self.invalidate() │ │ │ │ │ │ │ │ │ │ - # We don't really implement SubprocessTransport, but provide these as │ │ │ │ │ - # "extras" to our user. │ │ │ │ │ - def get_pid(self) -> int: │ │ │ │ │ - assert self._subprocess_transport is not None │ │ │ │ │ - return self._subprocess_transport.get_pid() │ │ │ │ │ + def got_event(self, mask: IN, cookie: int, name: Optional[bytes]) -> None: │ │ │ │ │ + logger.debug('target event %s: %s %s %s', self._path, mask, cookie, name) │ │ │ │ │ + self._listener.do_inotify_event(mask, cookie, name) │ │ │ │ │ │ │ │ │ │ - def get_returncode(self) -> 'int | None': │ │ │ │ │ - return self._returncode │ │ │ │ │ + def invalidate(self) -> None: │ │ │ │ │ + for invalidator in self._invalidators: │ │ │ │ │ + invalidator.close() │ │ │ │ │ + self._invalidators = [] │ │ │ │ │ │ │ │ │ │ - def kill(self) -> None: │ │ │ │ │ - assert self._subprocess_transport is not None │ │ │ │ │ - self._subprocess_transport.kill() │ │ │ │ │ + try: │ │ │ │ │ + fd = self.walk() │ │ │ │ │ + except OSError as error: │ │ │ │ │ + logger.debug('walk ended in error %d', error.errno) │ │ │ │ │ │ │ │ │ │ - def send_signal(self, number: int) -> None: │ │ │ │ │ - assert self._subprocess_transport is not None │ │ │ │ │ - self._subprocess_transport.send_signal(number) │ │ │ │ │ + if self._source or self._fd or self._errno != error.errno: │ │ │ │ │ + logger.debug('Ending existing watches.') │ │ │ │ │ + self._source = None │ │ │ │ │ + self._fd.close() │ │ │ │ │ + self._fd = Handle() │ │ │ │ │ + self._errno = error.errno │ │ │ │ │ │ │ │ │ │ - def terminate(self) -> None: │ │ │ │ │ - assert self._subprocess_transport is not None │ │ │ │ │ - self._subprocess_transport.terminate() │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/ferny/interaction_client.py': br'''#!/usr/bin/python3 │ │ │ │ │ + logger.debug('Notifying of new error state %d', self._errno) │ │ │ │ │ + self._listener.do_identity_changed(None, self._errno) │ │ │ │ │ │ │ │ │ │ -import array │ │ │ │ │ -import io │ │ │ │ │ -import os │ │ │ │ │ -import socket │ │ │ │ │ -import sys │ │ │ │ │ -from typing import Sequence │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ + with fd: │ │ │ │ │ + logger.debug('walk successful. Got fd %d', fd) │ │ │ │ │ + if fd == self._fd: │ │ │ │ │ + logger.debug('fd seems to refer to same file. Doing nothing.') │ │ │ │ │ + return │ │ │ │ │ │ │ │ │ │ -def command(stderr_fd: int, command: str, *args: object, fds: Sequence[int] = ()) -> None: │ │ │ │ │ - cmd_read, cmd_write = [io.open(*end) for end in zip(os.pipe(), 'rw')] │ │ │ │ │ + logger.debug('This file is new for us. Removing old watch.') │ │ │ │ │ + self._source = None │ │ │ │ │ + self._fd.close() │ │ │ │ │ + self._fd = fd.steal() │ │ │ │ │ │ │ │ │ │ - with cmd_write: │ │ │ │ │ - with cmd_read: │ │ │ │ │ - with socket.fromfd(stderr_fd, socket.AF_UNIX, socket.SOCK_STREAM) as sock: │ │ │ │ │ - fd_array = array.array('i', (cmd_read.fileno(), *fds)) │ │ │ │ │ - sock.sendmsg([b'\0'], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fd_array)]) │ │ │ │ │ + try: │ │ │ │ │ + logger.debug('Establishing a new watch.') │ │ │ │ │ + self._source = self._event.add_inotify_fd(self._fd, IN.CHANGED, self.got_event) │ │ │ │ │ + logger.debug('Watching successfully. Notifying of new identity.') │ │ │ │ │ + self._listener.do_identity_changed(self._fd, None) │ │ │ │ │ + except OSError as error: │ │ │ │ │ + logger.debug('Watching failed (%d). Notifying of new identity.', error.errno) │ │ │ │ │ + self._listener.do_identity_changed(self._fd, error.errno) │ │ │ │ │ │ │ │ │ │ - cmd_write.write(repr((command, args))) │ │ │ │ │ + def walk(self) -> Handle: │ │ │ │ │ + remaining_symlink_lookups = 40 │ │ │ │ │ + remaining_components = PathStack(self._path) │ │ │ │ │ + dirfd = Handle() │ │ │ │ │ │ │ │ │ │ + try: │ │ │ │ │ + logger.debug('Starting path walk') │ │ │ │ │ │ │ │ │ │ -def askpass(stderr_fd: int, stdout_fd: int, args: 'list[str]', env: 'dict[str, str]') -> int: │ │ │ │ │ - ours, theirs = socket.socketpair() │ │ │ │ │ + while remaining_components: │ │ │ │ │ + logger.debug('r=%s dfd=%s', remaining_components, dirfd) │ │ │ │ │ │ │ │ │ │ - with theirs: │ │ │ │ │ - command(stderr_fd, 'ferny.askpass', args, env, fds=(theirs.fileno(), stdout_fd)) │ │ │ │ │ + name = remaining_components.pop() │ │ │ │ │ │ │ │ │ │ - with ours: │ │ │ │ │ - return int(ours.recv(16) or b'1') │ │ │ │ │ + if dirfd and name != '/': │ │ │ │ │ + self._invalidators.append(WatchInvalidator(self, self._event, dirfd, name)) │ │ │ │ │ │ │ │ │ │ + with Handle.open(name, os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=dirfd) as fd: │ │ │ │ │ + mode = os.fstat(fd).st_mode │ │ │ │ │ │ │ │ │ │ -def main() -> None: │ │ │ │ │ - if len(sys.argv) == 1: │ │ │ │ │ - command(2, 'ferny.end', []) │ │ │ │ │ - else: │ │ │ │ │ - sys.exit(askpass(2, 1, sys.argv, dict(os.environ))) │ │ │ │ │ + if stat.S_ISLNK(mode): │ │ │ │ │ + if remaining_symlink_lookups == 0: │ │ │ │ │ + raise OSError(errno.ELOOP, os.strerror(errno.ELOOP)) │ │ │ │ │ + remaining_symlink_lookups -= 1 │ │ │ │ │ + linkpath = os.readlink('', dir_fd=fd) │ │ │ │ │ + logger.debug('%s is a symlink. adding %s to components', name, linkpath) │ │ │ │ │ + remaining_components.add_path(linkpath) │ │ │ │ │ │ │ │ │ │ + else: │ │ │ │ │ + dirfd.close() │ │ │ │ │ + dirfd = fd.steal() │ │ │ │ │ │ │ │ │ │ -if __name__ == '__main__': │ │ │ │ │ - main() │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/_vendor/ferny/__init__.py': br'''from .interaction_agent import ( │ │ │ │ │ - BEIBOOT_GADGETS, │ │ │ │ │ - COMMAND_TEMPLATE, │ │ │ │ │ - AskpassHandler, │ │ │ │ │ - InteractionAgent, │ │ │ │ │ - InteractionError, │ │ │ │ │ - InteractionHandler, │ │ │ │ │ - temporary_askpass, │ │ │ │ │ - write_askpass_to_tmpdir, │ │ │ │ │ -) │ │ │ │ │ -from .session import Session │ │ │ │ │ -from .ssh_askpass import ( │ │ │ │ │ - AskpassPrompt, │ │ │ │ │ - SshAskpassResponder, │ │ │ │ │ - SshFIDOPINPrompt, │ │ │ │ │ - SshFIDOUserPresencePrompt, │ │ │ │ │ - SshHostKeyPrompt, │ │ │ │ │ - SshPassphrasePrompt, │ │ │ │ │ - SshPasswordPrompt, │ │ │ │ │ - SshPKCS11PINPrompt, │ │ │ │ │ -) │ │ │ │ │ -from .ssh_errors import ( │ │ │ │ │ - SshAuthenticationError, │ │ │ │ │ - SshChangedHostKeyError, │ │ │ │ │ - SshError, │ │ │ │ │ - SshHostKeyError, │ │ │ │ │ - SshUnknownHostKeyError, │ │ │ │ │ -) │ │ │ │ │ -from .transport import FernyTransport, SubprocessError │ │ │ │ │ + return dirfd.steal() │ │ │ │ │ │ │ │ │ │ -__all__ = [ │ │ │ │ │ - 'AskpassHandler', │ │ │ │ │ - 'AskpassPrompt', │ │ │ │ │ - 'AuthenticationError', │ │ │ │ │ - 'BEIBOOT_GADGETS', │ │ │ │ │ - 'COMMAND_TEMPLATE', │ │ │ │ │ - 'ChangedHostKeyError', │ │ │ │ │ - 'FernyTransport', │ │ │ │ │ - 'HostKeyError', │ │ │ │ │ - 'InteractionAgent', │ │ │ │ │ - 'InteractionError', │ │ │ │ │ - 'InteractionHandler', │ │ │ │ │ - 'Session', │ │ │ │ │ - 'SshAskpassResponder', │ │ │ │ │ - 'SshAuthenticationError', │ │ │ │ │ - 'SshChangedHostKeyError', │ │ │ │ │ - 'SshError', │ │ │ │ │ - 'SshFIDOPINPrompt', │ │ │ │ │ - 'SshFIDOUserPresencePrompt', │ │ │ │ │ - 'SshHostKeyError', │ │ │ │ │ - 'SshHostKeyPrompt', │ │ │ │ │ - 'SshPKCS11PINPrompt', │ │ │ │ │ - 'SshPassphrasePrompt', │ │ │ │ │ - 'SshPasswordPrompt', │ │ │ │ │ - 'SshUnknownHostKeyError', │ │ │ │ │ - 'SubprocessError', │ │ │ │ │ - 'temporary_askpass', │ │ │ │ │ - 'write_askpass_to_tmpdir', │ │ │ │ │ -] │ │ │ │ │ + finally: │ │ │ │ │ + dirfd.close() │ │ │ │ │ │ │ │ │ │ -__version__ = '0' │ │ │ │ │ + def close(self) -> None: │ │ │ │ │ + for invalidator in self._invalidators: │ │ │ │ │ + invalidator.close() │ │ │ │ │ + self._invalidators = [] │ │ │ │ │ + self._source = None │ │ │ │ │ + self._fd.close() │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/ferny/py.typed': br'''''', │ │ │ │ │ - 'cockpit/_vendor/ferny/interaction_agent.py': r'''# ferny - asyncio SSH client library, using ssh(1) │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/py.typed': br'''''', │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/libsystemd.py': r'''# systemd_ctypes │ │ │ │ │ # │ │ │ │ │ -# Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ +# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ # │ │ │ │ │ # This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import array │ │ │ │ │ -import ast │ │ │ │ │ -import asyncio │ │ │ │ │ -import contextlib │ │ │ │ │ -import logging │ │ │ │ │ +import ctypes │ │ │ │ │ import os │ │ │ │ │ -import re │ │ │ │ │ -import socket │ │ │ │ │ -import tempfile │ │ │ │ │ -from typing import Any, Callable, ClassVar, Generator, Sequence │ │ │ │ │ +import sys │ │ │ │ │ +from typing import ClassVar, List, Optional, Tuple, Union │ │ │ │ │ │ │ │ │ │ -from . import interaction_client │ │ │ │ │ +from .inotify import inotify_event │ │ │ │ │ +from .librarywrapper import ( │ │ │ │ │ + Callback, │ │ │ │ │ + Errno, │ │ │ │ │ + Reference, │ │ │ │ │ + ReferenceType, │ │ │ │ │ + UserData, │ │ │ │ │ + WeakReference, │ │ │ │ │ + byref, │ │ │ │ │ +) │ │ │ │ │ +from .typing import Annotated │ │ │ │ │ │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ +class Trampoline(ReferenceType): │ │ │ │ │ + deferred: 'ClassVar[list[Callback] | None]' = None │ │ │ │ │ + trampoline: Callback │ │ │ │ │ + userdata: UserData = None │ │ │ │ │ │ │ │ │ │ -COMMAND_RE = re.compile(b'\0ferny\0([^\n]*)\0\0\n') │ │ │ │ │ -COMMAND_TEMPLATE = '\0ferny\0{(command, args)!r}\0\0\n' │ │ │ │ │ + def cancel(self) -> None: │ │ │ │ │ + self._unref() │ │ │ │ │ + self.value = None │ │ │ │ │ │ │ │ │ │ -BEIBOOT_GADGETS = { │ │ │ │ │ - "command": fr""" │ │ │ │ │ - import sys │ │ │ │ │ - def command(command, *args): │ │ │ │ │ - sys.stderr.write(f{COMMAND_TEMPLATE!r}) │ │ │ │ │ - sys.stderr.flush() │ │ │ │ │ - """, │ │ │ │ │ - "end": r""" │ │ │ │ │ - def end(): │ │ │ │ │ - command('ferny.end') │ │ │ │ │ - """, │ │ │ │ │ -} │ │ │ │ │ + def __del__(self) -> None: │ │ │ │ │ + # This might be the currently-dispatching callback — make sure we don't │ │ │ │ │ + # destroy the trampoline before we return. We drop the deferred list │ │ │ │ │ + # from the event loop when we're sure we're not doing any dispatches. │ │ │ │ │ + if Trampoline.deferred is not None: │ │ │ │ │ + Trampoline.deferred.append(self.trampoline) │ │ │ │ │ + if self.value is not None: │ │ │ │ │ + self._unref() │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class InteractionError(Exception): │ │ │ │ │ - pass │ │ │ │ │ +class sd_bus_error(ctypes.Structure): │ │ │ │ │ + # This is ABI, so we are safe to assume it doesn't change. │ │ │ │ │ + # Unfortunately, we lack anything like sd_bus_error_new(). │ │ │ │ │ + _fields_ = ( │ │ │ │ │ + ("name", ctypes.c_char_p), │ │ │ │ │ + ("message", ctypes.c_char_p), │ │ │ │ │ + ("_need_free", ctypes.c_int), │ │ │ │ │ + ) │ │ │ │ │ │ │ │ │ │ + def get(self) -> Tuple[str, str]: │ │ │ │ │ + return self.name.decode(), self.message.decode() │ │ │ │ │ │ │ │ │ │ -try: │ │ │ │ │ - recv_fds = socket.recv_fds │ │ │ │ │ -except AttributeError: │ │ │ │ │ - # Python < 3.9 │ │ │ │ │ + def set(self, name: str, message: str) -> None: │ │ │ │ │ + result = libsystemd.sd_bus_error_set(byref(self), name, message) │ │ │ │ │ + if result < 0: │ │ │ │ │ + raise OSError(-result, f"sd_bus_error_set: {os.strerror(-result)}") │ │ │ │ │ │ │ │ │ │ - def recv_fds( │ │ │ │ │ - sock: socket.socket, bufsize: int, maxfds: int, flags: int = 0 │ │ │ │ │ - ) -> 'tuple[bytes, list[int], int, None]': │ │ │ │ │ - fds = array.array("i") │ │ │ │ │ - msg, ancdata, flags, addr = sock.recvmsg(bufsize, socket.CMSG_LEN(maxfds * fds.itemsize)) │ │ │ │ │ - for cmsg_level, cmsg_type, cmsg_data in ancdata: │ │ │ │ │ - if (cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS): │ │ │ │ │ - fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) │ │ │ │ │ - return msg, list(fds), flags, addr │ │ │ │ │ + def __del__(self) -> None: │ │ │ │ │ + if self._b_needsfree_: │ │ │ │ │ + libsystemd.sd_bus_error_free(byref(self)) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -def get_running_loop() -> asyncio.AbstractEventLoop: │ │ │ │ │ - try: │ │ │ │ │ - return asyncio.get_running_loop() │ │ │ │ │ - except AttributeError: │ │ │ │ │ - # Python 3.6 │ │ │ │ │ - return asyncio.get_event_loop() │ │ │ │ │ +class sd_id128(ctypes.Structure): │ │ │ │ │ + # HACK: Pass-by-value of array-containing-structs is broken on Python │ │ │ │ │ + # 3.6. See https://bugs.python.org/issue22273 │ │ │ │ │ + _fields_: List[Tuple[str, type]] = ( │ │ │ │ │ + [("bytes", ctypes.c_uint8 * 16)] │ │ │ │ │ + if sys.version_info >= (3, 7, 0) │ │ │ │ │ + else [("one", ctypes.c_uint64), ("two", ctypes.c_uint64)] │ │ │ │ │ + ) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class InteractionHandler: │ │ │ │ │ - commands: ClassVar[Sequence[str]] │ │ │ │ │ +class sd_event_source(Trampoline): │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - async def run_command(self, command: str, args: 'tuple[object, ...]', fds: 'list[int]', stderr: str) -> None: │ │ │ │ │ + │ │ │ │ │ +class sd_event(ReferenceType): │ │ │ │ │ + def _add_inotify( │ │ │ │ │ + self: 'sd_event', │ │ │ │ │ + source: Reference[sd_event_source], │ │ │ │ │ + path: str, │ │ │ │ │ + event: int, │ │ │ │ │ + callback: Callback, │ │ │ │ │ + user_data: UserData, │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ + │ │ │ │ │ + def dispatch(self: 'sd_event') -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ + │ │ │ │ │ + def get_fd(self: 'sd_event') -> Union[int, Errno]: │ │ │ │ │ raise NotImplementedError │ │ │ │ │ │ │ │ │ │ + def get_state(self: 'sd_event') -> Union[int, Errno]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ -class AskpassHandler(InteractionHandler): │ │ │ │ │ - commands: ClassVar[Sequence[str]] = ('ferny.askpass',) │ │ │ │ │ + def loop(self: 'sd_event') -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - async def do_askpass(self, messages: str, prompt: str, hint: str) -> 'str | None': │ │ │ │ │ - """Prompt the user for an authentication or confirmation interaction. │ │ │ │ │ + def prepare(self: 'sd_event') -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - 'messages' is data that was sent to stderr before the interaction was requested. │ │ │ │ │ - 'prompt' is the interaction prompt. │ │ │ │ │ + def wait( │ │ │ │ │ + self: 'sd_event', timeout: Annotated[int, ctypes.c_uint64] │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - The expected response type depends on hint: │ │ │ │ │ + @staticmethod │ │ │ │ │ + def _default(ret: Reference['sd_event']) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - - "confirm": ask for permission, returning "yes" if accepted │ │ │ │ │ - - example: authorizing agent operation │ │ │ │ │ │ │ │ │ │ - - "none": show a request without need for a response │ │ │ │ │ - - example: please touch your authentication token │ │ │ │ │ +class sd_bus_slot(Trampoline): │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - - otherwise: return a password or other form of text token │ │ │ │ │ - - examples: enter password, unlock private key │ │ │ │ │ │ │ │ │ │ - In any case, the function should properly handle cancellation. For the │ │ │ │ │ - "none" case, this will be the normal way to dismiss the dialog. │ │ │ │ │ - """ │ │ │ │ │ - return None │ │ │ │ │ +class sd_bus_message(ReferenceType): │ │ │ │ │ + def rewind(self: 'sd_bus_message', complete: bool) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - async def do_hostkey(self, reason: str, host: str, algorithm: str, key: str, fingerprint: str) -> bool: │ │ │ │ │ - """Prompt the user for a decision regarding acceptance of a host key. │ │ │ │ │ + def _get_error(self: 'sd_bus_message') -> Reference[sd_bus_error]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - The "reason" will be either "HOSTNAME" or "ADDRESS" (if `CheckHostIP` is enabled). │ │ │ │ │ + def has_signature(self: 'sd_bus_message', signature: str) -> Union[bool, Errno]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - The host, algorithm, and key parameters are the values in the form that │ │ │ │ │ - they would appear one a single line in the known hosts file. The │ │ │ │ │ - fingerprint is the key fingerprint in the format that ssh would │ │ │ │ │ - normally present it to the user. │ │ │ │ │ + def is_method_error(self: 'sd_bus_message', name: str) -> Union[bool, Errno]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - In case the host key should be accepted, this function needs to return │ │ │ │ │ - True. Returning False means that ssh implements its default logic. To │ │ │ │ │ - interrupt the connection, raise an exception. │ │ │ │ │ - """ │ │ │ │ │ - return False │ │ │ │ │ + def _new_method_errnof( │ │ │ │ │ + self: 'sd_bus_message', │ │ │ │ │ + message: Reference['sd_bus_message'], │ │ │ │ │ + error: int, │ │ │ │ │ + format_str: str, │ │ │ │ │ + first_arg: str │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - async def do_custom_command( │ │ │ │ │ - self, command: str, args: 'tuple[object, ...]', fds: 'list[int]', stderr: str │ │ │ │ │ - ) -> None: │ │ │ │ │ - """Handle a custom command. │ │ │ │ │ + def _new_method_errorf( │ │ │ │ │ + self: 'sd_bus_message', │ │ │ │ │ + m: Reference['sd_bus_message'], │ │ │ │ │ + name: str, │ │ │ │ │ + format_str: str, │ │ │ │ │ + first_arg: str │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - The command name, its arguments, the passed fds, and the stderr leading │ │ │ │ │ - up to the command invocation are all provided. │ │ │ │ │ + def _new_method_return( │ │ │ │ │ + self: 'sd_bus_message', m: Reference['sd_bus_message'] │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - See doc/interaction-protocol.md │ │ │ │ │ - """ │ │ │ │ │ + def seal( │ │ │ │ │ + self: 'sd_bus_message', │ │ │ │ │ + cookie: Annotated[int, ctypes.c_uint64], │ │ │ │ │ + timeout: Annotated[int, ctypes.c_uint64], │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - async def _askpass_command(self, args: 'tuple[object, ...]', fds: 'list[int]', stderr: str) -> None: │ │ │ │ │ - logger.debug('_askpass_command(%s, %s, %s)', args, fds, stderr) │ │ │ │ │ - try: │ │ │ │ │ - argv, env = args │ │ │ │ │ - assert isinstance(argv, list) │ │ │ │ │ - assert all(isinstance(arg, str) for arg in argv) │ │ │ │ │ - assert isinstance(env, dict) │ │ │ │ │ - assert all(isinstance(key, str) and isinstance(val, str) for key, val in env.items()) │ │ │ │ │ - assert len(fds) == 2 │ │ │ │ │ - except (ValueError, TypeError, AssertionError) as exc: │ │ │ │ │ - logger.error('Invalid arguments to askpass interaction: %s, %s: %s', args, fds, exc) │ │ │ │ │ - return │ │ │ │ │ + def _get_bus(self: 'sd_bus_message') -> WeakReference: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - with open(fds.pop(0), 'w') as status, open(fds.pop(0), 'w') as stdout: │ │ │ │ │ - try: │ │ │ │ │ - loop = get_running_loop() │ │ │ │ │ - try: │ │ │ │ │ - task = asyncio.current_task() │ │ │ │ │ - except AttributeError: │ │ │ │ │ - task = asyncio.Task.current_task() # type:ignore[attr-defined] # (Python 3.6) │ │ │ │ │ - assert task is not None │ │ │ │ │ - loop.add_reader(status, task.cancel) │ │ │ │ │ + def get_destination(self: 'sd_bus_message') -> str: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - if len(argv) == 2: │ │ │ │ │ - # normal askpass │ │ │ │ │ - prompt = argv[1] │ │ │ │ │ - hint = env.get('SSH_ASKPASS_PROMPT', '') │ │ │ │ │ - logger.debug('do_askpass(%r, %r, %r)', stderr, prompt, hint) │ │ │ │ │ - answer = await self.do_askpass(stderr, prompt, hint) │ │ │ │ │ - logger.debug('do_askpass answer %r', answer) │ │ │ │ │ - if answer is not None: │ │ │ │ │ - print(answer, file=stdout) │ │ │ │ │ - print(0, file=status) │ │ │ │ │ + def get_interface(self: 'sd_bus_message') -> str: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - elif len(argv) == 6: │ │ │ │ │ - # KnownHostsCommand │ │ │ │ │ - argv0, reason, host, algorithm, key, fingerprint = argv │ │ │ │ │ - if reason in ['ADDRESS', 'HOSTNAME']: │ │ │ │ │ - logger.debug('do_hostkey(%r, %r, %r, %r, %r)', reason, host, algorithm, key, fingerprint) │ │ │ │ │ - if await self.do_hostkey(reason, host, algorithm, key, fingerprint): │ │ │ │ │ - print(host, algorithm, key, file=stdout) │ │ │ │ │ - else: │ │ │ │ │ - logger.debug('ignoring KnownHostsCommand reason %r', reason) │ │ │ │ │ + def get_member(self: 'sd_bus_message') -> str: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - print(0, file=status) │ │ │ │ │ + def get_path(self: 'sd_bus_message') -> str: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - else: │ │ │ │ │ - logger.error('Incorrect number of command-line arguments to ferny-askpass: %s', argv) │ │ │ │ │ - finally: │ │ │ │ │ - loop.remove_reader(status) │ │ │ │ │ + def get_sender(self: 'sd_bus_message') -> Optional[str]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - async def run_command(self, command: str, args: 'tuple[object, ...]', fds: 'list[int]', stderr: str) -> None: │ │ │ │ │ - logger.debug('run_command(%s, %s, %s, %s)', command, args, fds, stderr) │ │ │ │ │ - if command == 'ferny.askpass': │ │ │ │ │ - await self._askpass_command(args, fds, stderr) │ │ │ │ │ - else: │ │ │ │ │ - await self.do_custom_command(command, args, fds, stderr) │ │ │ │ │ + def get_signature(self: 'sd_bus_message', complete: bool) -> str: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class InteractionAgent: │ │ │ │ │ - _handlers: 'dict[str, InteractionHandler]' │ │ │ │ │ +class sd_bus(ReferenceType): │ │ │ │ │ + def _add_match( │ │ │ │ │ + self: 'sd_bus', │ │ │ │ │ + slot: Reference[sd_bus_slot], │ │ │ │ │ + match: str, │ │ │ │ │ + handler: Callback, │ │ │ │ │ + user_data: UserData, │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - _loop: asyncio.AbstractEventLoop │ │ │ │ │ + def _add_match_async( │ │ │ │ │ + self: 'sd_bus', │ │ │ │ │ + slot: Reference[sd_bus_slot], │ │ │ │ │ + match: str, │ │ │ │ │ + callback: Callback, │ │ │ │ │ + install_callback: Callback, │ │ │ │ │ + user_data: UserData, │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - _tasks: 'set[asyncio.Task]' │ │ │ │ │ + def _add_object( │ │ │ │ │ + self: 'sd_bus', │ │ │ │ │ + slot: Reference[sd_bus_slot], │ │ │ │ │ + path: str, │ │ │ │ │ + callback: Callback, │ │ │ │ │ + user_data: UserData, │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - _buffer: bytearray │ │ │ │ │ - _ours: socket.socket │ │ │ │ │ - _theirs: socket.socket │ │ │ │ │ + def attach_event( │ │ │ │ │ + self: 'sd_bus', event: Optional[sd_event], priority: int │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - _completion_future: 'asyncio.Future[str]' │ │ │ │ │ - _pending_result: 'None | str | Exception' = None │ │ │ │ │ - _end: bool = False │ │ │ │ │ + def _call( │ │ │ │ │ + self: 'sd_bus', │ │ │ │ │ + message: sd_bus_message, │ │ │ │ │ + timeout: Annotated[int, ctypes.c_uint64], │ │ │ │ │ + ret_error: Reference[sd_bus_error], │ │ │ │ │ + reply: Reference[sd_bus_message], │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - def _consider_completion(self) -> None: │ │ │ │ │ - logger.debug('_consider_completion(%r)', self) │ │ │ │ │ + def _call_async( │ │ │ │ │ + self: 'sd_bus', │ │ │ │ │ + slot: Reference[sd_bus_slot], │ │ │ │ │ + message: sd_bus_message, │ │ │ │ │ + callback: Callback, │ │ │ │ │ + user_data: UserData, │ │ │ │ │ + timeout_usec: Annotated[int, ctypes.c_uint64], │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - if self._pending_result is None or self._tasks: │ │ │ │ │ - logger.debug(' but not ready yet') │ │ │ │ │ + def flush(self: 'sd_bus') -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - elif self._completion_future.done(): │ │ │ │ │ - logger.debug(' but already complete') │ │ │ │ │ + def get_fd(self: 'sd_bus') -> Union[int, Errno]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ │ │ │ │ │ - elif isinstance(self._pending_result, str): │ │ │ │ │ - logger.debug(' submitting stderr (%r) to completion_future', self._pending_result) │ │ │ │ │ - self._completion_future.set_result(self._pending_result) │ │ │ │ │ + def _message_new_method_call( │ │ │ │ │ + self: 'sd_bus', │ │ │ │ │ + message: Reference[sd_bus_message], │ │ │ │ │ + destination: Optional[str], │ │ │ │ │ + path: str, │ │ │ │ │ + interface: str, │ │ │ │ │ + member: str, │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - else: │ │ │ │ │ - logger.debug(' submitting exception (%r) to completion_future') │ │ │ │ │ - self._completion_future.set_exception(self._pending_result) │ │ │ │ │ + def _message_new_signal( │ │ │ │ │ + self: 'sd_bus', │ │ │ │ │ + message: Reference[sd_bus_message], │ │ │ │ │ + path: str, │ │ │ │ │ + interface: str, │ │ │ │ │ + member: str, │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - def _result(self, result: 'str | Exception') -> None: │ │ │ │ │ - logger.debug('_result(%r, %r)', self, result) │ │ │ │ │ + def release_name(self: 'sd_bus', name: str) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - if self._pending_result is None: │ │ │ │ │ - self._pending_result = result │ │ │ │ │ + def request_name( │ │ │ │ │ + self: 'sd_bus', name: str, flags: Annotated[int, ctypes.c_uint64] │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - if self._ours.fileno() != -1: │ │ │ │ │ - logger.debug(' remove_reader(%r)', self._ours) │ │ │ │ │ - self._loop.remove_reader(self._ours.fileno()) │ │ │ │ │ + def set_address(self: 'sd_bus', address: str) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - for task in self._tasks: │ │ │ │ │ - logger.debug(' cancel(%r)', task) │ │ │ │ │ - task.cancel() │ │ │ │ │ + def set_bus_client(self: 'sd_bus', b: bool) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - logger.debug(' closing sockets') │ │ │ │ │ - self._theirs.close() # idempotent │ │ │ │ │ - self._ours.close() │ │ │ │ │ + def set_fd(self: 'sd_bus', input_fd: int, output_fd: int) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - self._consider_completion() │ │ │ │ │ + def set_server(self: 'sd_bus', b: bool, bus_d: sd_id128) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - def _invoke_command(self, stderr: bytes, command_blob: bytes, fds: 'list[int]') -> None: │ │ │ │ │ - logger.debug('_invoke_command(%r, %r, %r)', stderr, command_blob, fds) │ │ │ │ │ - try: │ │ │ │ │ - command, args = ast.literal_eval(command_blob.decode()) │ │ │ │ │ - if not isinstance(command, str) or not isinstance(args, tuple): │ │ │ │ │ - raise TypeError('Invalid argument types') │ │ │ │ │ - except (UnicodeDecodeError, SyntaxError, ValueError, TypeError) as exc: │ │ │ │ │ - logger.error('Received invalid ferny command: %s: %s', command_blob, exc) │ │ │ │ │ - return │ │ │ │ │ + def start(self: 'sd_bus') -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - if command == 'ferny.end': │ │ │ │ │ - self._end = True │ │ │ │ │ - self._result(self._buffer.decode(errors='replace')) │ │ │ │ │ - return │ │ │ │ │ + def wait( │ │ │ │ │ + self: 'sd_bus', timeout_usec: Annotated[int, ctypes.c_uint64] │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - handler = self._handlers[command] │ │ │ │ │ - except KeyError: │ │ │ │ │ - logger.error('Received unhandled ferny command: %s', command) │ │ │ │ │ - return │ │ │ │ │ + def send( │ │ │ │ │ + self: 'sd_bus', message: sd_bus_message, cookie: Optional[Reference[ctypes.c_uint64]] │ │ │ │ │ + ) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - # The task is responsible for the list of fds and removing itself │ │ │ │ │ - # from the set. │ │ │ │ │ - task_fds = list(fds) │ │ │ │ │ - task = self._loop.create_task(handler.run_command(command, args, task_fds, stderr.decode())) │ │ │ │ │ + @staticmethod │ │ │ │ │ + def _default_system(ret: Reference['sd_bus']) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - def bottom_half(completed_task: asyncio.Task) -> None: │ │ │ │ │ - assert completed_task is task │ │ │ │ │ - while task_fds: │ │ │ │ │ - os.close(task_fds.pop()) │ │ │ │ │ - self._tasks.remove(task) │ │ │ │ │ + @staticmethod │ │ │ │ │ + def _default_user(ret: Reference['sd_bus']) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - task.result() │ │ │ │ │ - logger.debug('%r completed cleanly', handler) │ │ │ │ │ - except asyncio.CancelledError: │ │ │ │ │ - # this is not an error — it just means ferny-askpass exited via signal │ │ │ │ │ - logger.debug('%r was cancelled', handler) │ │ │ │ │ - except Exception as exc: │ │ │ │ │ - logger.debug('%r raised %r', handler, exc) │ │ │ │ │ - self._result(exc) │ │ │ │ │ + @staticmethod │ │ │ │ │ + def _new(ret: Reference['sd_bus']) -> Union[None, Errno]: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - self._consider_completion() │ │ │ │ │ │ │ │ │ │ - task.add_done_callback(bottom_half) │ │ │ │ │ - self._tasks.add(task) │ │ │ │ │ - fds[:] = [] │ │ │ │ │ +sd_bus_message_handler_t = ctypes.CFUNCTYPE( │ │ │ │ │ + ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(sd_bus_error)) │ │ │ │ │ +sd_event_inotify_handler_t = ctypes.CFUNCTYPE( │ │ │ │ │ + ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(inotify_event), ctypes.c_void_p) │ │ │ │ │ │ │ │ │ │ - def _got_data(self, data: bytes, fds: 'list[int]') -> None: │ │ │ │ │ - logger.debug('_got_data(%r, %r)', data, fds) │ │ │ │ │ │ │ │ │ │ - if data == b'': │ │ │ │ │ - self._result(self._buffer.decode(errors='replace')) │ │ │ │ │ - return │ │ │ │ │ +libsystemd = ctypes.CDLL("libsystemd.so.0") │ │ │ │ │ +for cls in { │ │ │ │ │ + sd_bus, │ │ │ │ │ + sd_bus_message, │ │ │ │ │ + sd_bus_slot, │ │ │ │ │ + sd_event, │ │ │ │ │ + sd_event_source, │ │ │ │ │ +}: │ │ │ │ │ + cls._install_cfuncs(libsystemd) │ │ │ │ │ +'''.encode('utf-8'), │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/inotify.py': br'''# systemd_ctypes │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ - self._buffer.extend(data) │ │ │ │ │ +import ctypes │ │ │ │ │ +from enum import IntFlag, auto │ │ │ │ │ +from typing import Optional │ │ │ │ │ │ │ │ │ │ - # Read zero or more "remote" messages │ │ │ │ │ - chunks = COMMAND_RE.split(self._buffer) │ │ │ │ │ - self._buffer = bytearray(chunks.pop()) │ │ │ │ │ - while len(chunks) > 1: │ │ │ │ │ - self._invoke_command(chunks[0], chunks[1], []) │ │ │ │ │ - chunks = chunks[2:] │ │ │ │ │ │ │ │ │ │ - # Maybe read one "local" message │ │ │ │ │ - if fds: │ │ │ │ │ - assert self._buffer.endswith(b'\0'), self._buffer │ │ │ │ │ - stderr = self._buffer[:-1] │ │ │ │ │ - self._buffer = bytearray(b'') │ │ │ │ │ - with open(fds.pop(0), 'rb') as command_channel: │ │ │ │ │ - command = command_channel.read() │ │ │ │ │ - self._invoke_command(stderr, command, fds) │ │ │ │ │ +class inotify_event(ctypes.Structure): │ │ │ │ │ + _fields_ = ( │ │ │ │ │ + ('wd', ctypes.c_int32), │ │ │ │ │ + ('mask', ctypes.c_uint32), │ │ │ │ │ + ('cookie', ctypes.c_uint32), │ │ │ │ │ + ('len', ctypes.c_uint32), │ │ │ │ │ + ) │ │ │ │ │ │ │ │ │ │ - def _read_ready(self) -> None: │ │ │ │ │ - try: │ │ │ │ │ - data, fds, _flags, _addr = recv_fds(self._ours, 4096, 10, flags=socket.MSG_DONTWAIT) │ │ │ │ │ - except BlockingIOError: │ │ │ │ │ - return │ │ │ │ │ - except OSError as exc: │ │ │ │ │ - self._result(exc) │ │ │ │ │ - else: │ │ │ │ │ - self._got_data(data, fds) │ │ │ │ │ - finally: │ │ │ │ │ - while fds: │ │ │ │ │ - os.close(fds.pop()) │ │ │ │ │ + @property │ │ │ │ │ + def name(self) -> Optional[bytes]: │ │ │ │ │ + if self.len == 0: │ │ │ │ │ + return None │ │ │ │ │ │ │ │ │ │ - def __init__( │ │ │ │ │ - self, │ │ │ │ │ - handlers: Sequence[InteractionHandler], │ │ │ │ │ - loop: 'asyncio.AbstractEventLoop | None' = None, │ │ │ │ │ - done_callback: 'Callable[[asyncio.Future[str]], None] | None' = None, │ │ │ │ │ - ) -> None: │ │ │ │ │ - self._loop = loop or get_running_loop() │ │ │ │ │ - self._completion_future = self._loop.create_future() │ │ │ │ │ - self._tasks = set() │ │ │ │ │ - self._handlers = {} │ │ │ │ │ + class event_with_name(ctypes.Structure): │ │ │ │ │ + _fields_ = (*inotify_event._fields_, ('name', ctypes.c_char * self.len)) │ │ │ │ │ │ │ │ │ │ - for handler in handlers: │ │ │ │ │ - for command in handler.commands: │ │ │ │ │ - self._handlers[command] = handler │ │ │ │ │ + name = ctypes.cast(ctypes.addressof(self), ctypes.POINTER(event_with_name)).contents.name │ │ │ │ │ + assert isinstance(name, bytes) │ │ │ │ │ + return name │ │ │ │ │ │ │ │ │ │ - if done_callback is not None: │ │ │ │ │ - self._completion_future.add_done_callback(done_callback) │ │ │ │ │ │ │ │ │ │ - self._theirs, self._ours = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) │ │ │ │ │ - self._buffer = bytearray() │ │ │ │ │ +class Event(IntFlag): │ │ │ │ │ + ACCESS = auto() │ │ │ │ │ + MODIFY = auto() │ │ │ │ │ + ATTRIB = auto() │ │ │ │ │ + CLOSE_WRITE = auto() │ │ │ │ │ + CLOSE_NOWRITE = auto() │ │ │ │ │ + OPEN = auto() │ │ │ │ │ + MOVED_FROM = auto() │ │ │ │ │ + MOVED_TO = auto() │ │ │ │ │ + CREATE = auto() │ │ │ │ │ + DELETE = auto() │ │ │ │ │ + DELETE_SELF = auto() │ │ │ │ │ + MOVE_SELF = auto() │ │ │ │ │ │ │ │ │ │ - def fileno(self) -> int: │ │ │ │ │ - return self._theirs.fileno() │ │ │ │ │ + UNMOUNT = 1 << 13 │ │ │ │ │ + Q_OVERFLOW = auto() │ │ │ │ │ + IGNORED = auto() │ │ │ │ │ │ │ │ │ │ - def start(self) -> None: │ │ │ │ │ - logger.debug('start(%r)', self) │ │ │ │ │ - if self._ours.fileno() != -1: │ │ │ │ │ - logger.debug(' add_reader(%r)', self._ours) │ │ │ │ │ - self._loop.add_reader(self._ours.fileno(), self._read_ready) │ │ │ │ │ - else: │ │ │ │ │ - logger.debug(' ...but agent is already finished.') │ │ │ │ │ + ONLYDIR = 1 << 24 │ │ │ │ │ + DONT_FOLLOW = auto() │ │ │ │ │ + EXCL_UNLINK = auto() │ │ │ │ │ │ │ │ │ │ - logger.debug(' close(%r)', self._theirs) │ │ │ │ │ - self._theirs.close() │ │ │ │ │ + MASK_CREATE = 1 << 28 │ │ │ │ │ + MASK_ADD = auto() │ │ │ │ │ + ISDIR = auto() │ │ │ │ │ + ONESHOT = auto() │ │ │ │ │ │ │ │ │ │ - def force_completion(self) -> None: │ │ │ │ │ - logger.debug('force_completion(%r)', self) │ │ │ │ │ + CLOSE = CLOSE_WRITE | CLOSE_NOWRITE │ │ │ │ │ + MOVE = MOVED_FROM | MOVED_TO │ │ │ │ │ + CHANGED = (MODIFY | ATTRIB | CLOSE_WRITE | MOVE | │ │ │ │ │ + CREATE | DELETE | DELETE_SELF | MOVE_SELF) │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/librarywrapper.py': br'''# systemd_ctypes │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ - # read any residual data on stderr, but don't process commands, and │ │ │ │ │ - # don't block │ │ │ │ │ - try: │ │ │ │ │ - if self._ours.fileno() != -1: │ │ │ │ │ - logger.debug(' draining pending stderr data (non-blocking)') │ │ │ │ │ - with contextlib.suppress(BlockingIOError): │ │ │ │ │ - while True: │ │ │ │ │ - data = self._ours.recv(4096, socket.MSG_DONTWAIT) │ │ │ │ │ - logger.debug(' got %d bytes', len(data)) │ │ │ │ │ - if not data: │ │ │ │ │ - break │ │ │ │ │ - self._buffer.extend(data) │ │ │ │ │ - except OSError as exc: │ │ │ │ │ - self._result(exc) │ │ │ │ │ - else: │ │ │ │ │ - self._result(self._buffer.decode(errors='replace')) │ │ │ │ │ +import ctypes │ │ │ │ │ +import inspect │ │ │ │ │ +import logging │ │ │ │ │ +import os │ │ │ │ │ +import sys │ │ │ │ │ +import types │ │ │ │ │ +from typing import ( │ │ │ │ │ + Any, │ │ │ │ │ + Callable, │ │ │ │ │ + Dict, │ │ │ │ │ + Generic, │ │ │ │ │ + NewType, │ │ │ │ │ + NoReturn, │ │ │ │ │ + Optional, │ │ │ │ │ + Tuple, │ │ │ │ │ + Type, │ │ │ │ │ + TypeVar, │ │ │ │ │ + Union, │ │ │ │ │ +) │ │ │ │ │ │ │ │ │ │ - async def communicate(self) -> None: │ │ │ │ │ - logger.debug('_communicate(%r)', self) │ │ │ │ │ - try: │ │ │ │ │ - self.start() │ │ │ │ │ - # We assume that we are the only ones to write to │ │ │ │ │ - # self._completion_future. If we directly await it, though, it can │ │ │ │ │ - # also have a asyncio.CancelledError posted to it from outside. │ │ │ │ │ - # Shield it to prevent that from happening. │ │ │ │ │ - stderr = await asyncio.shield(self._completion_future) │ │ │ │ │ - logger.debug('_communicate(%r) stderr result is %r', self, stderr) │ │ │ │ │ - finally: │ │ │ │ │ - logger.debug('_communicate finished. Ensuring completion.') │ │ │ │ │ - self.force_completion() │ │ │ │ │ - if not self._end: │ │ │ │ │ - logger.debug('_communicate never saw ferny.end. raising InteractionError.') │ │ │ │ │ - raise InteractionError(stderr.strip()) │ │ │ │ │ +from . import typing │ │ │ │ │ │ │ │ │ │ +# First in 3.10, and conditional import gives type errors │ │ │ │ │ +NoneType = type(None) │ │ │ │ │ │ │ │ │ │ -def write_askpass_to_tmpdir(tmpdir: str) -> str: │ │ │ │ │ - askpass_path = os.path.join(tmpdir, 'ferny-askpass') │ │ │ │ │ - fd = os.open(askpass_path, os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC | os.O_EXCL | os.O_NOFOLLOW, 0o777) │ │ │ │ │ - try: │ │ │ │ │ - os.write(fd, __loader__.get_data(interaction_client.__file__)) # type: ignore │ │ │ │ │ - finally: │ │ │ │ │ - os.close(fd) │ │ │ │ │ - return askpass_path │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ +if typing.TYPE_CHECKING: │ │ │ │ │ + CType = TypeVar("CType", bound=ctypes._CData) │ │ │ │ │ + Callback = ctypes._FuncPointer │ │ │ │ │ +else: │ │ │ │ │ + CType = TypeVar("CType") │ │ │ │ │ + Callback = ctypes.c_void_p │ │ │ │ │ │ │ │ │ │ -@contextlib.contextmanager │ │ │ │ │ -def temporary_askpass(**kwargs: Any) -> Generator[str, None, None]: │ │ │ │ │ - with tempfile.TemporaryDirectory(**kwargs) as directory: │ │ │ │ │ - yield write_askpass_to_tmpdir(directory) │ │ │ │ │ -'''.encode('utf-8'), │ │ │ │ │ - 'cockpit/_vendor/ferny/ssh_askpass.py': br'''import logging │ │ │ │ │ -import re │ │ │ │ │ -from typing import ClassVar, Match, Sequence │ │ │ │ │ │ │ │ │ │ -from .interaction_agent import AskpassHandler │ │ │ │ │ +if typing.TYPE_CHECKING: │ │ │ │ │ + class Reference(Generic[CType], ctypes._Pointer[CType]): │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ + def byref(x: CType) -> Reference[CType]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ +else: │ │ │ │ │ + class Reference(Generic[CType]): │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ + byref = ctypes.byref │ │ │ │ │ │ │ │ │ │ -class AskpassPrompt: │ │ │ │ │ - """An askpass prompt resulting from a call to ferny-askpass. │ │ │ │ │ │ │ │ │ │ - stderr: the contents of stderr from before ferny-askpass was called. │ │ │ │ │ - Likely related to previous failed operations. │ │ │ │ │ - messages: all but the last line of the prompt as handed to ferny-askpass. │ │ │ │ │ - Usually contains context about the question. │ │ │ │ │ - prompt: the last line handed to ferny-askpass. The prompt itself. │ │ │ │ │ - """ │ │ │ │ │ - stderr: str │ │ │ │ │ - messages: str │ │ │ │ │ - prompt: str │ │ │ │ │ +UserData = Optional[ctypes.c_void_p] │ │ │ │ │ │ │ │ │ │ - def __init__(self, prompt: str, messages: str, stderr: str) -> None: │ │ │ │ │ - self.stderr = stderr │ │ │ │ │ - self.messages = messages │ │ │ │ │ - self.prompt = prompt │ │ │ │ │ │ │ │ │ │ - def reply(self, response: str) -> None: │ │ │ │ │ - pass │ │ │ │ │ +class negative_errno(ctypes.c_int): │ │ │ │ │ + def errcheck(self, func: Callable[..., object], _args: Tuple[object, ...]) -> int: │ │ │ │ │ + result = self.value │ │ │ │ │ + if result < 0: │ │ │ │ │ + raise OSError(-result, f"{func.__name__}: {os.strerror(-result)}") │ │ │ │ │ + return result │ │ │ │ │ │ │ │ │ │ - def close(self) -> None: │ │ │ │ │ - pass │ │ │ │ │ │ │ │ │ │ - async def handle_via(self, responder: 'SshAskpassResponder') -> None: │ │ │ │ │ - try: │ │ │ │ │ - response = await self.dispatch(responder) │ │ │ │ │ - if response is not None: │ │ │ │ │ - self.reply(response) │ │ │ │ │ - finally: │ │ │ │ │ - self.close() │ │ │ │ │ +class utf8(ctypes.c_char_p): │ │ │ │ │ + def errcheck(self, func: Callable[..., object], _args: Tuple[object, ...]) -> str: │ │ │ │ │ + assert self.value is not None │ │ │ │ │ + return self.value.decode() │ │ │ │ │ │ │ │ │ │ - async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ - return await responder.do_prompt(self) │ │ │ │ │ + @classmethod │ │ │ │ │ + def from_param(cls, value: str) -> 'utf8': │ │ │ │ │ + return cls(value.encode()) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class SSHAskpassPrompt(AskpassPrompt): │ │ │ │ │ - # The valid answers to prompts of this type. If this is None then any │ │ │ │ │ - # answer is permitted. If it's a sequence then only answers from the │ │ │ │ │ - # sequence are permitted. If it's an empty sequence, then no answer is │ │ │ │ │ - # permitted (ie: the askpass callback should never return). │ │ │ │ │ - answers: 'ClassVar[Sequence[str] | None]' = None │ │ │ │ │ +class utf8_or_null(ctypes.c_char_p): │ │ │ │ │ + def errcheck(self, │ │ │ │ │ + func: Callable[..., object], │ │ │ │ │ + _args: Tuple[object, ...]) -> Optional[str]: │ │ │ │ │ + return self.value.decode() if self.value is not None else None │ │ │ │ │ │ │ │ │ │ - # Patterns to capture. `_pattern` *must* match. │ │ │ │ │ - _pattern: ClassVar[str] │ │ │ │ │ - # `_extra_patterns` can fill in extra class attributes if they match. │ │ │ │ │ - _extra_patterns: ClassVar[Sequence[str]] = () │ │ │ │ │ + @classmethod │ │ │ │ │ + def from_param(cls, value: Optional[str]) -> 'utf8_or_null': │ │ │ │ │ + return cls(value.encode() if value is not None else None) │ │ │ │ │ │ │ │ │ │ - def __init__(self, prompt: str, messages: str, stderr: str, match: Match) -> None: │ │ │ │ │ - super().__init__(prompt, messages, stderr) │ │ │ │ │ - self.__dict__.update(match.groupdict()) │ │ │ │ │ │ │ │ │ │ - for pattern in self._extra_patterns: │ │ │ │ │ - extra_match = re.search(with_helpers(pattern), messages, re.M) │ │ │ │ │ - if extra_match is not None: │ │ │ │ │ - self.__dict__.update(extra_match.groupdict()) │ │ │ │ │ +class boolint(ctypes.c_int): │ │ │ │ │ + def errcheck(self, func: Callable[..., object], _args: Tuple[object, ...]) -> bool: │ │ │ │ │ + return bool(self.value) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -# Specific prompts │ │ │ │ │ -HELPERS = { │ │ │ │ │ - "%{algorithm}": r"(?P\b[-\w]+\b)", │ │ │ │ │ - "%{filename}": r"(?P.+)", │ │ │ │ │ - "%{fingerprint}": r"(?PSHA256:[0-9A-Za-z+/]{43})", │ │ │ │ │ - "%{hostname}": r"(?P[^ @']+)", │ │ │ │ │ - "%{pkcs11_id}": r"(?P.+)", │ │ │ │ │ - "%{username}": r"(?P[^ @']+)", │ │ │ │ │ -} │ │ │ │ │ +WeakReference = NewType("WeakReference", int) │ │ │ │ │ +Errno = typing.Annotated[NoReturn, "errno"] │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class SshPasswordPrompt(SSHAskpassPrompt): │ │ │ │ │ - _pattern = r"%{username}@%{hostname}'s password: " │ │ │ │ │ - username: 'str | None' = None │ │ │ │ │ - hostname: 'str | None' = None │ │ │ │ │ +type_map = { │ │ │ │ │ + Union[None, Errno]: negative_errno, # technically returns int │ │ │ │ │ + Union[bool, Errno]: negative_errno, # technically returns int │ │ │ │ │ + Union[int, Errno]: negative_errno, │ │ │ │ │ + bool: boolint, │ │ │ │ │ + Optional[str]: utf8_or_null, │ │ │ │ │ + str: utf8, │ │ │ │ │ + int: ctypes.c_int, │ │ │ │ │ + WeakReference: ctypes.c_void_p │ │ │ │ │ +} │ │ │ │ │ │ │ │ │ │ - async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ - return await responder.do_password_prompt(self) │ │ │ │ │ │ │ │ │ │ +def map_type(annotation: Any, global_vars: Dict[str, object]) -> Any: │ │ │ │ │ + try: │ │ │ │ │ + return type_map[annotation] │ │ │ │ │ + except KeyError: │ │ │ │ │ + pass # ... and try more cases below │ │ │ │ │ │ │ │ │ │ -class SshPassphrasePrompt(SSHAskpassPrompt): │ │ │ │ │ - _pattern = r"Enter passphrase for key '%{filename}': " │ │ │ │ │ - filename: str │ │ │ │ │ + if isinstance(annotation, typing.ForwardRef): │ │ │ │ │ + annotation = annotation.__forward_arg__ │ │ │ │ │ │ │ │ │ │ - async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ - return await responder.do_passphrase_prompt(self) │ │ │ │ │ + if isinstance(annotation, str): │ │ │ │ │ + annotation = global_vars[annotation] │ │ │ │ │ │ │ │ │ │ + origin = typing.get_origin(annotation) │ │ │ │ │ + args = typing.get_args(annotation) │ │ │ │ │ │ │ │ │ │ -class SshFIDOPINPrompt(SSHAskpassPrompt): │ │ │ │ │ - _pattern = r"Enter PIN for %{algorithm} key %{filename}: " │ │ │ │ │ - algorithm: str │ │ │ │ │ - filename: str │ │ │ │ │ + if origin is Reference: │ │ │ │ │ + return ctypes.POINTER(map_type(args[0], global_vars)) │ │ │ │ │ │ │ │ │ │ - async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ - return await responder.do_fido_pin_prompt(self) │ │ │ │ │ + elif origin is Union and NoneType in args: │ │ │ │ │ + # the C pointer types are already nullable │ │ │ │ │ + other_arg, = set(args) - {NoneType} │ │ │ │ │ + return map_type(other_arg, global_vars) │ │ │ │ │ │ │ │ │ │ + elif origin is typing.Annotated: │ │ │ │ │ + return args[1] │ │ │ │ │ │ │ │ │ │ -class SshFIDOUserPresencePrompt(SSHAskpassPrompt): │ │ │ │ │ - _pattern = r"Confirm user presence for key %{algorithm} %{fingerprint}" │ │ │ │ │ - answers = () │ │ │ │ │ - algorithm: str │ │ │ │ │ - fingerprint: str │ │ │ │ │ + else: │ │ │ │ │ + assert origin is None, origin │ │ │ │ │ + return annotation │ │ │ │ │ │ │ │ │ │ - async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ - return await responder.do_fido_user_presence_prompt(self) │ │ │ │ │ │ │ │ │ │ +class ReferenceType(ctypes.c_void_p): │ │ │ │ │ + @classmethod │ │ │ │ │ + def _install_cfuncs(cls, cdll: ctypes.CDLL) -> None: │ │ │ │ │ + logger.debug('Installing stubs for %s:', cls) │ │ │ │ │ + stubs = tuple(cls.__dict__.items()) │ │ │ │ │ + for name, stub in stubs: │ │ │ │ │ + if name.startswith("__"): │ │ │ │ │ + continue │ │ │ │ │ + cls._wrap(cdll, stub) │ │ │ │ │ │ │ │ │ │ -class SshPKCS11PINPrompt(SSHAskpassPrompt): │ │ │ │ │ - _pattern = r"Enter PIN for '%{pkcs11_id}': " │ │ │ │ │ - pkcs11_id: str │ │ │ │ │ + cls._wrap(cdll, cls._ref) │ │ │ │ │ + cls._wrap(cdll, cls._unref) │ │ │ │ │ │ │ │ │ │ - async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ - return await responder.do_pkcs11_pin_prompt(self) │ │ │ │ │ + @classmethod │ │ │ │ │ + def _wrap(cls, cdll: ctypes.CDLL, stub: object) -> None: │ │ │ │ │ + stub_type = type(stub) │ │ │ │ │ + if isinstance(stub, staticmethod): │ │ │ │ │ + # In older Python versions, staticmethod() isn't considered │ │ │ │ │ + # callable, doesn't have a name, and can't be introspected with │ │ │ │ │ + # inspect.signature(). Unwrap it. │ │ │ │ │ + stub = stub.__func__ │ │ │ │ │ + assert isinstance(stub, types.FunctionType) │ │ │ │ │ + name = stub.__name__ │ │ │ │ │ + signature = inspect.signature(stub) │ │ │ │ │ + stub_globals = sys.modules.get(cls.__module__).__dict__ │ │ │ │ │ │ │ │ │ │ + func = cdll[f'{cls.__name__}_{name.lstrip("_")}'] │ │ │ │ │ + func.argtypes = tuple( │ │ │ │ │ + map_type(parameter.annotation, stub_globals) │ │ │ │ │ + for parameter in signature.parameters.values() │ │ │ │ │ + ) │ │ │ │ │ + func.restype = map_type(signature.return_annotation, stub_globals) │ │ │ │ │ + errcheck = getattr(func.restype, 'errcheck', None) │ │ │ │ │ + if errcheck is not None: │ │ │ │ │ + func.errcheck = errcheck │ │ │ │ │ │ │ │ │ │ -class SshHostKeyPrompt(SSHAskpassPrompt): │ │ │ │ │ - _pattern = r"Are you sure you want to continue connecting \(yes/no(/\[fingerprint\])?\)\? " │ │ │ │ │ - _extra_patterns = [ │ │ │ │ │ - r"%{fingerprint}[.]$", │ │ │ │ │ - r"^%{algorithm} key fingerprint is", │ │ │ │ │ - r"^The fingerprint for the %{algorithm} key sent by the remote host is$" │ │ │ │ │ - ] │ │ │ │ │ - answers = ('yes', 'no') │ │ │ │ │ - algorithm: str │ │ │ │ │ - fingerprint: str │ │ │ │ │ + logger.debug(' create wrapper %s.%s%s', cls.__name__, name, signature) │ │ │ │ │ + logger.debug(' args %s res %s', func.argtypes, func.restype) │ │ │ │ │ │ │ │ │ │ - async def dispatch(self, responder: 'SshAskpassResponder') -> 'str | None': │ │ │ │ │ - return await responder.do_host_key_prompt(self) │ │ │ │ │ + # ctypes function pointer objects don't implement the usual function │ │ │ │ │ + # descriptor logic, which means they won't bind as methods. For static │ │ │ │ │ + # methods, that's good, but for instance methods, we add a wrapper as │ │ │ │ │ + # the easiest and most performant way to get the binding behaviour. │ │ │ │ │ + if stub_type is not staticmethod: │ │ │ │ │ + setattr(cls, name, lambda *args: func(*args)) │ │ │ │ │ + else: │ │ │ │ │ + setattr(cls, name, func) │ │ │ │ │ │ │ │ │ │ + def _unref(self: 'ReferenceType') -> None: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ -def with_helpers(pattern: str) -> str: │ │ │ │ │ - for name, helper in HELPERS.items(): │ │ │ │ │ - pattern = pattern.replace(name, helper) │ │ │ │ │ + def _ref(self: 'ReferenceType') -> None: │ │ │ │ │ + ... │ │ │ │ │ │ │ │ │ │ - assert '%{' not in pattern │ │ │ │ │ - return pattern │ │ │ │ │ + T = TypeVar("T", bound='ReferenceType') │ │ │ │ │ │ │ │ │ │ + @classmethod │ │ │ │ │ + def ref(cls: Type[T], origin: WeakReference) -> T: │ │ │ │ │ + self = cls(origin) │ │ │ │ │ + self._ref() │ │ │ │ │ + return self │ │ │ │ │ │ │ │ │ │ -def categorize_ssh_prompt(string: str, stderr: str) -> AskpassPrompt: │ │ │ │ │ - classes = [ │ │ │ │ │ - SshFIDOPINPrompt, │ │ │ │ │ - SshFIDOUserPresencePrompt, │ │ │ │ │ - SshHostKeyPrompt, │ │ │ │ │ - SshPKCS11PINPrompt, │ │ │ │ │ - SshPassphrasePrompt, │ │ │ │ │ - SshPasswordPrompt, │ │ │ │ │ - ] │ │ │ │ │ + def __del__(self) -> None: │ │ │ │ │ + if self.value is not None: │ │ │ │ │ + self._unref() │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/typing.py': br'''import typing │ │ │ │ │ +from typing import TYPE_CHECKING │ │ │ │ │ │ │ │ │ │ - # The last line is the line after the last newline character, excluding the │ │ │ │ │ - # optional final newline character. eg: "x\ny\nLAST\n" or "x\ny\nLAST" │ │ │ │ │ - second_last_newline = string.rfind('\n', 0, -1) │ │ │ │ │ - if second_last_newline >= 0: │ │ │ │ │ - last_line = string[second_last_newline + 1:] │ │ │ │ │ - extras = string[:second_last_newline + 1] │ │ │ │ │ - else: │ │ │ │ │ - last_line = string │ │ │ │ │ - extras = '' │ │ │ │ │ +# The goal here is to continue to work on Python 3.6 while pretending to have │ │ │ │ │ +# access to some modern typing features. The shims provided here are only │ │ │ │ │ +# enough for what we need for systemd_ctypes to work at runtime. │ │ │ │ │ │ │ │ │ │ - for cls in classes: │ │ │ │ │ - pattern = with_helpers(cls._pattern) │ │ │ │ │ - match = re.fullmatch(pattern, last_line) │ │ │ │ │ - if match is not None: │ │ │ │ │ - return cls(last_line, extras, stderr, match) │ │ │ │ │ │ │ │ │ │ - return AskpassPrompt(last_line, extras, stderr) │ │ │ │ │ +if TYPE_CHECKING: │ │ │ │ │ + # See https://github.com/python/mypy/issues/1153 for why we do this separately │ │ │ │ │ + from typing import Annotated, ForwardRef, TypeGuard, get_args, get_origin │ │ │ │ │ │ │ │ │ │ +else: │ │ │ │ │ + # typing.get_args() and .get_origin() appeared in Python 3.8 but Annotated │ │ │ │ │ + # arrived in 3.9. Unfortunately, it's difficult to implement a mocked up │ │ │ │ │ + # version of Annotated which works with the real typing.get_args() and │ │ │ │ │ + # .get_origin() in Python 3.8, so we use our own versions there as well. │ │ │ │ │ + try: │ │ │ │ │ + from typing import Annotated, get_args, get_origin │ │ │ │ │ + except ImportError: │ │ │ │ │ + class AnnotatedMeta(type): │ │ │ │ │ + def __getitem__(cls, params): │ │ │ │ │ + class AnnotatedType: │ │ │ │ │ + __origin__ = Annotated │ │ │ │ │ + __args__ = params │ │ │ │ │ + return AnnotatedType │ │ │ │ │ │ │ │ │ │ -class SshAskpassResponder(AskpassHandler): │ │ │ │ │ - async def do_askpass(self, stderr: str, prompt: str, hint: str) -> 'str | None': │ │ │ │ │ - return await categorize_ssh_prompt(prompt, stderr).dispatch(self) │ │ │ │ │ + class Annotated(metaclass=AnnotatedMeta): │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ - async def do_prompt(self, prompt: AskpassPrompt) -> 'str | None': │ │ │ │ │ - # Default fallback for unrecognised message types: unimplemented │ │ │ │ │ - return None │ │ │ │ │ + def get_args(annotation: typing.Any) -> typing.Tuple[typing.Any]: │ │ │ │ │ + return getattr(annotation, '__args__', ()) │ │ │ │ │ │ │ │ │ │ - async def do_fido_pin_prompt(self, prompt: SshFIDOPINPrompt) -> 'str | None': │ │ │ │ │ - return await self.do_prompt(prompt) │ │ │ │ │ + def get_origin(annotation: typing.Any) -> typing.Any: │ │ │ │ │ + return getattr(annotation, '__origin__', None) │ │ │ │ │ │ │ │ │ │ - async def do_fido_user_presence_prompt(self, prompt: SshFIDOUserPresencePrompt) -> 'str | None': │ │ │ │ │ - return await self.do_prompt(prompt) │ │ │ │ │ + try: │ │ │ │ │ + from typing import ForwardRef │ │ │ │ │ + except ImportError: │ │ │ │ │ + from typing import _ForwardRef as ForwardRef │ │ │ │ │ │ │ │ │ │ - async def do_host_key_prompt(self, prompt: SshHostKeyPrompt) -> 'str | None': │ │ │ │ │ - return await self.do_prompt(prompt) │ │ │ │ │ + try: │ │ │ │ │ + from typing import TypeGuard │ │ │ │ │ + except ImportError: │ │ │ │ │ + T = typing.TypeVar('T') │ │ │ │ │ │ │ │ │ │ - async def do_pkcs11_pin_prompt(self, prompt: SshPKCS11PINPrompt) -> 'str | None': │ │ │ │ │ - return await self.do_prompt(prompt) │ │ │ │ │ + class TypeGuard(typing.Generic[T]): │ │ │ │ │ + pass │ │ │ │ │ │ │ │ │ │ - async def do_passphrase_prompt(self, prompt: SshPassphrasePrompt) -> 'str | None': │ │ │ │ │ - return await self.do_prompt(prompt) │ │ │ │ │ │ │ │ │ │ - async def do_password_prompt(self, prompt: SshPasswordPrompt) -> 'str | None': │ │ │ │ │ - return await self.do_prompt(prompt) │ │ │ │ │ +__all__ = ( │ │ │ │ │ + 'Annotated', │ │ │ │ │ + 'ForwardRef', │ │ │ │ │ + 'TypeGuard', │ │ │ │ │ + 'get_args', │ │ │ │ │ + 'get_origin', │ │ │ │ │ + 'TYPE_CHECKING', │ │ │ │ │ +) │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/_vendor/ferny/session.py': r'''# ferny - asyncio SSH client library, using ssh(1) │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/__init__.py': br'''# systemd_ctypes │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ @@ -9332,197 +8928,177 @@ │ │ │ │ │ # 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import asyncio │ │ │ │ │ -import ctypes │ │ │ │ │ -import functools │ │ │ │ │ -import logging │ │ │ │ │ -import os │ │ │ │ │ -import shlex │ │ │ │ │ -import signal │ │ │ │ │ -import subprocess │ │ │ │ │ -import tempfile │ │ │ │ │ -from typing import Mapping, Sequence │ │ │ │ │ - │ │ │ │ │ -from . import ssh_errors │ │ │ │ │ -from .interaction_agent import InteractionAgent, InteractionError, InteractionHandler, write_askpass_to_tmpdir │ │ │ │ │ - │ │ │ │ │ -prctl = ctypes.cdll.LoadLibrary('libc.so.6').prctl │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ -PR_SET_PDEATHSIG = 1 │ │ │ │ │ +"""systemd_ctypes""" │ │ │ │ │ │ │ │ │ │ +__version__ = "0" │ │ │ │ │ │ │ │ │ │ -@functools.lru_cache() │ │ │ │ │ -def has_feature(feature: str, teststr: str = 'x') -> bool: │ │ │ │ │ - try: │ │ │ │ │ - subprocess.check_output(['ssh', f'-o{feature} {teststr}', '-G', 'nonexisting'], stderr=subprocess.DEVNULL) │ │ │ │ │ - return True │ │ │ │ │ - except subprocess.CalledProcessError: │ │ │ │ │ - return False │ │ │ │ │ +from .bus import Bus, BusError, BusMessage │ │ │ │ │ +from .bustypes import BusType, JSONEncoder, Variant │ │ │ │ │ +from .event import Event, EventLoopPolicy, run_async │ │ │ │ │ +from .pathwatch import Handle, PathWatch │ │ │ │ │ │ │ │ │ │ +__all__ = [ │ │ │ │ │ + "Bus", │ │ │ │ │ + "BusError", │ │ │ │ │ + "BusMessage", │ │ │ │ │ + "BusType", │ │ │ │ │ + "Event", │ │ │ │ │ + "EventLoopPolicy", │ │ │ │ │ + "Handle", │ │ │ │ │ + "JSONEncoder", │ │ │ │ │ + "PathWatch", │ │ │ │ │ + "Variant", │ │ │ │ │ + "run_async", │ │ │ │ │ +] │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/event.py': br'''# systemd_ctypes │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Allison Karlitskaya │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -class SubprocessContext: │ │ │ │ │ - def wrap_subprocess_args(self, args: Sequence[str]) -> Sequence[str]: │ │ │ │ │ - """Return the args required to launch a process in the given context. │ │ │ │ │ +import asyncio │ │ │ │ │ +import selectors │ │ │ │ │ +import sys │ │ │ │ │ +from typing import Callable, ClassVar, Coroutine, List, Optional, Tuple │ │ │ │ │ │ │ │ │ │ - For example, this might return a vector with │ │ │ │ │ - ["sudo"] │ │ │ │ │ - or │ │ │ │ │ - ["flatpak-spawn", "--host"] │ │ │ │ │ - prepended. │ │ │ │ │ +from . import inotify, libsystemd │ │ │ │ │ +from .librarywrapper import Reference, UserData, byref │ │ │ │ │ │ │ │ │ │ - It is also possible that more substantial changes may be performed. │ │ │ │ │ │ │ │ │ │ - This function is not permitted to modify its argument, although it may │ │ │ │ │ - (optionally) return it unmodified, if no changes are required. │ │ │ │ │ - """ │ │ │ │ │ - return args │ │ │ │ │ +class Event(libsystemd.sd_event): │ │ │ │ │ + class Source(libsystemd.sd_event_source): │ │ │ │ │ + def cancel(self) -> None: │ │ │ │ │ + self._unref() │ │ │ │ │ + self.value = None │ │ │ │ │ │ │ │ │ │ - def wrap_subprocess_env(self, env: Mapping[str, str]) -> Mapping[str, str]: │ │ │ │ │ - """Return the envp required to launch a process in the given context. │ │ │ │ │ + _default_instance: ClassVar[Optional['Event']] = None │ │ │ │ │ │ │ │ │ │ - For example, this might set the "SUDO_ASKPASS" environment variable, if │ │ │ │ │ - needed. │ │ │ │ │ + @staticmethod │ │ │ │ │ + def default() -> 'Event': │ │ │ │ │ + if Event._default_instance is None: │ │ │ │ │ + Event._default_instance = Event() │ │ │ │ │ + Event._default(byref(Event._default_instance)) │ │ │ │ │ + return Event._default_instance │ │ │ │ │ │ │ │ │ │ - As with wrap_subprocess_args(), this function is not permitted to │ │ │ │ │ - modify its argument, although it may (optionally) return it unmodified │ │ │ │ │ - if no changes are required. │ │ │ │ │ - """ │ │ │ │ │ - return env │ │ │ │ │ + InotifyHandler = Callable[[inotify.Event, int, Optional[bytes]], None] │ │ │ │ │ │ │ │ │ │ + class InotifySource(Source): │ │ │ │ │ + def __init__(self, handler: 'Event.InotifyHandler') -> None: │ │ │ │ │ + def callback(source: libsystemd.sd_event_source, │ │ │ │ │ + _event: Reference[inotify.inotify_event], │ │ │ │ │ + userdata: UserData) -> int: │ │ │ │ │ + event = _event.contents │ │ │ │ │ + handler(inotify.Event(event.mask), event.cookie, event.name) │ │ │ │ │ + return 0 │ │ │ │ │ + self.trampoline = libsystemd.sd_event_inotify_handler_t(callback) │ │ │ │ │ │ │ │ │ │ -class Session(SubprocessContext, InteractionHandler): │ │ │ │ │ - # Set after .connect() called, even if failed │ │ │ │ │ - _controldir: 'tempfile.TemporaryDirectory | None' = None │ │ │ │ │ - _controlsock: 'str | None' = None │ │ │ │ │ + def add_inotify(self, path: str, mask: inotify.Event, handler: InotifyHandler) -> InotifySource: │ │ │ │ │ + source = Event.InotifySource(handler) │ │ │ │ │ + self._add_inotify(byref(source), path, mask, source.trampoline, source.userdata) │ │ │ │ │ + return source │ │ │ │ │ │ │ │ │ │ - # Set if connected, else None │ │ │ │ │ - _process: 'asyncio.subprocess.Process | None' = None │ │ │ │ │ + def add_inotify_fd(self, fd: int, mask: inotify.Event, handler: InotifyHandler) -> InotifySource: │ │ │ │ │ + # HACK: sd_event_add_inotify_fd() got added in 250, which is too new. Fake it. │ │ │ │ │ + return self.add_inotify(f'/proc/self/fd/{fd}', mask, handler) │ │ │ │ │ │ │ │ │ │ - async def connect(self, │ │ │ │ │ - destination: str, │ │ │ │ │ - handle_host_key: bool = False, │ │ │ │ │ - configfile: 'str | None' = None, │ │ │ │ │ - identity_file: 'str | None' = None, │ │ │ │ │ - login_name: 'str | None' = None, │ │ │ │ │ - options: 'Mapping[str, str] | None' = None, │ │ │ │ │ - pkcs11: 'str | None' = None, │ │ │ │ │ - port: 'int | None' = None, │ │ │ │ │ - interaction_responder: 'InteractionHandler | None' = None) -> None: │ │ │ │ │ - rundir = os.path.join(os.environ.get('XDG_RUNTIME_DIR', '/run'), 'ferny') │ │ │ │ │ - os.makedirs(rundir, exist_ok=True) │ │ │ │ │ - self._controldir = tempfile.TemporaryDirectory(dir=rundir) │ │ │ │ │ - self._controlsock = f'{self._controldir.name}/socket' │ │ │ │ │ │ │ │ │ │ - # In general, we can't guarantee an accessible and executable version │ │ │ │ │ - # of this file, but since it's small and we're making a temporary │ │ │ │ │ - # directory anyway, let's just copy it into place and use it from │ │ │ │ │ - # there. │ │ │ │ │ - askpass_path = write_askpass_to_tmpdir(self._controldir.name) │ │ │ │ │ +# This is all a bit more awkward than it should have to be: systemd's event │ │ │ │ │ +# loop chaining model is designed for glib's prepare/check/dispatch paradigm; │ │ │ │ │ +# failing to call prepare() can lead to deadlocks, for example. │ │ │ │ │ +# │ │ │ │ │ +# Hack a selector subclass which calls prepare() before sleeping and this for us. │ │ │ │ │ +class Selector(selectors.DefaultSelector): │ │ │ │ │ + def __init__(self, event: Optional[Event] = None) -> None: │ │ │ │ │ + super().__init__() │ │ │ │ │ + self.sd_event = event or Event.default() │ │ │ │ │ + self.key = self.register(self.sd_event.get_fd(), selectors.EVENT_READ) │ │ │ │ │ │ │ │ │ │ - env = dict(os.environ) │ │ │ │ │ - env['SSH_ASKPASS'] = askpass_path │ │ │ │ │ - env['SSH_ASKPASS_REQUIRE'] = 'force' │ │ │ │ │ - # old SSH doesn't understand SSH_ASKPASS_REQUIRE and guesses based on DISPLAY instead │ │ │ │ │ - env['DISPLAY'] = '-' │ │ │ │ │ + def select( │ │ │ │ │ + self, timeout: Optional[float] = None │ │ │ │ │ + ) -> List[Tuple[selectors.SelectorKey, int]]: │ │ │ │ │ + # It's common to drop the last reference to a Source or Slot object on │ │ │ │ │ + # a dispatch of that same source/slot from the main loop. If we happen │ │ │ │ │ + # to garbage collect before returning, the trampoline could be │ │ │ │ │ + # destroyed before we're done using it. Provide a mechanism to defer │ │ │ │ │ + # the destruction of trampolines for as long as we might be │ │ │ │ │ + # dispatching. This gets cleared again at the bottom, before return. │ │ │ │ │ + libsystemd.Trampoline.deferred = [] │ │ │ │ │ │ │ │ │ │ - args = [ │ │ │ │ │ - '-M', │ │ │ │ │ - '-N', │ │ │ │ │ - '-S', self._controlsock, │ │ │ │ │ - '-o', 'PermitLocalCommand=yes', │ │ │ │ │ - '-o', f'LocalCommand={askpass_path}', │ │ │ │ │ - ] │ │ │ │ │ + while self.sd_event.prepare(): │ │ │ │ │ + self.sd_event.dispatch() │ │ │ │ │ + ready = super().select(timeout) │ │ │ │ │ + # workaround https://github.com/systemd/systemd/issues/23826 │ │ │ │ │ + # keep calling wait() until there's nothing left │ │ │ │ │ + while self.sd_event.wait(0): │ │ │ │ │ + self.sd_event.dispatch() │ │ │ │ │ + while self.sd_event.prepare(): │ │ │ │ │ + self.sd_event.dispatch() │ │ │ │ │ │ │ │ │ │ - if configfile is not None: │ │ │ │ │ - args.append(f'-F{configfile}') │ │ │ │ │ + # We can be sure we're not dispatching callbacks anymore │ │ │ │ │ + libsystemd.Trampoline.deferred = None │ │ │ │ │ │ │ │ │ │ - if identity_file is not None: │ │ │ │ │ - args.append(f'-i{identity_file}') │ │ │ │ │ + # This could return zero events with infinite timeout, but nobody seems to mind. │ │ │ │ │ + return [(key, events) for (key, events) in ready if key != self.key] │ │ │ │ │ │ │ │ │ │ - if options is not None: │ │ │ │ │ - for key in options: # Note: Mapping may not have .items() │ │ │ │ │ - args.append(f'-o{key} {options[key]}') │ │ │ │ │ │ │ │ │ │ - if pkcs11 is not None: │ │ │ │ │ - args.append(f'-I{pkcs11}') │ │ │ │ │ +class EventLoopPolicy(asyncio.DefaultEventLoopPolicy): │ │ │ │ │ + def new_event_loop(self) -> asyncio.AbstractEventLoop: │ │ │ │ │ + return asyncio.SelectorEventLoop(Selector()) │ │ │ │ │ │ │ │ │ │ - if port is not None: │ │ │ │ │ - args.append(f'-p{port}') │ │ │ │ │ │ │ │ │ │ - if login_name is not None: │ │ │ │ │ - args.append(f'-l{login_name}') │ │ │ │ │ +def run_async(main: Coroutine[None, None, None], debug: Optional[bool] = None) -> None: │ │ │ │ │ + asyncio.set_event_loop_policy(EventLoopPolicy()) │ │ │ │ │ │ │ │ │ │ - if handle_host_key and has_feature('KnownHostsCommand'): │ │ │ │ │ - args.extend([ │ │ │ │ │ - '-o', f'KnownHostsCommand={askpass_path} %I %H %t %K %f', │ │ │ │ │ - '-o', 'StrictHostKeyChecking=yes', │ │ │ │ │ - ]) │ │ │ │ │ + polyfill = sys.version_info < (3, 7, 0) and not hasattr(asyncio, 'run') │ │ │ │ │ + if polyfill: │ │ │ │ │ + # Polyfills for Python 3.6: │ │ │ │ │ + loop = asyncio.get_event_loop() │ │ │ │ │ │ │ │ │ │ - agent = InteractionAgent([interaction_responder] if interaction_responder is not None else []) │ │ │ │ │ + assert not hasattr(asyncio, 'get_running_loop') │ │ │ │ │ + asyncio.get_running_loop = lambda: loop │ │ │ │ │ │ │ │ │ │ - # SSH_ASKPASS_REQUIRE is not generally available, so use setsid │ │ │ │ │ - process = await asyncio.create_subprocess_exec( │ │ │ │ │ - *('/usr/bin/ssh', *args, destination), env=env, │ │ │ │ │ - start_new_session=True, stdin=asyncio.subprocess.DEVNULL, │ │ │ │ │ - stdout=asyncio.subprocess.DEVNULL, stderr=agent, # type: ignore │ │ │ │ │ - preexec_fn=lambda: prctl(PR_SET_PDEATHSIG, signal.SIGKILL)) │ │ │ │ │ + assert not hasattr(asyncio, 'create_task') │ │ │ │ │ + asyncio.create_task = loop.create_task │ │ │ │ │ │ │ │ │ │ - # This is tricky: we need to clean up the subprocess, but only in case │ │ │ │ │ - # if failure. Otherwise, we keep it around. │ │ │ │ │ - try: │ │ │ │ │ - await agent.communicate() │ │ │ │ │ - assert os.path.exists(self._controlsock) │ │ │ │ │ - self._process = process │ │ │ │ │ - except InteractionError as exc: │ │ │ │ │ - await process.wait() │ │ │ │ │ - raise ssh_errors.get_exception_for_ssh_stderr(str(exc)) from None │ │ │ │ │ - except BaseException: │ │ │ │ │ - # If we get here because the InteractionHandler raised an │ │ │ │ │ - # exception then SSH might still be running, and may even attempt │ │ │ │ │ - # further interactions (ie: 2nd attempt for password). We already │ │ │ │ │ - # have our exception and don't need any more info. Kill it. │ │ │ │ │ - try: │ │ │ │ │ - process.kill() │ │ │ │ │ - except ProcessLookupError: │ │ │ │ │ - pass # already exited? good. │ │ │ │ │ - await process.wait() │ │ │ │ │ - raise │ │ │ │ │ + assert not hasattr(asyncio, 'run') │ │ │ │ │ │ │ │ │ │ - def is_connected(self) -> bool: │ │ │ │ │ - return self._process is not None │ │ │ │ │ + def run( │ │ │ │ │ + main: Coroutine[None, None, None], debug: Optional[bool] = None │ │ │ │ │ + ) -> None: │ │ │ │ │ + if debug is not None: │ │ │ │ │ + loop.set_debug(debug) │ │ │ │ │ + loop.run_until_complete(main) │ │ │ │ │ │ │ │ │ │ - async def wait(self) -> None: │ │ │ │ │ - assert self._process is not None │ │ │ │ │ - await self._process.wait() │ │ │ │ │ + asyncio.run = run # type: ignore[assignment] │ │ │ │ │ │ │ │ │ │ - def exit(self) -> None: │ │ │ │ │ - assert self._process is not None │ │ │ │ │ - self._process.terminate() │ │ │ │ │ + asyncio._systemd_ctypes_polyfills = True # type: ignore[attr-defined] │ │ │ │ │ │ │ │ │ │ - async def disconnect(self) -> None: │ │ │ │ │ - self.exit() │ │ │ │ │ - await self.wait() │ │ │ │ │ + asyncio.run(main, debug=debug) │ │ │ │ │ │ │ │ │ │ - # Launching of processes │ │ │ │ │ - def wrap_subprocess_args(self, args: Sequence[str]) -> Sequence[str]: │ │ │ │ │ - assert self._controlsock is not None │ │ │ │ │ - # 1. We specify the hostname as the empty string: it will be ignored │ │ │ │ │ - # when ssh is trying to use the control socket, but in case the │ │ │ │ │ - # socket has stopped working, ssh will try to fall back to directly │ │ │ │ │ - # connecting, in which case an empty hostname will prevent that. │ │ │ │ │ - # 2. We need to quote the arguments — ssh will paste them together │ │ │ │ │ - # using only spaces, executing the result using the user's shell. │ │ │ │ │ - return ('ssh', '-S', self._controlsock, '', *map(shlex.quote, args)) │ │ │ │ │ -'''.encode('utf-8'), │ │ │ │ │ - 'cockpit/_vendor/ferny/ssh_errors.py': br'''# ferny - asyncio SSH client library, using ssh(1) │ │ │ │ │ + if polyfill: │ │ │ │ │ + del asyncio.create_task, asyncio.get_running_loop, asyncio.run │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/_vendor/systemd_ctypes/bustypes.py': br'''# systemd_ctypes │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2023 Allison Karlitskaya │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ @@ -9531,124 +9107,548 @@ │ │ │ │ │ # 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ + │ │ │ │ │ +# This file is responsible for creating functions to (de)serialize Python │ │ │ │ │ +# objects into and out of BusMessage objects. │ │ │ │ │ +# │ │ │ │ │ +# Each Type corresponds to a (possibly complex) D-Bus type. It has a .reader │ │ │ │ │ +# and a .writer property. The readers take a message and deserialize a single │ │ │ │ │ +# value from it, returning the value: │ │ │ │ │ +# │ │ │ │ │ +# def reader(message: BusMessage) -> object: │ │ │ │ │ +# │ │ │ │ │ +# The writers take a message and a value, and append the value to the message. │ │ │ │ │ +# │ │ │ │ │ +# def writer(message: BusMessage, value: object) -> None: │ │ │ │ │ +# │ │ │ │ │ +# The necessary information for the specific type of object to be handled is │ │ │ │ │ +# part of the function. No additional information needs to be provided. │ │ │ │ │ + │ │ │ │ │ +import binascii │ │ │ │ │ import ctypes │ │ │ │ │ -import errno │ │ │ │ │ -import os │ │ │ │ │ +import functools │ │ │ │ │ +import inspect │ │ │ │ │ +import json │ │ │ │ │ import re │ │ │ │ │ -import socket │ │ │ │ │ -from typing import ClassVar, Iterable, Match, Pattern │ │ │ │ │ +from enum import Enum │ │ │ │ │ +from typing import Any, Callable, ClassVar, Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union │ │ │ │ │ │ │ │ │ │ +from . import libsystemd, typing │ │ │ │ │ +from .typing import Annotated, TypeGuard │ │ │ │ │ │ │ │ │ │ -class SshError(Exception): │ │ │ │ │ - PATTERN: ClassVar[Pattern] │ │ │ │ │ +_object_path_re = re.compile(r'/|(/[A-Za-z0-9_]+)+') │ │ │ │ │ │ │ │ │ │ - def __init__(self, match: 'Match | None', stderr: str) -> None: │ │ │ │ │ - super().__init__(match.group(0) if match is not None else stderr) │ │ │ │ │ - self.stderr = stderr │ │ │ │ │ │ │ │ │ │ +def is_object_path(candidate: str) -> TypeGuard['BusType.objectpath']: │ │ │ │ │ + return _object_path_re.fullmatch(candidate) is not None │ │ │ │ │ │ │ │ │ │ -class SshAuthenticationError(SshError): │ │ │ │ │ - PATTERN = re.compile(r'^([^:]+): Permission denied \(([^()]+)\)\.$', re.M) │ │ │ │ │ │ │ │ │ │ - def __init__(self, match: Match, stderr: str) -> None: │ │ │ │ │ - super().__init__(match, stderr) │ │ │ │ │ - self.destination = match.group(1) │ │ │ │ │ - self.methods = match.group(2).split(',') │ │ │ │ │ - self.message = match.group(0) │ │ │ │ │ +def is_signature(candidate: str) -> TypeGuard['BusType.signature']: │ │ │ │ │ + offset = 0 │ │ │ │ │ + │ │ │ │ │ + def maybe_pop(acceptable: str) -> Optional[str]: │ │ │ │ │ + nonlocal offset │ │ │ │ │ + char = candidate[offset] │ │ │ │ │ + if char in acceptable: │ │ │ │ │ + offset += 1 │ │ │ │ │ + return char │ │ │ │ │ + else: │ │ │ │ │ + return None │ │ │ │ │ │ │ │ │ │ + def pop(acceptable: str) -> str: │ │ │ │ │ + char = maybe_pop(acceptable) │ │ │ │ │ + assert char is not None │ │ │ │ │ + return char │ │ │ │ │ │ │ │ │ │ -# generic host key error for OSes without KnownHostsCommand support │ │ │ │ │ -class SshHostKeyError(SshError): │ │ │ │ │ - PATTERN = re.compile(r'^Host key verification failed.$', re.M) │ │ │ │ │ + def find_next() -> None: │ │ │ │ │ + first = pop('ybnqiuxtsogdva(') # valid first characters │ │ │ │ │ + if first == 'a': │ │ │ │ │ + if maybe_pop('{'): # dict │ │ │ │ │ + pop('ybnqiuxtsogd') # key │ │ │ │ │ + find_next() # value │ │ │ │ │ + pop('}') │ │ │ │ │ + else: # array │ │ │ │ │ + find_next() # item │ │ │ │ │ + elif first == '(': # structure │ │ │ │ │ + find_next() # at least one item │ │ │ │ │ + while not maybe_pop(')'): │ │ │ │ │ + find_next() # and possibly more │ │ │ │ │ │ │ │ │ │ + try: │ │ │ │ │ + while offset < len(candidate): │ │ │ │ │ + find_next() │ │ │ │ │ + return True │ │ │ │ │ + except (AssertionError, IndexError): │ │ │ │ │ + return False │ │ │ │ │ │ │ │ │ │ -# specific errors for OSes with KnownHostsCommand │ │ │ │ │ -class SshUnknownHostKeyError(SshHostKeyError): │ │ │ │ │ - PATTERN = re.compile(r'^No .* host key is known.*Host key verification failed.$', re.S | re.M) │ │ │ │ │ │ │ │ │ │ +def yield_base_helpers() -> Iterable[Tuple[str, object]]: │ │ │ │ │ + for method in ['enter_container', 'exit_container', 'open_container', 'close_container', │ │ │ │ │ + 'append_basic', 'read_basic', 'append_array', 'read_array']: │ │ │ │ │ + yield method, libsystemd.libsystemd[f'sd_bus_message_{method}'] │ │ │ │ │ │ │ │ │ │ -class SshChangedHostKeyError(SshHostKeyError): │ │ │ │ │ - PATTERN = re.compile(r'warning.*remote host identification has changed', re.I) │ │ │ │ │ + for name in ['size_t', 'char_p']: │ │ │ │ │ + instance = getattr(ctypes, f'c_{name}')() │ │ │ │ │ + yield f'{name}', instance │ │ │ │ │ + yield f'{name}_ref', ctypes.byref(instance) │ │ │ │ │ + yield f'{name}_setter', instance.__class__.value.__set__ │ │ │ │ │ │ │ │ │ │ + for char in 'aervy': │ │ │ │ │ + yield char, ctypes.c_char(ord(char)) │ │ │ │ │ │ │ │ │ │ -# Functionality for mapping getaddrinfo()-family error messages to their │ │ │ │ │ -# equivalent Python exceptions. │ │ │ │ │ -def make_gaierror_map() -> 'Iterable[tuple[str, int]]': │ │ │ │ │ - libc = ctypes.CDLL(None) │ │ │ │ │ - libc.gai_strerror.restype = ctypes.c_char_p │ │ │ │ │ + # https://docs.python.org/3/c-api/unicode.html#c.PyUnicode_FromString │ │ │ │ │ + to_bytes = ctypes.pythonapi.PyBytes_FromStringAndSize │ │ │ │ │ + to_bytes.restype = ctypes.py_object │ │ │ │ │ + yield 'to_bytes', to_bytes │ │ │ │ │ │ │ │ │ │ - for key in dir(socket): │ │ │ │ │ - if key.startswith('EAI_'): │ │ │ │ │ - errnum = getattr(socket, key) │ │ │ │ │ - yield libc.gai_strerror(errnum).decode('utf-8'), errnum │ │ │ │ │ │ │ │ │ │ +_base_helpers = dict(yield_base_helpers()) │ │ │ │ │ │ │ │ │ │ -gaierror_map = dict(make_gaierror_map()) │ │ │ │ │ +T = TypeVar('T') │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -# Functionality for passing strerror() error messages to their equivalent │ │ │ │ │ -# Python exceptions. │ │ │ │ │ -# There doesn't seem to be an official API for turning an errno into the │ │ │ │ │ -# correct subtype of OSError, and the list that cpython uses is hidden fairly │ │ │ │ │ -# deeply inside of the implementation. This is basically copied from the │ │ │ │ │ -# ADD_ERRNO() lines in _PyExc_InitState in cpython/Objects/exceptions.c │ │ │ │ │ -oserror_subclass_map = dict((errnum, cls) for cls, errnum in [ │ │ │ │ │ - (BlockingIOError, errno.EAGAIN), │ │ │ │ │ - (BlockingIOError, errno.EALREADY), │ │ │ │ │ - (BlockingIOError, errno.EINPROGRESS), │ │ │ │ │ - (BlockingIOError, errno.EWOULDBLOCK), │ │ │ │ │ - (BrokenPipeError, errno.EPIPE), │ │ │ │ │ - (BrokenPipeError, errno.ESHUTDOWN), │ │ │ │ │ - (ChildProcessError, errno.ECHILD), │ │ │ │ │ - (ConnectionAbortedError, errno.ECONNABORTED), │ │ │ │ │ - (ConnectionRefusedError, errno.ECONNREFUSED), │ │ │ │ │ - (ConnectionResetError, errno.ECONNRESET), │ │ │ │ │ - (FileExistsError, errno.EEXIST), │ │ │ │ │ - (FileNotFoundError, errno.ENOENT), │ │ │ │ │ - (IsADirectoryError, errno.EISDIR), │ │ │ │ │ - (NotADirectoryError, errno.ENOTDIR), │ │ │ │ │ - (InterruptedError, errno.EINTR), │ │ │ │ │ - (PermissionError, errno.EACCES), │ │ │ │ │ - (PermissionError, errno.EPERM), │ │ │ │ │ - (ProcessLookupError, errno.ESRCH), │ │ │ │ │ - (TimeoutError, errno.ETIMEDOUT), │ │ │ │ │ -]) │ │ │ │ │ +def call_with_kwargs(func: Callable[..., T], kwargs: Dict[str, Any]) -> T: │ │ │ │ │ + parameters = set(inspect.signature(func).parameters) │ │ │ │ │ + return func(**{key: value for key, value in kwargs.items() if key in parameters}) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -def get_exception_for_ssh_stderr(stderr: str) -> Exception: │ │ │ │ │ - stderr = stderr.replace('\r\n', '\n') # fix line separators │ │ │ │ │ +class Type: │ │ │ │ │ + _cache: ClassVar[Dict[Tuple[type, Tuple[object, ...]], 'Type']] = {} │ │ │ │ │ │ │ │ │ │ - # check for the specific error messages first, then for generic SshHostKeyError │ │ │ │ │ - for ssh_cls in [SshAuthenticationError, SshChangedHostKeyError, SshUnknownHostKeyError, SshHostKeyError]: │ │ │ │ │ - match = ssh_cls.PATTERN.search(stderr) │ │ │ │ │ - if match is not None: │ │ │ │ │ - return ssh_cls(match, stderr) │ │ │ │ │ + __slots__ = 'typestring', 'bytes_typestring', 'writer', 'reader' │ │ │ │ │ + typestring: str │ │ │ │ │ + bytes_typestring: bytes │ │ │ │ │ + reader: Callable[[libsystemd.sd_bus_message], object] │ │ │ │ │ + writer: Callable[[libsystemd.sd_bus_message, object], None] │ │ │ │ │ │ │ │ │ │ - before, colon, after = stderr.rpartition(':') │ │ │ │ │ - if colon and after: │ │ │ │ │ - potential_strerror = after.strip() │ │ │ │ │ + def __new__(cls, *args: Any) -> 'Type': │ │ │ │ │ + instance = Type._cache.get((cls, args)) │ │ │ │ │ + if instance is None: │ │ │ │ │ + instance = object.__new__(cls) │ │ │ │ │ + Type._cache[(cls, args)] = instance │ │ │ │ │ + return instance │ │ │ │ │ │ │ │ │ │ - # DNS lookup errors │ │ │ │ │ - if potential_strerror in gaierror_map: │ │ │ │ │ - errnum = gaierror_map[potential_strerror] │ │ │ │ │ - return socket.gaierror(errnum, stderr) │ │ │ │ │ + def __init__(self, typestring: str, **kwargs: Any): │ │ │ │ │ + self.typestring = typestring │ │ │ │ │ + self.bytes_typestring = typestring.encode('ascii') │ │ │ │ │ │ │ │ │ │ - # Network connect errors │ │ │ │ │ - for errnum in errno.errorcode: │ │ │ │ │ - if os.strerror(errnum) == potential_strerror: │ │ │ │ │ - os_cls = oserror_subclass_map.get(errnum, OSError) │ │ │ │ │ - return os_cls(errnum, stderr) │ │ │ │ │ + kwargs = dict(_base_helpers, **kwargs) │ │ │ │ │ + self.writer = call_with_kwargs(self.get_writer, kwargs) │ │ │ │ │ + self.reader = call_with_kwargs(self.get_reader, kwargs) │ │ │ │ │ │ │ │ │ │ - # No match? Generic. │ │ │ │ │ - return SshError(None, stderr) │ │ │ │ │ + def __repr__(self) -> str: │ │ │ │ │ + return f"{self.__class__.__name__}('{self.typestring}')" │ │ │ │ │ + │ │ │ │ │ + def get_writer(self, **kwargs: object) -> Callable[[object, object], None]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + def get_reader(self, **kwargs: object) -> Callable[[object], object]: │ │ │ │ │ + raise NotImplementedError │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class BasicType(Type): │ │ │ │ │ + __slots__ = () │ │ │ │ │ + │ │ │ │ │ + def __init__(self, typestring: str, ctype, get_wrapper=None, **kwargs): │ │ │ │ │ + variable = ctype() # NB: not thread-safe │ │ │ │ │ + super().__init__(typestring, ctype=ctype, type_constant=ctypes.c_char(ord(typestring)), │ │ │ │ │ + getter=get_wrapper or ctype.value.__get__, setter=ctype.value.__set__, │ │ │ │ │ + variable=variable, reference=ctypes.byref(variable), **kwargs) │ │ │ │ │ + │ │ │ │ │ + def get_reader(self, read_basic, type_constant, variable, reference, getter): │ │ │ │ │ + def basic_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ + if read_basic(message, type_constant, reference) <= 0: │ │ │ │ │ + raise StopIteration │ │ │ │ │ + return getter(variable) │ │ │ │ │ + return basic_reader │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class FixedType(BasicType): │ │ │ │ │ + __slots__ = () │ │ │ │ │ + │ │ │ │ │ + def get_writer(self, append_basic, type_constant, variable, reference, setter, getter): │ │ │ │ │ + def fixed_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ + setter(variable, value) │ │ │ │ │ + if getter(variable) != value: │ │ │ │ │ + raise TypeError(f"Cannot represent value {value} with type '{self.typestring}'") │ │ │ │ │ + append_basic(message, type_constant, reference) │ │ │ │ │ + return fixed_writer │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class StringLikeType(BasicType): │ │ │ │ │ + __slots__ = () │ │ │ │ │ + │ │ │ │ │ + @staticmethod │ │ │ │ │ + def get_guarded_conversion(typestring: str, guard: Callable[[str], bool]) -> Callable[[object], bytes]: │ │ │ │ │ + def convert(candidate: object) -> bytes: │ │ │ │ │ + if not isinstance(candidate, str): │ │ │ │ │ + raise TypeError(f"'{typestring}' encodes 'str', not '{candidate.__class__.__name__}'") │ │ │ │ │ + if not guard(candidate): │ │ │ │ │ + raise ValueError(f"Invalid value provided for type '{typestring}'") │ │ │ │ │ + return str.encode(candidate) │ │ │ │ │ + return convert │ │ │ │ │ + │ │ │ │ │ + def __init__(self, typestring: str, guard: Optional[Callable[[str], bool]] = None): │ │ │ │ │ + # https://docs.python.org/3/c-api/unicode.html#c.PyUnicode_FromString │ │ │ │ │ + to_unicode = ctypes.pythonapi.PyUnicode_FromString │ │ │ │ │ + to_unicode.restype = ctypes.py_object │ │ │ │ │ + │ │ │ │ │ + if guard is not None: │ │ │ │ │ + convert = StringLikeType.get_guarded_conversion(typestring, guard) │ │ │ │ │ + else: │ │ │ │ │ + convert = str.encode # type: ignore[assignment] # can throw TypeError on call │ │ │ │ │ + │ │ │ │ │ + super().__init__(typestring, ctypes.c_char_p, to_unicode, convert=convert) │ │ │ │ │ + │ │ │ │ │ + def get_writer(self, append_basic, type_constant, convert): │ │ │ │ │ + def string_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ + append_basic(message, type_constant, convert(value)) │ │ │ │ │ + return string_writer │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class BytestringType(Type): │ │ │ │ │ + __slots__ = () │ │ │ │ │ + │ │ │ │ │ + def get_writer(self, append_array, y, size_t_setter, size_t): │ │ │ │ │ + def bytes_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ + if not isinstance(value, bytes): │ │ │ │ │ + if isinstance(value, str): │ │ │ │ │ + try: │ │ │ │ │ + value = binascii.a2b_base64(value.encode('ascii')) # or decode base64 │ │ │ │ │ + except binascii.Error as exc: │ │ │ │ │ + raise ValueError("'ay' cannot encode invalid base64 string") from exc │ │ │ │ │ + elif isinstance(value, (memoryview, bytearray)): │ │ │ │ │ + value = bytes(value) │ │ │ │ │ + else: │ │ │ │ │ + raise TypeError("'ay' can only encode bytes-like or base64 string objects, " │ │ │ │ │ + f"not '{value.__class__.__name__}'.") │ │ │ │ │ + size_t_setter(size_t, len(value)) │ │ │ │ │ + append_array(message, y, value, size_t) │ │ │ │ │ + return bytes_writer │ │ │ │ │ + │ │ │ │ │ + def get_reader(self, read_array, y, to_bytes, char_p, char_p_ref, size_t, size_t_ref): │ │ │ │ │ + def bytes_reader(message): │ │ │ │ │ + if read_array(message, y, char_p_ref, size_t_ref) <= 0: │ │ │ │ │ + raise StopIteration │ │ │ │ │ + return to_bytes(char_p, size_t) │ │ │ │ │ + return bytes_reader │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class ContainerType(Type): │ │ │ │ │ + _typestring_template: ClassVar[str] │ │ │ │ │ + __slots__ = 'item_types' │ │ │ │ │ + item_types: Sequence[Type] │ │ │ │ │ + │ │ │ │ │ + def __init__(self, *item_types: Type, **kwargs: Any): │ │ │ │ │ + assert len(item_types) > 0 │ │ │ │ │ + item_typestrings = ''.join(item.typestring for item in item_types) │ │ │ │ │ + self.item_types = item_types │ │ │ │ │ + super().__init__(self._typestring_template.replace('_', item_typestrings), │ │ │ │ │ + type_contents=ctypes.c_char_p(item_typestrings.encode('ascii')), │ │ │ │ │ + **kwargs) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class ArrayType(ContainerType): │ │ │ │ │ + _typestring_template = 'a_' │ │ │ │ │ + __slots__ = () │ │ │ │ │ + │ │ │ │ │ + def __init__(self, item_type: Type): │ │ │ │ │ + super().__init__(item_type, │ │ │ │ │ + item_writer=item_type.writer, │ │ │ │ │ + item_reader=item_type.reader, │ │ │ │ │ + list_append=list.append) │ │ │ │ │ + │ │ │ │ │ + def get_reader(self, enter_container, exit_container, list_append, item_reader): │ │ │ │ │ + def array_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ + if enter_container(message, 0, None) <= 0: │ │ │ │ │ + raise StopIteration │ │ │ │ │ + result: List[object] = [] │ │ │ │ │ + try: │ │ │ │ │ + while True: │ │ │ │ │ + list_append(result, item_reader(message)) │ │ │ │ │ + except StopIteration: │ │ │ │ │ + return result │ │ │ │ │ + finally: │ │ │ │ │ + exit_container(message) │ │ │ │ │ + return array_reader │ │ │ │ │ + │ │ │ │ │ + def get_writer(self, a, type_contents, open_container, close_container, item_writer): │ │ │ │ │ + def array_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ + open_container(message, a, type_contents) │ │ │ │ │ + for item in value: # type: ignore[attr-defined] # can throw TypeError │ │ │ │ │ + item_writer(message, item) │ │ │ │ │ + close_container(message) │ │ │ │ │ + return array_writer │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class StructType(ContainerType): │ │ │ │ │ + _typestring_template = '(_)' │ │ │ │ │ + __slots__ = () │ │ │ │ │ + │ │ │ │ │ + def get_reader(self, enter_container, exit_container): │ │ │ │ │ + item_readers = tuple(item_type.reader for item_type in self.item_types) │ │ │ │ │ + │ │ │ │ │ + def array_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ + if enter_container(message, 0, None) <= 0: │ │ │ │ │ + raise StopIteration │ │ │ │ │ + result = tuple(item_reader(message) for item_reader in item_readers) │ │ │ │ │ + exit_container(message) │ │ │ │ │ + return result │ │ │ │ │ + return array_reader │ │ │ │ │ + │ │ │ │ │ + def get_writer(self, r, type_contents, open_container, close_container): │ │ │ │ │ + item_writers = tuple(item_type.writer for item_type in self.item_types) │ │ │ │ │ + │ │ │ │ │ + def struct_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ + n_items = len(value) # type: ignore[arg-type] # can throw TypeError │ │ │ │ │ + if n_items != len(item_writers): │ │ │ │ │ + raise TypeError(f"Wrong numbers of items ({n_items}) for structure type '{self.typestring}'") │ │ │ │ │ + open_container(message, r, type_contents) │ │ │ │ │ + for item_writer, item in zip(item_writers, value): # type: ignore[call-overload] # can throw TypeError │ │ │ │ │ + item_writer(message, item) │ │ │ │ │ + close_container(message) │ │ │ │ │ + return struct_writer │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class DictionaryType(ContainerType): │ │ │ │ │ + _typestring_template = 'a{_}' │ │ │ │ │ + __slots__ = () │ │ │ │ │ + │ │ │ │ │ + def __init__(self, key_type: Type, value_type: Type): │ │ │ │ │ + assert isinstance(key_type, BasicType) │ │ │ │ │ + item_type = '{' + key_type.typestring + value_type.typestring + '}' │ │ │ │ │ + super().__init__(key_type, value_type, │ │ │ │ │ + key_reader=key_type.reader, key_writer=key_type.writer, │ │ │ │ │ + value_reader=value_type.reader, value_writer=value_type.writer, │ │ │ │ │ + item_type=ctypes.c_char_p(item_type.encode('ascii'))) │ │ │ │ │ + │ │ │ │ │ + def get_reader(self, enter_container, exit_container, key_reader, value_reader): │ │ │ │ │ + def dict_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ + if enter_container(message, 0, None) <= 0: # array │ │ │ │ │ + raise StopIteration │ │ │ │ │ + result = {} │ │ │ │ │ + while enter_container(message, 0, None) > 0: # entry │ │ │ │ │ + key = key_reader(message) │ │ │ │ │ + value = value_reader(message) │ │ │ │ │ + result[key] = value │ │ │ │ │ + exit_container(message) │ │ │ │ │ + exit_container(message) │ │ │ │ │ + return result │ │ │ │ │ + return dict_reader │ │ │ │ │ + │ │ │ │ │ + def get_writer(self, a, item_type, e, type_contents, open_container, close_container, key_writer, value_writer): │ │ │ │ │ + def dict_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ + open_container(message, a, item_type) # array │ │ │ │ │ + for key, val in value.items(): # type: ignore[attr-defined] # can raise AttributeError │ │ │ │ │ + open_container(message, e, type_contents) # entry │ │ │ │ │ + key_writer(message, key) # key │ │ │ │ │ + value_writer(message, val) # value │ │ │ │ │ + close_container(message) # end entry │ │ │ │ │ + close_container(message) # end array │ │ │ │ │ + return dict_writer │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class VariantType(Type): │ │ │ │ │ + __slots__ = () │ │ │ │ │ + │ │ │ │ │ + def get_reader(self, enter_container, exit_container): │ │ │ │ │ + def variant_reader(message: libsystemd.sd_bus_message) -> object: │ │ │ │ │ + if enter_container(message, 0, None) <= 0: │ │ │ │ │ + raise StopIteration │ │ │ │ │ + typestring = message.get_signature(False) │ │ │ │ │ + type_, = from_signature(typestring) │ │ │ │ │ + value = type_.reader(message) │ │ │ │ │ + exit_container(message) │ │ │ │ │ + return Variant(value, type_) │ │ │ │ │ + return variant_reader │ │ │ │ │ + │ │ │ │ │ + def get_writer(self, open_container, close_container, v): │ │ │ │ │ + def variant_writer(message: libsystemd.sd_bus_message, value: object) -> None: │ │ │ │ │ + if isinstance(value, Variant): │ │ │ │ │ + type_ = value.type │ │ │ │ │ + contents = value.value │ │ │ │ │ + else: │ │ │ │ │ + try: │ │ │ │ │ + type_, = from_signature(value['t']) # type: ignore[index] # can throw TypeError │ │ │ │ │ + contents = value['v'] # type: ignore[index] # can throw TypeError │ │ │ │ │ + except KeyError as exc: │ │ │ │ │ + raise TypeError("'v' can encode Variant objects, or mappings with 't' and 'v' keys") from exc │ │ │ │ │ + │ │ │ │ │ + open_container(message, v, type_.bytes_typestring) │ │ │ │ │ + type_.writer(message, contents) │ │ │ │ │ + close_container(message) │ │ │ │ │ + return variant_writer │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class Variant: │ │ │ │ │ + __slots__ = 'type', 'value' │ │ │ │ │ + type: Type │ │ │ │ │ + value: object │ │ │ │ │ + │ │ │ │ │ + def __init__(self, value: object, hint: object = None): │ │ │ │ │ + if isinstance(hint, Type): │ │ │ │ │ + self.type = hint │ │ │ │ │ + elif isinstance(hint, str): │ │ │ │ │ + self.type, = from_signature(hint) │ │ │ │ │ + else: │ │ │ │ │ + self.type = from_annotation(hint or value.__class__) │ │ │ │ │ + self.value = value │ │ │ │ │ + │ │ │ │ │ + def __repr__(self) -> str: │ │ │ │ │ + return f"systemd_ctypes.Variant({self.value}, '{self.type.typestring}')" │ │ │ │ │ + │ │ │ │ │ + def __eq__(self, other: object) -> bool: │ │ │ │ │ + if isinstance(other, Variant): │ │ │ │ │ + return self.type == other.type and self.value == other.value │ │ │ │ │ + elif isinstance(other, dict): │ │ │ │ │ + return (self.type,) == from_signature(other['t']) and self.value == other['v'] │ │ │ │ │ + else: │ │ │ │ │ + return False │ │ │ │ │ + │ │ │ │ │ + def __hash__(self) -> int: │ │ │ │ │ + return hash(self.type) ^ hash(self.value) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class BusType(Enum): │ │ │ │ │ + boolean = Annotated[bool, FixedType('b', ctypes.c_int, ctypes.c_int.__bool__)] │ │ │ │ │ + byte = Annotated[int, FixedType('y', ctypes.c_uint8)] │ │ │ │ │ + int16 = Annotated[int, FixedType('n', ctypes.c_int16)] │ │ │ │ │ + uint16 = Annotated[int, FixedType('q', ctypes.c_uint16)] │ │ │ │ │ + int32 = Annotated[int, FixedType('i', ctypes.c_int32)] │ │ │ │ │ + uint32 = Annotated[int, FixedType('u', ctypes.c_uint32)] │ │ │ │ │ + int64 = Annotated[int, FixedType('x', ctypes.c_int64)] │ │ │ │ │ + uint64 = Annotated[int, FixedType('t', ctypes.c_uint64)] │ │ │ │ │ + double = Annotated[float, FixedType('d', ctypes.c_double)] │ │ │ │ │ + string = Annotated[str, StringLikeType('s')] │ │ │ │ │ + objectpath = Annotated[str, StringLikeType('o', is_object_path)] │ │ │ │ │ + signature = Annotated[str, StringLikeType('g', is_signature)] │ │ │ │ │ + bytestring = Annotated[bytes, BytestringType('ay')] │ │ │ │ │ + variant = Annotated[dict, VariantType('v')] │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +# mypy gets confused by enums, so just use Any │ │ │ │ │ +_base_equivalence_map: Dict[type, Any] = { │ │ │ │ │ + bool: BusType.boolean, │ │ │ │ │ + bytes: BusType.bytestring, │ │ │ │ │ + int: BusType.int32, │ │ │ │ │ + str: BusType.string, │ │ │ │ │ + Variant: BusType.variant, │ │ │ │ │ +} │ │ │ │ │ + │ │ │ │ │ +_factory_map: Dict[object, Callable[..., Type]] = { │ │ │ │ │ + dict: DictionaryType, Dict: DictionaryType, │ │ │ │ │ + list: ArrayType, List: ArrayType, │ │ │ │ │ + tuple: StructType, Tuple: StructType, │ │ │ │ │ +} │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +@functools.lru_cache() │ │ │ │ │ +def from_annotation(annotation: Union[str, type, BusType]) -> Type: │ │ │ │ │ + # Simple Python types │ │ │ │ │ + if isinstance(annotation, str): │ │ │ │ │ + types = from_signature(annotation) │ │ │ │ │ + if len(types) != 1: │ │ │ │ │ + raise TypeError(f"Signature '{annotation}' invalid as a type string " │ │ │ │ │ + f"because it describes {len(types)} types, not one.") │ │ │ │ │ + return types[0] │ │ │ │ │ + │ │ │ │ │ + if isinstance(annotation, type): │ │ │ │ │ + annotation = _base_equivalence_map.get(annotation, annotation) │ │ │ │ │ + │ │ │ │ │ + # Our own BusType types │ │ │ │ │ + if isinstance(annotation, BusType): │ │ │ │ │ + bus_type = typing.get_args(annotation.value)[1] │ │ │ │ │ + assert isinstance(bus_type, Type) │ │ │ │ │ + return bus_type │ │ │ │ │ + │ │ │ │ │ + # Container types │ │ │ │ │ + try: │ │ │ │ │ + factory = _factory_map[typing.get_origin(annotation)] │ │ │ │ │ + args = [from_annotation(arg) for arg in typing.get_args(annotation)] │ │ │ │ │ + return factory(*args) │ │ │ │ │ + except (AssertionError, AttributeError, KeyError, TypeError): │ │ │ │ │ + raise TypeError(f"Cannot interpret {annotation} as a dbus type") from None │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +_base_typestring_map: Dict[str, Type] = { │ │ │ │ │ + bustype.typestring: bustype for bustype in (from_annotation(entry) for entry in BusType) │ │ │ │ │ +} │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +@functools.lru_cache() │ │ │ │ │ +def from_signature(signature: str) -> Tuple[Type, ...]: │ │ │ │ │ + stack = list(reversed(signature)) │ │ │ │ │ + │ │ │ │ │ + def get_one() -> Type: │ │ │ │ │ + first = stack.pop() │ │ │ │ │ + if first == 'a': │ │ │ │ │ + if stack[-1] == 'y': │ │ │ │ │ + first += stack.pop() │ │ │ │ │ + elif stack[-1] == '{': │ │ │ │ │ + stack.pop() │ │ │ │ │ + return DictionaryType(*get_several('}')) │ │ │ │ │ + else: │ │ │ │ │ + return ArrayType(get_one()) │ │ │ │ │ + elif first == '(': │ │ │ │ │ + return StructType(*get_several(')')) │ │ │ │ │ + │ │ │ │ │ + return _base_typestring_map[first] │ │ │ │ │ + │ │ │ │ │ + def get_several(end: str) -> Iterable[Type]: │ │ │ │ │ + yield get_one() │ │ │ │ │ + while stack[-1] != end: │ │ │ │ │ + yield get_one() │ │ │ │ │ + stack.pop() │ │ │ │ │ + │ │ │ │ │ + def get_all() -> Iterable[Type]: │ │ │ │ │ + while stack: │ │ │ │ │ + yield get_one() │ │ │ │ │ + │ │ │ │ │ + try: │ │ │ │ │ + return tuple(get_all()) │ │ │ │ │ + except (AssertionError, IndexError, KeyError) as exc: │ │ │ │ │ + raise TypeError(f"Invalid type signature '{signature}'") from exc │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class MessageType: │ │ │ │ │ + item_types: Sequence[Type] │ │ │ │ │ + typestrings: List[str] │ │ │ │ │ + signature: str │ │ │ │ │ + │ │ │ │ │ + def __init__(self, item_types: Sequence[Union[str, type, BusType]]): │ │ │ │ │ + self.item_types = [from_annotation(item_type) for item_type in item_types] │ │ │ │ │ + self.typestrings = [item_type.typestring for item_type in self.item_types] │ │ │ │ │ + self.signature = ''.join(self.typestrings) │ │ │ │ │ + │ │ │ │ │ + def write(self, message: libsystemd.sd_bus_message, *items: object) -> None: │ │ │ │ │ + assert len(items) == len(self.item_types) │ │ │ │ │ + for item_type, item in zip(self.item_types, items): │ │ │ │ │ + item_type.writer(message, item) │ │ │ │ │ + │ │ │ │ │ + def read(self, message: libsystemd.sd_bus_message) -> Optional[Tuple[object, ...]]: │ │ │ │ │ + if not message.has_signature(self.signature): │ │ │ │ │ + return None │ │ │ │ │ + return tuple(item_type.reader(message) for item_type in self.item_types) │ │ │ │ │ + │ │ │ │ │ + def __len__(self) -> int: │ │ │ │ │ + return len(self.item_types) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class JSONEncoder(json.JSONEncoder): │ │ │ │ │ + def default(self, obj: object) -> object: │ │ │ │ │ + if isinstance(obj, Variant): │ │ │ │ │ + return {"t": obj.type.typestring, "v": obj.value} │ │ │ │ │ + elif isinstance(obj, bytes): │ │ │ │ │ + return binascii.b2a_base64(obj, newline=False).decode('ascii') │ │ │ │ │ + return super().default(obj) │ │ │ │ │ ''', │ │ │ │ │ 'cockpit/data/fail.html': br''' │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ @@message@@ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ @@ -9706,14 +9706,480 @@ │ │ │ │ │ # https://github.com/python/mypy/issues/4182 │ │ │ │ │ loader = __loader__ # type: ignore[name-defined] │ │ │ │ │ assert isinstance(loader, importlib.abc.ResourceLoader) │ │ │ │ │ │ │ │ │ │ path = __file__.replace('__init__.py', filename) │ │ │ │ │ return loader.get_data(path) │ │ │ │ │ ''', │ │ │ │ │ + 'cockpit/channels/stream.py': br'''# This file is part of Cockpit. │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ + │ │ │ │ │ +import asyncio │ │ │ │ │ +import logging │ │ │ │ │ +import os │ │ │ │ │ +import subprocess │ │ │ │ │ +from typing import Dict │ │ │ │ │ + │ │ │ │ │ +from ..channel import ChannelError, ProtocolChannel │ │ │ │ │ +from ..jsonutil import JsonDict, JsonObject, get_bool, get_int, get_object, get_str, get_strv │ │ │ │ │ +from ..transports import SubprocessProtocol, SubprocessTransport, WindowSize │ │ │ │ │ + │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class SocketStreamChannel(ProtocolChannel): │ │ │ │ │ + payload = 'stream' │ │ │ │ │ + │ │ │ │ │ + async def create_transport(self, loop: asyncio.AbstractEventLoop, options: JsonObject) -> asyncio.Transport: │ │ │ │ │ + if 'unix' in options and 'port' in options: │ │ │ │ │ + raise ChannelError('protocol-error', message='cannot specify both "port" and "unix" options') │ │ │ │ │ + │ │ │ │ │ + try: │ │ │ │ │ + # Unix │ │ │ │ │ + if 'unix' in options: │ │ │ │ │ + path = get_str(options, 'unix') │ │ │ │ │ + label = f'Unix socket {path}' │ │ │ │ │ + transport, _ = await loop.create_unix_connection(lambda: self, path) │ │ │ │ │ + │ │ │ │ │ + # TCP │ │ │ │ │ + elif 'port' in options: │ │ │ │ │ + port = get_int(options, 'port') │ │ │ │ │ + host = get_str(options, 'address', 'localhost') │ │ │ │ │ + label = f'TCP socket {host}:{port}' │ │ │ │ │ + │ │ │ │ │ + transport, _ = await loop.create_connection(lambda: self, host, port) │ │ │ │ │ + else: │ │ │ │ │ + raise ChannelError('protocol-error', │ │ │ │ │ + message='no "port" or "unix" or other address option for channel') │ │ │ │ │ + │ │ │ │ │ + logger.debug('SocketStreamChannel: connected to %s', label) │ │ │ │ │ + except OSError as error: │ │ │ │ │ + logger.info('SocketStreamChannel: connecting to %s failed: %s', label, error) │ │ │ │ │ + if isinstance(error, ConnectionRefusedError): │ │ │ │ │ + problem = 'not-found' │ │ │ │ │ + else: │ │ │ │ │ + problem = 'terminated' │ │ │ │ │ + raise ChannelError(problem, message=str(error)) from error │ │ │ │ │ + self.close_on_eof() │ │ │ │ │ + assert isinstance(transport, asyncio.Transport) │ │ │ │ │ + return transport │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class SubprocessStreamChannel(ProtocolChannel, SubprocessProtocol): │ │ │ │ │ + payload = 'stream' │ │ │ │ │ + restrictions = (('spawn', None),) │ │ │ │ │ + │ │ │ │ │ + def process_exited(self) -> None: │ │ │ │ │ + self.close_on_eof() │ │ │ │ │ + │ │ │ │ │ + def _get_close_args(self) -> JsonObject: │ │ │ │ │ + assert isinstance(self._transport, SubprocessTransport) │ │ │ │ │ + args: JsonDict = {'exit-status': self._transport.get_returncode()} │ │ │ │ │ + stderr = self._transport.get_stderr() │ │ │ │ │ + if stderr is not None: │ │ │ │ │ + args['message'] = stderr │ │ │ │ │ + return args │ │ │ │ │ + │ │ │ │ │ + def do_options(self, options): │ │ │ │ │ + window = get_object(options, 'window', WindowSize, None) │ │ │ │ │ + if window is not None: │ │ │ │ │ + self._transport.set_window_size(window) │ │ │ │ │ + │ │ │ │ │ + async def create_transport(self, loop: asyncio.AbstractEventLoop, options: JsonObject) -> SubprocessTransport: │ │ │ │ │ + args = get_strv(options, 'spawn') │ │ │ │ │ + err = get_str(options, 'err', 'msg') │ │ │ │ │ + cwd = get_str(options, 'directory', '.') │ │ │ │ │ + pty = get_bool(options, 'pty', default=False) │ │ │ │ │ + window = get_object(options, 'window', WindowSize, None) │ │ │ │ │ + environ = get_strv(options, 'environ', []) │ │ │ │ │ + │ │ │ │ │ + if err == 'out': │ │ │ │ │ + stderr = subprocess.STDOUT │ │ │ │ │ + elif err == 'ignore': │ │ │ │ │ + stderr = subprocess.DEVNULL │ │ │ │ │ + else: │ │ │ │ │ + stderr = subprocess.PIPE │ │ │ │ │ + │ │ │ │ │ + env: Dict[str, str] = dict(os.environ) │ │ │ │ │ + try: │ │ │ │ │ + env.update(dict(e.split('=', 1) for e in environ)) │ │ │ │ │ + except ValueError: │ │ │ │ │ + raise ChannelError('protocol-error', message='invalid "environ" option for stream channel') from None │ │ │ │ │ + │ │ │ │ │ + try: │ │ │ │ │ + transport = SubprocessTransport(loop, self, args, pty=pty, window=window, env=env, cwd=cwd, stderr=stderr) │ │ │ │ │ + logger.debug('Spawned process args=%s pid=%i', args, transport.get_pid()) │ │ │ │ │ + return transport │ │ │ │ │ + except FileNotFoundError as error: │ │ │ │ │ + raise ChannelError('not-found') from error │ │ │ │ │ + except PermissionError as error: │ │ │ │ │ + raise ChannelError('access-denied') from error │ │ │ │ │ + except OSError as error: │ │ │ │ │ + logger.info("Failed to spawn %s: %s", args, str(error)) │ │ │ │ │ + raise ChannelError('internal-error') from error │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/channels/http.py': br'''# This file is part of Cockpit. │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ + │ │ │ │ │ +import asyncio │ │ │ │ │ +import http.client │ │ │ │ │ +import logging │ │ │ │ │ +import socket │ │ │ │ │ +import ssl │ │ │ │ │ + │ │ │ │ │ +from ..channel import AsyncChannel, ChannelError │ │ │ │ │ +from ..jsonutil import JsonObject, get_dict, get_int, get_object, get_str, typechecked │ │ │ │ │ + │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class HttpChannel(AsyncChannel): │ │ │ │ │ + payload = 'http-stream2' │ │ │ │ │ + │ │ │ │ │ + @staticmethod │ │ │ │ │ + def get_headers(response: http.client.HTTPResponse, binary: 'str | None') -> JsonObject: │ │ │ │ │ + # Never send these headers │ │ │ │ │ + remove = {'Connection', 'Transfer-Encoding'} │ │ │ │ │ + │ │ │ │ │ + if binary != 'raw': │ │ │ │ │ + # Only send these headers for raw binary streams │ │ │ │ │ + remove.update({'Content-Length', 'Range'}) │ │ │ │ │ + │ │ │ │ │ + return {key: value for key, value in response.getheaders() if key not in remove} │ │ │ │ │ + │ │ │ │ │ + @staticmethod │ │ │ │ │ + def create_client(options: JsonObject) -> http.client.HTTPConnection: │ │ │ │ │ + opt_address = get_str(options, 'address', 'localhost') │ │ │ │ │ + opt_tls = get_dict(options, 'tls', None) │ │ │ │ │ + opt_unix = get_str(options, 'unix', None) │ │ │ │ │ + opt_port = get_int(options, 'port', None) │ │ │ │ │ + │ │ │ │ │ + if opt_tls is not None and opt_unix is not None: │ │ │ │ │ + raise ChannelError('protocol-error', message='TLS on Unix socket is not supported') │ │ │ │ │ + if opt_port is None and opt_unix is None: │ │ │ │ │ + raise ChannelError('protocol-error', message='no "port" or "unix" option for channel') │ │ │ │ │ + if opt_port is not None and opt_unix is not None: │ │ │ │ │ + raise ChannelError('protocol-error', message='cannot specify both "port" and "unix" options') │ │ │ │ │ + │ │ │ │ │ + if opt_tls is not None: │ │ │ │ │ + authority = get_dict(opt_tls, 'authority', None) │ │ │ │ │ + if authority is not None: │ │ │ │ │ + data = get_str(authority, 'data', None) │ │ │ │ │ + if data is not None: │ │ │ │ │ + context = ssl.create_default_context(cadata=data) │ │ │ │ │ + else: │ │ │ │ │ + context = ssl.create_default_context(cafile=get_str(authority, 'file')) │ │ │ │ │ + else: │ │ │ │ │ + context = ssl.create_default_context() │ │ │ │ │ + │ │ │ │ │ + if 'validate' in opt_tls and not opt_tls['validate']: │ │ │ │ │ + context.check_hostname = False │ │ │ │ │ + context.verify_mode = ssl.VerifyMode.CERT_NONE │ │ │ │ │ + │ │ │ │ │ + # See https://github.com/python/typeshed/issues/11057 │ │ │ │ │ + return http.client.HTTPSConnection(opt_address, port=opt_port, context=context) # type: ignore[arg-type] │ │ │ │ │ + │ │ │ │ │ + else: │ │ │ │ │ + return http.client.HTTPConnection(opt_address, port=opt_port) │ │ │ │ │ + │ │ │ │ │ + @staticmethod │ │ │ │ │ + def connect(connection: http.client.HTTPConnection, opt_unix: 'str | None') -> None: │ │ │ │ │ + # Blocks. Runs in a thread. │ │ │ │ │ + if opt_unix: │ │ │ │ │ + # create the connection's socket so that it won't call .connect() internally (which only supports TCP) │ │ │ │ │ + connection.sock = socket.socket(socket.AF_UNIX) │ │ │ │ │ + connection.sock.connect(opt_unix) │ │ │ │ │ + else: │ │ │ │ │ + # explicitly call connect(), so that we can do proper error handling │ │ │ │ │ + connection.connect() │ │ │ │ │ + │ │ │ │ │ + @staticmethod │ │ │ │ │ + def request( │ │ │ │ │ + connection: http.client.HTTPConnection, method: str, path: str, headers: 'dict[str, str]', body: bytes │ │ │ │ │ + ) -> http.client.HTTPResponse: │ │ │ │ │ + # Blocks. Runs in a thread. │ │ │ │ │ + connection.request(method, path, headers=headers or {}, body=body) │ │ │ │ │ + return connection.getresponse() │ │ │ │ │ + │ │ │ │ │ + async def run(self, options: JsonObject) -> None: │ │ │ │ │ + logger.debug('open %s', options) │ │ │ │ │ + │ │ │ │ │ + binary = get_str(options, 'binary', None) │ │ │ │ │ + method = get_str(options, 'method') │ │ │ │ │ + path = get_str(options, 'path') │ │ │ │ │ + headers = get_object(options, 'headers', lambda d: {k: typechecked(v, str) for k, v in d.items()}, None) │ │ │ │ │ + │ │ │ │ │ + if 'connection' in options: │ │ │ │ │ + raise ChannelError('protocol-error', message='connection sharing is not implemented on this bridge') │ │ │ │ │ + │ │ │ │ │ + loop = asyncio.get_running_loop() │ │ │ │ │ + connection = self.create_client(options) │ │ │ │ │ + │ │ │ │ │ + self.ready() │ │ │ │ │ + │ │ │ │ │ + body = b'' │ │ │ │ │ + while True: │ │ │ │ │ + data = await self.read() │ │ │ │ │ + if data == b'': │ │ │ │ │ + break │ │ │ │ │ + body += data │ │ │ │ │ + │ │ │ │ │ + # Connect in a thread and handle errors │ │ │ │ │ + try: │ │ │ │ │ + await loop.run_in_executor(None, self.connect, connection, get_str(options, 'unix', None)) │ │ │ │ │ + except ssl.SSLCertVerificationError as exc: │ │ │ │ │ + raise ChannelError('unknown-hostkey', message=str(exc)) from exc │ │ │ │ │ + except (OSError, IOError) as exc: │ │ │ │ │ + raise ChannelError('not-found', message=str(exc)) from exc │ │ │ │ │ + │ │ │ │ │ + # Submit request in a thread and handle errors │ │ │ │ │ + try: │ │ │ │ │ + response = await loop.run_in_executor(None, self.request, connection, method, path, headers or {}, body) │ │ │ │ │ + except (http.client.HTTPException, OSError) as exc: │ │ │ │ │ + raise ChannelError('terminated', message=str(exc)) from exc │ │ │ │ │ + │ │ │ │ │ + self.send_control(command='response', │ │ │ │ │ + status=response.status, │ │ │ │ │ + reason=response.reason, │ │ │ │ │ + headers=self.get_headers(response, binary)) │ │ │ │ │ + │ │ │ │ │ + # Receive the body and finish up │ │ │ │ │ + try: │ │ │ │ │ + while True: │ │ │ │ │ + block = await loop.run_in_executor(None, response.read1, self.BLOCK_SIZE) │ │ │ │ │ + if not block: │ │ │ │ │ + break │ │ │ │ │ + await self.write(block) │ │ │ │ │ + │ │ │ │ │ + logger.debug('reading response done') │ │ │ │ │ + # this returns immediately and does not read anything more, but updates the http.client's │ │ │ │ │ + # internal state machine to "response done" │ │ │ │ │ + block = response.read() │ │ │ │ │ + assert block == b'' │ │ │ │ │ + │ │ │ │ │ + await loop.run_in_executor(None, connection.close) │ │ │ │ │ + except (http.client.HTTPException, OSError) as exc: │ │ │ │ │ + raise ChannelError('terminated', message=str(exc)) from exc │ │ │ │ │ + │ │ │ │ │ + self.done() │ │ │ │ │ +''', │ │ │ │ │ + 'cockpit/channels/metrics.py': br'''# This file is part of Cockpit. │ │ │ │ │ +# │ │ │ │ │ +# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ +# │ │ │ │ │ +# This program 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. │ │ │ │ │ +# │ │ │ │ │ +# This program 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 this program. If not, see . │ │ │ │ │ + │ │ │ │ │ +import asyncio │ │ │ │ │ +import json │ │ │ │ │ +import logging │ │ │ │ │ +import sys │ │ │ │ │ +import time │ │ │ │ │ +from collections import defaultdict │ │ │ │ │ +from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union │ │ │ │ │ + │ │ │ │ │ +from ..channel import AsyncChannel, ChannelError │ │ │ │ │ +from ..jsonutil import JsonList │ │ │ │ │ +from ..samples import SAMPLERS, SampleDescription, Sampler, Samples │ │ │ │ │ + │ │ │ │ │ +logger = logging.getLogger(__name__) │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class MetricInfo(NamedTuple): │ │ │ │ │ + derive: Optional[str] │ │ │ │ │ + desc: SampleDescription │ │ │ │ │ + │ │ │ │ │ + │ │ │ │ │ +class InternalMetricsChannel(AsyncChannel): │ │ │ │ │ + payload = 'metrics1' │ │ │ │ │ + restrictions = [('source', 'internal')] │ │ │ │ │ + │ │ │ │ │ + metrics: List[MetricInfo] │ │ │ │ │ + samplers: Set │ │ │ │ │ + samplers_cache: Optional[Dict[str, Tuple[Sampler, SampleDescription]]] = None │ │ │ │ │ + │ │ │ │ │ + interval: int = 1000 │ │ │ │ │ + need_meta: bool = True │ │ │ │ │ + last_timestamp: float = 0 │ │ │ │ │ + next_timestamp: float = 0 │ │ │ │ │ + │ │ │ │ │ + @classmethod │ │ │ │ │ + def ensure_samplers(cls): │ │ │ │ │ + if cls.samplers_cache is None: │ │ │ │ │ + cls.samplers_cache = {desc.name: (sampler, desc) for sampler in SAMPLERS for desc in sampler.descriptions} │ │ │ │ │ + │ │ │ │ │ + def parse_options(self, options): │ │ │ │ │ + logger.debug('metrics internal open: %s, channel: %s', options, self.channel) │ │ │ │ │ + │ │ │ │ │ + interval = options.get('interval', self.interval) │ │ │ │ │ + if not isinstance(interval, int) or interval <= 0 or interval > sys.maxsize: │ │ │ │ │ + raise ChannelError('protocol-error', message=f'invalid "interval" value: {interval}') │ │ │ │ │ + │ │ │ │ │ + self.interval = interval │ │ │ │ │ + │ │ │ │ │ + metrics = options.get('metrics') │ │ │ │ │ + if not isinstance(metrics, list) or len(metrics) == 0: │ │ │ │ │ + logger.error('invalid "metrics" value: %s', metrics) │ │ │ │ │ + raise ChannelError('protocol-error', message='invalid "metrics" option was specified (not an array)') │ │ │ │ │ + │ │ │ │ │ + sampler_classes = set() │ │ │ │ │ + for metric in metrics: │ │ │ │ │ + # validate it's an object │ │ │ │ │ + name = metric.get('name') │ │ │ │ │ + units = metric.get('units') │ │ │ │ │ + derive = metric.get('derive') │ │ │ │ │ + │ │ │ │ │ + try: │ │ │ │ │ + sampler, desc = self.samplers_cache[name] │ │ │ │ │ + except KeyError as exc: │ │ │ │ │ + logger.error('unsupported metric: %s', name) │ │ │ │ │ + raise ChannelError('not-supported', message=f'unsupported metric: {name}') from exc │ │ │ │ │ + │ │ │ │ │ + if units and units != desc.units: │ │ │ │ │ + raise ChannelError('not-supported', message=f'{name} has units {desc.units}, not {units}') │ │ │ │ │ + │ │ │ │ │ + sampler_classes.add(sampler) │ │ │ │ │ + self.metrics.append(MetricInfo(derive=derive, desc=desc)) │ │ │ │ │ + │ │ │ │ │ + self.samplers = {cls() for cls in sampler_classes} │ │ │ │ │ + │ │ │ │ │ + def send_meta(self, samples: Samples, timestamp: float): │ │ │ │ │ + metrics: JsonList = [] │ │ │ │ │ + for metricinfo in self.metrics: │ │ │ │ │ + if metricinfo.desc.instanced: │ │ │ │ │ + metrics.append({ │ │ │ │ │ + 'name': metricinfo.desc.name, │ │ │ │ │ + 'units': metricinfo.desc.units, │ │ │ │ │ + 'instances': list(samples[metricinfo.desc.name].keys()), │ │ │ │ │ + 'semantics': metricinfo.desc.semantics │ │ │ │ │ + }) │ │ │ │ │ + else: │ │ │ │ │ + metrics.append({ │ │ │ │ │ + 'name': metricinfo.desc.name, │ │ │ │ │ + 'derive': metricinfo.derive, # type: ignore[dict-item] │ │ │ │ │ + 'units': metricinfo.desc.units, │ │ │ │ │ + 'semantics': metricinfo.desc.semantics │ │ │ │ │ + }) │ │ │ │ │ + │ │ │ │ │ + self.send_json(source='internal', interval=self.interval, timestamp=timestamp * 1000, metrics=metrics) │ │ │ │ │ + self.need_meta = False │ │ │ │ │ + │ │ │ │ │ + def sample(self): │ │ │ │ │ + samples = defaultdict(dict) │ │ │ │ │ + for sampler in self.samplers: │ │ │ │ │ + sampler.sample(samples) │ │ │ │ │ + return samples │ │ │ │ │ + │ │ │ │ │ + def calculate_sample_rate(self, value: float, old_value: Optional[float]) -> Union[float, bool]: │ │ │ │ │ + if old_value is not None and self.last_timestamp: │ │ │ │ │ + return (value - old_value) / (self.next_timestamp - self.last_timestamp) │ │ │ │ │ + else: │ │ │ │ │ + return False │ │ │ │ │ + │ │ │ │ │ + def send_updates(self, samples: Samples, last_samples: Samples): │ │ │ │ │ + data: List[Union[float, List[Optional[Union[float, bool]]]]] = [] │ │ │ │ │ + timestamp = time.time() │ │ │ │ │ + self.next_timestamp = timestamp │ │ │ │ │ + │ │ │ │ │ + for metricinfo in self.metrics: │ │ │ │ │ + value = samples[metricinfo.desc.name] │ │ │ │ │ + │ │ │ │ │ + if metricinfo.desc.instanced: │ │ │ │ │ + old_value = last_samples[metricinfo.desc.name] │ │ │ │ │ + assert isinstance(value, dict) │ │ │ │ │ + assert isinstance(old_value, dict) │ │ │ │ │ + │ │ │ │ │ + # If we have less or more keys the data changed, send a meta message. │ │ │ │ │ + if value.keys() != old_value.keys(): │ │ │ │ │ + self.need_meta = True │ │ │ │ │ + │ │ │ │ │ + if metricinfo.derive == 'rate': │ │ │ │ │ + instances: List[Optional[Union[float, bool]]] = [] │ │ │ │ │ + for key, val in value.items(): │ │ │ │ │ + instances.append(self.calculate_sample_rate(val, old_value.get(key))) │ │ │ │ │ + │ │ │ │ │ + data.append(instances) │ │ │ │ │ + else: │ │ │ │ │ + data.append(list(value.values())) │ │ │ │ │ + else: │ │ │ │ │ + old_value = last_samples.get(metricinfo.desc.name) │ │ │ │ │ + assert not isinstance(value, dict) │ │ │ │ │ + assert not isinstance(old_value, dict) │ │ │ │ │ + │ │ │ │ │ + if metricinfo.derive == 'rate': │ │ │ │ │ + data.append(self.calculate_sample_rate(value, old_value)) │ │ │ │ │ + else: │ │ │ │ │ + data.append(value) │ │ │ │ │ + │ │ │ │ │ + if self.need_meta: │ │ │ │ │ + self.send_meta(samples, timestamp) │ │ │ │ │ + │ │ │ │ │ + self.last_timestamp = self.next_timestamp │ │ │ │ │ + self.send_data(json.dumps([data]).encode()) │ │ │ │ │ + │ │ │ │ │ + async def run(self, options): │ │ │ │ │ + self.metrics = [] │ │ │ │ │ + self.samplers = set() │ │ │ │ │ + │ │ │ │ │ + InternalMetricsChannel.ensure_samplers() │ │ │ │ │ + │ │ │ │ │ + self.parse_options(options) │ │ │ │ │ + self.ready() │ │ │ │ │ + │ │ │ │ │ + last_samples = defaultdict(dict) │ │ │ │ │ + while True: │ │ │ │ │ + samples = self.sample() │ │ │ │ │ + self.send_updates(samples, last_samples) │ │ │ │ │ + last_samples = samples │ │ │ │ │ + │ │ │ │ │ + try: │ │ │ │ │ + await asyncio.wait_for(self.read(), self.interval / 1000) │ │ │ │ │ + return │ │ │ │ │ + except asyncio.TimeoutError: │ │ │ │ │ + # Continue the while loop, we use wait_for as an interval timer. │ │ │ │ │ + continue │ │ │ │ │ +''', │ │ │ │ │ 'cockpit/channels/filesystem.py': r'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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 │ │ │ │ │ @@ -10256,15 +10722,15 @@ │ │ │ │ │ │ │ │ │ │ else: │ │ │ │ │ # PathWatch will call do_identity_changed(), which does the same as │ │ │ │ │ # above: calls either report_initial_state() or report_error(), │ │ │ │ │ # depending on if it was provided with an fd or an error code. │ │ │ │ │ self.path_watch = PathWatch(self.path, self) │ │ │ │ │ '''.encode('utf-8'), │ │ │ │ │ - 'cockpit/channels/stream.py': br'''# This file is part of Cockpit. │ │ │ │ │ + 'cockpit/channels/packages.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program 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. │ │ │ │ │ @@ -10273,117 +10739,98 @@ │ │ │ │ │ # 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 this program. If not, see . │ │ │ │ │ │ │ │ │ │ -import asyncio │ │ │ │ │ import logging │ │ │ │ │ -import os │ │ │ │ │ -import subprocess │ │ │ │ │ -from typing import Dict │ │ │ │ │ +from typing import Optional │ │ │ │ │ │ │ │ │ │ -from ..channel import ChannelError, ProtocolChannel │ │ │ │ │ -from ..jsonutil import JsonDict, JsonObject, get_bool, get_int, get_object, get_str, get_strv │ │ │ │ │ -from ..transports import SubprocessProtocol, SubprocessTransport, WindowSize │ │ │ │ │ +from ..channel import AsyncChannel │ │ │ │ │ +from ..data import read_cockpit_data_file │ │ │ │ │ +from ..jsonutil import JsonObject, get_dict, get_str │ │ │ │ │ +from ..packages import Packages │ │ │ │ │ │ │ │ │ │ logger = logging.getLogger(__name__) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ -class SocketStreamChannel(ProtocolChannel): │ │ │ │ │ - payload = 'stream' │ │ │ │ │ +class PackagesChannel(AsyncChannel): │ │ │ │ │ + payload = 'http-stream1' │ │ │ │ │ + restrictions = [("internal", "packages")] │ │ │ │ │ │ │ │ │ │ - async def create_transport(self, loop: asyncio.AbstractEventLoop, options: JsonObject) -> asyncio.Transport: │ │ │ │ │ - if 'unix' in options and 'port' in options: │ │ │ │ │ - raise ChannelError('protocol-error', message='cannot specify both "port" and "unix" options') │ │ │ │ │ + # used to carry data forward from open to done │ │ │ │ │ + options: Optional[JsonObject] = None │ │ │ │ │ + │ │ │ │ │ + def http_error(self, status: int, message: str) -> None: │ │ │ │ │ + template = read_cockpit_data_file('fail.html') │ │ │ │ │ + self.send_json(status=status, reason='ERROR', headers={'Content-Type': 'text/html; charset=utf-8'}) │ │ │ │ │ + self.send_data(template.replace(b'@@message@@', message.encode('utf-8'))) │ │ │ │ │ + self.done() │ │ │ │ │ + self.close() │ │ │ │ │ + │ │ │ │ │ + async def run(self, options: JsonObject) -> None: │ │ │ │ │ + packages: Packages = self.router.packages # type: ignore[attr-defined] # yes, this is evil │ │ │ │ │ │ │ │ │ │ try: │ │ │ │ │ - # Unix │ │ │ │ │ - if 'unix' in options: │ │ │ │ │ - path = get_str(options, 'unix') │ │ │ │ │ - label = f'Unix socket {path}' │ │ │ │ │ - transport, _ = await loop.create_unix_connection(lambda: self, path) │ │ │ │ │ + if get_str(options, 'method') != 'GET': │ │ │ │ │ + raise ValueError(f'Unsupported HTTP method {options["method"]}') │ │ │ │ │ │ │ │ │ │ - # TCP │ │ │ │ │ - elif 'port' in options: │ │ │ │ │ - port = get_int(options, 'port') │ │ │ │ │ - host = get_str(options, 'address', 'localhost') │ │ │ │ │ - label = f'TCP socket {host}:{port}' │ │ │ │ │ + self.ready() │ │ │ │ │ + if await self.read() != b'': │ │ │ │ │ + raise ValueError('Received unexpected data') │ │ │ │ │ │ │ │ │ │ - transport, _ = await loop.create_connection(lambda: self, host, port) │ │ │ │ │ - else: │ │ │ │ │ - raise ChannelError('protocol-error', │ │ │ │ │ - message='no "port" or "unix" or other address option for channel') │ │ │ │ │ + path = get_str(options, 'path') │ │ │ │ │ + headers = get_dict(options, 'headers') │ │ │ │ │ + document = packages.load_path(path, headers) │ │ │ │ │ │ │ │ │ │ - logger.debug('SocketStreamChannel: connected to %s', label) │ │ │ │ │ - except OSError as error: │ │ │ │ │ - logger.info('SocketStreamChannel: connecting to %s failed: %s', label, error) │ │ │ │ │ - if isinstance(error, ConnectionRefusedError): │ │ │ │ │ - problem = 'not-found' │ │ │ │ │ - else: │ │ │ │ │ - problem = 'terminated' │ │ │ │ │ - raise ChannelError(problem, message=str(error)) from error │ │ │ │ │ - self.close_on_eof() │ │ │ │ │ - assert isinstance(transport, asyncio.Transport) │ │ │ │ │ - return transport │ │ │ │ │ + # Note: we can't cache documents right now. See │ │ │ │ │ + # https://github.com/cockpit-project/cockpit/issues/19071 │ │ │ │ │ + # for future plans. │ │ │ │ │ + out_headers = { │ │ │ │ │ + 'Cache-Control': 'no-cache, no-store', │ │ │ │ │ + 'Content-Type': document.content_type, │ │ │ │ │ + } │ │ │ │ │ │ │ │ │ │ + if document.content_encoding is not None: │ │ │ │ │ + out_headers['Content-Encoding'] = document.content_encoding │ │ │ │ │ │ │ │ │ │ -class SubprocessStreamChannel(ProtocolChannel, SubprocessProtocol): │ │ │ │ │ - payload = 'stream' │ │ │ │ │ - restrictions = (('spawn', None),) │ │ │ │ │ + if document.content_security_policy is not None: │ │ │ │ │ + policy = document.content_security_policy │ │ │ │ │ │ │ │ │ │ - def process_exited(self) -> None: │ │ │ │ │ - self.close_on_eof() │ │ │ │ │ + # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/connect-src │ │ │ │ │ + # │ │ │ │ │ + # Note: connect-src 'self' does not resolve to websocket │ │ │ │ │ + # schemes in all browsers, more info in this issue. │ │ │ │ │ + # │ │ │ │ │ + # https://github.com/w3c/webappsec-csp/issues/7 │ │ │ │ │ + if "connect-src 'self';" in policy: │ │ │ │ │ + protocol = headers.get('X-Forwarded-Proto') │ │ │ │ │ + host = headers.get('X-Forwarded-Host') │ │ │ │ │ + if not isinstance(protocol, str) or not isinstance(host, str): │ │ │ │ │ + raise ValueError('Invalid host or protocol header') │ │ │ │ │ │ │ │ │ │ - def _get_close_args(self) -> JsonObject: │ │ │ │ │ - assert isinstance(self._transport, SubprocessTransport) │ │ │ │ │ - args: JsonDict = {'exit-status': self._transport.get_returncode()} │ │ │ │ │ - stderr = self._transport.get_stderr() │ │ │ │ │ - if stderr is not None: │ │ │ │ │ - args['message'] = stderr │ │ │ │ │ - return args │ │ │ │ │ + websocket_scheme = "wss" if protocol == "https" else "ws" │ │ │ │ │ + websocket_origin = f"{websocket_scheme}://{host}" │ │ │ │ │ + policy = policy.replace("connect-src 'self';", f"connect-src {websocket_origin} 'self';") │ │ │ │ │ │ │ │ │ │ - def do_options(self, options): │ │ │ │ │ - window = get_object(options, 'window', WindowSize, None) │ │ │ │ │ - if window is not None: │ │ │ │ │ - self._transport.set_window_size(window) │ │ │ │ │ + out_headers['Content-Security-Policy'] = policy │ │ │ │ │ │ │ │ │ │ - async def create_transport(self, loop: asyncio.AbstractEventLoop, options: JsonObject) -> SubprocessTransport: │ │ │ │ │ - args = get_strv(options, 'spawn') │ │ │ │ │ - err = get_str(options, 'err', 'msg') │ │ │ │ │ - cwd = get_str(options, 'directory', '.') │ │ │ │ │ - pty = get_bool(options, 'pty', default=False) │ │ │ │ │ - window = get_object(options, 'window', WindowSize, None) │ │ │ │ │ - environ = get_strv(options, 'environ', []) │ │ │ │ │ + except ValueError as exc: │ │ │ │ │ + self.http_error(400, str(exc)) │ │ │ │ │ │ │ │ │ │ - if err == 'out': │ │ │ │ │ - stderr = subprocess.STDOUT │ │ │ │ │ - elif err == 'ignore': │ │ │ │ │ - stderr = subprocess.DEVNULL │ │ │ │ │ - else: │ │ │ │ │ - stderr = subprocess.PIPE │ │ │ │ │ + except KeyError: │ │ │ │ │ + self.http_error(404, 'Not found') │ │ │ │ │ │ │ │ │ │ - env: Dict[str, str] = dict(os.environ) │ │ │ │ │ - try: │ │ │ │ │ - env.update(dict(e.split('=', 1) for e in environ)) │ │ │ │ │ - except ValueError: │ │ │ │ │ - raise ChannelError('protocol-error', message='invalid "environ" option for stream channel') from None │ │ │ │ │ + except OSError as exc: │ │ │ │ │ + self.http_error(500, f'Internal error: {exc!s}') │ │ │ │ │ │ │ │ │ │ - try: │ │ │ │ │ - transport = SubprocessTransport(loop, self, args, pty=pty, window=window, env=env, cwd=cwd, stderr=stderr) │ │ │ │ │ - logger.debug('Spawned process args=%s pid=%i', args, transport.get_pid()) │ │ │ │ │ - return transport │ │ │ │ │ - except FileNotFoundError as error: │ │ │ │ │ - raise ChannelError('not-found') from error │ │ │ │ │ - except PermissionError as error: │ │ │ │ │ - raise ChannelError('access-denied') from error │ │ │ │ │ - except OSError as error: │ │ │ │ │ - logger.info("Failed to spawn %s: %s", args, str(error)) │ │ │ │ │ - raise ChannelError('internal-error') from error │ │ │ │ │ + else: │ │ │ │ │ + self.send_json(status=200, reason='OK', headers=out_headers) │ │ │ │ │ + await self.sendfile(document.data) │ │ │ │ │ ''', │ │ │ │ │ 'cockpit/channels/trivial.py': br'''# This file is part of Cockpit. │ │ │ │ │ # │ │ │ │ │ # Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ # │ │ │ │ │ # This program is free software: you can redistribute it and/or modify │ │ │ │ │ # it under the terms of the GNU General Public License as published by │ │ │ │ │ @@ -10986,457 +11433,10 @@ │ │ │ │ │ InternalMetricsChannel, │ │ │ │ │ NullChannel, │ │ │ │ │ PackagesChannel, │ │ │ │ │ SubprocessStreamChannel, │ │ │ │ │ SocketStreamChannel, │ │ │ │ │ ] │ │ │ │ │ ''', │ │ │ │ │ - 'cockpit/channels/http.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import asyncio │ │ │ │ │ -import http.client │ │ │ │ │ -import logging │ │ │ │ │ -import socket │ │ │ │ │ -import ssl │ │ │ │ │ - │ │ │ │ │ -from ..channel import AsyncChannel, ChannelError │ │ │ │ │ -from ..jsonutil import JsonObject, get_dict, get_int, get_object, get_str, typechecked │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class HttpChannel(AsyncChannel): │ │ │ │ │ - payload = 'http-stream2' │ │ │ │ │ - │ │ │ │ │ - @staticmethod │ │ │ │ │ - def get_headers(response: http.client.HTTPResponse, binary: 'str | None') -> JsonObject: │ │ │ │ │ - # Never send these headers │ │ │ │ │ - remove = {'Connection', 'Transfer-Encoding'} │ │ │ │ │ - │ │ │ │ │ - if binary != 'raw': │ │ │ │ │ - # Only send these headers for raw binary streams │ │ │ │ │ - remove.update({'Content-Length', 'Range'}) │ │ │ │ │ - │ │ │ │ │ - return {key: value for key, value in response.getheaders() if key not in remove} │ │ │ │ │ - │ │ │ │ │ - @staticmethod │ │ │ │ │ - def create_client(options: JsonObject) -> http.client.HTTPConnection: │ │ │ │ │ - opt_address = get_str(options, 'address', 'localhost') │ │ │ │ │ - opt_tls = get_dict(options, 'tls', None) │ │ │ │ │ - opt_unix = get_str(options, 'unix', None) │ │ │ │ │ - opt_port = get_int(options, 'port', None) │ │ │ │ │ - │ │ │ │ │ - if opt_tls is not None and opt_unix is not None: │ │ │ │ │ - raise ChannelError('protocol-error', message='TLS on Unix socket is not supported') │ │ │ │ │ - if opt_port is None and opt_unix is None: │ │ │ │ │ - raise ChannelError('protocol-error', message='no "port" or "unix" option for channel') │ │ │ │ │ - if opt_port is not None and opt_unix is not None: │ │ │ │ │ - raise ChannelError('protocol-error', message='cannot specify both "port" and "unix" options') │ │ │ │ │ - │ │ │ │ │ - if opt_tls is not None: │ │ │ │ │ - authority = get_dict(opt_tls, 'authority', None) │ │ │ │ │ - if authority is not None: │ │ │ │ │ - data = get_str(authority, 'data', None) │ │ │ │ │ - if data is not None: │ │ │ │ │ - context = ssl.create_default_context(cadata=data) │ │ │ │ │ - else: │ │ │ │ │ - context = ssl.create_default_context(cafile=get_str(authority, 'file')) │ │ │ │ │ - else: │ │ │ │ │ - context = ssl.create_default_context() │ │ │ │ │ - │ │ │ │ │ - if 'validate' in opt_tls and not opt_tls['validate']: │ │ │ │ │ - context.check_hostname = False │ │ │ │ │ - context.verify_mode = ssl.VerifyMode.CERT_NONE │ │ │ │ │ - │ │ │ │ │ - # See https://github.com/python/typeshed/issues/11057 │ │ │ │ │ - return http.client.HTTPSConnection(opt_address, port=opt_port, context=context) # type: ignore[arg-type] │ │ │ │ │ - │ │ │ │ │ - else: │ │ │ │ │ - return http.client.HTTPConnection(opt_address, port=opt_port) │ │ │ │ │ - │ │ │ │ │ - @staticmethod │ │ │ │ │ - def connect(connection: http.client.HTTPConnection, opt_unix: 'str | None') -> None: │ │ │ │ │ - # Blocks. Runs in a thread. │ │ │ │ │ - if opt_unix: │ │ │ │ │ - # create the connection's socket so that it won't call .connect() internally (which only supports TCP) │ │ │ │ │ - connection.sock = socket.socket(socket.AF_UNIX) │ │ │ │ │ - connection.sock.connect(opt_unix) │ │ │ │ │ - else: │ │ │ │ │ - # explicitly call connect(), so that we can do proper error handling │ │ │ │ │ - connection.connect() │ │ │ │ │ - │ │ │ │ │ - @staticmethod │ │ │ │ │ - def request( │ │ │ │ │ - connection: http.client.HTTPConnection, method: str, path: str, headers: 'dict[str, str]', body: bytes │ │ │ │ │ - ) -> http.client.HTTPResponse: │ │ │ │ │ - # Blocks. Runs in a thread. │ │ │ │ │ - connection.request(method, path, headers=headers or {}, body=body) │ │ │ │ │ - return connection.getresponse() │ │ │ │ │ - │ │ │ │ │ - async def run(self, options: JsonObject) -> None: │ │ │ │ │ - logger.debug('open %s', options) │ │ │ │ │ - │ │ │ │ │ - binary = get_str(options, 'binary', None) │ │ │ │ │ - method = get_str(options, 'method') │ │ │ │ │ - path = get_str(options, 'path') │ │ │ │ │ - headers = get_object(options, 'headers', lambda d: {k: typechecked(v, str) for k, v in d.items()}, None) │ │ │ │ │ - │ │ │ │ │ - if 'connection' in options: │ │ │ │ │ - raise ChannelError('protocol-error', message='connection sharing is not implemented on this bridge') │ │ │ │ │ - │ │ │ │ │ - loop = asyncio.get_running_loop() │ │ │ │ │ - connection = self.create_client(options) │ │ │ │ │ - │ │ │ │ │ - self.ready() │ │ │ │ │ - │ │ │ │ │ - body = b'' │ │ │ │ │ - while True: │ │ │ │ │ - data = await self.read() │ │ │ │ │ - if data == b'': │ │ │ │ │ - break │ │ │ │ │ - body += data │ │ │ │ │ - │ │ │ │ │ - # Connect in a thread and handle errors │ │ │ │ │ - try: │ │ │ │ │ - await loop.run_in_executor(None, self.connect, connection, get_str(options, 'unix', None)) │ │ │ │ │ - except ssl.SSLCertVerificationError as exc: │ │ │ │ │ - raise ChannelError('unknown-hostkey', message=str(exc)) from exc │ │ │ │ │ - except (OSError, IOError) as exc: │ │ │ │ │ - raise ChannelError('not-found', message=str(exc)) from exc │ │ │ │ │ - │ │ │ │ │ - # Submit request in a thread and handle errors │ │ │ │ │ - try: │ │ │ │ │ - response = await loop.run_in_executor(None, self.request, connection, method, path, headers or {}, body) │ │ │ │ │ - except (http.client.HTTPException, OSError) as exc: │ │ │ │ │ - raise ChannelError('terminated', message=str(exc)) from exc │ │ │ │ │ - │ │ │ │ │ - self.send_control(command='response', │ │ │ │ │ - status=response.status, │ │ │ │ │ - reason=response.reason, │ │ │ │ │ - headers=self.get_headers(response, binary)) │ │ │ │ │ - │ │ │ │ │ - # Receive the body and finish up │ │ │ │ │ - try: │ │ │ │ │ - while True: │ │ │ │ │ - block = await loop.run_in_executor(None, response.read1, self.BLOCK_SIZE) │ │ │ │ │ - if not block: │ │ │ │ │ - break │ │ │ │ │ - await self.write(block) │ │ │ │ │ - │ │ │ │ │ - logger.debug('reading response done') │ │ │ │ │ - # this returns immediately and does not read anything more, but updates the http.client's │ │ │ │ │ - # internal state machine to "response done" │ │ │ │ │ - block = response.read() │ │ │ │ │ - assert block == b'' │ │ │ │ │ - │ │ │ │ │ - await loop.run_in_executor(None, connection.close) │ │ │ │ │ - except (http.client.HTTPException, OSError) as exc: │ │ │ │ │ - raise ChannelError('terminated', message=str(exc)) from exc │ │ │ │ │ - │ │ │ │ │ - self.done() │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/channels/metrics.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import asyncio │ │ │ │ │ -import json │ │ │ │ │ -import logging │ │ │ │ │ -import sys │ │ │ │ │ -import time │ │ │ │ │ -from collections import defaultdict │ │ │ │ │ -from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union │ │ │ │ │ - │ │ │ │ │ -from ..channel import AsyncChannel, ChannelError │ │ │ │ │ -from ..jsonutil import JsonList │ │ │ │ │ -from ..samples import SAMPLERS, SampleDescription, Sampler, Samples │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class MetricInfo(NamedTuple): │ │ │ │ │ - derive: Optional[str] │ │ │ │ │ - desc: SampleDescription │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class InternalMetricsChannel(AsyncChannel): │ │ │ │ │ - payload = 'metrics1' │ │ │ │ │ - restrictions = [('source', 'internal')] │ │ │ │ │ - │ │ │ │ │ - metrics: List[MetricInfo] │ │ │ │ │ - samplers: Set │ │ │ │ │ - samplers_cache: Optional[Dict[str, Tuple[Sampler, SampleDescription]]] = None │ │ │ │ │ - │ │ │ │ │ - interval: int = 1000 │ │ │ │ │ - need_meta: bool = True │ │ │ │ │ - last_timestamp: float = 0 │ │ │ │ │ - next_timestamp: float = 0 │ │ │ │ │ - │ │ │ │ │ - @classmethod │ │ │ │ │ - def ensure_samplers(cls): │ │ │ │ │ - if cls.samplers_cache is None: │ │ │ │ │ - cls.samplers_cache = {desc.name: (sampler, desc) for sampler in SAMPLERS for desc in sampler.descriptions} │ │ │ │ │ - │ │ │ │ │ - def parse_options(self, options): │ │ │ │ │ - logger.debug('metrics internal open: %s, channel: %s', options, self.channel) │ │ │ │ │ - │ │ │ │ │ - interval = options.get('interval', self.interval) │ │ │ │ │ - if not isinstance(interval, int) or interval <= 0 or interval > sys.maxsize: │ │ │ │ │ - raise ChannelError('protocol-error', message=f'invalid "interval" value: {interval}') │ │ │ │ │ - │ │ │ │ │ - self.interval = interval │ │ │ │ │ - │ │ │ │ │ - metrics = options.get('metrics') │ │ │ │ │ - if not isinstance(metrics, list) or len(metrics) == 0: │ │ │ │ │ - logger.error('invalid "metrics" value: %s', metrics) │ │ │ │ │ - raise ChannelError('protocol-error', message='invalid "metrics" option was specified (not an array)') │ │ │ │ │ - │ │ │ │ │ - sampler_classes = set() │ │ │ │ │ - for metric in metrics: │ │ │ │ │ - # validate it's an object │ │ │ │ │ - name = metric.get('name') │ │ │ │ │ - units = metric.get('units') │ │ │ │ │ - derive = metric.get('derive') │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - sampler, desc = self.samplers_cache[name] │ │ │ │ │ - except KeyError as exc: │ │ │ │ │ - logger.error('unsupported metric: %s', name) │ │ │ │ │ - raise ChannelError('not-supported', message=f'unsupported metric: {name}') from exc │ │ │ │ │ - │ │ │ │ │ - if units and units != desc.units: │ │ │ │ │ - raise ChannelError('not-supported', message=f'{name} has units {desc.units}, not {units}') │ │ │ │ │ - │ │ │ │ │ - sampler_classes.add(sampler) │ │ │ │ │ - self.metrics.append(MetricInfo(derive=derive, desc=desc)) │ │ │ │ │ - │ │ │ │ │ - self.samplers = {cls() for cls in sampler_classes} │ │ │ │ │ - │ │ │ │ │ - def send_meta(self, samples: Samples, timestamp: float): │ │ │ │ │ - metrics: JsonList = [] │ │ │ │ │ - for metricinfo in self.metrics: │ │ │ │ │ - if metricinfo.desc.instanced: │ │ │ │ │ - metrics.append({ │ │ │ │ │ - 'name': metricinfo.desc.name, │ │ │ │ │ - 'units': metricinfo.desc.units, │ │ │ │ │ - 'instances': list(samples[metricinfo.desc.name].keys()), │ │ │ │ │ - 'semantics': metricinfo.desc.semantics │ │ │ │ │ - }) │ │ │ │ │ - else: │ │ │ │ │ - metrics.append({ │ │ │ │ │ - 'name': metricinfo.desc.name, │ │ │ │ │ - 'derive': metricinfo.derive, # type: ignore[dict-item] │ │ │ │ │ - 'units': metricinfo.desc.units, │ │ │ │ │ - 'semantics': metricinfo.desc.semantics │ │ │ │ │ - }) │ │ │ │ │ - │ │ │ │ │ - self.send_json(source='internal', interval=self.interval, timestamp=timestamp * 1000, metrics=metrics) │ │ │ │ │ - self.need_meta = False │ │ │ │ │ - │ │ │ │ │ - def sample(self): │ │ │ │ │ - samples = defaultdict(dict) │ │ │ │ │ - for sampler in self.samplers: │ │ │ │ │ - sampler.sample(samples) │ │ │ │ │ - return samples │ │ │ │ │ - │ │ │ │ │ - def calculate_sample_rate(self, value: float, old_value: Optional[float]) -> Union[float, bool]: │ │ │ │ │ - if old_value is not None and self.last_timestamp: │ │ │ │ │ - return (value - old_value) / (self.next_timestamp - self.last_timestamp) │ │ │ │ │ - else: │ │ │ │ │ - return False │ │ │ │ │ - │ │ │ │ │ - def send_updates(self, samples: Samples, last_samples: Samples): │ │ │ │ │ - data: List[Union[float, List[Optional[Union[float, bool]]]]] = [] │ │ │ │ │ - timestamp = time.time() │ │ │ │ │ - self.next_timestamp = timestamp │ │ │ │ │ - │ │ │ │ │ - for metricinfo in self.metrics: │ │ │ │ │ - value = samples[metricinfo.desc.name] │ │ │ │ │ - │ │ │ │ │ - if metricinfo.desc.instanced: │ │ │ │ │ - old_value = last_samples[metricinfo.desc.name] │ │ │ │ │ - assert isinstance(value, dict) │ │ │ │ │ - assert isinstance(old_value, dict) │ │ │ │ │ - │ │ │ │ │ - # If we have less or more keys the data changed, send a meta message. │ │ │ │ │ - if value.keys() != old_value.keys(): │ │ │ │ │ - self.need_meta = True │ │ │ │ │ - │ │ │ │ │ - if metricinfo.derive == 'rate': │ │ │ │ │ - instances: List[Optional[Union[float, bool]]] = [] │ │ │ │ │ - for key, val in value.items(): │ │ │ │ │ - instances.append(self.calculate_sample_rate(val, old_value.get(key))) │ │ │ │ │ - │ │ │ │ │ - data.append(instances) │ │ │ │ │ - else: │ │ │ │ │ - data.append(list(value.values())) │ │ │ │ │ - else: │ │ │ │ │ - old_value = last_samples.get(metricinfo.desc.name) │ │ │ │ │ - assert not isinstance(value, dict) │ │ │ │ │ - assert not isinstance(old_value, dict) │ │ │ │ │ - │ │ │ │ │ - if metricinfo.derive == 'rate': │ │ │ │ │ - data.append(self.calculate_sample_rate(value, old_value)) │ │ │ │ │ - else: │ │ │ │ │ - data.append(value) │ │ │ │ │ - │ │ │ │ │ - if self.need_meta: │ │ │ │ │ - self.send_meta(samples, timestamp) │ │ │ │ │ - │ │ │ │ │ - self.last_timestamp = self.next_timestamp │ │ │ │ │ - self.send_data(json.dumps([data]).encode()) │ │ │ │ │ - │ │ │ │ │ - async def run(self, options): │ │ │ │ │ - self.metrics = [] │ │ │ │ │ - self.samplers = set() │ │ │ │ │ - │ │ │ │ │ - InternalMetricsChannel.ensure_samplers() │ │ │ │ │ - │ │ │ │ │ - self.parse_options(options) │ │ │ │ │ - self.ready() │ │ │ │ │ - │ │ │ │ │ - last_samples = defaultdict(dict) │ │ │ │ │ - while True: │ │ │ │ │ - samples = self.sample() │ │ │ │ │ - self.send_updates(samples, last_samples) │ │ │ │ │ - last_samples = samples │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - await asyncio.wait_for(self.read(), self.interval / 1000) │ │ │ │ │ - return │ │ │ │ │ - except asyncio.TimeoutError: │ │ │ │ │ - # Continue the while loop, we use wait_for as an interval timer. │ │ │ │ │ - continue │ │ │ │ │ -''', │ │ │ │ │ - 'cockpit/channels/packages.py': br'''# This file is part of Cockpit. │ │ │ │ │ -# │ │ │ │ │ -# Copyright (C) 2022 Red Hat, Inc. │ │ │ │ │ -# │ │ │ │ │ -# This program 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. │ │ │ │ │ -# │ │ │ │ │ -# This program 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 this program. If not, see . │ │ │ │ │ - │ │ │ │ │ -import logging │ │ │ │ │ -from typing import Optional │ │ │ │ │ - │ │ │ │ │ -from ..channel import AsyncChannel │ │ │ │ │ -from ..data import read_cockpit_data_file │ │ │ │ │ -from ..jsonutil import JsonObject, get_dict, get_str │ │ │ │ │ -from ..packages import Packages │ │ │ │ │ - │ │ │ │ │ -logger = logging.getLogger(__name__) │ │ │ │ │ - │ │ │ │ │ - │ │ │ │ │ -class PackagesChannel(AsyncChannel): │ │ │ │ │ - payload = 'http-stream1' │ │ │ │ │ - restrictions = [("internal", "packages")] │ │ │ │ │ - │ │ │ │ │ - # used to carry data forward from open to done │ │ │ │ │ - options: Optional[JsonObject] = None │ │ │ │ │ - │ │ │ │ │ - def http_error(self, status: int, message: str) -> None: │ │ │ │ │ - template = read_cockpit_data_file('fail.html') │ │ │ │ │ - self.send_json(status=status, reason='ERROR', headers={'Content-Type': 'text/html; charset=utf-8'}) │ │ │ │ │ - self.send_data(template.replace(b'@@message@@', message.encode('utf-8'))) │ │ │ │ │ - self.done() │ │ │ │ │ - self.close() │ │ │ │ │ - │ │ │ │ │ - async def run(self, options: JsonObject) -> None: │ │ │ │ │ - packages: Packages = self.router.packages # type: ignore[attr-defined] # yes, this is evil │ │ │ │ │ - │ │ │ │ │ - try: │ │ │ │ │ - if get_str(options, 'method') != 'GET': │ │ │ │ │ - raise ValueError(f'Unsupported HTTP method {options["method"]}') │ │ │ │ │ - │ │ │ │ │ - self.ready() │ │ │ │ │ - if await self.read() != b'': │ │ │ │ │ - raise ValueError('Received unexpected data') │ │ │ │ │ - │ │ │ │ │ - path = get_str(options, 'path') │ │ │ │ │ - headers = get_dict(options, 'headers') │ │ │ │ │ - document = packages.load_path(path, headers) │ │ │ │ │ - │ │ │ │ │ - # Note: we can't cache documents right now. See │ │ │ │ │ - # https://github.com/cockpit-project/cockpit/issues/19071 │ │ │ │ │ - # for future plans. │ │ │ │ │ - out_headers = { │ │ │ │ │ - 'Cache-Control': 'no-cache, no-store', │ │ │ │ │ - 'Content-Type': document.content_type, │ │ │ │ │ - } │ │ │ │ │ - │ │ │ │ │ - if document.content_encoding is not None: │ │ │ │ │ - out_headers['Content-Encoding'] = document.content_encoding │ │ │ │ │ - │ │ │ │ │ - if document.content_security_policy is not None: │ │ │ │ │ - policy = document.content_security_policy │ │ │ │ │ - │ │ │ │ │ - # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/connect-src │ │ │ │ │ - # │ │ │ │ │ - # Note: connect-src 'self' does not resolve to websocket │ │ │ │ │ - # schemes in all browsers, more info in this issue. │ │ │ │ │ - # │ │ │ │ │ - # https://github.com/w3c/webappsec-csp/issues/7 │ │ │ │ │ - if "connect-src 'self';" in policy: │ │ │ │ │ - protocol = headers.get('X-Forwarded-Proto') │ │ │ │ │ - host = headers.get('X-Forwarded-Host') │ │ │ │ │ - if not isinstance(protocol, str) or not isinstance(host, str): │ │ │ │ │ - raise ValueError('Invalid host or protocol header') │ │ │ │ │ - │ │ │ │ │ - websocket_scheme = "wss" if protocol == "https" else "ws" │ │ │ │ │ - websocket_origin = f"{websocket_scheme}://{host}" │ │ │ │ │ - policy = policy.replace("connect-src 'self';", f"connect-src {websocket_origin} 'self';") │ │ │ │ │ - │ │ │ │ │ - out_headers['Content-Security-Policy'] = policy │ │ │ │ │ - │ │ │ │ │ - except ValueError as exc: │ │ │ │ │ - self.http_error(400, str(exc)) │ │ │ │ │ - │ │ │ │ │ - except KeyError: │ │ │ │ │ - self.http_error(404, 'Not found') │ │ │ │ │ - │ │ │ │ │ - except OSError as exc: │ │ │ │ │ - self.http_error(500, f'Internal error: {exc!s}') │ │ │ │ │ - │ │ │ │ │ - else: │ │ │ │ │ - self.send_json(status=200, reason='OK', headers=out_headers) │ │ │ │ │ - await self.sendfile(document.data) │ │ │ │ │ -''', │ │ │ │ │ })) │ │ │ │ │ from cockpit.bridge import main as main │ │ │ │ │ main(beipack=True) │ │ │ ├── ./usr/lib/python3/dist-packages/cockpit-311.dist-info/direct_url.json │ │ │ │ ├── Pretty-printed │ │ │ │ │┄ Similarity: 0.90625% │ │ │ │ │┄ Differences: {"'archive_info'": "{'hash': " │ │ │ │ │┄ "'sha256=db21ac8b9c9e699bfa4281ff97f13b94f631bc3cf1567ffa8a44246eeb81f9f7', " │ │ │ │ │┄ "'hashes': {'sha256': " │ │ │ │ │┄ "'db21ac8b9c9e699bfa4281ff97f13b94f631bc3cf1567ffa8a44246eeb81f9f7'}}"} │ │ │ │ │ @@ -1,9 +1,9 @@ │ │ │ │ │ { │ │ │ │ │ "archive_info": { │ │ │ │ │ - "hash": "sha256=1eeb38288684c94a41a89da1b7c490a6132460d2eb97fead27254de495f9f177", │ │ │ │ │ + "hash": "sha256=db21ac8b9c9e699bfa4281ff97f13b94f631bc3cf1567ffa8a44246eeb81f9f7", │ │ │ │ │ "hashes": { │ │ │ │ │ - "sha256": "1eeb38288684c94a41a89da1b7c490a6132460d2eb97fead27254de495f9f177" │ │ │ │ │ + "sha256": "db21ac8b9c9e699bfa4281ff97f13b94f631bc3cf1567ffa8a44246eeb81f9f7" │ │ │ │ │ } │ │ │ │ │ }, │ │ │ │ │ "url": "file:///build/reproducible-path/cockpit-311/tmp/wheel/cockpit-311-py3-none-any.whl" │ │ │ │ │ }