修「经中转几次后永久哑掉」——「按一下没反应」的真因

== 现象 ==

用户报:
  * 局域网能搜到电脑,IP/端口/配对码都对,连上后**没有任何反应**
  * 走中转「已配对」,但点按钮没反应

局域网那一半已经修过(preferLan)。这次抓到的是**经中转**那一半,
而且比预想的严重得多。

== 证据链(插桩复现出来的)==

被控端日志里直接抛了未捕获异常,线程当场死:

    Exception in thread client-relay:
      server.py:407  session.send(reply)
      relay.py:166   self._link.send_to_client(data)
      relay.py:357   self._post("/v1/agent/send", ...)
      relay.py:766   raise RelayError(f"请求失败: {last_error}")
    lanremote.relay.RelayError: 请求失败: Idle

之后的状态:
  * client-relay 线程没了 —— 电脑再也不往手表回任何东西
  * relay-link 线程还活着、还在长轮询 —— 中转那边看着「设备在线」
  * **手表看到的就是「连上了,但按一下毫无反应」**

写入仓库的测试 _tests/test_relay_local.py 一直是这个形状:
前面几项 PASS、跑到经中转发命令就卡死。之前没人深挖。

== 根因 1:一条 HTTP/1.1 连接被两个线程同时用 ==

_post() 里锁只包住「取连接」那一段:

    with self._http_lock:
        connection = self._http      # 锁到这里就放了
    try:
        connection.request("POST", ...)   # 锁外发请求

于是两个线程会同时用同一条 connection:
  * relay-link 线程跑 /v1/agent/poll —— 长轮询,一条请求挂 180 秒
  * client-relay 线程同时 POST /v1/agent/send

HTTP/1.1 一条连接同一时刻只能有一个在途请求,第二个线程一进来
就撞上 http.client 状态机,抛 CannotSendRequest("Idle")。

_post 的「重试一次」也救不了:它 _drop_http() 之后,另一个线程
手里还攥着那条旧连接对象在发,照样坏。

修法:
  * **发命令用独立连接**(_post 加 dedicated 参数)。
    长轮询那条常年被占着,发命令不该去挤它,各走各的。
  * 两条连接各自一把锁**锁住整个「发请求 + 读响应」周期**,
    不再只锁取连接那一下。
  * 普通请求若发现缓存连接正忙(长轮询在途),临时另开一条用完即关。
  * _drop_http(dedicated=) 区分清哪条;finally 里一定归还占用
    (否则那条连接会被永久标记为忙)。

== 根因 2:回包失败会打死整个会话线程 ==

server.py 的 _client_loop 里:

    if reply is not None:
        session.send(reply)      # <- 不在任何 try 里
    ...
    except OSError:              # <- 外层只捕获 OSError
        pass

而中转链路上 send 抛的是 RelayError,直接冒出去把线程打死。
**死一次就永久哑**,代价太大。

修法:session.send() 单独兜住所有异常,失败就断开这个会话
(让手表重连),绝不让线程消失。外层也补一个兜底 except。

== 修复效果 ==

    修复前:pair OK -> ping OK -> ping 卡死 -> 线程崩溃,永久哑
    修复后:pair 21ms -> ping 82ms -> ping 4ms -> ping 6ms,零异常

_tests/test_relay_local.py:**之前完全卡死 -> 现在 21/21 全过**

这个测试之前一直是红的,说明「35 个阶段的回归全绿」这件事
本身就不成立过 —— 某个阶段卡住时看起来像环境问题而不是缺陷。

== 同批修掉验证阶段找到的其它问题 ==

1. **TTL 清理 + 关掉接入开关 = 设备永久锁死**(严重)
   register() 用 `device_id in self.devices` 判断老设备,但超时清理
   把设备从 devices 和 codes 都删了。电脑关机过夜(必然 > 6 小时)
   第二天开机就会被自己的开关挡住,而且**重启也救不回来**
   (清 codes 时没落盘,重启后又当孤儿清一遍,自我维系)。
   管理员在页面上还看不到这台设备,不知道该放开谁。
   修法:状态文件里单独存 knownDevices 设备历史,超时清理绝不动它;
   register 改查这份历史;清理后补 _save();delete_device 才真正忘记。

2. **管理页 JS 语法错误 -> 所有按钮失效**(严重)
   admin.py 里 ADMIN_JS 是普通三引号字符串,我在 Python 源码里写的
   `\n` 被变成真实换行,拼进 JS 就是字符串里的裸换行 ->
   整段 <script> 不执行 -> 改码/删除/批量删除/全选全变幽灵按键。
   元凶是我加改码功能那次提交。改成 `\\n`。

