Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/seed/net/tests/check.py # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / seed / net / tests / check.py` 1520 lines ยท 64955 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """seed/net/tests/check.py -- host check of seed/net/http.om (omega-mv #788). 3 4 Python is only the referee here: it builds the corpus, computes expected results with an 5 independent reference parser (written from RFC 9112, not from http.om), cross-checks that 6 reference against the standard library's http.client, drives curl and http.client against the 7 Omega server, and compares bytes. Every implementation byte under test is compiled .om. 8 9 Usage: nice -n 19 ionice -c3 python3 seed/net/tests/check.py [--omc PATH] [--keep DIR] 10 Stages: build, corpus (hand cases + deterministic fuzz, seed 788), mutants (each must be 11 caught), live (tests/live.om: keep-alive, 300 KiB / 1 MiB bodies, chunked, HEAD, pipelining, 12 SSE, malformed requests, deadlines, fd leaks), e2e (examples/sse_server.om under curl and 13 http.client, examples/sse_client.om, server fd count), https (tests/https.om = http.om + 14 https.om + om/tls against a Python ssl TLS 1.3 server and openssl s_server with a throwaway PKI: 15 bodies, chunked, close-delimited, truncation, wrong name, untrusted issuer, deadline; mutants 16 of the glue and of the notls stub; with TLS_NET=1 two live read-only GETs). 17 Exit 0 = PASS, 1 = FAIL, 3 = NOT_RUN (a prerequisite such as curl or the compiler is missing). 18 Sockets: 127.0.0.1 with kernel-chosen ephemeral ports only. Never touches port 18091. 19 """ 20 import hashlib 21 import http.client 22 import io 23 import os 24 import random 25 import shutil 26 import socket 27 import subprocess 28 import sys 29 import tempfile 30 import time 31 32 HERE = os.path.dirname(os.path.abspath(__file__)) 33 NET = os.path.dirname(HERE) 34 ROOT = os.path.dirname(os.path.dirname(NET)) 35 LIB = os.path.join(NET, "http.om") 36 NOTLS = os.path.join(NET, "notls.om") 37 HTTPS = os.path.join(NET, "https.om") 38 TLS_UNITS = ["sha2", "hkdf", "drbg", "x25519", "sha3", "mlkem", "chacha", "aesgcm", "ec", "ecdh", "rsa", "x509", "rev", "fips", "tls"] 39 TLSDIR = os.path.join(ROOT, "om", "tls") 40 41 HEADMX = 2048 # parse.om: put cs HHEADMX 2048 42 HHMAX = 16 # parse.om: put cs HHMAX 16 43 BCAP = 4096 # parse.om: put cs HBCAP 4096 44 FRMAX = 1024 # parse.om: put cs HFRMAX 1024 45 FNV_OFF = `14695981039346656037` 46 FNV_PRIME = `1099511628211` 47 M64 = (1 << 64) - 1 48 TCHAR = set(b"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") 49 FUZZ_SEED = 788 50 FUZZ_COUNT = 1500 51 52 if shutil.which("ionice"): 53 NICE = ["nice", "-n", "19", "ionice", "-c3"] 54 else: 55 NICE = ["nice", "-n", "19"] 56 57 58 def sha(b): 59 return hashlib.sha256(b).hexdigest() 60 61 62 def fnv(h, data): 63 for c in data: 64 h = ((h ^ c) * FNV_PRIME) & M64 65 return h 66 67 68 # ======== reference parser (RFC 9112 with the documented http.om caps and choices) 69 70 class Err(Exception): 71 def __init__(self, code): 72 Exception.__init__(self, code) 73 self.code = code 74 75 76 def low(c): 77 return c + 32 if 65 <= c <= 90 else c 78 79 80 def ieq(a, t): 81 return len(a) == len(t) and all(low(x) == low(y) for x, y in zip(a, t)) 82 83 84 def vch(c): 85 return c == 9 or (c >= 32 and c != 127) 86 87 88 def scan_head(buf, server): 89 """Index after CRLF CRLF, or None for a clean end of input; raises Err.""" 90 n = len(buf) 91 st = 0 92 if server: 93 while st + 2 <= n and buf[st] == 13 and buf[st + 1] == 10: 94 st += 2 95 lim = min(n, HEADMX) 96 i = st 97 while i < lim: 98 c = buf[i] 99 if c == 10: 100 if i == st or buf[i - 1] != 13: 101 raise Err(400) 102 if i >= st + 3 and buf[i - 2] == 10 and buf[i - 3] == 13: 103 return st, i + 1 104 if c == 13: 105 if i + 1 >= n: 106 break 107 if buf[i + 1] != 10: 108 raise Err(400) 109 i += 1 110 if n >= HEADMX: 111 raise Err(431) 112 if n == st: 113 if server: 114 return st, None 115 raise Err(499) 116 raise Err(499) 117 118 119 def version(b): 120 if b[:5] != b"HTTP/": 121 raise Err(400) 122 mj, dt, mn = b[5], b[6], b[7] 123 if not (48 <= mj <= 57) or dt != 46 or not (48 <= mn <= 57): 124 raise Err(400) 125 if mj != 49 or mn not in (48, 49): 126 raise Err(505) 127 return mn - 48 128 129 130 def scheme_ok(t): 131 if len(t) < 4 or not (97 <= low(t[0]) <= 122): 132 return False 133 for i in range(1, len(t)): 134 c = low(t[i]) 135 if c == 58: 136 return i + 3 <= len(t) and t[i + 1] == 47 and t[i + 2] == 47 137 if not (97 <= c <= 122 or 48 <= c <= 57 or c in (43, 45, 46)): 138 return False 139 return False 140 141 142 def request_line(line, st): 143 i = 0 144 while i < len(line) and line[i] in TCHAR: 145 i += 1 146 if i == 0 or i > 32 or i >= len(line) or line[i] != 32: 147 raise Err(400) 148 method = line[:i] 149 j = i + 1 150 while j < len(line) and 33 <= line[j] <= 126: 151 j += 1 152 target = line[i + 1:j] 153 if len(target) == 0 or len(target) > 8192 or j >= len(line) or line[j] != 32: 154 raise Err(400) 155 rest = line[j + 1:] 156 if len(rest) != 8: 157 raise Err(400) 158 v = version(rest) 159 if not (target[0] == 47 or target == b"*" or method == b"CONNECT" or scheme_ok(target)): 160 raise Err(400) 161 return method, target, v 162 163 164 def status_line(line): 165 if len(line) < 8: 166 raise Err(400) 167 v = version(line[:8]) 168 if len(line) < 13 or line[8] != 32 or line[12] != 32: 169 raise Err(400) 170 d = line[9:12] 171 if not all(48 <= c <= 57 for c in d): 172 raise Err(400) 173 s = int(d) 174 if s < 100 or s > 599: 175 raise Err(400) 176 if not all(vch(c) for c in line[13:]): 177 raise Err(400) 178 return s, v 179 180 181 def field_line(a): 182 if len(a) == 0 or a[0] in (32, 9): 183 raise Err(400) 184 c = 0 185 while c < len(a) and a[c] in TCHAR: 186 c += 1 187 if c == 0 or c == len(a) or a[c] != 58: 188 raise Err(400) 189 if not all(vch(x) for x in a[c + 1:]): 190 raise Err(400) 191 return a[:c], a[c + 1:].strip(b" \t") 192 193 194 def parse_head(buf, server, ishead): 195 st, e = scan_head(buf, server) 196 if e is None: 197 return None 198 lines = buf[st:e - 4].split(b"\r\n") 199 m = {"st": st, "end": e, "status": 0, "fields": []} 200 if server: 201 m["method"], m["target"], m["ver"] = request_line(lines[0], st) 202 else: 203 m["status"], m["ver"] = status_line(lines[0]) 204 for ln in lines[1:]: 205 name, val = field_line(ln) 206 if len(m["fields"]) >= HHMAX: 207 raise Err(431) 208 m["fields"].append((name, val)) 209 semantics(m, server, ishead) 210 return m 211 212 213 def semantics(m, server, ishead): 214 cl = te = None 215 close = False 216 hosts = 0 217 for name, val in m["fields"]: 218 if ieq(name, b"content-length"): 219 if cl is not None: 220 raise Err(400) 221 if not (1 <= len(val) <= 19 and all(48 <= c <= 57 for c in val)): 222 raise Err(400) 223 cl = int(val) 224 elif ieq(name, b"transfer-encoding"): 225 if te is not None: 226 raise Err(400) 227 te = True 228 if not ieq(val, b"chunked"): 229 raise Err(501) 230 elif ieq(name, b"connection"): 231 for tok in val.split(b","): 232 if ieq(tok.strip(b" \t"), b"close"): 233 close = True 234 elif ieq(name, b"host"): 235 hosts += 1 236 elif ieq(name, b"expect"): 237 if server and m["ver"] == 1 and not ieq(val, b"100-continue"): 238 raise Err(417) 239 if cl is not None and te: 240 raise Err(400) 241 if te and m["ver"] == 0: 242 raise Err(400) 243 if server and m["ver"] == 1 and hosts != 1: 244 raise Err(400) 245 m["keep"] = 1 if (m["ver"] == 1 and not close) else 0 246 m["mode"], m["rem"] = 0, 0 247 s = m["status"] 248 if not server: 249 if s == 101: 250 m["keep"] = 0 251 if ishead or s < 200 or s in (204, 304): 252 return 253 if te: 254 m["mode"] = 2 255 elif cl is not None: 256 if cl > BCAP: 257 raise Err(413) 258 if cl > 0: 259 m["mode"], m["rem"] = 1, cl 260 elif not server: 261 m["mode"], m["keep"] = 3, 0 262 263 264 def body_line(b, pos): 265 """CR index of the CRLF line at pos (http.om hbline in memory mode).""" 266 n = len(b) 267 lim = min(n, pos + HEADMX) 268 i = pos 269 while i < lim: 270 c = b[i] 271 if c == 10: 272 raise Err(400) 273 if c == 13: 274 if i + 1 >= n: 275 break 276 if b[i + 1] != 10: 277 raise Err(400) 278 return i 279 i += 1 280 if n - pos >= HEADMX: 281 raise Err(431) 282 raise Err(499) 283 284 285 def chunk_size(a): 286 v, c = 0, len(a) 287 for i, x in enumerate(a): 288 h = int(chr(x), 16) if chr(x) in "0123456789abcdefABCDEF" else 16 289 if h == 16: 290 c = i 291 break 292 if i >= 15: 293 raise Err(400) 294 v = v * 16 + h 295 if c == 0: 296 raise Err(400) 297 if c < len(a) and (a[c] != 59 or not all(vch(x) for x in a[c:])): 298 raise Err(400) 299 return v 300 301 302 def body(m, rest): 303 mode = m["mode"] 304 if mode == 0: 305 return b"" 306 if mode == 1: 307 if len(rest) < m["rem"]: 308 raise Err(499) 309 return rest[:m["rem"]] 310 if mode == 3: 311 if len(rest) > BCAP: 312 raise Err(413) 313 return rest 314 out, pos, trn, frm = bytearray(), 0, 0, 0 315 316 def framing(k): 317 # http.om hfrchk: chunk framing bytes over HFRMAX + 8 * decoded bytes is 413 318 nonlocal frm 319 frm += k 320 if frm > FRMAX + 8 * len(out): 321 raise Err(413) 322 323 while True: 324 x = body_line(rest, pos) 325 v = chunk_size(rest[pos:x]) 326 framing(x + 2 - pos) 327 pos = x + 2 328 if v == 0: 329 break 330 if len(out) + v > BCAP: 331 raise Err(413) 332 if len(rest) - pos < v: 333 raise Err(499) 334 out += rest[pos:pos + v] 335 pos += v 336 if len(rest) - pos < 2: 337 raise Err(499) 338 if rest[pos:pos + 2] != b"\r\n": 339 raise Err(400) 340 framing(2) 341 pos += 2 342 while True: 343 x = body_line(rest, pos) 344 framing(x + 2 - pos) 345 if x == pos: 346 return bytes(out) 347 field_line(rest[pos:x]) 348 trn += 1 349 if trn > HHMAX: 350 raise Err(431) 351 pos = x + 2 352 353 354 def reference(mode, msg): 355 """The expected parse.om output (without the index) and the interim statuses seen.""" 356 server = mode == "q" 357 interim = [] 358 try: 359 buf = msg 360 if server: 361 m = parse_head(buf, True, False) 362 if m is None: 363 return "eof", interim 364 else: 365 for _ in range(16): 366 m = parse_head(buf, False, mode == "h") 367 if m["status"] >= 200 or m["status"] == 101: 368 break 369 interim.append(m["status"]) 370 buf = buf[m["end"]:] 371 else: 372 raise Err(400) 373 bd = body(m, buf[m["end"]:]) 374 except Err as e: 375 return "err %d" % e.code, interim 376 h = FNV_OFF 377 if server: 378 h = fnv(h, m["method"] + b" " + m["target"] + b"\n") 379 for name, val in m["fields"]: 380 h = fnv(h, bytes(low(c) for c in name) + b":" + val + b"\n") 381 line = "ok %d %d %d %d %d %016x %d %016x" % ( 382 m["status"], m["ver"], m["keep"], m["mode"], len(m["fields"]), h, len(bd), fnv(FNV_OFF, bd)) 383 return line, interim 384 385 386 # ======== independent cross-check with the standard library client 387 388 class _Sock: 389 def __init__(self, data): 390 self.f = io.BytesIO(data) 391 392 def makefile(self, *a, **k): 393 return self.f 394 395 396 def stdlib_response(mode, msg): 397 r = http.client.HTTPResponse(_Sock(msg), method="HEAD" if mode == "h" else "GET") 398 try: 399 r.begin() 400 bd = r.read() 401 except (http.client.HTTPException, ValueError): 402 return None 403 hdrs = [(k.lower().encode("latin-1"), v.encode("latin-1").strip(b" \t")) for k, v in r.getheaders()] 404 return r.status, 1 if r.version == 11 else 0, hdrs, bd 405 406 407 PARITY = {"agree": 0, "both_reject": 0, "stricter": 0, "skipped": 0} 408 409 410 def cross_check(mode, msg, line, interim): 411 """Problems where the reference disagrees with http.client (responses only).""" 412 if mode == "q": 413 return None 414 if any(s != 100 for s in interim): 415 PARITY["skipped"] += 1 416 return None 417 # http.client reads a chunked body even on 101/204/304 responses, which RFC 9112 6.3 gives 418 # no body; those messages are outside the comparison. 419 if line.startswith("ok") and line.split()[1] in ("101", "204", "304") and b"transfer-encoding" in msg.lower(): 420 PARITY["skipped"] += 1 421 return None 422 got = stdlib_response(mode, msg) 423 if got is None: 424 if line.startswith("ok"): 425 return "http.client rejects a response the reference accepts" 426 PARITY["both_reject"] += 1 427 return None 428 if not line.startswith("ok"): 429 PARITY["stricter"] += 1 430 return None 431 PARITY["agree"] += 1 432 status, ver, hdrs, bd = got 433 p = line.split() 434 if int(p[1]) != status or int(p[2]) != ver: 435 return "status/version differ from http.client" 436 if int(p[7]) != len(bd) or p[8] != "%016x" % fnv(FNV_OFF, bd): 437 return "body differs from http.client" 438 h = FNV_OFF 439 for name, val in hdrs: 440 h = fnv(h, name + b":" + val + b"\n") 441 if p[6] != "%016x" % h or int(p[5]) != len(hdrs): 442 return "fields differ from http.client" 443 return None 444 445 446 # ======== corpus 447 448 def crlf(s): 449 return s.replace(b"\n", b"\r\n") 450 451 452 def hand_cases(): 453 """(mode, message, expected outcome prefix): pins the reference itself.""" 454 q, s, h = "q", "s", "h" 455 big16 = b"".join(b"X%d: v\n" % i for i in range(15)) 456 big17 = b"".join(b"X%d: v\n" % i for i in range(16)) 457 long_head = b"GET / HTTP/1.1\nHost: a\nX: " + b"a" * 2100 + b"\n\n" 458 c4097 = b"1000\n" + b"a" * 4096 + b"\n1\nb\n0\n\n" 459 extbomb = (b"1;" + b"a" * 1000 + b"\nX\n") * 3 + b"0\n\n" 460 onebyte = b"1\nX\n" * 300 + b"0\n\n" 461 trbomb = b"0\n" + (b"X-T: " + b"t" * 400 + b"\n") * 3 + b"\n" 462 cases = [ 463 (q, crlf(b"GET / HTTP/1.1\nHost: a\n\n"), "ok 0 1 1 0 1"), 464 (q, b"GET / HTTP/1.1\nHost: a\n\n", "err 400"), 465 (q, b"GET / HTTP/1.1\r\nHost: a\n\r\n", "err 400"), 466 (q, crlf(b"\n\nGET / HTTP/1.1\nHost: a\n\n"), "ok"), 467 (q, b"", "eof"), 468 (q, b"\r\n\r\n", "eof"), 469 (q, crlf(b"GET / HTTP/1.1\nHost: a\n\n"), "err 400"), 470 (q, crlf(b"GET / HTTP/1.1 \nHost: a\n\n"), "err 400"), 471 (q, crlf(b"get / HTTP/1.1\nHost: a\n\n"), "ok"), 472 (q, crlf(b"GET / http/1.1\nHost: a\n\n"), "err 400"), 473 (q, crlf(b"GET / HTTP/1.0\n\n"), "ok 0 0 0 0 0"), 474 (q, crlf(b"GET / HTTP/2.0\nHost: a\n\n"), "err 505"), 475 (q, crlf(b"GET / HTTP/1.2\nHost: a\n\n"), "err 505"), 476 (q, crlf(b"GET / HTTP/1.x\nHost: a\n\n"), "err 400"), 477 (q, crlf(b"GET / HTTP/1.1\n\n"), "err 400"), 478 (q, crlf(b"GET / HTTP/1.1\nHost: a\nHost: b\n\n"), "err 400"), 479 (q, crlf(b"GET / HTTP/1.1\nHost: a\nX: 1\n folded\n\n"), "err 400"), 480 (q, crlf(b"GET / HTTP/1.1\nHost: a\nX: 1\n\tfolded\n\n"), "err 400"), 481 (q, crlf(b"GET / HTTP/1.1\nHost : a\n\n"), "err 400"), 482 (q, crlf(b"GET / HTTP/1.1\n Host: a\n\n"), "err 400"), 483 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: 3\n\nabc"), "ok 0 1 1 1 2"), 484 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: 3\nTransfer-Encoding: chunked\n\n"), "err 400"), 485 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\nContent-Length: 3\n\n"), "err 400"), 486 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: 3\nContent-Length: 3\n\nabc"), "err 400"), 487 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: 3,3\n\nabc"), "err 400"), 488 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: +3\n\nabc"), "err 400"), 489 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: -1\n\n"), "err 400"), 490 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length:\n\n"), "err 400"), 491 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: 0x10\n\n"), "err 400"), 492 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: `00000000000000000001`\n\nx"), "err 400"), 493 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: `0000000000000000001`\n\nx"), "ok"), 494 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: 4097\n\n"), "err 413"), 495 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: 4096\n\n") + b"z" * 4096, "ok"), 496 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: gzip\n\n"), "err 501"), 497 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: gzip, chunked\n\n"), "err 501"), 498 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: Chunked\n\n0\n\n"), "ok 0 1 1 2"), 499 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\nTransfer-Encoding: chunked\n\n0\n\n"), "err 400"), 500 (q, crlf(b"POST / HTTP/1.0\nTransfer-Encoding: chunked\n\n0\n\n"), "err 400"), 501 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n3\nabc\n0\n\n"), "ok"), 502 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n3;x=y\nabc\n0\n\n"), "ok"), 503 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n3 \nabc\n0\n\n"), "err 400"), 504 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n0000000000000003\nabc\n0\n\n"), "err 400"), 505 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n000000000000003\nabc\n0\n\n"), "ok"), 506 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n3\nabcX\n0\n\n"), "err 400"), 507 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n3\nab"), "err 499"), 508 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n" + c4097), "err 413"), 509 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n" + extbomb), "err 413"), 510 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n" + onebyte), "ok 0 1 1 2 2"), 511 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n" + trbomb), "err 413"), 512 (s, crlf(b"HTTP/1.1 200 OK\nTransfer-Encoding: chunked\n\n" + extbomb), "err 413"), 513 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n0\nX-T: 1\n\n"), "ok"), 514 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n0\nX-T: 1\n x\n\n"), "err 400"), 515 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n0\nX-T 1\n\n"), "err 400"), 516 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\n0\n"), "err 499"), 517 (q, crlf(b"POST / HTTP/1.1\nHost: a\nTransfer-Encoding: chunked\n\nx\n\n"), "err 400"), 518 (q, crlf(b"GET / HTTP/1.1\nHost: a\n" + big16 + b"\n"), "ok 0 1 1 0 16"), 519 (q, crlf(b"GET / HTTP/1.1\nHost: a\n" + big17 + b"\n"), "err 431"), 520 (q, crlf(long_head), "err 431"), 521 (q, crlf(b"GET / HTTP/1.1\nHost: a\nX: a\x00b\n\n"), "err 400"), 522 (q, crlf(b"GET / HTTP/1.1\nHost: a\nX: a\x7fb\n\n"), "err 400"), 523 (q, crlf(b"GET / HTTP/1.1\nHost: a\nX: a\x80b\n\n"), "ok"), 524 (q, crlf(b"GET / HTTP/1.1\nHost: a\nX: a\rb\n\n"), "err 400"), 525 (q, crlf(b"GET /\x80 HTTP/1.1\nHost: a\n\n"), "err 400"), 526 (q, crlf(b"GET /\x7f HTTP/1.1\nHost: a\n\n"), "err 400"), 527 (q, crlf(b"OPTIONS * HTTP/1.1\nHost: a\n\n"), "ok"), 528 (q, crlf(b"GET http://a/b HTTP/1.1\nHost: a\n\n"), "ok"), 529 (q, crlf(b"GET a:b HTTP/1.1\nHost: a\n\n"), "err 400"), 530 (q, crlf(b"CONNECT a:443 HTTP/1.1\nHost: a\n\n"), "ok"), 531 (q, crlf(b"GET a:443 HTTP/1.1\nHost: a\n\n"), "err 400"), 532 (q, crlf(b"POST / HTTP/1.1\nHost: a\nExpect: 100-continue\nContent-Length: 1\n\nx"), "ok"), 533 (q, crlf(b"GET / HTTP/1.1\nHost: a\nExpect: foo\n\n"), "err 417"), 534 (q, crlf(b"GET / HTTP/1.0\nExpect: foo\n\n"), "ok"), 535 (q, crlf(b"GET / HTTP/1.1\nHost: a\nConnection: close\n\n"), "ok 0 1 0"), 536 (q, crlf(b"GET / HTTP/1.1\nHost: a\nConnection: keep-alive, Close\n\n"), "ok 0 1 0"), 537 (q, crlf(b"GET / HTTP/1.1\nHost: a\n"), "err 499"), 538 (q, crlf(b"POST / HTTP/1.1\nHost: a\nContent-Length: 5\n\nab"), "err 499"), 539 (q, crlf(b"A" * 33 + b" / HTTP/1.1\nHost: a\n\n"), "err 400"), 540 (q, crlf(b"A" * 32 + b" / HTTP/1.1\nHost: a\n\n"), "ok"), 541 (s, crlf(b"HTTP/1.1 200 OK\nContent-Length: 2\n\nhi"), "ok 200 1 1 1 1"), 542 (s, crlf(b"HTTP/1.1 200\nContent-Length: 0\n\n"), "err 400"), 543 (s, crlf(b"HTTP/1.1 200 \nContent-Length: 0\n\n"), "ok 200"), 544 (s, crlf(b"HTTP/1.1 099 x\nContent-Length: 0\n\n"), "err 400"), 545 (s, crlf(b"HTTP/1.1 600 x\nContent-Length: 0\n\n"), "err 400"), 546 (s, crlf(b"HTTP/1.1 599 x\nContent-Length: 0\n\n"), "ok 599"), 547 (s, crlf(b"HTTP/1.1 2000 OK\nContent-Length: 0\n\n"), "err 400"), 548 (s, crlf(b"HTTP/1.0 200 OK\n\n") + b"abc", "ok 200 0 0 3"), 549 (s, crlf(b"HTTP/1.1 200 OK\n\n") + b"abc", "ok 200 1 0 3"), 550 (s, crlf(b"HTTP/1.1 200 OK\n\n") + b"q" * 4096, "ok 200 1 0 3"), 551 (s, crlf(b"HTTP/1.1 200 OK\n\n") + b"q" * 4097, "err 413"), 552 (s, crlf(b"HTTP/1.1 204 No Content\nContent-Length: 5\n\n"), "ok 204 1 1 0"), 553 (s, crlf(b"HTTP/1.1 304 Not Modified\nContent-Length: 5\n\n"), "ok 304 1 1 0"), 554 (s, crlf(b"HTTP/1.1 305 Use Proxy\nContent-Length: 5\n\n"), "err 499"), 555 (h, crlf(b"HTTP/1.1 200 OK\nContent-Length: 10\n\n"), "ok 200 1 1 0"), 556 (s, crlf(b"HTTP/1.1 100 Continue\n\nHTTP/1.1 200 OK\nContent-Length: 1\n\nx"), "ok 200"), 557 (s, crlf(b"HTTP/1.1 103 Early Hints\nLink: \n\nHTTP/1.1 200 OK\nContent-Length: 1\n\nx"), "ok 200"), 558 (s, crlf(b"HTTP/1.1 101 Switching Protocols\nUpgrade: x\n\n"), "ok 101 1 0 0"), 559 (s, crlf(b"HTTP/1.1 100 Continue\n\n" * 17), "err 400"), 560 (s, crlf(b"HTTP/1.1 200 OK\nTransfer-Encoding: chunked\n\n2\nhi\n0\n\n"), "ok 200 1 1 2"), 561 (s, b"", "err 499"), 562 (s, crlf(b"HTTP/1.1 200 OK\nContent-Length: 1\nTransfer-Encoding: chunked\n\n"), "err 400"), 563 (s, crlf(b"HTTP/2 200 OK\n\n"), "err 400"), 564 (s, crlf(b"HTTP/1.1 200 OK\nTransfer-Encoding: gzip\n\n"), "err 501"), 565 (s, crlf(b"HTTP/1.1 200 \x80k\nContent-Length: 0\n\n"), "ok"), 566 (s, crlf(b"HTTP/1.1 200 a\x00k\nContent-Length: 0\n\n"), "err 400"), 567 (s, crlf(b"HTTP/1.0 200 OK\nTransfer-Encoding: chunked\n\n0\n\n"), "err 400"), 568 ] 569 return cases 570 571 572 NAMES = [b"Host", b"Accept", b"User-Agent", b"X-Req", b"Cache-Control", b"Link", b"Connection", 573 b"Content-Type", b"Expect", b"content-length", b"Transfer-Encoding", b"X-Empty"] 574 VALUES = [b"a", b"text/event-stream", b"omega/1", b"no-cache", b"
; rel=next", b"close", 575 b"keep-alive", b"application/json", b"100-continue", b"", b" padded ", b"\x80\xff"] 576 INTEREST = [0, 9, 10, 13, 32, 34, 44, 48, 58, 59, 70, 127, 128, 255] 577 578 579 def gen_body(rnd, framing, data): 580 hdrs, wire = [], b"" 581 if framing == 1: 582 hdrs.append(b"Content-Length: %d" % len(data)) 583 wire = data 584 elif framing == 2: 585 hdrs.append(b"Transfer-Encoding: chunked") 586 p = 0 587 while p < len(data): 588 k = rnd.randint(1, max(1, min(700, len(data) - p))) 589 ext = b";e=%d" % k if rnd.random() < 0.2 else b"" 590 if rnd.random() < 0.05: 591 ext = b";x=" + b"y" * rnd.randint(100, 1500) 592 wire += b"%x%s\r\n%s\r\n" % (k, ext, data[p:p + k]) 593 p += k 594 wire += b"0\r\n" 595 if rnd.random() < 0.2: 596 wire += b"X-Trailer: t\r\n" 597 wire += b"\r\n" 598 return hdrs, wire 599 600 601 def gen_message(rnd): 602 mode = rnd.choice("qqqssh") 603 data = bytes(rnd.randrange(256) for _ in range(rnd.choice([0, 1, 5, 100, 1000, 3000, 4096, 5000]))) 604 framing = rnd.choice([0, 1, 1, 2, 2]) 605 hdrs, wire = gen_body(rnd, framing, data) 606 fields = [] 607 for _ in range(rnd.randint(0, 6)): 608 fields.append(rnd.choice(NAMES[1:9]) + b": " + rnd.choice(VALUES[:9])) 609 if mode == "q": 610 meth = rnd.choice([b"GET", b"POST", b"PUT", b"HEAD", b"OPTIONS", b"X-Do"]) 611 tgt = rnd.choice([b"/", b"/a/b?c=d", b"*", b"http://h/p", b"/%41"]) 612 ver = rnd.choice([b"HTTP/1.1"] * 6 + [b"HTTP/1.0"]) 613 start = meth + b" " + tgt + b" " + ver 614 if ver == b"HTTP/1.1": 615 fields.insert(rnd.randint(0, len(fields)), b"Host: h") 616 else: 617 st = rnd.choice([100, 101, 103, 200, 201, 204, 206, 304, 404, 500, 599]) 618 start = b"HTTP/1.%d %d R" % (rnd.choice([1, 1, 1, 0]), st) 619 if st < 200 and st != 101: 620 start = start + b"\r\n\r\nHTTP/1.1 200 OK" 621 fields += hdrs 622 if rnd.random() < 0.15: 623 fields.append(b"Connection: close") 624 return mode, start, fields, wire 625 626 627 def mutate(rnd, start, fields, wire): 628 op = rnd.randrange(14) 629 f = list(fields) 630 if op == 0 and f: 631 f.append(rnd.choice(f)) # duplicate a field line 632 elif op == 1: 633 f.append(rnd.choice([b"Content-Length: 7", b"Transfer-Encoding: chunked", 634 b"Transfer-Encoding: identity", b"Content-Length: 1, 1"])) 635 elif op == 2 and f: 636 i = rnd.randrange(len(f)) 637 f[i] = f[i].replace(b":", b" :", 1) 638 elif op == 3 and f: 639 i = rnd.randrange(len(f)) 640 f[i] = rnd.choice([b" ", b"\t"]) + f[i] # obs-fold 641 elif op == 4: 642 f.append(rnd.choice(NAMES) + b": " + rnd.choice(VALUES)) 643 elif op == 5: 644 f += [b"X-%d: y" % i for i in range(rnd.randint(8, 20))] 645 elif op == 6: 646 start = start.replace(b" ", b" ", 1) 647 elif op == 7: 648 start = start.replace(b"1.1", rnd.choice([b"1.2", b"2.0", b"1.x", b"11"]), 1) 649 msg = start + b"\r\n" + b"".join(x + b"\r\n" for x in f) + b"\r\n" + wire 650 b = bytearray(msg) 651 if op == 8 and b: 652 b[rnd.randrange(len(b))] = rnd.choice(INTEREST) 653 elif op == 9: 654 b.insert(rnd.randrange(len(b) + 1), rnd.choice(INTEREST)) 655 elif op == 10 and b: 656 del b[rnd.randrange(len(b))] 657 elif op == 11: 658 b = bytearray(bytes(b).replace(b"\r\n", b"\n", rnd.randint(1, 3))) 659 elif op == 12 and b: 660 b = b[:rnd.randrange(len(b))] 661 return bytes(b) 662 663 664 def fuzz_cases(): 665 rnd = random.Random(FUZZ_SEED) 666 out = [] 667 for k in range(FUZZ_COUNT): 668 mode, start, fields, wire = gen_message(rnd) 669 if k % 4 == 0: 670 msg = start + b"\r\n" + b"".join(x + b"\r\n" for x in fields) + b"\r\n" + wire 671 else: 672 msg = mutate(rnd, start, fields, wire) 673 for _ in range(rnd.choice([0, 0, 1, 2])): 674 msg = mutate_bytes(rnd, msg) 675 out.append((mode, msg, None)) 676 return out 677 678 679 def mutate_bytes(rnd, msg): 680 b = bytearray(msg) 681 if b and rnd.random() < 0.5: 682 b[rnd.randrange(len(b))] = rnd.choice(INTEREST) 683 else: 684 b.insert(rnd.randrange(len(b) + 1), rnd.choice(INTEREST)) 685 return bytes(b) 686 687 688 def corpus_bytes(cases): 689 return b"".join(b"C %s %d\n" % (m.encode(), len(msg)) + msg + b"\n" for m, msg, _ in cases) 690 691 692 # ======== build and run 693 694 class Fail(Exception): 695 pass 696 697 698 class NotRun(Exception): 699 pass 700 701 702 def compile_unit(omc, out, lib_src, unit): 703 src = b"om2\n" + lib_src + open(os.path.join(NET, unit), "rb").read() 704 p = subprocess.run(NICE + [omc], input=src, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600) 705 if p.returncode != 0: 706 raise Fail("compile %s rc=%d %s" % (unit, p.returncode, p.stderr.decode(errors="replace").strip())) 707 with open(out, "wb") as f: 708 f.write(p.stdout) 709 os.chmod(out, 0o700) 710 return sha(src), sha(p.stdout) 711 712 713 def run_corpus(binary, corpus_path, ncases): 714 with open(corpus_path, "rb") as f: 715 p = subprocess.run(NICE + [binary], stdin=f, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600) 716 lines = p.stdout.decode(errors="replace").splitlines() 717 return p.returncode, lines 718 719 720 def stage_corpus(omc, work, lib_src, log): 721 cases = [(m, msg, exp) for m, msg, exp in hand_cases()] 722 nhand = len(cases) 723 cases += fuzz_cases() 724 expected, problems = [], [] 725 for i, (mode, msg, exp) in enumerate(cases): 726 line, interim = reference(mode, msg) 727 if exp is not None and not line.startswith(exp): 728 problems.append("hand case %d: reference says %r, table says %r" % (i, line, exp)) 729 cc = cross_check(mode, msg, line, interim) 730 if cc: 731 problems.append("case %d (%s): %s; reference %r" % (i, mode, cc, line)) 732 expected.append("%d %s" % (i, line)) 733 if problems: 734 raise Fail("reference self-check:\n " + "\n ".join(problems[:20])) 735 data = corpus_bytes(cases) 736 cpath = os.path.join(work, "corpus.bin") 737 with open(cpath, "wb") as f: 738 f.write(data) 739 with open(os.path.join(work, "corpus.expected"), "w") as f: 740 f.write("\n".join(expected) + "\n") 741 binary = os.path.join(work, "parse") 742 ssrc, sbin = compile_unit(omc, binary, lib_src, "tests/parse.om") 743 rc, lines = run_corpus(binary, cpath, len(cases)) 744 bad = [(i, e, g) for i, (e, g) in enumerate(zip(expected, lines)) if e != g] 745 log("corpus sha256=%s cases=%d hand=%d fuzz=%d parse.src=%s parse.bin=%s" % ( 746 sha(data), len(cases), nhand, len(cases) - nhand, ssrc, sbin)) 747 if rc != 0 or len(lines) != len(cases) or bad: 748 detail = "; ".join("want %r got %r" % (e, g) for _, e, g in bad[:8]) 749 raise Fail("corpus rc=%d lines=%d/%d mismatches=%d %s" % (rc, len(lines), len(cases), len(bad), detail)) 750 log("http.client parity on responses: agree=%(agree)d both_reject=%(both_reject)d " 751 "reference_stricter=%(stricter)d skipped=%(skipped)d" % PARITY) 752 dist = {} 753 for e in expected: 754 k = " ".join(e.split()[1:3]) if " err " in e else e.split()[1] 755 dist[k] = dist.get(k, 0) + 1 756 log("outcomes: " + " ".join("%s=%d" % (k, dist[k]) for k in sorted(dist))) 757 log("HTTP-CORPUS PASS cases=%d" % len(cases)) 758 return cpath, expected 759 760 761 MUTANTS = [ 762 ("CL+TE accepted", "if and cl te", "if and cl cl"), 763 ("chunk size decimal", "v = add mul v 16 h", "v = add mul v 10 h"), 764 ("field cap off by one", "if or ge n get cs HHMAX ge n HHSLOTS", "if or gt n get cs HHMAX ge n HHSLOTS"), 765 ("304 has a body", "if or or eq get cs HISHEAD 1 lt s 200 or eq s 204 eq s 304", 766 "if or or eq get cs HISHEAD 1 lt s 200 or eq s 204 eq s 305"), 767 ("status range", "if or lt c 100 gt c 599", "if or lt c 100 gt c 999"), 768 ("Expect value ignored", "if not hieq view part io vo vl hv100c", "if hieq view part io vo vl hv100c"), 769 ("duplicate TE flag", "if ne and get cs HFLAGS 2 0", "if ne and get cs HFLAGS 1 0"), 770 ("HTTP/1.0 read as 1.1", "if eq mn 48", "if eq mn 49"), 771 ("close body cap", "if gt add got n cap", "if ge add got n cap"), 772 ("bare LF accepted", "if ne get io sub i 1 13", "if eq get io sub i 1 10"), 773 ("F4 chunk framing uncapped", "if gt f add get cs HFRMAX mul get cs HBGOT 8", "if eq f 0"), 774 ] 775 776 777 def stage_mutants(omc, work, lib_src, cpath, expected, log): 778 text = lib_src.decode() 779 lines = text.split("\n") 780 for name, old, new in MUTANTS: 781 hits = [i for i, l in enumerate(lines) if l == old] 782 if len(hits) != 1: 783 raise Fail("mutant %r: line %r occurs %d times (must be exactly once)" % (name, old, len(hits))) 784 ml = list(lines) 785 ml[hits[0]] = new 786 mbin = os.path.join(work, "parse-mutant") 787 try: 788 compile_unit(omc, mbin, "\n".join(ml).encode(), "tests/parse.om") 789 except Fail as e: 790 raise Fail("mutant %r does not compile (invalid mutant): %s" % (name, e)) 791 rc, got = run_corpus(mbin, cpath, len(expected)) 792 if rc == 0 and got == expected: 793 raise Fail("mutant %r SURVIVED: the corpus does not detect it" % name) 794 log("mutant killed: %s (line %d)" % (name, hits[0] + 1)) 795 log("HTTP-MUTANTS PASS killed=%d/%d" % (len(MUTANTS), len(MUTANTS))) 796 797 798 def stage_live(omc, work, lib_src, log): 799 binary = os.path.join(work, "live") 800 ssrc, sbin = compile_unit(omc, binary, lib_src, "tests/live.om") 801 p = subprocess.run(NICE + [binary], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300) 802 log("live.src=%s live.bin=%s rc=%d" % (ssrc, sbin, p.returncode)) 803 if p.returncode != 0: 804 raise Fail("tests/live.om exit %d (see the ret numbers in live.om)" % p.returncode) 805 log("HTTP-LIVE PASS") 806 807 808 LIVE_MUTANTS = [ 809 ("head deadline never armed", "put cs HDL add ulong monons get cs HHDLV", "put cs HDL 0"), 810 ("hclose leaks the descriptor", "ret fclose int get cs HFD", "ret 0"), 811 ("SSE data CR not a line break", "if eq get v q 13", "if eq get v q 14"), 812 ("chunk-size digit mask", "put io add b i hhexd and x 15", "put io add b i hhexd and x 7"), 813 ("F1 no body deadline after the head", "put cs HDL hbdl cs", "put cs HDL 0"), 814 ("F2 Content-Length overrun buffered", "ret gt add get cs HWOUT n get cs HWCL", "ret false"), 815 ("F3 100 Continue keyed on HWLEN", "if or ne get cs HFINAL 0 ne get cs HMEM 0", 816 "if or ne get cs HWLEN 0 ne get cs HMEM 0"), 817 ] 818 819 820 def stage_live_mutants(omc, work, lib_src, log): 821 """Negative controls for tests/live.om: each mutant of http.om must make it fail.""" 822 lines = lib_src.decode().split("\n") 823 for name, old, new in LIVE_MUTANTS: 824 hits = [i for i, l in enumerate(lines) if l == old] 825 if len(hits) != 1: 826 raise Fail("live mutant %r: line %r occurs %d times (must be exactly once)" % (name, old, len(hits))) 827 ml = list(lines) 828 ml[hits[0]] = new 829 mbin = os.path.join(work, "live-mutant") 830 try: 831 compile_unit(omc, mbin, "\n".join(ml).encode(), "tests/live.om") 832 except Fail as e: 833 raise Fail("live mutant %r does not compile (invalid mutant): %s" % (name, e)) 834 try: 835 p = subprocess.run(NICE + [mbin], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120) 836 rc = p.returncode 837 except subprocess.TimeoutExpired: 838 rc = "timeout" 839 if rc == 0: 840 raise Fail("live mutant %r SURVIVED: tests/live.om exits 0" % name) 841 log("live mutant killed: %s (line %d, exit %s)" % (name, hits[0] + 1, rc)) 842 log("HTTP-LIVE-MUTANTS PASS killed=%d/%d" % (len(LIVE_MUTANTS), len(LIVE_MUTANTS))) 843 844 845 846 EXPECTED_SSE = (b"id: 1\ndata: hello from Omega\n\n" 847 b"event: multi\nid: 2\ndata: line one\ndata: line two\n\n" 848 b"id: 3\ndata: bye\n\n") 849 EXPECTED_CLIENT = (b"event= id=1 data=hello from Omega\n" 850 b"event=multi id=2 data=line one\\nline two\n" 851 b"event= id=3 data=bye\n") 852 HEALTH = b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\n\r\n{"ok":true}' 853 BAD = b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" 854 E2E_CONNS = 9 855 856 857 def fdcount(pid): 858 return len(os.listdir("/proc/%d/fd" % pid)) 859 860 861 def settle(pid, base): 862 t = time.monotonic() + 3 863 while time.monotonic() < t: 864 if fdcount(pid) == base: 865 return 866 time.sleep(0.05) 867 raise Fail("server fd count %d, expected %d after the connection closed (leak)" % (fdcount(pid), base)) 868 869 870 def raw_exchange(port, data): 871 s = socket.create_connection(("127.0.0.1", port), timeout=10) 872 try: 873 if data: 874 s.sendall(data) 875 s.shutdown(socket.SHUT_WR) 876 out = b"" 877 while True: 878 k = s.recv(65536) 879 if not k: 880 return out 881 out += k 882 finally: 883 s.close() 884 885 886 def curl(args, timeout=30): 887 p = subprocess.run(NICE + ["curl", "-sS"] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout) 888 if p.returncode != 0: 889 raise Fail("curl %s rc=%d %s" % (" ".join(args), p.returncode, p.stderr.decode(errors="replace"))) 890 return p.stdout 891 892 893 def e2e_checks(port, pid, base, work, client_bin): 894 url = "http://127.0.0.1:%d" % port 895 got = curl(["-N", "--max-time", "10", url + "/events"]) 896 if got != EXPECTED_SSE: 897 raise Fail("curl /events: %r" % got[:200]) 898 settle(pid, base) 899 got = curl(["-i", "--max-time", "10", url + "/health"]) 900 if got != HEALTH: 901 raise Fail("curl -i /health: %r" % got[:200]) 902 settle(pid, base) 903 blob = random.Random(300).randbytes(300 * 1024) 904 bpath = os.path.join(work, "blob.bin") 905 with open(bpath, "wb") as f: 906 f.write(blob) 907 got = curl(["--max-time", "20", "--data-binary", "@" + bpath, url + "/echo"]) 908 if got != blob: 909 raise Fail("curl 300 KiB echo (Expect: 100-continue) differs, %d bytes" % len(got)) 910 settle(pid, base) 911 got = curl(["--max-time", "20", "-H", "Transfer-Encoding: chunked", "--data-binary", "@" + bpath, url + "/echo"]) 912 if got != blob: 913 raise Fail("curl chunked 300 KiB echo differs, %d bytes" % len(got)) 914 settle(pid, base) 915 c = http.client.HTTPConnection("127.0.0.1", port, timeout=10) 916 c.request("GET", "/health") 917 r = c.getresponse() 918 if r.status != 200 or r.read() != b'{"ok":true}': 919 raise Fail("http.client GET /health") 920 s0 = c.sock 921 c.request("HEAD", "/health") 922 r = c.getresponse() 923 if r.status != 200 or r.getheader("Content-Length") != "11" or r.read() != b"": 924 raise Fail("http.client HEAD /health") 925 c.request("POST", "/echo", body=blob[:1000]) 926 r = c.getresponse() 927 if r.status != 200 or r.read() != blob[:1000]: 928 raise Fail("http.client POST /echo") 929 c.request("GET", "/nope") 930 r = c.getresponse() 931 if r.status != 404 or r.read() != b"" or c.sock is not s0: 932 raise Fail("http.client 404 on the same keep-alive connection") 933 c.request("DELETE", "/echo") 934 r = c.getresponse() 935 if r.status != 405 or r.read() != b"" or c.sock is not s0: 936 raise Fail("http.client 405 on the same keep-alive connection") 937 c.request("GET", "/health", headers={"Connection": "close"}) 938 r = c.getresponse() 939 if r.status != 200 or r.getheader("Connection") != "close" or r.read() != b'{"ok":true}': 940 raise Fail("http.client GET /health with Connection: close") 941 c.close() 942 settle(pid, base) 943 got = raw_exchange(port, b"GET / HTTP/1.1\r\nHost: a\r\nX: 1\r\n folded\r\n\r\n") 944 if got != BAD: 945 raise Fail("obs-fold request answered %r" % got[:200]) 946 settle(pid, base) 947 got = raw_exchange(port, b"") 948 if got != b"": 949 raise Fail("empty connection answered %r" % got[:200]) 950 settle(pid, base) 951 p = subprocess.run(NICE + [client_bin, str(port), "/events"], stdout=subprocess.PIPE, timeout=30) 952 if p.returncode != 0 or p.stdout != EXPECTED_CLIENT: 953 raise Fail("sse_client rc=%d out=%r" % (p.returncode, p.stdout[:300])) 954 settle(pid, base) 955 got = raw_exchange(port, b"GET /health HTTP/1.0\r\n\r\n") 956 want = (b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\n' 957 b'Connection: close\r\n\r\n{"ok":true}') 958 if got != want: 959 raise Fail("HTTP/1.0 request answered %r" % got[:200]) 960 961 962 def stage_e2e(omc, work, lib_src, log): 963 if not shutil.which("curl"): 964 raise NotRun("curl is not installed") 965 sbin = os.path.join(work, "sse_server") 966 cbin = os.path.join(work, "sse_client") 967 s1 = compile_unit(omc, sbin, lib_src, "examples/sse_server.om") 968 s2 = compile_unit(omc, cbin, lib_src, "examples/sse_client.om") 969 log("sse_server src=%s bin=%s; sse_client src=%s bin=%s" % (s1 + s2)) 970 srv = subprocess.Popen(NICE + [sbin, str(E2E_CONNS)], stdout=subprocess.PIPE) 971 try: 972 line = srv.stdout.readline() 973 if not line.startswith(b"PORT "): 974 raise Fail("sse_server printed %r" % line) 975 port = int(line[5:]) 976 if port == 18091 or port == 0: 977 raise Fail("unexpected port %d" % port) 978 base = fdcount(srv.pid) 979 e2e_checks(port, srv.pid, base, work, cbin) 980 rc = srv.wait(timeout=15) 981 if rc != 0: 982 raise Fail("sse_server exit %d" % rc) 983 finally: 984 if srv.poll() is None: 985 srv.kill() 986 srv.wait() 987 log("HTTP-E2E PASS connections=%d (curl, http.client, raw, sse_client)" % E2E_CONNS) 988 989 990 # ======== https: http.om + https.om + om/tls against TLS 1.3 servers with a throwaway PKI 991 def ossl(work, *args): 992 p = subprocess.run(["openssl"] + list(args), cwd=work, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120) 993 if p.returncode != 0: 994 raise Fail("openssl %s rc=%d %s" % (" ".join(args), p.returncode, p.stderr.decode(errors="replace").strip())) 995 996 997 HTTPS_CA_CNF = """[ca] 998 default_ca = c 999 [c] 1000 database = index.txt 1001 new_certs_dir = issued 1002 serial = serial 1003 default_md = sha256 1004 policy = p 1005 copy_extensions = copy 1006 unique_subject = no 1007 [p] 1008 commonName = supplied 1009 """ 1010 1011 1012 def https_pki(work): 1013 """root -> leaf for localhost (EC P-256); a leaf for another name; an unrelated root's leaf; 1014 leaves of root that expired (2025) or are not valid yet (2048); a self-signed localhost leaf.""" 1015 d = os.path.join(work, "pki") 1016 os.makedirs(os.path.join(d, "issued"), exist_ok=True) 1017 ca_ext = ["-addext", "basicConstraints=critical,CA:true", "-addext", "keyUsage=critical,keyCertSign,cRLSign"] 1018 leaf_ext = ["-addext", "basicConstraints=critical,CA:false", "-addext", "keyUsage=critical,digitalSignature", 1019 "-addext", "extendedKeyUsage=serverAuth"] 1020 for root in ("root", "other"): 1021 ossl(d, "genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", root + ".key") 1022 ossl(d, "req", "-x509", "-new", "-key", root + ".key", "-subj", "/CN=http-check-" + root, "-days", "30", 1023 "-sha256", *ca_ext, "-out", root + ".pem") 1024 with open(os.path.join(d, "ca.cnf"), "w") as f: 1025 f.write(HTTPS_CA_CNF) 1026 open(os.path.join(d, "index.txt"), "w").close() 1027 with open(os.path.join(d, "serial"), "w") as f: 1028 f.write("1000\n") 1029 for name, san, root in (("leaf", "localhost", "root"), ("wrong", "other.example", "root"), ("stray", "localhost", "other"), 1030 ("expired", "localhost", "root"), ("notyet", "localhost", "root"), ("self", "localhost", None)): 1031 ossl(d, "genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", name + ".key") 1032 if root is None: 1033 ossl(d, "req", "-x509", "-new", "-key", name + ".key", "-subj", "/CN=" + san, "-addext", "subjectAltName=DNS:" + san, 1034 *leaf_ext, "-days", "10", "-sha256", "-out", name + ".pem") 1035 continue 1036 ossl(d, "req", "-new", "-key", name + ".key", "-subj", "/CN=" + san, "-addext", "subjectAltName=DNS:" + san, 1037 *leaf_ext, "-out", name + ".csr") 1038 if name in ("expired", "notyet"): 1039 start, end = ("250101000000Z", "250201000000Z") if name == "expired" else ("480101000000Z", "490101000000Z") 1040 ossl(d, "ca", "-batch", "-config", "ca.cnf", "-cert", root + ".pem", "-keyfile", root + ".key", "-in", name + ".csr", 1041 "-startdate", start, "-enddate", end, "-notext", "-out", name + ".pem") 1042 continue 1043 ossl(d, "x509", "-req", "-in", name + ".csr", "-CA", root + ".pem", "-CAkey", root + ".key", "-CAcreateserial", 1044 "-days", "10", "-copy_extensions", "copy", "-out", name + ".pem") 1045 return d 1046 1047 1048 HTTPS_BIG = bytes((i * 7 + 3) & 255 for i in range(307200)) 1049 HTTPS_CHUNKS = [1, 17, 4096, 16384, 16385, 3, 60000, 100] 1050 HTTPS_FRAG = [1, 2, 3, 5, 7, 11] 1051 HTTPS_SEEN = {} # Python TLS server name -> request heads it received 1052 HTTPS_PLAIN_SEEN = [] # first bytes each connection brought to the plain HTTP server 1053 1054 1055 def https_body(path): 1056 """(response bytes, body the client must print, close mode) for one path of the Python server. 1057 close mode: 'notify' = close_notify then close, 'raw' = close the socket without close_notify, 1058 'frag' = the response in TLS records of 1..11 bytes, 'partial' = an incomplete TLS record after the 1059 head then a raw close, 'dribble' = the body one byte every 250 ms, 'silent' = no answer.""" 1060 if path == "/small": 1061 return b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nhello\n", b"hello\n", "notify" 1062 if path == "/big": 1063 return b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n" % len(HTTPS_BIG) + HTTPS_BIG, HTTPS_BIG, "notify" 1064 if path == "/chunked": 1065 body = HTTPS_BIG[:100000] 1066 out = [b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n"] 1067 pos = 0 1068 i = 0 1069 while pos < len(body): 1070 n = min(HTTPS_CHUNKS[i % len(HTTPS_CHUNKS)], len(body) - pos) 1071 out.append(b"%x\r\n" % n + body[pos:pos + n] + b"\r\n") 1072 pos += n 1073 i += 1 1074 out.append(b"0\r\n\r\n") 1075 return b"".join(out), body, "notify" 1076 if path == "/frag": 1077 body = HTTPS_BIG[:3000] 1078 return b"HTTP/1.1 200 OK\r\nContent-Length: 3000\r\nConnection: close\r\n\r\n" + body, body, "frag" 1079 if path == "/close": 1080 return b"HTTP/1.0 200 OK\r\n\r\n" + HTTPS_BIG[:50000], HTTPS_BIG[:50000], "notify" 1081 if path == "/closeraw": 1082 return b"HTTP/1.0 200 OK\r\n\r\n" + HTTPS_BIG[:5000], HTTPS_BIG[:5000], "raw" 1083 if path == "/trunc": 1084 return b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n0123456789", b"`0123456789`", "raw" 1085 if path == "/partial": 1086 return b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n", b"", "partial" 1087 if path == "/bighead": 1088 return b"HTTP/1.1 200 OK\r\nX-Pad: " + b"a" * 20000 + b"\r\nContent-Length: 0\r\n\r\n", b"", "notify" 1089 if path == "/dribble": 1090 return b"HTTP/1.1 200 OK\r\nContent-Length: 40\r\nConnection: close\r\n\r\n" + b"d" * 40, b"d" * 40, "dribble" 1091 if path == "/silent": 1092 return b"", b"", "silent" 1093 return b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", b"", "notify" 1094 1095 1096 def https_serve(conn, name): 1097 """One connection of the Python TLS server: read a request head, answer by path.""" 1098 import ssl 1099 try: 1100 conn.settimeout(10) 1101 head = b"" 1102 while b"\r\n\r\n" not in head and len(head) < 65536: 1103 b = conn.recv(4096) 1104 if not b: 1105 return 1106 head += b 1107 HTTPS_SEEN[name] = HTTPS_SEEN.get(name, 0) + 1 1108 path = head.split(b" ", 2)[1].decode() 1109 resp, _, mode = https_body(path) 1110 if mode == "silent": 1111 time.sleep(4) 1112 conn.close() 1113 return 1114 if mode == "frag": 1115 pos = i = 0 1116 while pos < len(resp): 1117 n = HTTPS_FRAG[i % len(HTTPS_FRAG)] 1118 conn.sendall(resp[pos:pos + n]) 1119 pos += n 1120 i += 1 1121 elif mode == "dribble": 1122 k = resp.index(b"\r\n\r\n") + 4 1123 conn.sendall(resp[:k]) 1124 for j in range(k, len(resp)): 1125 time.sleep(0.25) 1126 conn.sendall(resp[j:j + 1]) 1127 else: 1128 conn.sendall(resp) 1129 if mode in ("raw", "partial"): 1130 fd = conn.detach() 1131 if mode == "partial": 1132 # an application_data record header announcing 100 bytes, then only 10 of them 1133 os.write(fd, b"\x17\x03\x03\x00\x64" + b"\x00" * 10) 1134 os.close(fd) 1135 return 1136 try: 1137 conn.unwrap() 1138 except (OSError, ssl.SSLError): 1139 pass 1140 conn.close() 1141 except (OSError, ssl.SSLError): 1142 try: 1143 conn.close() 1144 except OSError: 1145 pass 1146 1147 1148 def https_listen(stop, on_conn): 1149 """A listener on 127.0.0.1 (ephemeral port) in a thread; on_conn(socket) per connection in its own thread.""" 1150 import threading 1151 ls = socket.socket() 1152 ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 1153 ls.bind(("127.0.0.1", 0)) 1154 ls.listen(16) 1155 ls.settimeout(0.5) 1156 port = ls.getsockname()[1] 1157 1158 def loop(): 1159 while not stop.is_set(): 1160 try: 1161 c, _ = ls.accept() 1162 except socket.timeout: 1163 continue 1164 except OSError: 1165 break 1166 threading.Thread(target=on_conn, args=(c,), daemon=True).start() 1167 ls.close() 1168 threading.Thread(target=loop, daemon=True).start() 1169 return port 1170 1171 1172 def https_plain(c): 1173 """The plain HTTP server: record what the client sent first, answer in cleartext, close.""" 1174 try: 1175 c.settimeout(5) 1176 first = c.recv(4096) 1177 HTTPS_PLAIN_SEEN.append(first) 1178 c.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nhello\n") 1179 except OSError: 1180 pass 1181 c.close() 1182 1183 1184 def https_hsilent(c): 1185 """A TCP peer that accepts and never answers the ClientHello.""" 1186 time.sleep(6) 1187 c.close() 1188 1189 1190 def https_server(pki, cert, stop): 1191 """A Python TLS 1.3 server with certificate cert on 127.0.0.1; returns its port.""" 1192 import ssl 1193 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) 1194 ctx.minimum_version = ssl.TLSVersion.TLSv1_3 1195 ctx.load_cert_chain(os.path.join(pki, cert + ".pem"), os.path.join(pki, cert + ".key")) 1196 ctx.set_alpn_protocols(["http/1.1"]) 1197 1198 def on_conn(c): 1199 try: 1200 c.settimeout(10) 1201 tc = ctx.wrap_socket(c, server_side=True) 1202 except (OSError, ssl.SSLError): 1203 c.close() 1204 return 1205 https_serve(tc, cert) 1206 return https_listen(stop, on_conn) 1207 1208 1209 def https_ossl(pki, cert): 1210 """openssl s_server -www -tls1_3 with certificate cert; returns (port, process).""" 1211 # openssl s_server cannot report a kernel-chosen port: pick a free one and bind it 1212 s = socket.socket() 1213 s.bind(("127.0.0.1", 0)) 1214 port = s.getsockname()[1] 1215 s.close() 1216 p = subprocess.Popen(["openssl", "s_server", "-accept", "127.0.0.1:%d" % port, "-cert", os.path.join(pki, cert + ".pem"), 1217 "-key", os.path.join(pki, cert + ".key"), "-www", "-tls1_3"], 1218 stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 1219 for _ in range(50): 1220 try: 1221 socket.create_connection(("127.0.0.1", port), timeout=0.2).close() 1222 break 1223 except OSError: 1224 time.sleep(0.1) 1225 return port, p 1226 1227 1228 def https_run(binary, host, port, store, path, connect="127.0.0.1", idle=None, total=None, spare=None, timeout=20): 1229 """Run tests/https.om; (exit, body, status or None, HTTPSERR code or None, TLSDETAIL or None).""" 1230 args = [binary, host, str(port), store, path, connect] 1231 for opt in (idle, total, spare): 1232 if opt is None: 1233 break 1234 args.append(str(opt)) 1235 if spare is not None and total is None: 1236 raise Fail("https_run: IOSPARE needs TOTALMS (positional)") 1237 try: 1238 p = subprocess.run(NICE + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout) 1239 except subprocess.TimeoutExpired: 1240 return "timeout", b"", None, None, None 1241 st = err = det = None 1242 for l in p.stderr.decode(errors="replace").splitlines(): 1243 if l.startswith("status "): 1244 st = int(l[7:]) 1245 if l.startswith("HTTPSERR "): 1246 err = int(l[9:]) 1247 if l.startswith("TLSDETAIL "): 1248 det = int(l[10:]) 1249 return p.returncode, p.stdout, st, err, det 1250 1251 1252 HETLS = -600 1253 HETIME = -110 1254 HEINVAL = -22 1255 HEHEAD = -431 1256 X5EEXP, X5ENYV, X5ENAME, X5EUNK = 2, 3, 4, 5 # om/tls/x509.om reject codes (x509_errname) 1257 1258 1259 def R(name, path, srv, rc, err=None, det=None, idle=None, total=None, spare=None, status=None, noreq=False, timeout=20): 1260 """One row: server srv (a Python TLS server by certificate, 'o: