# -*- coding: utf-8 -*- """查我改的 _post 到底发出去什么坏请求。 线索:隧道日志每 16 秒(= 轮询间隔)刷: Unsolicited response received on idle HTTP channel Error code: 400 Message: Bad request syntax ('0'). "Bad request syntax ('0')" 很像 **chunked 编码的结尾**(0\r\n\r\n) 被当成请求行了 —— 也就是 http.client 用了 Transfer-Encoding: chunked, 而 Python 的 BaseHTTPRequestHandler 默认**不解析 chunked 请求体**。 这个测试: 1. 起本地 relay 2. 用 RelayLink._post 连打几次 3. 把 relay 收到的原始请求行/头打出来 """ from __future__ import annotations import http.client import json import os import shutil import socket import subprocess import sys import tempfile import threading import time from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "windows")) PORT = 8120 BASE = f"http://127.0.0.1:{PORT}" passed = 0 failed = 0 def check(name, ok, detail=""): global passed, failed if ok: passed += 1 print(" [PASS] " + name) else: failed += 1 print(" [FAIL] " + name + " " + str(detail)) def main() -> int: work = Path(tempfile.mkdtemp(prefix="post_probe_")) relay = None try: data = work / "d" data.mkdir(parents=True, exist_ok=True) env = dict(os.environ) env.update({"RELAY_PORT": str(PORT), "RELAY_BIND": "127.0.0.1", "RELAY_DATA": str(data), "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"}) log_path = work / "relay.log" log_file = open(log_path, "wb") relay = subprocess.Popen( [sys.executable, "-u", str(ROOT / "relay" / "relay.py")], env=env, stdout=log_file, stderr=subprocess.STDOUT) up = False for _ in range(40): time.sleep(0.5) try: conn = http.client.HTTPConnection("127.0.0.1", PORT, timeout=3) conn.request("GET", "/v1/health") if conn.getresponse().status == 200: up = True conn.close() break except Exception: # noqa: BLE001 continue check("本地 relay 起来了", up) if not up: return 1 # ---------- 1. 看 http.client 实际发出什么 ---------- print() print("一、http.client 带 body 时发的是 Content-Length 还是 chunked?") # 自己搭个极简服务器,把原始请求打出来 raw_seen = [] def serve_once(): server = socket.socket() server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(("127.0.0.1", PORT + 1)) server.listen(1) server.settimeout(8) try: client, _addr = server.accept() client.settimeout(3) chunks = [] try: while True: piece = client.recv(4096) if not piece: break chunks.append(piece) if b"\r\n\r\n" in b"".join(chunks): break except socket.timeout: pass raw_seen.append(b"".join(chunks)) client.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n" b"Connection: close\r\n\r\n{}") client.close() except Exception: # noqa: BLE001 pass finally: server.close() thread = threading.Thread(target=serve_once, daemon=True) thread.start() time.sleep(0.3) conn = http.client.HTTPConnection("127.0.0.1", PORT + 1, timeout=5) body = json.dumps({"deviceId": "probe-1", "code": "123456", "name": "探针", "version": "1.4.0"} ).encode("utf-8") conn.request("POST", "/v1/agent/register", body=body, headers={"Content-Type": "application/octet-stream", "User-Agent": "probe", "Connection": "keep-alive"}) try: conn.getresponse().read() except Exception: # noqa: BLE001 pass conn.close() thread.join(timeout=3) raw = raw_seen[0].decode("utf-8", "replace") if raw_seen else "" head = raw.split("\r\n\r\n")[0] print(" 实际发出的请求头:") for line in head.splitlines(): print(f" {line}") has_len = "content-length" in head.lower() has_chunked = "transfer-encoding" in head.lower() check("带了 Content-Length(不是 chunked)", has_len and not has_chunked, f"content-length={has_len} chunked={has_chunked}") # ---------- 2. 用 RelayLink._post 连打几次 ---------- print() print("二、RelayLink._post 对本地 relay 连打 5 次") from lanremote.config import Store from lanremote.relay import RelayLink store = Store(work / "store") store.set("relay_url", BASE) store.set("device_name", "post-probe") link = RelayLink(store, log=lambda m: None) link.candidates = [BASE] link.url = BASE link.device_id = "post-probe-1" link.code = "123456" ok_count = 0 for index in range(5): try: status, reply = link._post( "/v1/agent/register", json.dumps({"deviceId": "post-probe-1", "code": "123456", "name": "post-probe", "version": "1.4.0"} ).encode("utf-8"), {}, timeout=10) if status == 200: ok_count += 1 print(f" {index + 1}) HTTP {status} {reply[:70]!r}") except Exception as exc: # noqa: BLE001 print(f" {index + 1}) 异常 {type(exc).__name__}: {exc}") time.sleep(0.3) check("5 次 POST 全部成功", ok_count == 5, ok_count) # ---------- 3. relay 日志里的错误 ---------- print() print("三、relay 日志里有没有 Bad request syntax") time.sleep(0.5) log_file.flush() text = log_path.read_text(encoding="utf-8", errors="replace") bad = text.count("Bad request syntax") code400 = text.count("code 400") + text.count("Error code: 400") print(f" Bad request syntax: {bad} 次") check("没有 Bad request syntax", bad == 0, bad) if bad: for line in text.splitlines(): if "Bad request" in line or "400" in line: print(f" {line.strip()[:140]}") print() print("=" * 58) print(f"通过 {passed} 项,失败 {failed} 项") return 0 if failed == 0 else 1 finally: if relay is not None: try: relay.terminate() relay.wait(timeout=8) except Exception: # noqa: BLE001 try: relay.kill() except Exception: # noqa: BLE001 pass time.sleep(0.5) shutil.rmtree(work, ignore_errors=True) if __name__ == "__main__": sys.exit(main())