#!/usr/bin/env python3 """Deterministic loopback HTTP server for ext-http domain tests. Accepts exactly N connections (one request each), reads the request head and a Content-Length body, records method/path/headers/body, answers with a fixed HTTP/1.1 response and closes the connection. Prints the ephemeral port on stdout as one line so the test runner can pass it to the program. """ from __future__ import annotations import json import socket import sys from pathlib import Path RESPONSES = { "/one": ("第一个", 200, "OK"), "/two": ("第二个", 201, "Created"), } def read_request(conn: socket.socket) -> dict: data = b"" while b"\r\n\r\n" not in data: chunk = conn.recv(4096) if not chunk: break data += chunk head, _, rest = data.partition(b"\r\n\r\n") lines = head.decode("utf-8", errors="replace").split("\r\n") method, path, _ = (lines[0].split(" ") + ["", ""])[:3] headers = {} for line in lines[1:]: if ":" in line: name, value = line.split(":", 1) headers[name.strip().lower()] = value.strip() length = int(headers.get("content-length", "0")) body = rest while len(body) < length: chunk = conn.recv(4096) if not chunk: break body += chunk return { "method": method, "path": path, "headers": headers, "body": body.decode("utf-8", errors="replace"), } def main() -> int: if len(sys.argv) != 3: print("usage: loopback_server.py RECORD_PATH REQUEST_COUNT", file=sys.stderr) return 2 record_path = Path(sys.argv[1]) count = int(sys.argv[2]) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(("127.0.0.1", 0)) server.listen(4) port = server.getsockname()[1] print(port, flush=True) records = [] try: for _ in range(count): conn, _ = server.accept() with conn: request = read_request(conn) records.append(request) body, status, reason = RESPONSES.get( request["path"], ("unknown", 404, "Not Found") ) payload = body.encode("utf-8") response = ( f"HTTP/1.1 {status} {reason}\r\n" "Content-Type: text/plain; charset=utf-8\r\n" f"Content-Length: {len(payload)}\r\n" "Connection: close\r\n\r\n" ).encode("utf-8") + payload conn.sendall(response) finally: server.close() record_path.write_text(json.dumps(records, ensure_ascii=False, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())