Files
ykxmz/_tests/probe_post_raw.py
T
xmz7891 b705216e4a ykxmz 1.5.0锛氫慨澶嶆墜琛ㄧ TLS 璇佷功鏍¢獙 + MTU 淇缃戠粶绋冲畾鎬?
琚帶绔?- 淇 MTU 闂锛氬す MSS + 璺緞 MTU 鎺㈡祴锛堝叕缃戝彲鐢ㄧ巼 48% -> 100%锛?- 澶嶇敤 HTTP 杩炴帴锛堝厤鎺夋瘡娆℃柊寤?TLS 鐨?30% 鎻℃墜澶辫触锛?- 姣忓垎閽熷洖澶存壘灞€鍩熺綉锛岃嚜鍔ㄥ垏鍥炲揩 400 鍊嶇殑璺緞
- 鐢婚潰蹇冭烦甯э細闈欐鏃剁渷娴侀噺锛屽鎴风浠嶇煡閬撴祦鏄椿鐨?- 閿佸睆鏃剁粰鍑哄彲鎿嶄綔鐨勬彁绀?
鎵嬭〃绔?- 鍐呯疆 GTS Root R4 / GlobalSign Root CA锛屼慨 SSLHandshakeException
- 杩炴帴閿欒缈昏瘧鎴愪汉璇濓紙璇佷功/鏃堕棿/瑙f瀽/瓒呮椂鍒嗗埆鎻愮ず锛?- 缁忎腑杞繛涓婂悗鐢ㄦ湇鍔″櫒鎶ョ殑鍦板潃鍒锋柊宸查厤瀵硅褰?- 鏂板灞€鍩熺綉杩炴帴椤甸潰銆佹湇鍔″櫒寤惰繜妫€娴?
鏈嶅姟鍣ㄧ
- 鏀寔 chunked 璇锋眰浣擄紙淇瘡 16 绉掍竴娆$殑杩炴帴閿欎贡涓庡ぇ闈㈢Н 502锛?- 缃戠粶璋冧紭鑴氭湰 net-tune.sh锛堝紑鏈鸿嚜鍔ㄥ簲鐢級
- 绠$悊椤碉細鎵归噺鍒犻櫎銆佺綉缁滀綋妫€銆佷笅杞藉尯
- 闅ч亾鏀?HTTP/2 + 鍙岃繛鎺?
鏂囨。
- 璁稿彲鍗忚 / 瀹夎鍓嶅繀璇?/ 瀹夎鍚庨』鐭ワ紙浣滆€咃細灏忛害瀛愶級
2026-10-06 19:01:05 +08:00

212 lines
7.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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())