Files
STM32F4-Base/test/host/bench/ftp/ftp_abort_probe.py
T
wandering1 685a366890 refactor(test): 把 test/host 顶层 25 个台架脚本按域收进 bench/
原来 test/host 一层混了三类东西:51 个主机侧单测模块目录、25 个台架驱动
与探针、若干专用目录。台架脚本平铺在顶层,与单测目录并列,看不出哪个是
「连板跑一次的」,也看不出加新脚本该往哪放。

现在按被验对象分域归档,单测模块目录一律不动(22 根 pre-commit 钩子逐个
点名它们,50 个运行器按固定层数推仓库根):

- bench/bench_defaults.py 台架连接默认值单一真源
- bench/ftp/ (10) FTP 功能、速率、鉴权、中止、完整性、背靠背复现
- bench/net/ (9) CH395F socket、keepalive 判死、挂机、复连压力、PASV、
  UDP 队列、链路时延对端
- bench/iec104/ (2) 主站客户端与它的离线样帧自检
- bench/wave/ (1) 录波段文件 PC 侧解码
- bench/screenlink/ (2) 屏板链路顶替与拉帧压测

顶层条目 78 -> 53。逐脚本作用、运行前置与「加新脚本往哪放」写在新建的
test/host/bench/README.md;test/host/README.md 增目录地图表,把原平铺的
网络/FTP 两节压成指针。

配套修正(移动后不修就会坏):
- 17 个脚本加上 bench/ 到 sys.path 的 bootstrap(sys.path[0] 是脚本自身
  目录,不补就 import bench_defaults 失败)
- cal/cal_write.py 本来就坏的(只插 cal/ 到自己 sys.path,import
  bench_defaults 直接 ModuleNotFoundError),补两段路径后可用
- e6_soak 与 wave_read 用 dirname 固定层数推仓库根,多两层后分别指向
  test/test 与 test/ci-artifacts(后者静默写错目录、不报错),层数已改对
- scripts/board_ui_nav.py 与 MDK-ARM 两个探针的 bench_defaults 搜索路径

清理与标注:删掉 test/host/iec104/(旧自研协议层单测退役后只剩一个零引用
的 stub 桩头);文档里对 test/host/iec104 与 iec104_serv 的引用加上「已
删除/已不存在 2026-11-18」状态词。冻结历史证据(带日期戳的台架日志)与
编号别名登记表里的旧路径按原样保留。
2026-11-18 12:46:03 +08:00

