From 77abf1b515b1c343b22c3f89aaa347927ebbea09 Mon Sep 17 00:00:00 2001 From: tsosunchia <59512455+tsosunchia@users.noreply.github.com> Date: Fri, 6 Mar 2026 14:07:58 +0800 Subject: [PATCH] Refactor MTR signal handling and context management - Unified signal handling in MTR CLI using `signal.NotifyContext(...)` for Ctrl-C/SIGTERM, removing the need for separate `sigCh` and goroutine. - Updated `runMTRTUI`, `runMTRReport`, and `runMTRRaw` functions to utilize the new context management. - Enhanced `mtrUI` to safely call `cancel()` only if it is not nil. - Modified `IPDBOneClient` to clone HTTP clients with timeout settings, ensuring proper timeout handling without modifying global state. - Adjusted raw aggregation keys in the frontend to collapse based on TTL, improving display of timeout/success results. - Added context support in various tracer functions to allow cancellation and timeout handling. - Improved error handling and test coverage for MTR operations, ensuring robustness against nil results and empty responses. - Refined DNS resolver functions to use mutexes for thread-safe access to the geo resolver override. --- AGENTS.md | 272 +----------------------------------- CLAUDE.md | 9 +- cmd/mtr_mode.go | 37 +---- cmd/mtr_ui.go | 4 +- ipgeo/ipdbone.go | 22 ++- server/web/assets/app.js | 10 +- trace/icmp_ipv4.go | 6 +- trace/icmp_ipv6.go | 6 +- trace/mtr_raw.go | 1 + trace/mtr_raw_test.go | 3 +- trace/mtr_runner.go | 14 +- trace/mtr_scheduler.go | 2 +- trace/mtr_scheduler_test.go | 2 +- trace/mtr_stats.go | 4 + trace/mtr_stats_test.go | 10 ++ trace/tcp_ipv4.go | 6 +- trace/tcp_ipv6.go | 6 +- trace/trace.go | 15 ++ trace/udp_ipv4.go | 6 +- trace/udp_ipv6.go | 6 +- util/dns_resolver.go | 16 ++- util/dns_resolver_test.go | 8 +- util/http_client_geo.go | 50 +++---- util/latency.go | 20 +-- 24 files changed, 164 insertions(+), 371 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 646d029..3cd8a42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,271 +1 @@ -# NTrace-core 项目记忆文件(2026-02 快照,rev-2) - -# 供 LLM 在后续会话中快速加载上下文,减少重复分析。 - -## 项目概览 - -- 名称:NextTrace (NTrace-core) -- 仓库:github.com/nxtrace/NTrace-core -- 模块:`github.com/nxtrace/NTrace-core` -- 语言:Go(`go 1.26.0`) -- 入口:`main.go -> cmd.Execute()` -- 核心能力:ICMP/TCP/UDP traceroute、GeoIP/RDNS、MTR 连续探测、Web/API、多平台构建 - -## 构建与测试(必须遵守) - -- 常用命令: - - 构建:`go build ./...` - - 测试:`go test ./...` -- 交叉编译脚本:`.cross_compile.sh` -- Darwin 下 `trace/internal/icmp_darwin.go` 已不再使用 `//go:linkname`,改为 - `syscall.Socket` + `os.NewFile` + 自定义 `icmpPacketConn`(实现 `net.PacketConn` / - `net.Conn` / `syscall.Conn` + `ReadMsgIP` 以满足 `x/net/internal/socket.ipConn` - 接口),并在 `ReadFrom` 中调用 `stripIPv4Header` 剥离 macOS DGRAM ICMP socket - 返回的外层 IP 头。 - -## 当前 CLI 语义(重点) - -### 常规 traceroute 路径 - -- `--table`:现在是"最终汇总表"模式(一次探测完成后输出汇总表),不再是旧的异步 table 刷新模式。 -- `--route-path`:仍由 `reporter.New(...).Print()` 负责(与 MTR report 无关)。 - -### 间隔默认值(分层体系) - -- `-z/--send-time`:每包间隔,默认 `defaultPacketIntervalMs = 50` ms。 -- `-i/--ttl-time`: - - **常规 traceroute**:TTL 分组间隔,默认 `defaultTracerouteTTLIntervalMs = 300` ms。 - - **MTR 模式**:`normalizeMTRTraceConfig()` 始终覆盖为 `defaultMTRInternalTTLIntervalMs = 0` ms(各 TTL 间不间隔)。 - - MTR 每跳探测间隔由 `-i` 显式传值 或 默认 1000ms 决定(见下文 `-q/-i` 语义)。`-z/--send-time` 在 MTR 模式下被忽略。 - -### MTR 相关参数 - -- `-t/--mtr`:开启 MTR 交互模式(TTY 全屏 TUI)。 -- `-r/--report`:MTR 报告模式(非交互),隐式开启 MTR。 -- `-w/--wide`:宽报告模式,隐式等价 `--mtr --report --wide`。 -- `--raw`:与 MTR 组合时进入 **MTR raw 流式模式**(`runMTRRaw`),不再与 MTR 冲突。 -- 有效 MTR 开关:`effectiveMTR = mtr || report || wide`。 -- MTR 三路分支(`chooseMTRRunMode`): - 1. `effectiveMTRRaw` → `runMTRRaw`(流式行输出,适合管道/脚本) - 2. `effectiveReport` → `runMTRReport`(非交互报告表) - 3. 默认 → `runMTRTUI`(全屏 TUI) -- MTR 冲突参数(会直接报错退出):`--table` `--classic` `--json` `--output` `--route-path` `--from` `--fast-trace` `--file` `--deploy`。 - - **注意**:`--raw` 不再是冲突参数。 - -### MTR 中 `-q/-i/-y` 的新语义 - -- `-q/--queries`: - - 在 MTR report 下表示每跳探测次数,默认 10(仅当用户未显式传 `-q`)。 - - 在 MTR TUI 下表示每跳最大探测次数,未显式传时默认无限运行。 -- `-i/--ttl-time`: - - 在 MTR 下表示每跳探测间隔毫秒,默认 1000ms(仅当用户未显式传 `-i`)。 - - 各 TTL 间内部扫描间隔固定 0ms(`normalizeMTRTraceConfig` 覆盖为 `defaultMTRInternalTTLIntervalMs = 0`)。 - - `-z/--send-time` 在 MTR 模式下被忽略。 -- `-y/--ipinfo <0..4>`: - - TUI 初始 Host 显示模式,默认 0(IP/PTR only)。 - - 0=Base(IP/PTR) 1=ASN 2=City 3=Owner 4=Full - - 仅 TUI 模式生效,report/raw 不受影响。 - -### MTR report wide / non-wide 区别 - -- **wide 模式**(`-w` 或 `--mtr --report --wide`): - - 查询 GeoIP,显示完整 host 信息(ASN + geo + MPLS)。 -- **非 wide 模式**(`-r` 或 `--mtr --report`): - - `normalizeMTRReportConfig` 设 `IPGeoSource=nil`(不查 geo)、`AlwaysWaitRDNS=true`。 - - 显示 `formatCompactReportHost`:仅 IP/PTR + ASN,无 geo 列。 - -## MTR 运行链路(重要文件) - -- 入口与调度:`cmd/mtr_mode.go`(~315 行) - - `runMTRTUI(...)` / `runMTRReport(...)` / `runMTRRaw(...)` - - `normalizeMTRTraceConfig(conf)` / `normalizeMTRReportConfig(conf, wide)` - - `buildAPIInfo(...)` / `buildRawAPIInfoLine(...)` -- 交互控制:`cmd/mtr_ui.go` - - alternate screen + raw mode - - 输入状态机 `mtrInputParser`(字节流,吞掉 CSI/SS3/OSC/鼠标/焦点等序列) - - Enter/Leave 显式关闭输入扩展模式:1000/1002/1003/1006/1015/1004/2004 -- 核心探测循环:`trace/mtr_runner.go` - - `RunMTR` / `mtrLoop` / `RunMTRRaw` - - 支持暂停、重置、流式预览(`ProgressThrottle` 默认 200ms) - - ICMP 持久引擎 + TCP/UDP fallback -- 统计聚合:`trace/mtr_stats.go` - - `MTRAggregator` / `MTRHopStat` - - unknown 合并策略:单路径时把 unknown 合并到唯一已知路径,避免同 TTL 分裂成 waiting + 真实 IP 两行 -- 输出层: - - TUI:`printer/mtr_tui.go` - - table/report:`printer/mtr_table.go` - - raw 行格式化:`printer.FormatMTRRawLine(rec)` - - TUI 颜色:`printer/mtr_tui_color.go` - -## MTR 交互行为(当前) - -- `q`/`Q`/`Ctrl-C`:退出 -- `p`:暂停 -- `SPACE`:恢复 -- `r`:重置统计 -- `y`:切换 Host 显示模式(IP/PTR → ASN → City → Owner → Full → 循环) -- `n`:切换 Host 基名显示(PTR-or-IP / IP-only) -- `e`:切换 MPLS 标签显示(toggle MPLS on/off) - -## MTR 显示与统计规则(当前) - -- Host 显示支持 5 种模式(`-y/--ipinfo` 设初始值,`y` 键运行时循环): - - `HostModeBase=0`:仅 IP/PTR,无 ASN 前缀 - - `HostModeASN=1` / `HostModeCity=2` / `HostModeOwner=3` / `HostModeFull=4` - - `HostNamePTRorIP` / `HostNameIPOnly` -- 默认语言:`cn`(`--language en` 才优先英文字段) -- waiting 判定:`loss >= 99.95 && IP=="" && Host==""` - - 显示为 `(waiting for reply)` - - 指标列(Loss/Snt/Last/Avg/Best/Wrst/StDev)留空 -- TUI Host 对齐(重要,已从 tab 改为手动空格): - - `buildTUIHostParts(stat, mode, nameMode, lang, showIPs)` 生成结构化 parts - - `computeTUIASNWidth(stats, ...)` 扫描所有 hop 确定 ASN 列最大宽度 - - `formatTUIHost(parts, asnW)` 用 `padRight(asn, asnW)` + 空格拼接(不用 `\t`) - - ASN 为空但 IP 已知时填 `"AS???"` 占位符,保证列对齐(HostModeBase 除外,该模式不显示 ASN) - - waiting hop 不填占位符 -- compact report host(非 wide report): - - `formatCompactReportHost(stat, nameMode, lang)` 仅输出 hostname/IP + ASN -- TUI 其他特性: - - 终端宽度自适应 + CJK 宽度计算(go-runewidth) - - 窄屏右锚定指标区 - - 动态 hop 前缀宽度(覆盖 3 位/4 位 TTL) - - MPLS 独立续行显示 - - 紧凑指标列宽度:Loss=5 Snt=3 RTT=7 RTTMin=5 - -## MTR 目的地检测与高 TTL 丢弃 - -- 当 `knownFinalTTL` 已确定后,所有 `TTL > knownFinalTTL` 的调度槽位被标记为 `disabled`。 -- disabled TTL 的探测回包(包括在途探测返回的 dst-ip 回复)**一律丢弃**,不折叠、不计入任何统计。 -- **MaxPerHop 上限检查**(`states[originTTL].completed + inFlightCount >= MaxPerHop`): - - 调度时使用 `completed + inFlightCount >= MaxPerHop` 防止超发。 - - 完成时仍检查 `completed >= MaxPerHop` 丢弃溢出结果。 -- `originTTL < curFinal` 时(更低 TTL 先到 dst-ip → 降低 `knownFinalTTL`): - - 保存 `oldFinal`,更新 `knownFinalTTL = originTTL`,disable 所有 `originTTL+1..maxHops`。 - - 调用 `agg.ClearHop(oldFinal)`:清除旧 finalTTL 的聚合数据(避免幽灵行),**不合并**到新 finalTTL。 - - 新 finalTTL 由独立的 per-hop 调度器自行积累新鲜探测数据,不存在 Snt 膨胀问题。 -- 调度状态(`inFlightCount`/`nextAt`/`consecutiveErrs`)更新在 `originTTL`。 -- 统计聚合(`completed++`/`agg.Update`/`onProbe`)均使用 `originTTL`(不再有 `accountTTL` 分离)。 - -## MTR Per-Hop 调度器关键设计(当前) - -- **多 in-flight 探测**:每 TTL 允许最多 `MaxInFlightPerHop`(默认 3)个并发探测。 - - `mtrHopState.inFlightCount` 是计数器(非 bool)。 - - 这解决了高丢包 hop 因超时阻塞导致 Snt 积累速率远低于低丢包 hop 的问题。 -- **nextAt 基于发送时间**:`launchProbe` 时设 `nextAt = now + hopInterval`。 - - 不再等探测完成才设 nextAt,调度器可在超时探测还在飞行中时为同一 TTL 发射新探测。 - - 这保证了所有 TTL 的 Snt 积累速率大致相同,不受丢包率影响。 -- **全局并发限制**:`inFlight`(全局计数器)< `parallelism` 仍然有效。 -- **`MaxInFlightPerHop` 配置**:`mtrSchedulerConfig.MaxInFlightPerHop`,默认动态计算。 - - 动态默认 = `ceil(Timeout / HopInterval) + 1`(至少 1)。 - - 例:`Timeout=2s, HopInterval=1s` → 默认 3;`Timeout=2s, HopInterval=200ms` → 默认 11。 - - 用户显式设置 > 0 时优先使用用户值。 - -## MTR 引擎关键机制(易踩坑) - -- 目的地提前停止: - - `knownFinalTTL`(持久缓存)用于缩短后续探测的 TTL 上界;高 TTL 标记 disabled 后不再调度。 -- seq 16 位回卷处理: - - `seqWillWrap(...)` 触发 `rotateEngine(...)` - - 轮换 echoID 并重建 listener,协议层隔离新旧回包。 -- 额外安全网: - - onICMP 中有 RTT 合理性检查(`<=0` 或 `>timeout` 丢弃)。 -- 流式预览: - - 仅已发送 TTL 才会参与预览;未发送 TTL 保持 nil 槽位,避免提前计入 Snt/Loss。 - -## Web Console / WebSocket(server/) - -### WS 架构(`server/ws_handler.go`,~451 行) - -- **异步写模型**:`wsTraceSession` 使用 `sendCh`(buffered channel,1024)+ `writeLoop` goroutine。 - - 调用方通过 `send(envelope)` 非阻塞投递;channel 满时返回 `errWSSlowConsumer`。 - - `writeLoop` 从 `sendCh` 取消息,`SetWriteDeadline` + `WriteJSON`。 -- **关闭路径**: - - `closeWithCode(code, reason)`:异常关闭(slow consumer / write error),关 `stopCh` + 发 close frame。 - - `finish()`:正常结束,`sendMu` 下关 `sendCh`,等 `writerDone`,再关 conn。 - - 两者均幂等(`closeOnce` / `finishOnce`)。 -- **可测试性**:`wsConn` 接口 + `fakeWSConn` mock(`server/ws_handler_test.go`)。 -- **常量**:`wsSendQueueSize=1024`,`wsWriteTimeout=5s`。 - -### Web MTR 调度模式(重要变更) - -- **已从 round-based 迁移到 per-hop 调度**。 -- `runMTRTrace()`: - - 优先读 `HopIntervalMs`,fallback `IntervalMs`,再缺省 1000ms。 - - `MaxRounds` → `MaxPerHop`(0 = 无限运行直到客户端断开)。 - - 不再使用 legacy round-based 的 `Interval` / `RunRound`。 -- `executeMTRRaw()` 两路分支: - - `HopInterval > 0`:per-hop 模式,**短暂加锁** `setupTraceGlobals` 后立即释放 `traceMu`,不阻塞其他请求。 - - fallback:legacy round-based 模式(保留兼容),`RunRound` 回调内 per-round 锁定。 -- `setupTraceGlobals(setup)` / `restoreTraceGlobals(setup)`:统一全局变量设置逻辑,`executeTrace` 也已复用。 -- `traceRequest` 新增 `HopIntervalMs` 字段(`json:"hop_interval_ms"`),与 `IntervalMs` 解耦。 -- 前端(`app.js`、`mtr_agg.js`)无需改动——已有客户端聚合,与调度模型无关。 - -### 前端渲染节流(`server/web/assets/app.js`) - -- MTR raw 消息通过 `scheduleMTRRender()` 节流,最小间隔 100ms,优先 `requestAnimationFrame`。 -- `cancelScheduledMTRRender()` 在 `clearResult`、socket close/error 路径调用,避免孤儿回调。 -- `flushMTRRender()` 立即执行挂起渲染。 - -### 其他 server 文件 - -- `server/server.go`:Gin 路由注册 -- `server/handlers.go`:REST 接口 -- `server/mtr.go`:MTR 专用 handler 逻辑 -- `server/trace_handler.go`:traceroute handler -- `server/cache_handler.go`:缓存 - -## DoT 与 Geo DNS - -- `--dot-server` 不仅影响目标域名解析,也影响 GeoIP API / LeoMoe FastIP 的域名解析链路。 -- 关键文件:`util/dns_resolver.go` - - `SetGeoDNSResolver(dotServer)` - - `LookupHostForGeo(ctx, host)`:IP 字面量短路 -> DoT -> 失败时按配置 fallback 系统 DNS -- `cmd/cmd.go` 在早期阶段(fast-trace / ws 初始化之前)注入 DoT 解析策略,避免早期分支绕过。 -- Geo HTTP 请求统一走 `util.NewGeoHTTPClient(...)`(`util/http_client_geo.go`)。 - -## LeoMoe FastIP 与 MTR 首行 - -- `util/latency.go`: - - `FastIPMetaCache` 缓存节点元数据(IP/Latency/NodeName) - - `SuppressFastIPOutput` 可抑制彩色横幅 -- MTR 模式在进入 TUI 前会设 `SuppressFastIPOutput=true`,避免污染主终端历史。 -- MTR TUI/report 首行 `APIInfo` 由 `cmd/mtr_mode.go` 的 `buildAPIInfo(...)` 生成(仅 LeoMoeAPI 且有元数据时显示)。 -- MTR raw 首行由 `buildRawAPIInfoLine(...)` 生成(格式略不同,包含延迟信息)。 - -## `--source` / `--dev` 现状 - -- `--dev` 在 `cmd/cmd.go` 先解析网卡并推导 `srcAddr`(已处理非 `*net.IPNet` 地址类型,避免 panic)。 -- MTR 标题显示源信息来自: - - `--source`(最高优先) - - `--dev` 推导 - - UDP dial fallback -- 相关函数:`cmd/mtr_mode.go -> resolveSrcIP(...)` - -## CI 与工具链(当前) - -- `go.mod`: `go 1.26.0` -- GitHub Actions: - - `.github/workflows/build.yml` 使用 `setup-go@v6` + `go-version: 1.26.x` - - `.github/workflows/test.yml` 使用 `setup-go@v6` + `go-version: 1.26.x` - - test workflow 中 `GOTOOLCHAIN=go1.26.0+auto` - - build matrix 已移除 `windows/arm` - -## 关键文件导航 - -- CLI 主调度:`cmd/cmd.go`(~855 行) -- MTR 参数/流程:`cmd/mtr_mode.go`(~315 行) -- MTR 交互输入:`cmd/mtr_ui.go` -- MTR 引擎:`trace/mtr_runner.go` -- MTR 聚合:`trace/mtr_stats.go` -- MTR TUI:`printer/mtr_tui.go`(~691 行) -- MTR table/report:`printer/mtr_table.go`(~625 行) -- MTR TUI 颜色:`printer/mtr_tui_color.go` -- WS handler:`server/ws_handler.go`(~449 行) -- 前端:`server/web/assets/app.js` -- Geo DoT 解析:`util/dns_resolver.go` -- Geo HTTP 客户端:`util/http_client_geo.go` -- FastIP:`util/latency.go` - -## 仍需记住的残余风险(非阻断) - -- `closeWithCode` 中 `closed.Store(true)` 在 `closeOnce.Do` 外部,理论上有微小竞态窗口(实际无害,因 `sendMu` 保护;且无法简单移入 Once 内部,否则第二个调用者无法设置 closed)。 +每次执行命令前均需阅读项目根目录下的 ./CLAUDE.md 文件 \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md index 2a055b2..28d0064 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,10 +80,12 @@ - `runMTRTUI(...)` / `runMTRReport(...)` / `runMTRRaw(...)` - `normalizeMTRTraceConfig(conf)` / `normalizeMTRReportConfig(conf, wide)` - `buildAPIInfo(...)` / `buildRawAPIInfoLine(...)` + - MTR CLI 现在统一使用 `signal.NotifyContext(...)` 管理 Ctrl-C / SIGTERM;不再保留额外的 `sigCh` + goroutine 等待器。 - 交互控制:`cmd/mtr_ui.go` - alternate screen + raw mode - 输入状态机 `mtrInputParser`(字节流,吞掉 CSI/SS3/OSC/鼠标/焦点等序列) - Enter/Leave 显式关闭输入扩展模式:1000/1002/1003/1006/1015/1004/2004 + - Quit 路径会先判空 `cancel`,因此 `newMTRUI(nil, ...)` / 测试注入 nil 不会 panic。 - 核心探测循环:`trace/mtr_runner.go` - `RunMTR` / `mtrLoop` / `RunMTRRaw` - 支持暂停、重置、流式预览(`ProgressThrottle` 默认 200ms) @@ -199,6 +201,7 @@ - `trace/runMTRRawRoundBased()` 也会先做 `normalizeRuntimeConfig(&cfg)`,因此 legacy raw 路径同样能继承 `SourceDevice`;`DisableMPLS` 不再从全局反向覆盖会话配置。 - `traceRequest` 新增 `HopIntervalMs` 字段(`json:"hop_interval_ms"`),与 `IntervalMs` 解耦。 - 前端 MTR 请求现在发送 `hop_interval_ms=1000`,不再把旧的 `interval_ms=2000` 当默认值。 +- 前端 raw 聚合键现在按 TTL 折叠,避免同一 hop 的 timeout / success 被拆成两行。 ### 前端渲染节流(`server/web/assets/app.js`) @@ -220,16 +223,18 @@ - 关键文件:`util/dns_resolver.go` - `SetGeoDNSResolver(dotServer)` - `WithGeoDNSResolver(dotServer, fn)`:为 Web/API 请求提供作用域化的 resolver 切换;不同 resolver 串行切换,相同 resolver 允许安全嵌套,避免 `GetSourceWithGeoDNS` + 外层作用域组合时死锁。 + - `geoResolverOverride` 的读写现在也走 `geoMu`,避免测试覆盖 resolver 时的数据竞争。 - `LookupHostForGeo(ctx, host)`:IP 字面量短路 -> DoT -> 失败时按配置 fallback 系统 DNS - `cmd/cmd.go` 在早期阶段(fast-trace / ws 初始化之前)注入 DoT 解析策略,避免早期分支绕过。 - `server/trace_handler.go` 通过 `ipgeo.GetSourceWithGeoDNS(...)` + `WithGeoDNSResolver(...)` 让 Web/API 请求也遵守 `dot_server`,包括 LeoMoe/FastIP 初始化阶段。 -- Geo HTTP 请求统一走 `util.NewGeoHTTPClient(...)`(`util/http_client_geo.go`)。 +- Geo HTTP 请求统一走 `util.NewGeoHTTPClient(...)`(`util/http_client_geo.go`),其 Transport 现在从默认 Transport `Clone()` 而来,保留代理/HTTP2/连接池等标准行为。 ## LeoMoe FastIP 与 MTR 首行 - `util/latency.go`: - `FastIPMetaCache` 缓存节点元数据(IP/Latency/NodeName) - `SuppressFastIPOutput` 可抑制彩色横幅 +- `GetFastIP(...)` 的 DNS 阶段现在显式受 `timeout` 限制;`FastIPMetaCache` 也改为在 fallback/default IP 决定后再写入,避免缓存空 IP。 - MTR 模式在进入 TUI 前会设 `SuppressFastIPOutput=true`,避免污染主终端历史。 - MTR TUI/report 首行 `APIInfo` 由 `cmd/mtr_mode.go` 的 `buildAPIInfo(...)` 生成(仅 LeoMoeAPI 且有元数据时显示)。 - MTR raw 首行由 `buildRawAPIInfoLine(...)` 生成(格式略不同,包含延迟信息)。 @@ -238,6 +243,7 @@ - `--dev` 在 `cmd/cmd.go` 先解析网卡并推导 `srcAddr`(已处理非 `*net.IPNet` 地址类型,避免 panic)。 - `trace.Config` 现在显式携带 `SourceDevice` / `DisableMPLS`,Darwin TCP/UDP 抓包与 MPLS 解析优先走会话级配置,不再依赖 Web 侧临时改写全局变量。 +- `trace.Config` 也显式携带 `Context`;`TracerouteWithContext(...)` 通过把上游 ctx 传入各 tracer 的 `signal.NotifyContext(...)` 基底,让 TCP/UDP fallback MTR 可以响应取消。 - Windows TCP 目前仍无法把 `SourceDevice` 映射到 WinDivert 接口选择;当前策略是显式报错拒绝,而不是静默忽略该字段。 - MTR 标题显示源信息来自: - `--source`(最高优先) @@ -254,6 +260,7 @@ - test workflow 中 `GOTOOLCHAIN=go1.26.0+auto` - build matrix 已移除 `windows/arm` - `.cross_compile.sh` 与 workflow 里的 `go build` 现在都用数组构造 `-tags` 参数,避免 shell word-splitting;脚本也会把当前 `GOARM` 传给 `compress_with_upx`,使 linux/armv7 目标能命中对应压缩分支。 +- `ipgeo/ipdbone.go` 不再原地修改全局 `defaultClient.httpClient.Timeout`;超时覆盖会通过克隆 client(复用 token cache / token init,同步替换整个 HTTP client)实现,避免 dial timeout 与 client timeout 脱节。 ## 关键文件导航 diff --git a/cmd/mtr_mode.go b/cmd/mtr_mode.go index fc989b2..6c053f4 100644 --- a/cmd/mtr_mode.go +++ b/cmd/mtr_mode.go @@ -54,17 +54,11 @@ func runMTRTUI(method trace.Method, conf trace.Config, hopIntervalMs int, maxPer } // Ctrl-C 优雅退出 - ctx, cancel := context.WithCancel(context.Background()) + sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + ctx, cancel := context.WithCancel(sigCtx) defer cancel() - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) - defer signal.Stop(sigCh) - go func() { - <-sigCh - cancel() - }() - // 初始化 TUI 控制器 ui := newMTRUI(cancel, initialDisplayMode) ui.Enter() @@ -114,7 +108,6 @@ func runMTRTUI(method trace.Method, conf trace.Config, hopIntervalMs int, maxPer err := trace.RunMTR(ctx, method, roundConf, opts, onSnapshot) if err != nil && !errors.Is(err, context.Canceled) { // 离开备用屏幕后再打印错误 - ui.Leave() fmt.Println(err) } } @@ -129,16 +122,8 @@ func runMTRReport(method trace.Method, conf trace.Config, hopIntervalMs int, max maxPerHop = 10 } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) - defer signal.Stop(sigCh) - go func() { - <-sigCh - cancel() - }() + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() startTime := time.Now() @@ -192,16 +177,8 @@ func runMTRRaw(method trace.Method, conf trace.Config, hopIntervalMs int, maxPer hopIntervalMs = 1000 } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) - defer signal.Stop(sigCh) - go func() { - <-sigCh - cancel() - }() + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() opts := trace.MTRRawOptions{ HopInterval: time.Duration(hopIntervalMs) * time.Millisecond, diff --git a/cmd/mtr_ui.go b/cmd/mtr_ui.go index 51a8b03..97ce72e 100644 --- a/cmd/mtr_ui.go +++ b/cmd/mtr_ui.go @@ -352,7 +352,9 @@ func (u *mtrUI) ReadKeysLoop(ctx context.Context) { action := parser.Feed(buf[i]) switch action { case mtrActionQuit: - u.cancel() + if u.cancel != nil { + u.cancel() + } return case mtrActionPause: atomic.StoreInt32(&u.paused, 1) diff --git a/ipgeo/ipdbone.go b/ipgeo/ipdbone.go index 946f95a..dc8eecb 100644 --- a/ipgeo/ipdbone.go +++ b/ipgeo/ipdbone.go @@ -68,7 +68,7 @@ func (c *IPDBOneTokenCache) SetToken(token string, expiresIn time.Duration) { type IPDBOneClient struct { config *IPDBOneConfig tokenCache *IPDBOneTokenCache - tokenInit sync.Once + tokenInit *sync.Once httpClient *http.Client } @@ -77,10 +77,23 @@ func NewIPDBOneClient() *IPDBOneClient { return &IPDBOneClient{ config: GetDefaultConfig(), tokenCache: &IPDBOneTokenCache{}, + tokenInit: &sync.Once{}, httpClient: util.NewGeoHTTPClient(3 * time.Second), } } +func (c *IPDBOneClient) cloneWithTimeout(timeout time.Duration) *IPDBOneClient { + if c == nil || timeout <= 0 { + return c + } + return &IPDBOneClient{ + config: c.config, + tokenCache: c.tokenCache, + tokenInit: c.tokenInit, + httpClient: util.NewGeoHTTPClient(timeout), + } +} + // fetchToken requests a new authentication token from the API func (c *IPDBOneClient) fetchToken() error { authURL := c.config.BaseURL + "/auth/requestToken/query" @@ -255,10 +268,9 @@ var defaultClient = NewIPDBOneClient() // IPDBOne looks up IP information from IPDB.One (maintains backward compatibility) func IPDBOne(ip string, timeout time.Duration, lang string, _ bool) (*IPGeoData, error) { - // Override timeout if specified + client := defaultClient if timeout > 0 { - defaultClient.httpClient.Timeout = timeout + client = defaultClient.cloneWithTimeout(timeout) } - - return defaultClient.LookupIP(ip, lang) + return client.LookupIP(ip, lang) } diff --git a/server/web/assets/app.js b/server/web/assets/app.js index 2f9544a..ee81609 100644 --- a/server/web/assets/app.js +++ b/server/web/assets/app.js @@ -1071,15 +1071,7 @@ function stopTrace() { function mtrRawKey(rec) { const ttl = Number(rec && rec.ttl); - const ip = rec && rec.ip ? String(rec.ip).trim() : ''; - const host = rec && rec.host ? String(rec.host).trim().toLowerCase() : ''; - if (ip) { - return `${ttl}|ip:${ip}`; - } - if (host) { - return `${ttl}|host:${host}`; - } - return `${ttl}|unknown`; + return `${ttl}|ttl`; } function onlyTimeoutErrors(errors) { diff --git a/trace/icmp_ipv4.go b/trace/icmp_ipv4.go index f43f157..b130abe 100644 --- a/trace/icmp_ipv4.go +++ b/trace/icmp_ipv4.go @@ -284,7 +284,11 @@ func (t *ICMPTracer) Execute() (res *Result, err error) { s.InitICMP() defer s.Close() - sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + baseCtx := t.Context + if baseCtx == nil { + baseCtx = context.Background() + } + sigCtx, stop := signal.NotifyContext(baseCtx, os.Interrupt, syscall.SIGTERM) ctx, cancel := context.WithCancelCause(sigCtx) t.final.Store(-1) diff --git a/trace/icmp_ipv6.go b/trace/icmp_ipv6.go index 5018b8f..320dc6a 100644 --- a/trace/icmp_ipv6.go +++ b/trace/icmp_ipv6.go @@ -284,7 +284,11 @@ func (t *ICMPTracerv6) Execute() (res *Result, err error) { s.InitICMP() defer s.Close() - sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + baseCtx := t.Context + if baseCtx == nil { + baseCtx = context.Background() + } + sigCtx, stop := signal.NotifyContext(baseCtx, os.Interrupt, syscall.SIGTERM) ctx, cancel := context.WithCancelCause(sigCtx) t.final.Store(-1) diff --git a/trace/mtr_raw.go b/trace/mtr_raw.go index e5cc46c..3a01c97 100644 --- a/trace/mtr_raw.go +++ b/trace/mtr_raw.go @@ -96,6 +96,7 @@ func runMTRRawPerHop(ctx context.Context, method Method, cfg Config, opts MTRRaw } defer engine.close() if err := engine.start(ctx); err != nil { + engine.close() return fmt.Errorf("mtr raw: %w", err) } prober = engine diff --git a/trace/mtr_raw_test.go b/trace/mtr_raw_test.go index fd1af56..e301565 100644 --- a/trace/mtr_raw_test.go +++ b/trace/mtr_raw_test.go @@ -92,7 +92,8 @@ func TestRunMTRRaw_RespectsMaxRoundsAndInterval(t *testing.T) { if calls != 3 { t.Fatalf("traceroute call count = %d, want 3", calls) } - if time.Since(start) < 35*time.Millisecond { + // Three rounds wait twice at 20ms each; allow a small scheduler tolerance below 40ms. + if time.Since(start) < 38*time.Millisecond { t.Fatalf("interval appears not applied, elapsed=%v", time.Since(start)) } } diff --git a/trace/mtr_runner.go b/trace/mtr_runner.go index 538c5a7..f7eb619 100644 --- a/trace/mtr_runner.go +++ b/trace/mtr_runner.go @@ -121,6 +121,7 @@ func runMTRPerHop(ctx context.Context, method Method, baseConfig Config, opts MT } defer engine.close() if err := engine.start(ctx); err != nil { + engine.close() return fmt.Errorf("mtr: %w", err) } prober = engine @@ -180,6 +181,7 @@ func runMTRRoundBased(ctx context.Context, method Method, baseConfig Config, opt } defer engine.close() if err := engine.start(ctx); err != nil { + engine.close() return fmt.Errorf("mtr: %w", err) } return mtrLoop(ctx, engine, baseConfig, opts, agg, onSnapshot, true, nil) @@ -474,8 +476,10 @@ func (e *mtrICMPEngine) start(ctx context.Context) error { select { case <-ready: case <-ctx.Done(): + e.close() return ctx.Err() case <-time.After(5 * time.Second): + e.close() return fmt.Errorf("ICMP listener startup timeout") } time.Sleep(100 * time.Millisecond) @@ -580,8 +584,10 @@ func (e *mtrICMPEngine) rotateEngine(ctx context.Context) error { select { case <-ready: case <-ctx.Done(): + e.close() return ctx.Err() case <-time.After(5 * time.Second): + e.close() return fmt.Errorf("ICMP listener restart timeout on echoID rotation") } return nil @@ -867,8 +873,8 @@ type mtrFallbackProber struct { config Config } -func (p *mtrFallbackProber) probeRound(_ context.Context) (*Result, error) { - return Traceroute(p.method, p.config) +func (p *mtrFallbackProber) probeRound(ctx context.Context) (*Result, error) { + return TracerouteWithContext(ctx, p.method, p.config) } func (p *mtrFallbackProber) close() {} @@ -987,7 +993,7 @@ type mtrFallbackTTLProber struct { config Config } -func (p *mtrFallbackTTLProber) ProbeTTL(_ context.Context, ttl int) (mtrProbeResult, error) { +func (p *mtrFallbackTTLProber) ProbeTTL(ctx context.Context, ttl int) (mtrProbeResult, error) { cfg := p.config cfg.BeginHop = ttl cfg.MaxHops = ttl @@ -997,7 +1003,7 @@ func (p *mtrFallbackTTLProber) ProbeTTL(_ context.Context, ttl int) (mtrProbeRes cfg.RealtimePrinter = nil cfg.AsyncPrinter = nil - res, err := Traceroute(p.method, cfg) + res, err := TracerouteWithContext(ctx, p.method, cfg) if err != nil { return mtrProbeResult{TTL: ttl}, err } diff --git a/trace/mtr_scheduler.go b/trace/mtr_scheduler.go index 7b77c13..9e461e1 100644 --- a/trace/mtr_scheduler.go +++ b/trace/mtr_scheduler.go @@ -375,7 +375,7 @@ func runMTRScheduler( return false } } - return true + return inFlight == 0 } handleReset := func() { diff --git a/trace/mtr_scheduler_test.go b/trace/mtr_scheduler_test.go index 32eaee1..d62e2d0 100644 --- a/trace/mtr_scheduler_test.go +++ b/trace/mtr_scheduler_test.go @@ -72,7 +72,7 @@ func TestScheduler_MaxPerHopCompletion(t *testing.T) { return mtrProbeResult{ TTL: ttl, Success: true, - Addr: &net.IPAddr{IP: net.ParseIP("10.0.0." + string(rune('0'+ttl)))}, + Addr: &net.IPAddr{IP: net.ParseIP(fmt.Sprintf("10.0.0.%d", ttl))}, RTT: time.Duration(ttl) * time.Millisecond, }, nil }, diff --git a/trace/mtr_stats.go b/trace/mtr_stats.go index 38b3804..8544729 100644 --- a/trace/mtr_stats.go +++ b/trace/mtr_stats.go @@ -74,6 +74,10 @@ func NewMTRAggregator() *MTRAggregator { // Update 接收一轮 traceroute 的 Result 并更新统计,返回当前快照。 func (agg *MTRAggregator) Update(res *Result, queries int) []MTRHopStat { + if res == nil || len(res.Hops) == 0 { + return nil + } + agg.mu.Lock() defer agg.mu.Unlock() diff --git a/trace/mtr_stats_test.go b/trace/mtr_stats_test.go index 1d3b0d0..0718ed0 100644 --- a/trace/mtr_stats_test.go +++ b/trace/mtr_stats_test.go @@ -225,6 +225,16 @@ func TestAllTimeout(t *testing.T) { } } +func TestUpdate_NilResult(t *testing.T) { + agg := NewMTRAggregator() + if got := agg.Update(nil, 1); got != nil { + t.Fatalf("Update(nil, 1) = %v, want nil", got) + } + if got := agg.Update(&Result{}, 1); got != nil { + t.Fatalf("Update(empty result, 1) = %v, want nil", got) + } +} + func TestHostnamePropagation(t *testing.T) { agg := NewMTRAggregator() hop := mkHop(1, "1.1.1.1", 10*time.Millisecond) diff --git a/trace/tcp_ipv4.go b/trace/tcp_ipv4.go index 19464e7..6848bc4 100644 --- a/trace/tcp_ipv4.go +++ b/trace/tcp_ipv4.go @@ -277,7 +277,11 @@ func (t *TCPTracer) Execute() (res *Result, err error) { s.InitTCP() defer s.Close() - sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + baseCtx := t.Context + if baseCtx == nil { + baseCtx = context.Background() + } + sigCtx, stop := signal.NotifyContext(baseCtx, os.Interrupt, syscall.SIGTERM) ctx, cancel := context.WithCancelCause(sigCtx) t.final.Store(-1) diff --git a/trace/tcp_ipv6.go b/trace/tcp_ipv6.go index 7375a8a..311aa07 100644 --- a/trace/tcp_ipv6.go +++ b/trace/tcp_ipv6.go @@ -277,7 +277,11 @@ func (t *TCPTracerIPv6) Execute() (res *Result, err error) { s.InitTCP() defer s.Close() - sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + baseCtx := t.Context + if baseCtx == nil { + baseCtx = context.Background() + } + sigCtx, stop := signal.NotifyContext(baseCtx, os.Interrupt, syscall.SIGTERM) ctx, cancel := context.WithCancelCause(sigCtx) t.final.Store(-1) diff --git a/trace/trace.go b/trace/trace.go index c7c7963..47c34d2 100644 --- a/trace/trace.go +++ b/trace/trace.go @@ -30,6 +30,7 @@ var ( ) type Config struct { + Context context.Context OSType int ICMPMode int SrcAddr string @@ -103,6 +104,9 @@ func Traceroute(method Method, config Config) (*Result, error) { if config.MaxHops == 0 { config.MaxHops = 30 } + if config.PktSize < 0 { + config.PktSize = 0 + } if config.NumMeasurements == 0 { config.NumMeasurements = 3 @@ -187,6 +191,14 @@ func Traceroute(method Method, config Config) (*Result, error) { return result, err } +func TracerouteWithContext(ctx context.Context, method Method, config Config) (*Result, error) { + if ctx == nil { + ctx = context.Background() + } + config.Context = ctx + return Traceroute(method, config) +} + func normalizeRuntimeConfig(config *Config) { if config == nil { return @@ -194,6 +206,9 @@ func normalizeRuntimeConfig(config *Config) { if config.SourceDevice == "" && util.SrcDev != "" { config.SourceDevice = util.SrcDev } + if config.PktSize < 0 { + config.PktSize = 0 + } } type Result struct { diff --git a/trace/udp_ipv4.go b/trace/udp_ipv4.go index 339e1c3..379890b 100644 --- a/trace/udp_ipv4.go +++ b/trace/udp_ipv4.go @@ -324,7 +324,11 @@ func (t *UDPTracer) Execute() (res *Result, err error) { s.InitUDP() defer s.Close() - sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + baseCtx := t.Context + if baseCtx == nil { + baseCtx = context.Background() + } + sigCtx, stop := signal.NotifyContext(baseCtx, os.Interrupt, syscall.SIGTERM) ctx, cancel := context.WithCancelCause(sigCtx) t.final.Store(-1) diff --git a/trace/udp_ipv6.go b/trace/udp_ipv6.go index 13f27b8..30081bc 100644 --- a/trace/udp_ipv6.go +++ b/trace/udp_ipv6.go @@ -276,7 +276,11 @@ func (t *UDPTracerIPv6) Execute() (res *Result, err error) { s.InitUDP() defer s.Close() - sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + baseCtx := t.Context + if baseCtx == nil { + baseCtx = context.Background() + } + sigCtx, stop := signal.NotifyContext(baseCtx, os.Interrupt, syscall.SIGTERM) ctx, cancel := context.WithCancelCause(sigCtx) t.final.Store(-1) diff --git a/util/dns_resolver.go b/util/dns_resolver.go index 3a77657..9bded6c 100644 --- a/util/dns_resolver.go +++ b/util/dns_resolver.go @@ -33,6 +33,18 @@ var ( geoResolverOverride *net.Resolver ) +func setGeoResolverOverride(resolver *net.Resolver) { + geoMu.Lock() + defer geoMu.Unlock() + geoResolverOverride = resolver +} + +func getGeoResolverOverride() *net.Resolver { + geoMu.RLock() + defer geoMu.RUnlock() + return geoResolverOverride +} + // SetGeoDNSResolver 设置 Geo 解析使用的 DoT 服务器名称。 // 空字符串表示仅使用系统 DNS。 func SetGeoDNSResolver(dotServer string) { @@ -148,8 +160,8 @@ func LookupHostForGeo(ctx context.Context, host string) ([]net.IP, error) { // ── 2. DoT 解析 ── r := ResolverForDot(dotServer) - if geoResolverOverride != nil { - r = geoResolverOverride + if override := getGeoResolverOverride(); override != nil { + r = override } if r != nil { ips, err := resolveHost(ctx, r, host) diff --git a/util/dns_resolver_test.go b/util/dns_resolver_test.go index cabca27..f5f3923 100644 --- a/util/dns_resolver_test.go +++ b/util/dns_resolver_test.go @@ -109,9 +109,9 @@ func TestLookupHostForGeo_DoTFailFallback(t *testing.T) { } SetGeoDNSResolver("cloudflare") // 需要非空,ResolverForDot 会被 override 覆盖 SetGeoDNSFallback(true) - geoResolverOverride = badResolver + setGeoResolverOverride(badResolver) defer func() { - geoResolverOverride = nil + setGeoResolverOverride(nil) SetGeoDNSResolver("") SetGeoDNSFallback(true) }() @@ -139,9 +139,9 @@ func TestLookupHostForGeo_DoTFailNoFallback(t *testing.T) { } SetGeoDNSResolver("cloudflare") SetGeoDNSFallback(false) - geoResolverOverride = badResolver + setGeoResolverOverride(badResolver) defer func() { - geoResolverOverride = nil + setGeoResolverOverride(nil) SetGeoDNSResolver("") SetGeoDNSFallback(true) }() diff --git a/util/http_client_geo.go b/util/http_client_geo.go index 3a4a9e2..83768a9 100644 --- a/util/http_client_geo.go +++ b/util/http_client_geo.go @@ -2,7 +2,6 @@ package util import ( "context" - "crypto/tls" "net" "net/http" "time" @@ -18,33 +17,34 @@ func NewGeoHTTPClient(timeout time.Duration) *http.Client { KeepAlive: 30 * time.Second, } - transport := &http.Transport{ - TLSClientConfig: &tls.Config{}, - DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { - host, port, err := net.SplitHostPort(addr) - if err != nil { - // addr 可能不含端口号;原样拨号 - return dialer.DialContext(ctx, network, addr) - } + transport := &http.Transport{} + if base, ok := http.DefaultTransport.(*http.Transport); ok && base != nil { + transport = base.Clone() + } + transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + host, port, err := net.SplitHostPort(addr) + if err != nil { + // addr 可能不含端口号;原样拨号 + return dialer.DialContext(ctx, network, addr) + } - // 用 Geo DNS 策略解析 host - ips, err := LookupHostForGeo(ctx, host) - if err != nil { - return nil, err - } + // 用 Geo DNS 策略解析 host + ips, err := LookupHostForGeo(ctx, host) + if err != nil { + return nil, err + } - // 依次尝试解析到的 IP,优先使用地址族匹配的 - var lastErr error - for _, ip := range ips { - target := net.JoinHostPort(ip.String(), port) - conn, dialErr := dialer.DialContext(ctx, network, target) - if dialErr == nil { - return conn, nil - } - lastErr = dialErr + // 依次尝试解析到的 IP,优先使用地址族匹配的 + var lastErr error + for _, ip := range ips { + target := net.JoinHostPort(ip.String(), port) + conn, dialErr := dialer.DialContext(ctx, network, target) + if dialErr == nil { + return conn, nil } - return nil, lastErr - }, + lastErr = dialErr + } + return nil, lastErr } return &http.Client{ diff --git a/util/latency.go b/util/latency.go index 3a50c4c..61f2f1e 100644 --- a/util/latency.go +++ b/util/latency.go @@ -53,10 +53,12 @@ func GetFastIP(domain string, port string, enableOutput bool) string { var ips []net.IP var err error + lookupCtx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() if domain == "api.nxtrace.org" { - ips, err = LookupHostForGeo(context.Background(), "api.nxtrace.org") + ips, err = LookupHostForGeo(lookupCtx, "api.nxtrace.org") } else { - ips, err = LookupHostForGeo(context.Background(), domain) + ips, err = LookupHostForGeo(lookupCtx, domain) } if err != nil { @@ -77,6 +79,7 @@ func GetFastIP(domain string, port string, enableOutput bool) string { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt) + defer signal.Stop(sigChan) select { case result = <-results: @@ -88,8 +91,11 @@ func GetFastIP(domain string, port string, enableOutput bool) string { os.Exit(0) } - //if len(ips) > 0 { - // 填充结构化缓存 + //有些时候真的啥都不通,还是挑一个顶上吧 + if result.IP == "" { + result.IP = "45.88.195.154" + } + FastIPMetaCache = FastIPMeta{ IP: result.IP, Latency: result.Latency, @@ -104,12 +110,6 @@ func GetFastIP(domain string, port string, enableOutput bool) string { color.New(color.FgGreen, color.Bold).Sprintf("%s", result.Content), ) } - //} - - //有些时候真的啥都不通,还是挑一个顶上吧 - if result.IP == "" { - result.IP = "45.88.195.154" - } FastIpCache = result.IP return result.IP