aboutsummaryrefslogtreecommitdiff
path: root/xmpp-cli-bridge/xmpp_cli_bridge/__main__.py
blob: b6200399bebe41dfd5f54919932bd34494c9fc24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""xmpp-cli-bridge --jid JID [--password PW] [--allow JID]... CMD [ARGS...]"""
from __future__ import annotations

import argparse
import logging
import os
import re
import selectors
import shlex
import subprocess
import threading
import time

# SGR sequences and lone ESC, so terminal colors don't leak into replies
_ANSI = re.compile(r"\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07]*\x07|.)")

from slixmpp import JID

from . import serve

logger = logging.getLogger(__name__)

QUIET = 0.5   # seconds of silent stdout before a reply is considered complete
MAX_WAIT = 30.0
BOOT_WAIT = 30.0  # how long to wait for the child's first prompt at startup


def _drain(proc: subprocess.Popen) -> None:
    # discard stale output (startup prompt, stragglers) so a reply only
    # contains what the child produced after the current command
    sel = selectors.DefaultSelector()
    sel.register(proc.stdout, selectors.EVENT_READ)
    while sel.select(0.05):
        if not os.read(proc.stdout.fileno(), 65536):
            break
    sel.close()


def _tail_match(text: str, prompt: re.Pattern[str]) -> re.Match[str] | None:
    # only a match ending at the very end of the buffer counts, and it must
    # be finditer's LAST match: search()'s leftmost one can be an earlier
    # prompt-like line (blockquote "> ", PS2 continuation), which shadows
    # the real prompt and stalls the reply until the max-wait timeout
    matches = list(prompt.finditer(text))
    return matches[-1] if matches and matches[-1].end() == len(text) else None


def _read_output(
    proc: subprocess.Popen, prompt: re.Pattern[str] | None, max_wait: float
) -> str:
    sel = selectors.DefaultSelector()
    sel.register(proc.stdout, selectors.EVENT_READ)
    buf = bytearray()
    started = time.monotonic()
    deadline = started + max_wait
    while time.monotonic() < deadline:
        if not sel.select(QUIET):
            if prompt is None:
                break
            continue  # prompt mode: silence doesn't end the reply
        chunk = os.read(proc.stdout.fileno(), 65536)
        if not chunk:
            logger.info("child closed stdout after %.1fs", time.monotonic() - started)
            break
        buf += chunk
        if prompt is not None:
            # chat-sized outputs; decode() per chunk would split multibyte chars
            text = bytes(buf).decode("utf-8", "replace")
            m = _tail_match(text, prompt)
            if m is not None:
                logger.info(
                    "reply complete after %.1fs (prompt %r%s)",
                    time.monotonic() - started,
                    text[m.start() : m.end()],
                    "" if text[: m.start()].strip() else ", but empty",
                )
                return _ANSI.sub("", text[: m.start()])
    sel.close()
    text = _ANSI.sub("", bytes(buf).decode("utf-8", "replace"))
    if prompt is not None:
        m = _tail_match(text, prompt)
        if m is not None:
            return text[: m.start()]  # timeout: still strip a trailing prompt
        logger.warning(
            "no prompt match after %.1fs, replying with the raw buffer; tail: %r",
            time.monotonic() - started, text[-120:],
        )
    return text


def make_handler(
    argv: list[str],
    allowed: set[str],
    prompt: re.Pattern[str] | None = None,
    max_wait: float = MAX_WAIT,
):
    # MULTILINE so user-supplied ^/$ anchors work against the whole buffer
    if prompt is not None and prompt.flags & re.MULTILINE == 0:
        prompt = re.compile(prompt.pattern, prompt.flags | re.MULTILINE)
    # argv runs directly, never via a shell -- this is the trust boundary
    proc = subprocess.Popen(
        argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None
    )
    logger.info("child started: %s", shlex.join(argv))
    # consume the startup banner/prompt now: left in the pipe it races the
    # first message into an empty reply and gets the real answer discarded
    t0 = time.monotonic()
    banner = _read_output(proc, prompt, BOOT_WAIT)
    if proc.poll() is not None:
        logger.warning("child exited during startup (code %s)", proc.returncode)
    elif time.monotonic() - t0 >= BOOT_WAIT:
        logger.warning("no startup prompt within %.0fs; first replies may be off", BOOT_WAIT)
    else:
        logger.info("child ready after %.1fs", time.monotonic() - t0)
        if banner.strip():
            logger.info("discarded startup output: %.200r", banner)
    lock = threading.Lock()  # serialize messages: one stdin/stdout conversation

    def handle(body: str, sender: str):
        if JID(sender).bare not in allowed:
            logger.info("ignored message from %s (not allowlisted)", sender)
            return None
        with lock:
            if proc.poll() is not None:
                return f"process exited ({proc.returncode})"
            try:
                _drain(proc)
                logger.info("-> child: %.200r", body)
                proc.stdin.write(body.encode() + b"\n")
                proc.stdin.flush()
            except (BrokenPipeError, ValueError):
                return f"process exited ({proc.returncode})"
            out = _read_output(proc, prompt, max_wait)
            if proc.poll() is not None and not out:
                return f"process exited ({proc.returncode})"
            if not out.strip():
                # bare prompt or empty turn: silence, not an empty XMPP message
                logger.warning("child produced an empty reply; sending nothing")
                return None
            return out

    return handle


def main(argv: list[str] | None = None) -> None:
    p = argparse.ArgumentParser(description="Expose a CLI application over XMPP.")
    p.add_argument("--jid", required=True)
    p.add_argument("--password", default=os.environ.get("XMPP_PASSWORD"))
    p.add_argument("--allow", action="append", default=[], metavar="JID",
                   help="sender bare JID allowed to interact (repeatable)")
    p.add_argument("--prompt", metavar="REGEX", default=None,
                   help="reply ends when stdout ends with a line matching REGEX; "
                        "without it replies end after %.1fs of silence" % QUIET)
    p.add_argument("--max-wait", type=float, default=MAX_WAIT, metavar="SECONDS",
                   help="overall reply timeout (default %g)" % MAX_WAIT)
    p.add_argument("cmd", nargs=argparse.REMAINDER, metavar="CMD")
    args = p.parse_args(argv)
    if not args.password:
        p.error("--password or XMPP_PASSWORD required")
    if not args.cmd:
        p.error("CMD required")
    if args.cmd[0] == "--":  # REMAINDER keeps the separator
        args.cmd.pop(0)
    # default deny: only the bridge account's own bare JID
    allowed = {JID(j).bare for j in args.allow} or {JID(args.jid).bare}
    prompt = re.compile(args.prompt) if args.prompt else None
    serve(
        args.jid,
        args.password,
        make_handler(args.cmd, allowed, prompt, args.max_wait),
    )


if __name__ == "__main__":
    main()