#!/usr/bin/python3 -u

import time

_startt = time.time()

import base64
import errno
import fcntl
import json
import os
import select
import signal
import struct
import subprocess
import sys
import syslog
import traceback
from shlex import quote


MAX_MUX_READ = 128 * 1024
PACKLEN = 8
PACKFORMAT = "!HbIx"


def set_proc_name(newname):
    from ctypes import cdll, byref, create_string_buffer

    if isinstance(newname, str):
        # argv can carry surrogateescape characters (PEP 383: bytes the
        # interpreter could not decode appear in sys.argv as
        # \udc80-\udcff); the comm string must stay encodable.
        newname = newname.encode("utf-8", "backslashreplace")
    libc = cdll.LoadLibrary("libc.so.6")
    buff = create_string_buffer(len(newname) + 1)
    buff.value = newname
    libc.prctl(15, byref(buff), 0, 0, 0)


_CMDLINE_ANCHOR = b"\x00-u\x00-c\x00"
debug_enabled = False
logging = None


def _arg_range(data, anchor_pos, b64, has_d):
    """Self-check the launch shape at `anchor_pos` (the byte after argv0
    in `<argv0>\x00-u\x00-c\x00<source>\x00[-d\x00]<b64>\x00`); return
    the argv span (arg_start, arg_end) as offsets into `data`, else None.
    Every byte is checked against our own argv -- an env value can only
    fake the anchor by carrying \x00-u\x00-c\x00 PLUS a token tail that
    equals our session's b64 payload, which is not possible short of a
    collision this wide."""
    src_start = anchor_pos + len(_CMDLINE_ANCHOR)
    src_end = data.find(b"\x00", src_start)
    if src_end < 0 or src_end - src_start < 32:
        return None
    tok = src_end + 1
    if has_d:
        if data[tok : tok + 3] != b"-d\x00":
            return None
        tok += 3
    if tok + len(b64) >= len(data):
        return None  # tail cut by the read window: no verify
    if data[tok : tok + len(b64)] != b64 or data[tok + len(b64)] != 0:
        return None
    # back-scan over argv0 (argv tokens never contain \x00); the byte
    # below argv0 is the zero padding under the args region
    p = anchor_pos - 1
    while p >= 0 and data[p] != 0:
        p -= 1
    argv0 = bytes(data[p + 1 : anchor_pos])
    if not 1 <= len(argv0) <= 128 or any(c < 32 for c in argv0):
        return None
    return p + 1, tok + len(b64) + 1


