| 1 | package diagnostics |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "strings" |
| 6 | ) |
| 7 | |
| 8 | |
| 9 | |
| 10 | func GuestRunner() string { |
| 11 | rules := make([][2]string, 0, len(patterns)) |
| 12 | for _, p := range patterns { |
| 13 | rules = append(rules, [2]string{p.re.String(), strings.ReplaceAll(p.replacement, "${1}", `\g<1>`)}) |
| 14 | } |
| 15 | b, _ := json.Marshal(rules) |
| 16 | return "#!/usr/bin/python3\n" + `import json, os, re, signal, subprocess, sys |
| 17 | rules = [(re.compile(pattern), replacement) for pattern, replacement in json.loads(` + string(mustJSON(string(b))) + `)] |
| 18 | child = subprocess.Popen(sys.argv[1:], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) |
| 19 | stopped_signal = 0 |
| 20 | def stop(sig, _frame): |
| 21 | global stopped_signal |
| 22 | stopped_signal = sig |
| 23 | try: |
| 24 | child.send_signal(sig) |
| 25 | except ProcessLookupError: |
| 26 | pass |
| 27 | for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): |
| 28 | signal.signal(sig, stop) |
| 29 | private_key = False |
| 30 | while True: |
| 31 | data = child.stdout.readline(24577) |
| 32 | if not data: |
| 33 | break |
| 34 | if len(data) > 24576: |
| 35 | while data and not data.endswith(b'\n'): |
| 36 | data = child.stdout.readline(24577) |
| 37 | print('[oversized output line omitted]', flush=True) |
| 38 | continue |
| 39 | line = data.decode('utf-8', 'replace') |
| 40 | if '-----BEGIN ' in line: |
| 41 | private_key = True |
| 42 | if private_key: |
| 43 | if '-----END ' in line: |
| 44 | private_key = False |
| 45 | continue |
| 46 | for pattern, replacement in rules: |
| 47 | line = pattern.sub(lambda match: match.expand(replacement), line) |
| 48 | print(line.rstrip(), flush=True) |
| 49 | code = child.wait() |
| 50 | if stopped_signal and code in (-stopped_signal, 128 + stopped_signal): |
| 51 | code = 0 |
| 52 | sys.exit(code if code >= 0 else 128-code) |
| 53 | ` |
| 54 | } |
| 55 | func mustJSON(v string) []byte { b, _ := json.Marshal(v); return b } |