3. **--relay / --relay-status 崩溃**(严重)
   RelayLink.start(url) 的 url 是必填参数,我把默认地址改空白时
   run_agent.py 两处调用没跟着改。一处被 try 吞成「测试失败:missing
   1 required positional argument」(用户以为地址填错了),
   一处直接报栈。两处都补上 url。

4. 非法 deviceId(控制字符 / 路径分隔符)现在被拒(白名单:
   字母数字 + - _ . :)

5. enable_relay() 第二次调用不再谎报成功(加 RelayLink.running 属性,
   返回值反映真实运行状态;不再用「对象建过没有」判断)

6. snapshot() 清孤儿码后补 _save(),磁盘和内存不再脱节

== 局域网全面优化(task-2,另一个智能体完成)==

4 个真问题:
  * **网段判断写死 /24** —— 在 /16 网络上 10.8.1.5 和 10.8.2.5
    被判成不同网络,明明能直连却去走中转还费流量。
    改成按网卡真实掩码比较。
  * **广播只发一个包** —— 丢一个就整轮搜不到。改成 5 个时间点重发。
  * **只探一个网段** —— 多网卡手表搜不到另一网段的电脑。改成全探。
  * **走中转之后再也回不到局域网** —— 出门再回家永远挂中转。
    新增定期回切(先便宜地 TCP ping,通了才动真格,
    不破坏正在工作的中转连接)。

实测:局域网握手 2ms、50/50 = 100%、中位 0ms。
(跨网络那半之前拿不到数字,就是被上面那个线程崩溃挡住的 ——
  现已修复。)

顺带:instance.py 单实例锁端口加 YKXMZ_LOCK_PORT 覆盖(默认不变)。
用户自己那台被控端正跑在这台机器上占着 8767/TCP + 8766/UDP,
是这次排查里好几个「测试怎么都不通」的根因。

== 服务端一键部署脚本(task-1,另一个智能体完成)==

relay/deploy.sh + relay/deploy-tune.sh,随服务端 zip 发布:
  * 自动检查并安装 cloudflared
  * 部署程序、装 4 个 systemd 服务、网络调优、配隧道、自检打公网地址
  * **不传 --hostname 且没有 TUNNEL_TOKEN 时明确提示要填**,
    不会静默用一个写死的域名(用户明确说过这个中转站是他自己用的,
    不对外开放,绝不能把私人域名烧成默认值)
  * 重跑 = 升级,已有数据/配对码/管理密码/凭据都不动

顺带修了发布包一直缺 site_shots/ 的老 bug
(package_remote.py 用 iterdir()+is_file() 收文件,目录进不去,
新机器装完官网截图全是 404)。

== 默认中转地址改成空白 ==

用户要求:软件默认不带任何中转地址,由用户自己填。
四处硬编码全部清空(server.py / MainActivity.java / run_agent.py /
relay.py 的注释和文档示例),全仓已无非注释的硬编码地址。

== 文档同步(task-5,另一个智能体完成)==

README / BEFORE-INSTALL / AFTER-INSTALL / 打包模板:
  * 新增「软件里不带任何中转地址」告示,讲清跨网络要自己部署
  * 修正 Android 版本(写的是 9.0/API28,实际 API 24 / Android 7.0)
  * 删掉「地址已经内置好了」(现在是错的)
  * AGENT_README 原来把作者自己的中转地址当成「内置地址」发给用户,已重写
  * RELAY_README 原来写「两条隧道同时跑会互相争抢」,
    和真机/CHANGELOG 矛盾;按实测改成「两种协议同时在跑(故意的)」