def set_cmdline(title):
    """Rewrite /proc/self/cmdline in place, so that a local `ps` on the
    remote shows one short, clean line (`title`) instead of the launch
    form used to bootstrap the remote  --  the master's one-liner
    `python -u -c '<whole source>' [-d] <b64>` (wire contract, spec
    section 1.1), whose argv would print the entire script.
    `set_proc_name` alone cannot do this: prctl(2) only sets the 15-byte
    comm (top/htop/`ps -C`); `ps` prints the argv.

    The kernel hands /proc/<pid>/cmdline the very memory range
    (mm->arg_start..arg_end) built at exec and never updates it, so
    writing a shorter argv into that range -- NUL-padded back to the
    original size -- changes what `ps` shows without a re-exec,
    touch-free to the wire and to the interpreter (sys.argv is
    untouched; only the memory behind it changes).

    The range is located by anchoring on the known launch shape in the
    args region at the top of our own [stack] mapping and is
    self-checked byte-for-byte (including our b64 payload) before
    anything is written.  Any unexpected condition (layout not as
    assumed, title too long for the range, platform without the
    expected stack mapping) makes the rewrite silently no-op (debug
    log): it is a display aid, never load-bearing -- the session
    proceeds in all cases.
    """
    b64 = sys.argv[-1].encode("utf-8")
    has_d = "-d" in sys.argv[1:-1]

    try:
        with open("/proc/self/maps") as maps:
            for line in maps:
                if line.rstrip().endswith("[stack]"):
                    low, rest = line.split("-", 1)
                    map_low = int(low, 16)
                    map_end = int(rest.split()[0], 16)
                    break
            else:
                logging.debug("set_cmdline: no [stack] mapping; skip")
                return False
    except (OSError, ValueError) as e:
        logging.debug("set_cmdline: cannot read /proc/self/maps: %s", e)
        return False

    window = min(map_end - map_low, 1 << 22)
    try:
        with open("/proc/self/mem", "rb") as mem:
            mem.seek(map_end - window)
            data = mem.read(window)
    except (OSError, ValueError) as e:
        logging.debug("set_cmdline: cannot read the stack: %s", e)
        return False
    if len(data) != window:
        logging.debug("set_cmdline: short stack read (%d); skip", len(data))
        return False
    base = map_end - window

    a = data.find(_CMDLINE_ANCHOR)
    span = None
    while a >= 0:
        span = _arg_range(data, a, b64, has_d)
        if span is not None:
            break
        a = data.find(_CMDLINE_ANCHOR, a + 1)
    if span is None:
        # the -s launch forms (local probe drives) carry no -c at all; a
        # miss also covers platforms that lay the args out elsewhere
        logging.debug("set_cmdline: launch shape not found on the stack; skip")
        return False
    arg_start, arg_end = span

    new = (title + "\x00").encode("utf-8", "backslashreplace")
    total = arg_end - arg_start
    if len(new) > total:
        logging.debug(
            "set_cmdline: title (%d) will not fit the argv range (%d); skip",
            len(new),
            total,
        )
        return False
    new += b"\x00" * (total - len(new))
    try:
        with open("/proc/self/mem", "r+b") as mem:
            mem.seek(base + arg_start)
            mem.write(new)
    except OSError as e:
        logging.debug("set_cmdline: cannot write the stack: %s", e)
        return False
    try:
        with open("/proc/self/cmdline", "rb") as f:
            got = f.read().split(b"\x00", 1)[0]
    except OSError as e:
        logging.debug("set_cmdline: readback failed: %s", e)
        return False
    if got != new.split(b"\x00", 1)[0]:
        logging.debug("set_cmdline: readback mismatch: %r", got[:60])
        return False
    logging.debug("set_cmdline: argv range (%d B) now reads: %r", total, got)
    return True


def unset_cloexec(fd):
    old = fcntl.fcntl(fd, fcntl.F_GETFD)
    fcntl.fcntl(fd, fcntl.F_SETFD, old & ~fcntl.FD_CLOEXEC)


def openfdforappend(fd):
    f = None
    try:
        f = os.fdopen(fd, "ab", 0)
    except IOError as e:
        if e.errno != errno.ESPIPE:
            raise
        f = os.fdopen(fd, "wb", 0)
    unset_cloexec(f.fileno())
    return f


def openfdforread(fd):
    f = os.fdopen(fd, "rb", 0)
    unset_cloexec(f.fileno())
    return f


class LoggingEmu:
    def __init__(self, prefix):
        self.prefix = prefix
        syslog.openlog("bombshell-client.%s" % self.prefix)

    def debug(self, *a, **kw):
        if not debug_enabled:
            return
        self._print(syslog.LOG_DEBUG, *a, **kw)

    def info(self, *a, **kw):
        self._print(syslog.LOG_INFO, *a, **kw)

    def error(self, *a, **kw):
        self._print(syslog.LOG_ERR, *a, **kw)

    def _print(self, prio, *a, **kw):
        global _startt
        deltat = time.time() - _startt
        if len(a) == 1:
            string = a[0]
        else:
            string = a[0] % a[1:]
        # The syslog C lattice encodes strictly and dies on the
        # surrogateescape characters argv can legitimately carry
        # (PEP 383) -- one composition point, composed from here.
        string = bytes(string, "utf-8", "backslashreplace").decode("utf-8")
        syslog.syslog(
            prio,
            ("%.3f  " % deltat) + self.prefix + ": " + string,
        )


