| 1 | """Run the workbench's control scripts over one SSH connection. |
| 2 | |
| 3 | Requests: "R <id> <length>\n" followed by the script, or "C <id>\n" to stop |
| 4 | one. Replies: "D <id> <exit> <stdout length> <stderr length>\n" and both. |
| 5 | """ |
| 6 | import os |
| 7 | import signal |
| 8 | import subprocess |
| 9 | import sys |
| 10 | import threading |
| 11 | |
| 12 | |
| 13 | OUTPUT_LIMIT = 64 * 1024 + 256 |
| 14 | ERROR_LIMIT = 4096 |
| 15 | SCRIPT_LIMIT = 1 << 20 |
| 16 | requests, replies = sys.stdin.buffer, sys.stdout.buffer |
| 17 | writing = threading.Lock() |
| 18 | running = {} |
| 19 | |
| 20 | |
| 21 | def stop(child): |
| 22 | try: |
| 23 | os.killpg(child.pid, signal.SIGKILL) |
| 24 | except OSError: |
| 25 | pass |
| 26 | |
| 27 | |
| 28 | def keep(pipe, limit, exceeded=None): |
| 29 | """The first `limit` bytes. The rest is read and dropped, or refused.""" |
| 30 | data = b'' |
| 31 | while True: |
| 32 | chunk = pipe.read1(65536) |
| 33 | if not chunk: |
| 34 | return data |
| 35 | data += chunk[:limit - len(data)] |
| 36 | if len(data) == limit and exceeded: |
| 37 | exceeded() |
| 38 | exceeded = None |
| 39 | |
| 40 | |
| 41 | def run(ident, script): |
| 42 | code, output, errors = 127, b'', [] |
| 43 | try: |
| 44 | child = subprocess.Popen(['/bin/bash', '--noprofile', '--norc', '-c', script], stdin=subprocess.DEVNULL, |
| 45 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True) |
| 46 | except OSError as error: |
| 47 | errors.append(str(error).encode()[:ERROR_LIMIT]) |
| 48 | else: |
| 49 | running[ident] = child |
| 50 | drain = threading.Thread(target=lambda: errors.append(keep(child.stderr, ERROR_LIMIT)), daemon=True) |
| 51 | drain.start() |
| 52 | output = keep(child.stdout, OUTPUT_LIMIT, lambda: stop(child)) |
| 53 | code = child.wait() |
| 54 | drain.join() |
| 55 | running.pop(ident, None) |
| 56 | with writing: |
| 57 | replies.write(b'D %d %d %d %d\n' % (ident, code, len(output), len(errors[0])) + output + errors[0]) |
| 58 | replies.flush() |
| 59 | |
| 60 | |
| 61 | replies.write(b'CAGE-GUEST-SESSION 1\n') |
| 62 | replies.flush() |
| 63 | while True: |
| 64 | fields = requests.readline(64).split() |
| 65 | try: |
| 66 | if len(fields) == 3 and fields[0] == b'R' and 0 < int(fields[2]) <= SCRIPT_LIMIT: |
| 67 | script = requests.read(int(fields[2])) |
| 68 | if len(script) != int(fields[2]): |
| 69 | break |
| 70 | threading.Thread(target=run, args=(int(fields[1]), script.decode()), daemon=True).start() |
| 71 | elif len(fields) == 2 and fields[0] == b'C': |
| 72 | child = running.get(int(fields[1])) |
| 73 | if child: |
| 74 | stop(child) |
| 75 | else: |
| 76 | break |
| 77 | except ValueError: |
| 78 | break |
| 79 | |
| 80 | for child in list(running.values()): |
| 81 | stop(child) |