This commit is contained in:
xmz7891
2026-10-07 17:59:39 +08:00
parent b2bfa6ffbf
commit 8880e7033d
290 changed files with 13216 additions and 1159 deletions
+400
View File
@@ -0,0 +1,400 @@
# -*- coding: utf-8 -*-
"""对抗性验证:中转状态机的边界场景(verifier 独立编写)。
不依赖任何人的自述,直接起一个真中转、打真接口、看真结果。
重点打这些:
1. **DEVICE_TTL 清理 + allow_new=False 的死亡组合**
设备离线超过 DEVICE_TTL 后被 snapshot 清掉,
而 register() 判断"是不是老设备"用的是 self.devices ——
那台设备再回来会不会被当成新设备、被开关永久挡死?
2. **改码之后 codes / devices / state.json 三者自洽**
同一台设备连续改码 A->B->C,中间态会不会留孤儿?
3. **snapshot 的清理顺序**
会不会出现「codes 清了但 devices 还在」或反过来?
4. **deviceId 塞奇怪字符**
超长、控制字符、路径分隔符、Unicode。
5. **并发改码**
两个线程同时给同一台设备改成不同的码,会不会出现两个码都指向它。
6. **未鉴权访问管理接口**
不带 cookie / 不带 X-Admin 能不能改状态。
用 RELAY_DEVICE_TTL 把超时压到几秒,就能在测试里真实触发清理路径,
不用等 6 小时。
"""
from __future__ import annotations
import http.cookiejar
import json
import os
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
PORT = 8137
BASE = f"http://127.0.0.1:{PORT}"
TTL = 3.0 # 设备 3 秒不上报就算超时
_UA = {"User-Agent": "LanRemote/1.8.2"}
passed = 0
failed = 0
findings: list[str] = []
def check(name: str, ok: bool, detail: str = "") -> bool:
global passed, failed
if ok:
passed += 1
print(" [PASS] " + name)
else:
failed += 1
print(" [FAIL] " + name + ((" —— " + str(detail)) if detail else ""))
return ok
def note(text: str) -> None:
findings.append(text)
print(" [!!] " + text)
def main() -> int:
work = Path(tempfile.mkdtemp(prefix="advrelay_"))
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),
"RELAY_DEVICE_TTL": str(TTL),
"RELAY_ADMIN_KEY": "test-admin-key-12345",
"RELAY_POLL": "2",
"PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1",
})
relay = subprocess.Popen(
[sys.executable, "-u", str(ROOT / "relay" / "relay.py")], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
up = False
for _ in range(60):
time.sleep(0.5)
try:
r = urllib.request.Request(BASE + "/v1/health", headers=_UA)
with urllib.request.urlopen(r, timeout=3) as resp:
if resp.status == 200:
up = True
break
except Exception: # noqa: BLE001
continue
check("真中转起来了", up)
if not up:
return 1
ADMIN = {"**": "**"}
def admin_post(path: str, payload: dict) -> tuple:
body = json.dumps(payload).encode()
r = urllib.request.Request(BASE + path, data=body, method="POST",
headers={**_UA, "X-Admin":
"test-admin-key-12345",
"Content-Type":
"application/json"})
try:
with urllib.request.urlopen(r, timeout=20) as resp:
return resp.status, json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", "replace")
try:
return exc.code, json.loads(raw)
except Exception: # noqa: BLE001
return exc.code, {"raw": raw[:160]}
def health() -> dict:
r = urllib.request.Request(BASE + "/v1/health", headers=_UA)
with urllib.request.urlopen(r, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
def reg(dev: str, code: str, name: str = "对抗测试机") -> dict:
body = json.dumps({"deviceId": dev, "code": code, "name": name,
"version": "1.8.2",
"lanIps": ["192.168.1.5"],
"port": 8765}).encode()
r = urllib.request.Request(
BASE + "/v1/agent/register", data=body, method="POST",
headers={**_UA, "Content-Type": "application/json"})
try:
with urllib.request.urlopen(r, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", "replace")
try:
return json.loads(raw)
except Exception: # noqa: BLE001
return {"ok": False, "raw": raw[:160]}
stamp = int(time.time()) % 100000
# ============================================================
print()
print("═══ 场景 1:DEVICE_TTL 清理 + allow_new=False 的死亡组合 ═══")
# ============================================================
dev1 = f"ttl-dev-{stamp}"
code1 = "%06d" % (stamp % 1000000)
r1 = reg(dev1, code1)
check("设备首次注册成功", r1.get("ok") is True, r1)
st, res = admin_post("/v1/admin/allow_new", {"allow": False})
check("关掉「允许新设备接入」成功",
st == 200 and res.get("allowNew") is False, (st, res))
# 立刻再注册一次(设备还在 devices 里)—— 应该放行
r2 = reg(dev1, code1)
check("【对照】设备还在 devices 里时,老设备能通过开关",
r2.get("ok") is True, r2)
# 等超过 TTL,然后调 health 触发 snapshot 清理
print(f" 等 {TTL + 2:.0f} 秒让设备超时…")
time.sleep(TTL + 2)
h = health() # snapshot() 在这里跑清理
devs_now = [d["deviceId"] for d in h.get("devices", [])]
check("【前提】超时设备已被 snapshot 清出 devices",
dev1 not in devs_now, devs_now)
check("【前提】该设备的码绑定也已被清(codes 成对清理)",
h.get("codeCount") == 0, h.get("codeCount"))
# 关键一击:设备"回来"了
r3 = reg(dev1, code1)
if r3.get("ok") is True:
check("超时清理后老设备仍能重新上线", True)
else:
check("超时清理后老设备仍能重新上线", False, r3)
note("🔴 **严重**:设备离线超过 DEVICE_TTL 被清理后,"
"若 allow_new=False,该设备再回来会被当成新设备**永久拒绝**。"
f" 复现:register({dev1!r}) -> allow_new=False -> 等 {TTL+2:.0f}s "
f"-> GET /v1/health -> register 同 deviceId 得到 {r3}")
# 打开开关再试,确认确实是开关挡的
admin_post("/v1/admin/allow_new", {"allow": True})
r4 = reg(dev1, code1)
check("【归因】打开开关后同一 deviceId 立刻能注册(证明是被开关挡的)",
r4.get("ok") is True, r4)
# ============================================================
print()
print("═══ 场景 2:改码 A->B->C 后 codes 里有没有留孤儿 ═══")
# ============================================================
dev2 = f"code-dev-{stamp}"
codeA = "%06d" % ((stamp + 111) % 1000000)
codeB = "%06d" % ((stamp + 222) % 1000000)
codeC = "%06d" % ((stamp + 333) % 1000000)
ra = reg(dev2, codeA)
check("设备注册(码 A)", ra.get("ok") is True, ra)
st, res = admin_post("/v1/admin/set_code",
{"deviceId": dev2, "code": codeB})
check("改码 A->B 成功", st == 200 and res.get("ok"), (st, res))
st, res = admin_post("/v1/admin/set_code",
{"deviceId": dev2, "code": codeC})
check("改码 B->C 成功", st == 200 and res.get("ok"), (st, res))
h = health()
cnt = h.get("codeCount")
dev2_codes = [d["code"] for d in h["devices"]
if d["deviceId"] == dev2]
check("一台设备只占一个码(codeCount 与设备数一致)",
cnt == len(h["devices"]), f"codeCount={cnt} 设备数={len(h['devices'])}")
check("设备当前码是 C", dev2_codes == [codeC], dev2_codes)
# A 和 B 应该都能被别的设备抢走(如果还是孤儿就抢不走)
dev3 = f"code-dev3-{stamp}"
rA = reg(dev3, codeA)
check("旧码 A 已被释放(另一台设备能占用)", rA.get("ok") is True, rA)
# ============================================================
print()
print("═══ 场景 3:改码之后重启,codes 是否还原成自洽状态 ═══")
# ============================================================
st, res = admin_post("/v1/admin/set_code",
{"deviceId": dev2, "code": codeB})
check("再改成 B", st == 200 and res.get("ok"), (st, res))
state_file = data / "relay_state.json"
raw = json.loads(state_file.read_text(encoding="utf-8"))
bound = [c for c in raw.get("codes", [])
if c.get("deviceId") == dev2]
check("state.json 里该设备只有一条码绑定",
len(bound) == 1, bound)
# ============================================================
print()
print("═══ 场景 4:deviceId 塞奇怪字符 ═══")
# ============================================================
weird = [
("超长 200 字符", "x" * 200),
("控制字符", "dev\x00\x01\x02"),
("路径分隔符", "../../etc/passwd"),
("Unicode", "设备-😀-ünïcode"),
("只有空格", " "),
]
for label, bad in weird:
try:
r = reg(bad, "%06d" % ((stamp + 444) % 1000000))
ok_rejected = r.get("ok") is False
check(f"非法 deviceId({label})被拒绝而不是崩溃",
ok_rejected, r)
except Exception as exc: # noqa: BLE001
check(f"非法 deviceId({label})被拒绝而不是崩溃",
False, f"抛异常 {type(exc).__name__}: {exc}")
# ============================================================
print()
print("═══ 场景 5:并发改码(两个线程同时改同一台设备)═══")
# ============================================================
dev5 = f"race-dev-{stamp}"
reg(dev5, "%06d" % ((stamp + 555) % 1000000))
codeX = "%06d" % ((stamp + 666) % 1000000)
codeY = "%06d" % ((stamp + 777) % 1000000)
errors: list = []
def changer(target: str) -> None:
try:
admin_post("/v1/admin/set_code",
{"deviceId": dev5, "code": target})
except Exception as exc: # noqa: BLE001
errors.append(exc)
t1 = threading.Thread(target=changer, args=(codeX,))
t2 = threading.Thread(target=changer, args=(codeY,))
t1.start()
t2.start()
t1.join()
t2.join()
check("并发改码没抛异常", not errors, errors)
h = health()
owned = [c for c, d in [("?", None)] ] if False else None
dev5_row = [d for d in h["devices"] if d["deviceId"] == dev5]
check("并发后设备还在", len(dev5_row) == 1, dev5_row)
cur = dev5_row[0]["code"] if dev5_row else "?"
check("并发后设备当前码是 X 或 Y 之一",
cur in (codeX, codeY), cur)
# 另一台设备能不能用"输掉"的那个码?能就说明没留孤儿
dev6 = f"race-dev6-{stamp}"
loser = codeY if cur == codeX else codeX
r = reg(dev6, loser)
check("并发改码后输掉的那个码没有变成孤儿(别的设备能占)",
r.get("ok") is True, r)
# ============================================================
print()
print("═══ 场景 6:管理接口未鉴权访问 ═══")
# ============================================================
for path, payload in (
("/v1/admin/allow_new", {"allow": False}),
("/v1/admin/set_code", {"deviceId": dev1, "code": "999999"}),
("/v1/admin/delete", {"deviceId": dev1}),
("/v1/admin/delete_all", {}),
):
body = json.dumps(payload).encode()
r = urllib.request.Request(BASE + path, data=body, method="POST",
headers={**_UA, "Content-Type":
"application/json"})
try:
with urllib.request.urlopen(r, timeout=10) as resp:
code = resp.status
resp.read()
except urllib.error.HTTPError as exc:
code = exc.code
try:
exc.read()
except Exception: # noqa: BLE001
pass
except Exception as exc: # noqa: BLE001
code = f"异常 {type(exc).__name__}"
check(f"未鉴权 POST {path} 被拒(401/403)", code in (401, 403),
f"实际 {code}")
# ============================================================
print()
print("═══ 场景 7:设备列表为空时管理页是否 500 ═══")
# ============================================================
admin_post("/v1/admin/delete_all", {})
r = urllib.request.Request(BASE + "/zhongzhuanzhan",
headers={**_UA, "X-Admin":
"test-admin-key-12345"})
try:
with urllib.request.urlopen(r, timeout=10) as resp:
page = resp.read().decode("utf-8", "replace")
ok_page = resp.status == 200 and len(page) > 200
except urllib.error.HTTPError as exc:
page = exc.read().decode("utf-8", "replace")
ok_page = False
note(f"管理页在设备列表为空时返回 {exc.code}")
check("设备列表为空时管理页仍正常渲染", ok_page)
check("空列表页面没有 traceback",
"Traceback" not in page and "NameError" not in page)
# ============================================================
print()
print("═══ 场景 8:关掉开关后重启中转,开关状态是否还在 ═══")
# ============================================================
admin_post("/v1/admin/allow_new", {"allow": False})
h1 = health()
check("关掉开关", h1.get("allowNew") is False, h1.get("allowNew"))
relay.terminate()
relay.wait(timeout=15)
relay = subprocess.Popen(
[sys.executable, "-u", str(ROOT / "relay" / "relay.py")], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
up = False
for _ in range(40):
time.sleep(0.5)
try:
h2 = health()
up = True
break
except Exception: # noqa: BLE001
continue
check("重启后中转起来了", up)
if up:
check("重启后 allowNew 仍为 False(持久化生效)",
h2.get("allowNew") is False, h2.get("allowNew"))
# ============================================================
print()
print("=" * 62)
print(f" 通过 {passed} 项,失败 {failed} 项")
if findings:
print()
print(" 发现的问题:")
for f in findings:
print(" - " + f)
print("=" * 62)
Path("_build/_adv_relay_result.txt").write_text(
f"passed={passed} failed={failed}\n"
+ "\n".join(findings) + "\n", encoding="utf-8")
return 1 if failed else 0
finally:
if relay is not None and relay.poll() is None:
relay.terminate()
try:
relay.wait(timeout=10)
except Exception: # noqa: BLE001
relay.kill()
if __name__ == "__main__":
sys.exit(main())