def send_confirmation(chan, retval, errmsg):
    chan.write(struct.pack("!H", retval))
    ln = len(errmsg)
    assert ln < 1 << 32
    chan.write(struct.pack("!I", ln))
    chan.write(errmsg)
    chan.flush()
    logging.debug(
        "Sent confirmation on channel %s: %s %s",
        chan,
        retval,
        errmsg,
    )


def read_exact(f, n):
    """Blocking read of exactly n bytes. Returns None on EOF.
    Successor to the fragile 2/4/lc reads of recv_confirmation."""
    buf = b""
    while len(buf) < n:
        chunk = f.read(n - len(buf))
        if not chunk:
            return None
        buf += chunk
    return buf


def write_all_file(f, data):
    """Real partial-write loop for file objects. Returns bytes written.
    EPIPE/OSError propagate  --  callers apply per-sink policy (P9/P15/P12)."""
    mv = memoryview(data)
    written = 0
    while len(mv):
        k = f.write(mv)
        if k is None or k < 1:
            raise OSError(errno.EIO, "short write on %s" % f)
        written += k
        mv = mv[k:]
    return written


def writev_all(fd, buffers):
    """Loop os.writev until every buffer is fully written. A safe EPIPE
    raises. The header/payload pair of a frame leaves through here  --  one
    logical unit (spec section 2.3/section 4.4: the pre-rewrite end's
    adjacent separate syscalls were the tear class this removes)."""
    views = [memoryview(b) for b in buffers if b]
    total = sum(len(v) for v in views)
    done = 0
    while done < total:
        k = os.writev(fd, views)
        if k <= 0:
            raise OSError(errno.EIO, "writev did not advance")
        done += k
        i = 0
        while k and i < len(views):
            take = min(k, len(views[i]))
            views[i] = views[i][take:]
            k -= take
            i += 1
        while views and not len(views[0]):
            views.pop(0)
    return total


def send_frame(fd, stream, active, payload=b""):
    """One multiplex frame: 8-byte header + payload, one writev.
    close == active False, payload empty."""
    header = struct.pack(PACKFORMAT, stream, active, len(payload))
    if payload:
        writev_all(fd, [header, payload])
    else:
        os.write(fd, header)


def quotedargs():
    return " ".join(quote(x) for x in sys.argv[1:])


def quotedargs_ellipsized(cmdlist):
    text = " ".join(quote(x) for x in cmdlist)
    if len(text) > 80:
        text = text[:77] + "..."
    return text


HANDLED_SIGNALS = (
    signal.SIGINT,
    signal.SIGABRT,
    signal.SIGALRM,
    signal.SIGTERM,
    signal.SIGUSR1,
    signal.SIGUSR2,
    signal.SIGTSTP,
    signal.SIGCONT,
)


