#!/usr/bin/env python3 """A server that answers every request with headers and half a body, then drops the line. python3 scripts/half_response_server.py [port] [seconds] For one branch of the wallet's HTTP bridge: a response that arrives without data (QuickDataTask.swift:198-199, `data ?? Data()`). URLSession hands the app the response object as soon as the headers are in; when the connection then dies before the announced body is complete, the completion handler gets that response, an error, and NO data. A walk met this once in 935 (k-18-e00043, three minutes in another app with a long-poll open); a server that does it on purpose makes it a step. It listens on 127.0.0.1 only and stops by itself after `seconds` (default 240). """ import os import socket import struct import sys import threading import time PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8123 LIFE = int(sys.argv[2]) if len(sys.argv) > 2 else 240 LOG = "/tmp/half-response.log" def note(what: str) -> None: try: with open(LOG, "a") as f: f.write(time.strftime("%H:%M:%S ") + what + "\n") except OSError: pass def serve(conn: socket.socket) -> None: try: conn.settimeout(5) try: req = conn.recv(65536) except OSError: req = b"" note("request: " + req.split(b"\r\n", 1)[0].decode("latin-1", "replace")[:120]) conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" b"Content-Length: 4096\r\nConnection: close\r\n\r\n{\"half\":") time.sleep(0.8) # an abortive close: RST instead of FIN, so the client sees a lost connection conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) finally: conn.close() def main() -> int: srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind((os.environ.get("HALF_BIND", "127.0.0.1"), PORT)) srv.listen(16) note(f"listening on 127.0.0.1:{PORT} for {LIFE} s") srv.settimeout(1.0) end = time.time() + LIFE while time.time() < end: try: conn, _ = srv.accept() except socket.timeout: continue threading.Thread(target=serve, args=(conn,), daemon=True).start() return 0 if __name__ == "__main__": raise SystemExit(main())