| 1 | |
| 2 | |
| 3 | import json |
| 4 | import ctypes |
| 5 | import os |
| 6 | import selectors |
| 7 | import signal |
| 8 | import subprocess |
| 9 | import sys |
| 10 | import time |
| 11 | |
| 12 | def enable_subreaper(): |
| 13 | |
| 14 | |
| 15 | if not sys.platform.startswith("linux"): |
| 16 | return False |
| 17 | libc = ctypes.CDLL(None, use_errno=True) |
| 18 | if libc.prctl(36, 1, 0, 0, 0) != 0: |
| 19 | raise OSError(ctypes.get_errno(), "cannot contain guest CLI descendants") |
| 20 | with open("/proc/thread-self/children", "rb") as children: |
| 21 | children.read() |
| 22 | return True |
| 23 | |
| 24 | def reap_adopted(): |
| 25 | deadline = time.monotonic() + 3 |
| 26 | while True: |
| 27 | try: |
| 28 | while os.waitpid(-1, os.WNOHANG)[0]: |
| 29 | pass |
| 30 | except ChildProcessError: |
| 31 | return |
| 32 | with open("/proc/thread-self/children", "rb") as children: |
| 33 | pids = [int(value) for value in children.read().split()] |
| 34 | |
| 35 | |
| 36 | for pid in pids: |
| 37 | try: |
| 38 | os.kill(pid, signal.SIGKILL) |
| 39 | except ProcessLookupError: |
| 40 | pass |
| 41 | if time.monotonic() >= deadline: |
| 42 | raise RuntimeError("guest CLI descendants still await termination") |
| 43 | time.sleep(0.02) |
| 44 | |
| 45 | FRAME_LIMIT = 256 * 1024 |
| 46 | |
| 47 | def terminate(child): |
| 48 | try: |
| 49 | os.killpg(child.pid, signal.SIGTERM) |
| 50 | except ProcessLookupError: |
| 51 | return |
| 52 | deadline = time.monotonic() + 0.8 |
| 53 | while time.monotonic() < deadline: |
| 54 | child.poll() |
| 55 | try: |
| 56 | os.killpg(child.pid, 0) |
| 57 | except ProcessLookupError: |
| 58 | return |
| 59 | time.sleep(0.04) |
| 60 | try: |
| 61 | os.killpg(child.pid, signal.SIGKILL) |
| 62 | except ProcessLookupError: |
| 63 | pass |
| 64 | |
| 65 | def run(): |
| 66 | incoming = bytearray() |
| 67 | while b"\n" not in incoming: |
| 68 | block = os.read(0, 8192) |
| 69 | if not block or len(incoming) + len(block) > FRAME_LIMIT: |
| 70 | return 2 |
| 71 | incoming.extend(block) |
| 72 | first, _, incoming = incoming.partition(b"\n") |
| 73 | mode = json.loads(first) |
| 74 | streaming = mode == {"stream": True} |
| 75 | if not streaming and (not isinstance(mode, str) or not 0 < len(mode.encode()) <= 32768): |
| 76 | return 2 |
| 77 | if not os.path.isabs(sys.argv[1]): |
| 78 | return 2 |
| 79 | subreaper = enable_subreaper() |
| 80 | pending = bytearray() if streaming else bytearray(mode.encode()) |
| 81 | finished = not streaming |
| 82 | child = subprocess.Popen(sys.argv[2:], cwd=sys.argv[1], stdin=subprocess.PIPE, |
| 83 | bufsize=0, start_new_session=True) |
| 84 | def interrupted(_signal, _frame): |
| 85 | raise SystemExit(130) |
| 86 | completed = False |
| 87 | try: |
| 88 | for signum in (signal.SIGHUP, signal.SIGTERM, signal.SIGINT): |
| 89 | signal.signal(signum, interrupted) |
| 90 | os.set_blocking(child.stdin.fileno(), False) |
| 91 | with selectors.DefaultSelector() as selector: |
| 92 | selector.register(0, selectors.EVENT_READ) |
| 93 | watching_write = False |
| 94 | while child.poll() is None: |
| 95 | while b"\n" in incoming: |
| 96 | raw, _, incoming = incoming.partition(b"\n") |
| 97 | if finished or len(raw) > FRAME_LIMIT: |
| 98 | return 2 |
| 99 | frame = json.loads(raw) |
| 100 | if frame == {"finish": True}: |
| 101 | finished = True |
| 102 | elif isinstance(frame, dict) and set(frame) == {"input"} and isinstance(frame["input"], dict): |
| 103 | pending.extend(json.dumps(frame["input"], ensure_ascii=False, separators=(",", ":")).encode() + b"\n") |
| 104 | else: |
| 105 | return 2 |
| 106 | if len(incoming) > FRAME_LIMIT or len(pending) > FRAME_LIMIT * 2: |
| 107 | return 2 |
| 108 | if pending and not watching_write: |
| 109 | selector.register(child.stdin, selectors.EVENT_WRITE) |
| 110 | watching_write = True |
| 111 | elif not pending: |
| 112 | if watching_write: |
| 113 | selector.unregister(child.stdin) |
| 114 | watching_write = False |
| 115 | if finished and not child.stdin.closed: |
| 116 | child.stdin.close() |
| 117 | for key, _ in selector.select(0.15): |
| 118 | if key.fd == 0: |
| 119 | block = os.read(0, 64 * 1024) |
| 120 | if not block: |
| 121 | return 130 |
| 122 | incoming.extend(block) |
| 123 | elif pending: |
| 124 | try: |
| 125 | count = os.write(key.fd, pending) |
| 126 | del pending[:count] |
| 127 | except BlockingIOError: |
| 128 | pass |
| 129 | except BrokenPipeError: |
| 130 | code = child.wait(timeout=1) |
| 131 | completed = code == 0 |
| 132 | return code |
| 133 | completed = child.returncode == 0 |
| 134 | return child.returncode |
| 135 | finally: |
| 136 | if child.poll() is None: |
| 137 | if subreaper: |
| 138 | child.terminate() |
| 139 | try: |
| 140 | child.wait(timeout=0.8) |
| 141 | except subprocess.TimeoutExpired: |
| 142 | child.kill() |
| 143 | else: |
| 144 | terminate(child) |
| 145 | child.wait() |
| 146 | if subreaper and not completed: |
| 147 | reap_adopted() |
| 148 | |
| 149 | if __name__ == "__main__": |
| 150 | sys.exit(run()) |