def main_remote():
    set_proc_name("bombshell-client (remote) %s" % quotedargs())
    global logging
    logging = LoggingEmu("remote")

    logging.info("Started with arguments: %s", quotedargs_ellipsized(sys.argv[1:]))

    # The remote is invoked either self-embedded (python -c: CPython
    # normalizes sys.argv to ['-c', ...], dropping the interpreter, -u
    # and the source argument) or directly (-s); the base64 JSON
    # payload is ALWAYS the last argument in every launch form, and
    # the base64 alphabet never starts a token with '-'.
    global debug_enabled
    if "-d" in sys.argv[1:]:
        debug_enabled = True
    cmd_b64 = sys.argv[-1]

    try:
        cmd = json.loads(base64.b64decode(cmd_b64))
    except Exception as e:
        logging.error("Cannot decode command from remote side: %s", e)
        return 125
    # The carrier must not carry any code-execution primitive: the
    # pickle this replaced deserialized as arbitrary Python (`loads`
    # WILL execute on hostile or stale payloads), and no shape check
    # after it could have fixed that.  The JSON payload is exactly a
    # list of strings -- verify it, else refuse (a stale
    # mixed-version payload lands here too, as a clean 125).
    if not isinstance(cmd, list) or not all(isinstance(a, str) for a in cmd):
        logging.error(
            "Command payload is not a plain str list, refusing to execute "
            "(top-level type %s)",
            type(cmd).__name__,
        )
        return 125
    logging.debug("Received command: %s", cmd)

    nicecmd = quotedargs_ellipsized(cmd)

    # The remote lives under its whole launch form (`python -u -c
    # '<entire source>' [-d] <b64>`, spec section 1.1), so the local `ps`
    # would print the entire script as its command line.  Shrink the
    # argv a ps sees to the session line (set_cmdline, spec section
    # 9.k: rewritten in place, every byte self-checked, silent no-op on
    # any miss)  --  the wire, the confirmation and sys.argv themselves
    # are untouched.
    set_cmdline("bombshell-client (remote) %s" % nicecmd)

    # SIGCHLD self-pipe, wired before Popen (spec section 4.5 invariant 1): a child
    # that dies at exec must still wake the loop. The handler writes one
    # byte and nothing else; reaping happens only in the death branch.
    chld_rd, chld_wr = os.pipe()
    os.set_blocking(chld_wr, False)
    signal.signal(signal.SIGCHLD, lambda s, f: os.write(chld_wr, b"\x01"))

    try:
        p = subprocess.Popen(
            cmd,
            # The child gets its own session and process group, so
            # group-wide signals (e.g. the remote VM's own Ctrl-C) no
            # longer hit it at the kernel level  --  relay stays frame-only,
            # one delivery (spec section 5.1/section 9.1 c).
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            start_new_session=True,
            close_fds=True,
            bufsize=0,
        )
        # one defensive read right after spawn: instant exec failure is
        # caught harmlessly (Popen caches the status for the death branch)
        p.poll()
        send_confirmation(sys.stdout, 0, b"")
    except OSError as e:
        msg = "cannot execute %s: %s" % (nicecmd, e)
        logging.error(msg)
        send_confirmation(
            sys.stdout, 127, bytes(msg, "utf-8", "backslashreplace"))
        return 0
    except BaseException as e:
        msg = "cannot execute %s: %s" % (nicecmd, e)
        logging.error(msg)
        send_confirmation(
            sys.stdout, 126, bytes(msg, "utf-8", "backslashreplace"))
        return 0

    logging.info("Started %s", nicecmd)

    # The single loop: exactly four uniformly-ready sources per round  --
    # channel (sys.stdin), child stdout, child stderr, death pipe.
    # No timeout, no per-wake reaping probe: the death byte is the
    # waitable end-of-session (spec section 7.5.2).
    live_out = {0: p.stdout, 1: p.stderr}  # outward frames: 0=stdout, 1=stderr
    stdin_open = True  # inward stream 0's sink (child stdin)
    acc = bytearray()  # frame accumulator: short reads impossible
    buf = bytearray(MAX_MUX_READ)  # scratch for readinto
    chan_out = sys.stdout.fileno()
    channel_dead = False

    while True:
        r = select.select([sys.stdin, chld_rd] + list(live_out.values()), [], [])[0]
        # (after both close frames: [sys.stdin, chld_rd]  --  still meaningful,
        # still bounded: the child either dies (P5), or the peer goes (P6).)
        # channel_dead is per-wake (spec section 5.2, note 1): once set by a
        # failed channel send in branch (1), it skips branches (3)/(4) only
        # for the rest of this wake; the next wake re-tests, so P5/P6 stay
        # reachable after a channel loss instead of the loop spinning.
        channel_dead = False

        # (1) child stdout, (2) child stderr  --  drain order (spec section 7.5.3)
        for n in (0, 1):
            src = live_out.get(n)
            if src is None or src not in r:
                continue
            have = src.readinto(buf)
            if have == 0:  # EOF: close frame, once
                src.close()
                del live_out[n]
                try:
                    send_frame(chan_out, n, False)
                except OSError as e:
                    logging.error("can't close stream %d frame: %s", n, e)
                    channel_dead = True
                    break
            else:  # data: framed writev
                try:
                    send_frame(chan_out, n, True, memoryview(buf)[:have])
                except OSError as e:  # P10
                    logging.error("channel write failed: %s", e)
                    channel_dead = True
                    break

        # (3) child death  --  the waitable end-of-session; reaping is once, here.
        if not channel_dead and chld_rd in r:
            os.read(chld_rd, 64)  # drains the wake byte(s)
            p.poll()  # = waitpid(WNOHANG)
            rc = p.returncode
            logging.info("child exited, status %s", rc)
            # No group kill: grand-children are orphaned; they EPIPE at
            # their next write or linger  --  accepted (spec section 9.2).
            return rc if rc is not None else 1  # ABANDON: no drain

        # (4) channel input  --  last; any keystroke in the fatal wake is
        # never framed (spec section 9.1 g)
        if not channel_dead and sys.stdin in r:
            chunk = sys.stdin.read(MAX_MUX_READ)
            if not chunk:  # P6: channel EOF
                logging.error("channel closed, child still alive")
                return 1  # child orphaned
            acc += chunk
            while len(acc) >= PACKLEN:
                n, active, ln = struct.unpack(PACKFORMAT, acc[:PACKLEN])
                need = PACKLEN + (0 if not active else ln)
                if len(acc) < need:
                    break  # partial body: wait
                body = bytes(acc[PACKLEN:need])
                del acc[:need]
                if not active:  # P7/P8: close frame
                    if n == 0 and stdin_open:
                        p.stdin.close()
                        stdin_open = False
                        logging.debug("child stdin closed by peer")
                    # n==1 close has nothing to close (signals are stateless);
                    # repeated closes are no-ops, never errors
                    continue
                if n == 0:  # P9: keyboard input
                    if stdin_open:
                        try:
                            write_all_file(p.stdin, body)
                        except OSError as e:
                            # child died in this wake, before the death
                            # byte arrived; per-sink demotion, not fatal
                            logging.debug("child stdin dead: %s", e)
                            p.stdin.close()
                            stdin_open = False
                    # a stream-0 frame with stdin closed is dropped, never
                    # an error
                elif n == 1:  # P11: relayed signal
                    for i in range(0, len(body) - 1, 2):
                        try:
                            p.send_signal(struct.unpack("!H", body[i : i + 2])[0])
                        except OSError as e:
                            logging.debug("signal delivery failed: %s", e)
    # Only P5 (child death) and P6 (channel EOF) end the loop  --  both by return.
    return 0