147 lines
6.3 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 -*-
# Trustworthy abort/robustness probe for the production FTP path (no firmware probes).
#
# Scenario: client starts a STOR upload, sends part of the data, then ABORTS by
# resetting the data connection (SO_LINGER 0 -> RST), which is the common real-world
# pattern (user cancels an upload, client crashes, link drops). Then it checks:
# 1. the control channel still answers (NOOP on a fresh connection),
# 2. a FOLLOW-UP normal upload+download still passes the SHA-256 check,
# 3. the device's relisten actually happened (observable via a successful follow-up).
#
# Usage: ftp_abort_probe.py [--ip ..] [--port 21] [--rounds 10] [--send 8192] [--gap 2]
# [--graceful] [--check-abort]
# Output: TS <epoch> / ABORT <n> sent=<b> ctrl=<reply> alive=<yes|no> followup=<OK|FAIL:x>
# abort5xx=<OK|FAIL|-> (only with --check-abort: RST expects 4xx/5xx on the
# aborted STOR = no false 226 (TRAP-NET-18 hardening); graceful FIN expects 2xx
# = protocol boundary, still reported as success)
# SUMMARY rounds=<n> pass=<n> fail=<n>
# Exit 0 all rounds pass, 1 otherwise.
import argparse, hashlib, io, os, random, re, socket, struct, sys, time
from ftplib import FTP, all_errors
# 台架连接默认值单一真源已随域归档到 test/host/bench/bench_defaults.py:
# Python 的 sys.path[0] 是**脚本自身所在目录**,本脚本在 bench/<域>/ 下直接
# `import bench_defaults` 会 ModuleNotFoundError —— 先把 bench/ 补进 sys.path。
_BENCH_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _BENCH_DIR not in sys.path:
sys.path.insert(0, _BENCH_DIR)
import bench_defaults # noqa: E402 (台架连接默认值单一真源)
def log(m):
sys.stdout.write(m + "\n"); sys.stdout.flush()
def rd(sock):
try:
return sock.recv(4096).decode("latin1").strip()
except Exception:
return ""
def raw_login(ip, port, timeout=10.0):
s = socket.create_connection((ip, port), timeout=timeout)
rd(s) # 220 banner
# FTP auth is mandatory: anonymous login is rejected (530) -> use the factory default account
s.sendall(b"USER admin\r\n"); rd(s)
s.sendall(b"PASS admin\r\n"); rd(s)
s.sendall(b"TYPE I\r\n"); rd(s)
return s
def pasv_data_socket(ctl):
ctl.sendall(b"PASV\r\n")
r = rd(ctl)
m = re.search(r"\((\d+),(\d+),(\d+),(\d+),(\d+),(\d+)\)", r)
if not m:
raise RuntimeError("PASV failed: " + r)
host = ".".join(m.group(i) for i in (1, 2, 3, 4))
port = (int(m.group(5)) << 8) | int(m.group(6))
return socket.create_connection((host, port), timeout=10.0)
def followup_ok(ip, port, size=4096):
"""normal upload + download + sha256 -> True/False"""
data = bytes(random.getrandbits(8) for _ in range(size))
want = hashlib.sha256(data).hexdigest()
try:
f = FTP(); f.connect(ip, port, timeout=15.0); f.login("admin", "admin")
f.storbinary("STOR /ab_ok.bin", io.BytesIO(data))
buf = bytearray(); f.retrbinary("RETR /ab_ok.bin", buf.extend)
try:
f.delete("/ab_ok.bin")
except all_errors:
pass
f.quit()
return hashlib.sha256(bytes(buf)).hexdigest() == want
except all_errors:
return False
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ip", default=bench_defaults.DEVICE_IP)
ap.add_argument("--port", type=int, default=21)
ap.add_argument("--rounds", type=int, default=10)
ap.add_argument("--send", type=int, default=8192, help="bytes sent before the RST")
ap.add_argument("--gap", type=float, default=2.0)
ap.add_argument("--graceful", action="store_true",
help="close the data connection with FIN instead of RST")
ap.add_argument("--check-abort", action="store_true",
help="also assert the aborted STOR's control reply: RST -> 4xx/5xx "
"(no false 226, TRAP-NET-18 hardening); graceful FIN -> 2xx (boundary)")
a = ap.parse_args()
npass = nfail = 0
for n in range(1, a.rounds + 1):
log("TS %d" % int(time.time()))
ctl_reply = "NA"
alive = "no"
try:
ctl = raw_login(a.ip, a.port)
ds = pasv_data_socket(ctl)
ctl.sendall(("STOR /ab%04d.bin\r\n" % n).encode())
ctl_reply = rd(ctl) # 150
chunk = bytes(random.getrandbits(8) for _ in range(a.send))
ds.sendall(chunk)
if a.graceful:
ds.shutdown(socket.SHUT_RDWR) # graceful FIN (client cancel)
else:
# abort: RST the data connection (linger 0)
ds.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
ds.close()
time.sleep(0.5)
ctl_reply = rd(ctl) # 426/550/226
try:
ctl.sendall(b"QUIT\r\n"); rd(ctl)
except Exception:
pass
try:
ctl.close()
except Exception:
pass
except Exception as e:
ctl_reply = "EXC:%s" % type(e).__name__
# control-channel liveness on a fresh connection
try:
c2 = raw_login(a.ip, a.port)
c2.sendall(b"NOOP\r\n")
alive = "yes" if rd(c2).startswith("2") else "no"
c2.sendall(b"QUIT\r\n"); c2.close()
except Exception:
alive = "no"
fu = followup_ok(a.ip, a.port)
abort_ok = True
if a.check_abort:
code = ctl_reply[0] if (ctl_reply and ctl_reply[0].isdigit()) else "?"
# RST: device must report 4xx/5xx on the aborted STOR (450); graceful
# FIN still gets 226 (STOR has no length declaration - protocol boundary)
abort_ok = (code == "2") if a.graceful else (code in ("4", "5"))
ok = (alive == "yes" and fu and abort_ok)
npass += 1 if ok else 0
nfail += 0 if ok else 1
log("ABORT %d sent=%d ctrl=%s alive=%s followup=%s abort5xx=%s" %
(n, a.send, ctl_reply.replace("\r\n", "|")[:40], alive,
"OK" if fu else "FAIL", "OK" if abort_ok else "FAIL" if a.check_abort else "-"))
if a.gap > 0 and n < a.rounds:
time.sleep(a.gap)
log("SUMMARY rounds=%d pass=%d fail=%d" % (a.rounds, npass, nfail))
return 0 if nfail == 0 else 1
sys.exit(main())