def main_master():
    set_proc_name("bombshell-client (master) %s" % quotedargs())
    global logging
    logging = LoggingEmu("master")

    logging.info("Started with arguments: %s", quotedargs_ellipsized(sys.argv[1:]))

    global debug_enabled
    args = sys.argv[1:]
    if args[0] == "-d":
        args = args[1:]
        debug_enabled = True

    remote_vm = args[0]
    remote_command = args[1:]
    assert remote_command

    def anypython(exe):
        return "` test -x %s && echo %s || echo python3`" % (
            quote(exe),
            quote(exe),
        )

    # The remote bootstrap helper text stays byte-identical (wire contract,
    # spec section 1.1); do not reformat anything inside.
    remote_helper_text = b"exec "
    remote_helper_text += bytes(anypython(sys.executable), "utf-8")
    remote_helper_text += b" -u -c "
    remote_helper_text += bytes(
        quote(open(__file__, "r").read()),
        "ascii",
    )
    remote_helper_text += b" -d " if debug_enabled else b" "
    # The payload is always a plain str list (sys.argv tail): JSON is
    # the lossless carrier for it and, unlike the pickle this
    # replaced, `json.loads` cannot execute a thing (2026-10-27).
    # ensure_ascii keeps the pre-base64 text pure ASCII; the base64
    # lane makes it shell-token-safe on the helper one-liner.
    remote_helper_text += base64.b64encode(
        json.dumps(remote_command).encode("ascii")
    )
    remote_helper_text += b"\n"

    saved_stderr = openfdforappend(os.dup(sys.stderr.fileno()))

    # SIGCHLD self-pipe, wired before Popen (spec section 4.5 invariant 1): the
    # qrexec-client-vm proxy is our only child; its death is the master's
    # session-end event (P17).
    chld_rd, chld_wr = os.pipe()
    os.set_blocking(chld_wr, False)
    signal.signal(signal.SIGCHLD, lambda s, f: os.write(chld_wr, b"\x01"))

    try:
        p = subprocess.Popen(
            ["qrexec-client-vm", remote_vm, "qubes.VMShell"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            close_fds=True,
            preexec_fn=os.setpgrp,
            bufsize=0,
        )
        # one defensive read right after spawn (spec section 6.1 step 5)
        p.poll()
    except OSError as e:
        logging.error("cannot launch qrexec-client-vm: %s", e)
        return 127

    logging.debug("Writing the helper text into the other side")
    p.stdin.write(remote_helper_text)
    p.stdin.flush()

    # The confirmation phase (spec section 6.2): select-gated accumulation, before
    # the TTY or the signal pipe occur in any read list. The proxy may die
    # before the confirmation arrives; the two possibilities are
    # distinguished here, never polled.
    conf = bytearray()
    confirmation = None
    while confirmation is None:
        r = select.select([p.stdout, chld_rd], [], [])[0]
        if p.stdout in r:
            got = p.stdout.read(MAX_MUX_READ)
            if got:
                conf += got
                if len(conf) >= 2:
                    code = struct.unpack("!H", bytes(conf[:2]))[0]
                    if len(conf) >= 6:
                        ln = struct.unpack("!I", bytes(conf[2:6]))[0]
                        if len(conf) >= 6 + ln:
                            errmsg = bytes(conf[6 : 6 + ln])
                            if code != 0:
                                logging.error(
                                    "remote: %s", errmsg.decode("utf-8", "replace")
                                )
                            confirmation = code
            else:
                # EOF before anything parseable: "domain does not exist"
                return 125
        if chld_rd in r:
            os.read(chld_rd, 64)
            p.poll()
            rc = p.returncode
            logging.error("proxy died before confirmation, status %s", rc)
            return rc if rc is not None else 125

    if confirmation != 0:
        return confirmation
    # confirmation == 0: clean session start

    # The signal-relay self-pipe (master only, spec section 4.6): one byte = the
    # signum; reached only after a clean confirmation, matching the
    # current install order.
    sig_rd, sig_wr = os.pipe()
    os.set_blocking(sig_wr, False)
    for sig in HANDLED_SIGNALS:
        signal.signal(sig, lambda s, f: os.write(sig_wr, bytes((s,))))

    # The session loop: four uniformly-ready sources per round  --  proxy
    # stdout, user TTY (while it is live), signal pipe, death pipe.
    in_live = {0: sys.stdout, 1: saved_stderr}  # channel frame n -> local sink
    kbd_live = True  # TTY stream 0 still readable
    acc = bytearray()  # receiver accumulator
    channel_dead = False

    while True:
        r = select.select(
            [p.stdout] + ([sys.stdin] if kbd_live else []) + [sig_rd, chld_rd], [], []
        )[0]

        # (1) channel demux first  --  final lines arrive before any end (spec section 7.5.3)
        if p.stdout in r:
            got = p.stdout.read(MAX_MUX_READ)
            if got:
                acc += got
            while len(acc) >= PACKLEN:
                n, active, ln = struct.unpack(PACKFORMAT, acc[:PACKLEN])
                need = PACKLEN + (0 if not active else ln)
                if len(acc) < need:
                    break  # partial body: wait
                body = bytes(acc[PACKLEN:need])
                del acc[:need]
                sink = in_live.get(n)
                if sink is None:
                    continue  # sink already dropped: a no-op, never an error
                if active:  # P15
                    try:
                        write_all_file(sink, body)
                    except OSError as e:
                        logging.debug("local sink %d dead: %s", n, e)
                        sink.close()
                        del in_live[n]  # sink EPIPE: drop, continue
                else:  # P16
                    logging.debug("remote closed stream %d", n)
                    sink.close()
                    del in_live[n]
            if not got:  # P18: channel EOF
                logging.debug("channel EOF")
                channel_dead = True
                break  # any remainder in acc was delivered above

        # (2) proxy death  --  the master's session-end detector; reaping is once
        if not channel_dead and chld_rd in r:
            os.read(chld_rd, 64)
            p.poll()
            rc = p.returncode
            logging.info("proxy exit status %s (== remote session status)", rc)
            return rc if rc is not None else 1

        # (3) local signals -> frame n=1
        if not channel_dead and sig_rd in r:
            data = os.read(sig_rd, 64)
            for b in data:
                try:
                    send_frame(p.stdin.fileno(), 1, True, struct.pack("!H", b))
                except OSError as e:
                    logging.debug("signal frame failed: %s", e)
                    break

        # (4) keyboard -> frame n=0; Ctrl-D -> close frame n=0 (once)
        if not channel_dead and sys.stdin in r:
            got = sys.stdin.read(MAX_MUX_READ)
            if got:
                try:
                    send_frame(p.stdin.fileno(), 0, True, got)
                except OSError as e:
                    logging.debug("stdin frame failed: %s", e)
                    # the proxy is dying; its death wake (P17) ends the session
            elif kbd_live:
                try:
                    send_frame(p.stdin.fileno(), 0, False)
                except OSError as e:
                    logging.debug("stdin close frame failed: %s", e)
                kbd_live = False  # no longer read the TTY

    # P18 close-out: the remote's exit closed the channel, which ends the
    # proxy; the returned status is the remote session status.
    p.poll()
    if p.returncode is None:
        p.wait()
    return p.returncode if p.returncode is not None else 1


sys.stdin = openfdforread(sys.stdin.fileno())
sys.stdout = openfdforappend(sys.stdout.fileno())


def _shell_status(status):
    """THE single status conversion point (spec section 11.2 status
    note).  A CPython wait status for a process killed by a signal is
    NEGATIVE (-signum); a raw negative passed to sys.exit would surface
    as `(-signum) & 0xFF = 256-signum` (247 for SIGKILL, 254 for SIGINT)
    -- un-decodable by any caller.  Every status path converges on this
    boundary (section 3.4 flow; section 6.4 exit paths A/B), so convert
    to the shell convention 128+signum once here, at the exit point:
    the value the calling shell reports for the very same local kill
    (130 for SIGINT, 137 for SIGKILL).  Normal statuses pass through
    unchanged.
    """
    if status is None:
        return 1
    return 128 - status if status < 0 else status


def _main():
    global logging
    try:
        if "__file__" in globals() and not ("-s" in sys.argv[1:2]):
            return main_master()
        return main_remote()
    except SystemExit:
        raise
    except BaseException:
        if logging is None:
            logging = LoggingEmu("bootstrap")
        logging.error("unhandled exception in the main loop")
        logging.error("traceback: %s", traceback.format_exc())
        return 1


sys.exit(_shell_status(_main()))
