diff --git a/README.md b/README.md index df29ef7..88b6ab1 100644 --- a/README.md +++ b/README.md @@ -368,9 +368,12 @@ export NEXTTRACE_ENABLEHIDDENDSTIP=1 # Turn off the IP reverse parsing function nexttrace --no-rdns www.bbix.net -# Set the payload size to 1024 bytes +# Set the probe packet size to 1024 bytes (inclusive IP + probe headers) nexttrace --psize 1024 example.com +# Set the TOS / traffic class field +nexttrace -Q 46 example.com + # Feature: print Route-Path diagram # Route-Path diagram example: # AS6453 Tata Communication「Singapore『Singapore』」 @@ -398,7 +401,8 @@ export NO_COLOR=1 | `--send-time` | Gap between packets inside one TTL group | `50ms` | Raise to `100-200ms` on rate-limited devices; ignored in MTR | | `--ttl-time` | Gap between TTL groups in traceroute; per-hop interval in MTR | traceroute: `300ms`; MTR: `1000ms` when omitted | Lower to speed up; raise on remote/rate-limited paths | | `--timeout` | Per-probe timeout | `1000ms` | Raise to `2000-3000ms` for intercontinental or high-loss paths | -| `--psize` | Payload size | `52` bytes | Raise only for MTU or large-packet testing | +| `--psize` | Probe packet size | `52` bytes | Inclusive IP + probe headers; negative values randomize each probe up to `abs(value)` | +| `-Q`, `--tos` | IP TOS / traffic class | `0` | Set DSCP/TOS style marking in the IP header | These probe knobs are CLI-only today; `nt_config.yaml` does not yet store them. If you want reusable profiles, keep them in shell aliases or small wrapper scripts. @@ -736,9 +740,14 @@ Arguments: --timeout Per-probe timeout [ms]. Raise to 2000-3000 on slow intercontinental or high-loss paths. Default: 1000 - --psize Payload size in bytes. Keep 52 for normal - routing checks; raise only for MTU or - large-packet testing. Default: 52 + --psize Probe packet size in bytes, inclusive IP + and active probe headers. Keep 52 for + normal routing checks; raise for MTU or + large-packet testing. Negative values + randomize each probe up to abs(value). + Default: 52 + -Q --tos Set the IP type-of-service / traffic class + value [0-255]. Default: 0 --dot-server Use DoT Server for DNS Parse [dnssb, aliyun, dnspod, google, cloudflare] -g --language Choose the language for displaying [en, diff --git a/README_zh_CN.md b/README_zh_CN.md index 1343806..e3c10c2 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -365,9 +365,12 @@ export NEXTTRACE_ENABLEHIDDENDSTIP=1 # 关闭IP反向解析功能 nexttrace --no-rdns www.bbix.net -# 设置载荷大小为1024字节 +# 设置探测包总大小为1024字节(含 IP + 探测协议头) nexttrace --psize 1024 example.com +# 设置 TOS / traffic class 字段 +nexttrace -Q 46 example.com + # 特色功能:打印Route-Path图 # Route-Path图示例: # AS6453 塔塔通信「Singapore『Singapore』」 @@ -394,7 +397,8 @@ export NO_COLOR=1 | `--send-time` | 同一 TTL 组内相邻探测包间隔 | `50ms` | 设备限速时升到 `100-200ms`;MTR 下忽略 | | `--ttl-time` | 常规 traceroute 的 TTL 组间隔;MTR 的每跳探测间隔 | traceroute: `300ms`;MTR: 未指定时 `1000ms` | 想加速就调低;远程/限速链路调高 | | `--timeout` | 单个探测包超时 | `1000ms` | 跨洲或高丢包链路升到 `2000-3000ms` | -| `--psize` | 载荷大小 | `52` 字节 | 只在 MTU 或大包探测时增大 | +| `--psize` | 探测包大小 | `52` 字节 | 含 IP + 探测协议头;负值表示每个 probe 在 `abs(value)` 内随机 | +| `-Q`, `--tos` | IP TOS / traffic class | `0` | 设置 IP 头里的 TOS / traffic class | 这些探测参数目前仍是 CLI 级配置,`nt_config.yaml` 还不能直接保存它们。若要复用一组调优参数,建议写成 shell alias 或小脚本。 @@ -716,9 +720,14 @@ Arguments: --timeout Per-probe timeout [ms]. Raise to 2000-3000 on slow intercontinental or high-loss paths. Default: 1000 - --psize Payload size in bytes. Keep 52 for normal - routing checks; raise only for MTU or - large-packet testing. Default: 52 + --psize Probe packet size in bytes, inclusive IP + and active probe headers. Keep 52 for + normal routing checks; raise for MTU or + large-packet testing. Negative values + randomize each probe up to abs(value). + Default: 52 + -Q --tos Set the IP type-of-service / traffic class + value [0-255]. Default: 0 --dot-server Use DoT Server for DNS Parse [dnssb, aliyun, dnspod, google, cloudflare] -g --language Choose the language for displaying [en, diff --git a/cmd/cmd.go b/cmd/cmd.go index 3a79eba..9fb5538 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -336,7 +336,11 @@ func buildTimeoutHelp() string { } func buildPayloadSizeHelp() string { - return "Payload size in bytes. Keep 52 for normal routing checks; raise only for MTU or large-packet testing" + return "Probe packet size in bytes, inclusive IP and active probe headers. Keep 52 for normal routing checks; raise for MTU or large-packet testing. Negative values randomize each probe up to abs(value)" +} + +func buildTOSHelp() string { + return "Set the IP type-of-service / traffic class value [0-255]" } func registerTracerouteOutputFlags(parser *argparse.Parser) tracerouteOutputFlags { @@ -481,7 +485,7 @@ func deriveEffectiveMTRModes(mtrMode, reportMode, wideMode, rawPrint bool) effec } } -func detectExplicitProbeFlags(parser *argparse.Parser) (queriesExplicit, ttlTimeExplicit bool) { +func detectExplicitProbeFlags(parser *argparse.Parser) (queriesExplicit, ttlTimeExplicit, packetSizeExplicit, tosExplicit bool) { for _, a := range parser.GetArgs() { if !a.GetParsed() { continue @@ -491,9 +495,13 @@ func detectExplicitProbeFlags(parser *argparse.Parser) (queriesExplicit, ttlTime queriesExplicit = true case "ttl-time": ttlTimeExplicit = true + case "psize": + packetSizeExplicit = true + case "tos": + tosExplicit = true } } - return queriesExplicit, ttlTimeExplicit + return queriesExplicit, ttlTimeExplicit, packetSizeExplicit, tosExplicit } func applyColorMode(noColor bool) { @@ -798,14 +806,6 @@ func applySourceDevice(srcDev string, dstIP net.IP, srcAddr *string) { } } -func normalizeUDPPacketSize(udp bool, ip net.IP, packetSize *int) { - if !udp || !util.IsIPv6(ip) || *packetSize >= 2 { - return - } - fmt.Println("UDPv6 模式下,数据包长度不能小于 2,已自动调整为 2") - *packetSize = 2 -} - func printTraceNav(jsonPrint bool, effectiveMTR bool, ip net.IP, domain, dataOrigin string, maxHops, packetSize int, srcAddr string, method trace.Method) { if !jsonPrint && !effectiveMTR { printer.PrintTraceRouteNav(ip, domain, dataOrigin, maxHops, packetSize, srcAddr, string(method)) @@ -832,6 +832,8 @@ func buildTraceConfig( dataOrigin string, timeout int, packetSize int, + randomPacketSize bool, + tos int, disableMPLS bool, ) trace.Config { return trace.Config{ @@ -856,6 +858,8 @@ func buildTraceConfig( IPGeoSource: ipgeo.GetSource(dataOrigin), Timeout: time.Duration(timeout) * time.Millisecond, PktSize: packetSize, + RandomPacketSize: randomPacketSize, + TOS: tos, DisableMPLS: disableMPLS, } } @@ -1034,6 +1038,7 @@ func Execute() { ttlInterval := registerTTLIntervalFlag(parser) timeout := parser.Int("", "timeout", &argparse.Options{Default: 1000, Help: buildTimeoutHelp()}) packetSize := parser.Int("", "psize", &argparse.Options{Default: 52, Help: buildPayloadSizeHelp()}) + tos := parser.Int("Q", "tos", &argparse.Options{Default: 0, Help: buildTOSHelp()}) dot := parser.Selector("", "dot-server", []string{"dnssb", "aliyun", "dnspod", "google", "cloudflare"}, &argparse.Options{ Help: "Use DoT Server for DNS Parse [dnssb, aliyun, dnspod, google, cloudflare]"}) lang := parser.Selector("g", "language", []string{"en", "cn"}, &argparse.Options{Default: "cn", @@ -1106,18 +1111,31 @@ func Execute() { } } - queriesExplicit, ttlTimeExplicit := detectExplicitProbeFlags(parser) + queriesExplicit, ttlTimeExplicit, packetSizeExplicit, tosExplicit := detectExplicitProbeFlags(parser) applyTTLIntervalDefault(ttlInterval, ttlTimeExplicit, mtrModes.mtr) osType := resolveOSType() if handleStartupModes(*noColor, *jsonPrint, mtrModes, *ver, *deploy, *deployListen, *init, osType) { return } + if *tos < 0 || *tos > 255 { + fmt.Println("--tos 必须在 0-255 之间") + os.Exit(1) + } + applyDefaultPort(port, *udp) clampProbeSettings(*tcp, numMeasurements, maxAttempts) configureGeoDNS(*dot) if *mtuMode { + if packetSizeExplicit { + fmt.Println("--mtu 不支持 --psize") + os.Exit(1) + } + if tosExplicit { + fmt.Println("--mtu 不支持 --tos") + os.Exit(1) + } domain := resolveCLITargetOrExit(*str, sanitizeUsagePositionalArgs(parser.Usage(err))) if domain == "" { return @@ -1170,6 +1188,7 @@ func Execute() { AlwaysWaitRDNS: *alwaysrDNS, Lang: *lang, PktSize: *packetSize, + TOS: *tos, Timeout: time.Duration(*timeout) * time.Millisecond, File: *file, Dot: *dot, @@ -1186,6 +1205,17 @@ func Execute() { leoWs := prepareRuntimeEnvironment(mtrModes, *dn42, dataOrigin, disableMaptrace, powProvider) defer closeLeoWebsocket(leoWs) + if *from != "" { + if packetSizeExplicit { + fmt.Println("Globalping 模式不支持 --psize") + os.Exit(1) + } + if tosExplicit { + fmt.Println("Globalping 模式不支持 --tos") + os.Exit(1) + } + } + if maybeHandleGlobalping( *from, &trace.GlobalpingOptions{ @@ -1224,9 +1254,14 @@ func Execute() { ip := lookupTargetIPOrExit(domain, *ipv4Only, *ipv6Only, *dot, *jsonPrint) applySourceDevice(*srcDev, ip, srcAddr) - normalizeUDPPacketSize(*udp, ip, packetSize) printTraceNav(*jsonPrint, mtrModes.mtr, ip, domain, *dataOrigin, *maxHops, *packetSize, *srcAddr, method) + packetSizeSpec, packetSizeErr := trace.NormalizePacketSize(method, ip, *packetSize) + if packetSizeErr != nil { + fmt.Println(packetSizeErr) + os.Exit(1) + } + util.SrcPort = *srcPort util.DstIP = ip.String() conf := buildTraceConfig( @@ -1249,7 +1284,9 @@ func Execute() { *alwaysrDNS, *dataOrigin, *timeout, - *packetSize, + packetSizeSpec.PayloadSize, + packetSizeSpec.Random, + *tos, *disableMPLS, ) diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index 65f61b0..5acbd4c 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -84,3 +84,45 @@ func TestAdvancedHelpTextMentionsTuningGuidance(t *testing.T) { } } } + +func TestProbeOptionHelpMentionsRandomPacketSizeAndTOS(t *testing.T) { + parser := argparse.NewParser("ntr", "") + parser.Int("", "psize", &argparse.Options{Default: 52, Help: buildPayloadSizeHelp()}) + parser.Int("Q", "tos", &argparse.Options{Default: 0, Help: buildTOSHelp()}) + + usage := parser.Usage(nil) + for _, want := range []string{ + "Negative values randomize each probe", + "type-of-service / traffic class", + } { + if !strings.Contains(usage, want) { + t.Fatalf("usage missing %q:\n%s", want, usage) + } + } +} + +func TestDetectExplicitProbeFlags(t *testing.T) { + parser := argparse.NewParser("ntr", "") + parser.Int("q", "queries", &argparse.Options{Default: 3}) + parser.Int("i", "ttl-time", &argparse.Options{Default: 300}) + parser.Int("", "psize", &argparse.Options{Default: 52}) + parser.Int("Q", "tos", &argparse.Options{Default: 0}) + + if err := parser.Parse([]string{"ntr", "--psize", "-123", "-Q", "46", "-q", "5"}); err != nil { + t.Fatalf("Parse returned error: %v", err) + } + + queriesExplicit, ttlTimeExplicit, packetSizeExplicit, tosExplicit := detectExplicitProbeFlags(parser) + if !queriesExplicit { + t.Fatal("queriesExplicit = false, want true") + } + if ttlTimeExplicit { + t.Fatal("ttlTimeExplicit = true, want false") + } + if !packetSizeExplicit { + t.Fatal("packetSizeExplicit = false, want true") + } + if !tosExplicit { + t.Fatal("tosExplicit = false, want true") + } +} diff --git a/fast_trace/fast_trace ipv6.go b/fast_trace/fast_trace ipv6.go index 01bae3b..6c2c722 100644 --- a/fast_trace/fast_trace ipv6.go +++ b/fast_trace/fast_trace ipv6.go @@ -21,13 +21,17 @@ import ( func (f *FastTracer) tracert_v6(location string, ispCollection ISPCollection) { fmt.Fprintf(color.Output, "%s\n", color.New(color.FgYellow, color.Bold).Sprintf("『%s %s 』", location, ispCollection.ISPName)) - fmt.Printf("traceroute to %s, %d hops max, %d byte packets, %s mode\n", ispCollection.IPv6, f.ParamsFastTrace.MaxHops, f.ParamsFastTrace.PktSize, strings.ToUpper(string(f.TracerouteMethod))) + fmt.Printf("traceroute to %s, %d hops max, %s, %s mode\n", ispCollection.IPv6, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(f.ParamsFastTrace.PktSize), strings.ToUpper(string(f.TracerouteMethod))) // ip, err := util.DomainLookUp(ispCollection.IPv6, "6", "", true) ip, err := util.DomainLookUp(ispCollection.IPv6, "6", f.ParamsFastTrace.Dot, true) if err != nil { log.Fatal(err) } + packetSizeSpec, err := trace.NormalizePacketSize(f.TracerouteMethod, ip, f.ParamsFastTrace.PktSize) + if err != nil { + log.Fatal(err) + } var conf = trace.Config{ OSType: f.ParamsFastTrace.OSType, ICMPMode: f.ParamsFastTrace.ICMPMode, @@ -45,7 +49,9 @@ func (f *FastTracer) tracert_v6(location string, ispCollection ISPCollection) { IPGeoSource: ipgeo.GetSource("LeoMoeAPI"), Timeout: f.ParamsFastTrace.Timeout, SrcAddr: f.ParamsFastTrace.SrcAddr, - PktSize: f.ParamsFastTrace.PktSize, + PktSize: packetSizeSpec.PayloadSize, + RandomPacketSize: packetSizeSpec.Random, + TOS: f.ParamsFastTrace.TOS, Lang: f.ParamsFastTrace.Lang, } @@ -63,7 +69,7 @@ func (f *FastTracer) tracert_v6(location string, ispCollection ISPCollection) { log.SetOutput(fp) log.SetFlags(0) log.Printf("『%s %s 』\n", location, ispCollection.ISPName) - log.Printf("traceroute to %s, %d hops max, %d byte packets, %s mode\n", ispCollection.IPv6, f.ParamsFastTrace.MaxHops, f.ParamsFastTrace.PktSize, strings.ToUpper(string(f.TracerouteMethod))) + log.Printf("traceroute to %s, %d hops max, %s, %s mode\n", ispCollection.IPv6, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(f.ParamsFastTrace.PktSize), strings.ToUpper(string(f.TracerouteMethod))) conf.RealtimePrinter = tracelog.RealtimePrinter } else { conf.RealtimePrinter = printer.RealtimePrinter @@ -144,7 +150,6 @@ func FastTestv6(traceMode trace.Method, outEnable bool, paramsFastTrace ParamsFa oe = outEnable choice := readFastTestv6Choice() - normalizeFastTestv6PacketSize(traceMode, ¶msFastTrace) ft := FastTracer{ ParamsFastTrace: paramsFastTrace, TracerouteMethod: fastTestMethod(traceMode), @@ -171,13 +176,6 @@ func readFastTestv6Choice() string { return choice } -func normalizeFastTestv6PacketSize(traceMode trace.Method, paramsFastTrace *ParamsFastTrace) { - if traceMode == trace.UDPTrace && paramsFastTrace.PktSize < 2 { - fmt.Println("UDPv6 模式下,数据包长度不能小于 2,已自动调整为 2") - paramsFastTrace.PktSize = 2 - } -} - func fastTestMethod(traceMode trace.Method) trace.Method { switch traceMode { case trace.ICMPTrace, trace.TCPTrace, trace.UDPTrace: diff --git a/fast_trace/fast_trace.go b/fast_trace/fast_trace.go index 541881b..1c3d2b2 100644 --- a/fast_trace/fast_trace.go +++ b/fast_trace/fast_trace.go @@ -38,6 +38,7 @@ type ParamsFastTrace struct { AlwaysWaitRDNS bool Lang string PktSize int + TOS int Timeout time.Duration File string Dot string @@ -215,15 +216,20 @@ func printFileTraceHeader(ip IpListElement, params ParamsFastTrace, tracerouteMe if util.EnableHidDstIP { dst = util.HideIPPart(ip.Ip) } - fmt.Printf("traceroute to %s, %d hops max, %d bytes payload, %s mode\n", dst, params.MaxHops, params.PktSize, strings.ToUpper(string(tracerouteMethod))) + fmt.Printf("traceroute to %s, %d hops max, %s, %s mode\n", dst, params.MaxHops, trace.FormatPacketSizeLabel(params.PktSize), strings.ToUpper(string(tracerouteMethod))) } func buildFileTraceConfig(params ParamsFastTrace, tracerouteMethod trace.Method, ip IpListElement) trace.Config { + dstIP := net.ParseIP(ip.Ip) + packetSizeSpec, err := trace.NormalizePacketSize(tracerouteMethod, dstIP, params.PktSize) + if err != nil { + log.Fatal(err) + } return trace.Config{ OSType: params.OSType, ICMPMode: params.ICMPMode, BeginHop: params.BeginHop, - DstIP: net.ParseIP(ip.Ip), + DstIP: dstIP, DstPort: params.DstPort, MaxHops: params.MaxHops, NumMeasurements: 3, @@ -235,7 +241,9 @@ func buildFileTraceConfig(params ParamsFastTrace, tracerouteMethod trace.Method, IPGeoSource: ipgeo.GetSource("LeoMoeAPI"), Timeout: params.Timeout, SrcAddr: resolveFastTraceSourceAddr(params.SrcDev, ip.Version4), - PktSize: params.PktSize, + PktSize: packetSizeSpec.PayloadSize, + RandomPacketSize: packetSizeSpec.Random, + TOS: params.TOS, Lang: params.Lang, } } @@ -264,7 +272,7 @@ func runFileTraceTarget(params ParamsFastTrace, tracerouteMethod trace.Method, i printFileTraceHeader(ip, params, tracerouteMethod) conf := buildFileTraceConfig(params, tracerouteMethod, ip) - header := fmt.Sprintf("『%s』\ntraceroute to %s, %d hops max, %d byte packets, %s mode\n", ip.Desc, ip.Ip, params.MaxHops, params.PktSize, strings.ToUpper(string(tracerouteMethod))) + header := fmt.Sprintf("『%s』\ntraceroute to %s, %d hops max, %s, %s mode\n", ip.Desc, ip.Ip, params.MaxHops, trace.FormatPacketSizeLabel(params.PktSize), strings.ToUpper(string(tracerouteMethod))) if err := configureFastTraceRealtimePrinter(&conf, header); err != nil { return } @@ -277,13 +285,17 @@ func runFileTraceTarget(params ParamsFastTrace, tracerouteMethod trace.Method, i func (f *FastTracer) tracert(location string, ispCollection ISPCollection) { fmt.Fprintf(color.Output, "%s\n", color.New(color.FgYellow, color.Bold).Sprintf("『%s %s 』", location, ispCollection.ISPName)) - fmt.Printf("traceroute to %s, %d hops max, %d byte packets, %s mode\n", ispCollection.IP, f.ParamsFastTrace.MaxHops, f.ParamsFastTrace.PktSize, strings.ToUpper(string(f.TracerouteMethod))) + fmt.Printf("traceroute to %s, %d hops max, %s, %s mode\n", ispCollection.IP, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(f.ParamsFastTrace.PktSize), strings.ToUpper(string(f.TracerouteMethod))) // ip, err := util.DomainLookUp(ispCollection.IP, "4", "", true) ip, err := util.DomainLookUp(ispCollection.IP, "4", f.ParamsFastTrace.Dot, true) if err != nil { log.Fatal(err) } + packetSizeSpec, err := trace.NormalizePacketSize(f.TracerouteMethod, ip, f.ParamsFastTrace.PktSize) + if err != nil { + log.Fatal(err) + } var conf = trace.Config{ OSType: f.ParamsFastTrace.OSType, ICMPMode: f.ParamsFastTrace.ICMPMode, @@ -301,7 +313,9 @@ func (f *FastTracer) tracert(location string, ispCollection ISPCollection) { IPGeoSource: ipgeo.GetSource("LeoMoeAPI"), Timeout: f.ParamsFastTrace.Timeout, SrcAddr: f.ParamsFastTrace.SrcAddr, - PktSize: f.ParamsFastTrace.PktSize, + PktSize: packetSizeSpec.PayloadSize, + RandomPacketSize: packetSizeSpec.Random, + TOS: f.ParamsFastTrace.TOS, Lang: f.ParamsFastTrace.Lang, } @@ -320,7 +334,7 @@ func (f *FastTracer) tracert(location string, ispCollection ISPCollection) { log.SetOutput(fp) log.SetFlags(0) log.Printf("『%s %s 』\n", location, ispCollection.ISPName) - log.Printf("traceroute to %s, %d hops max, %d byte packets, %s mode\n", ispCollection.IP, f.ParamsFastTrace.MaxHops, f.ParamsFastTrace.PktSize, strings.ToUpper(string(f.TracerouteMethod))) + log.Printf("traceroute to %s, %d hops max, %s, %s mode\n", ispCollection.IP, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(f.ParamsFastTrace.PktSize), strings.ToUpper(string(f.TracerouteMethod))) conf.RealtimePrinter = tracelog.RealtimePrinter } else { conf.RealtimePrinter = printer.RealtimePrinter diff --git a/printer/basic.go b/printer/basic.go index 041ae7d..eea91a5 100644 --- a/printer/basic.go +++ b/printer/basic.go @@ -66,12 +66,12 @@ func PrintTraceRouteNav(ip net.IP, domain string, dataOrigin string, maxHops int } if !util.EnableHidDstIP { if ip.String() == domain { - fmt.Printf("%s %s, %d hops max, %d bytes payload, %s mode\n", srcAddr, ip.String(), maxHops, packetSize, strings.ToUpper(mode)) + fmt.Printf("%s %s, %d hops max, %s, %s mode\n", srcAddr, ip.String(), maxHops, trace.FormatPacketSizeLabel(packetSize), strings.ToUpper(mode)) } else { - fmt.Printf("%s %s (%s), %d hops max, %d bytes payload, %s mode\n", srcAddr, ip.String(), domain, maxHops, packetSize, strings.ToUpper(mode)) + fmt.Printf("%s %s (%s), %d hops max, %s, %s mode\n", srcAddr, ip.String(), domain, maxHops, trace.FormatPacketSizeLabel(packetSize), strings.ToUpper(mode)) } } else { - fmt.Printf("%s %s, %d hops max, %d bytes payload, %s mode\n", srcAddr, util.HideIPPart(ip.String()), maxHops, packetSize, strings.ToUpper(mode)) + fmt.Printf("%s %s, %d hops max, %s, %s mode\n", srcAddr, util.HideIPPart(ip.String()), maxHops, trace.FormatPacketSizeLabel(packetSize), strings.ToUpper(mode)) } } diff --git a/server/handlers.go b/server/handlers.go index b63a3ed..d3dd7ae 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -26,6 +26,7 @@ var ( "max_hops": 30, "timeout_ms": 1000, "packet_size": 52, + "tos": 0, "parallel_requests": 18, "begin_hop": 1, "language": "cn", diff --git a/server/trace_handler.go b/server/trace_handler.go index c298bd9..4a2a757 100644 --- a/server/trace_handler.go +++ b/server/trace_handler.go @@ -49,7 +49,8 @@ type traceRequest struct { Queries int `json:"queries"` MaxHops int `json:"max_hops"` TimeoutMs int `json:"timeout_ms"` - PacketSize int `json:"packet_size"` + PacketSize *int `json:"packet_size"` + TOS *int `json:"tos"` ParallelRequests int `json:"parallel_requests"` BeginHop int `json:"begin_hop"` IPv4Only bool `json:"ipv4_only"` @@ -133,6 +134,9 @@ func normalizeTraceRequest(req *traceRequest) (int, error) { if req.MaxRounds < 0 { req.MaxRounds = 0 } + if req.TOS != nil && (*req.TOS < 0 || *req.TOS > 255) { + return http.StatusBadRequest, errors.New("tos must be within range 0-255") + } return 0, nil } @@ -237,7 +241,10 @@ func prepareTrace(req traceRequest) (*traceExecution, int, error) { exec.DataProvider = dataProvider exec.PowProvider = strings.TrimSpace(exec.Req.PowProvider) exec.NeedsLeoWS = needsLeoWS - exec.Config = buildTraceConfig(exec.Req, ip, dataProvider, protocol.dstPort) + exec.Config, err = buildTraceConfig(exec.Req, exec.Method, ip, dataProvider, protocol.dstPort) + if err != nil { + return nil, http.StatusBadRequest, err + } return exec, 0, nil } @@ -316,7 +323,7 @@ func traceHandler(c *gin.Context) { c.JSON(200, response) } -func buildTraceConfig(req traceRequest, ip net.IP, dataProvider string, port int) trace.Config { +func buildTraceConfig(req traceRequest, method trace.Method, ip net.IP, dataProvider string, port int) (trace.Config, error) { lang := strings.TrimSpace(req.Language) if lang == "" { lang = defaults["language"].(string) @@ -327,9 +334,18 @@ func buildTraceConfig(req traceRequest, ip net.IP, dataProvider string, port int timeout = defaults["timeout_ms"].(int) } - packetSize := req.PacketSize - if packetSize <= 0 { - packetSize = defaults["packet_size"].(int) + packetSize := defaults["packet_size"].(int) + if req.PacketSize != nil { + packetSize = *req.PacketSize + } + packetSizeSpec, err := trace.NormalizePacketSize(method, ip, packetSize) + if err != nil { + return trace.Config{}, err + } + + tos := defaults["tos"].(int) + if req.TOS != nil { + tos = *req.TOS } if req.PacketInterval <= 0 { @@ -390,10 +406,12 @@ func buildTraceConfig(req traceRequest, ip net.IP, dataProvider string, port int TTLInterval: req.TTLInterval, Lang: lang, DN42: req.DN42, - PktSize: packetSize, + PktSize: packetSizeSpec.PayloadSize, + RandomPacketSize: packetSizeSpec.Random, + TOS: tos, Maptrace: !req.DisableMaptrace, DisableMPLS: req.DisableMPLS, - } + }, nil } func withTraceSetupContext[T any](setup *traceExecution, callback func() (T, error)) (T, error) { diff --git a/server/trace_handler_test.go b/server/trace_handler_test.go index c25c7d4..2932d11 100644 --- a/server/trace_handler_test.go +++ b/server/trace_handler_test.go @@ -44,11 +44,18 @@ func TestResolveWebMTRHopInterval_PrefersHopIntervalMs(t *testing.T) { } func TestBuildTraceConfig_PropagatesSessionScopedFields(t *testing.T) { - cfg := buildTraceConfig(traceRequest{ + packetSize := 52 + tos := 0 + cfg, err := buildTraceConfig(traceRequest{ SourceDevice: "en7", DisableMPLS: true, DotServer: "cloudflare", - }, net.ParseIP("1.1.1.1"), "IPInfo", 80) + PacketSize: &packetSize, + TOS: &tos, + }, trace.ICMPTrace, net.ParseIP("1.1.1.1"), "IPInfo", 80) + if err != nil { + t.Fatalf("buildTraceConfig returned error: %v", err) + } if cfg.SourceDevice != "en7" { t.Fatalf("buildTraceConfig SourceDevice = %q, want en7", cfg.SourceDevice) @@ -59,6 +66,38 @@ func TestBuildTraceConfig_PropagatesSessionScopedFields(t *testing.T) { if cfg.IPGeoSource == nil { t.Fatal("buildTraceConfig IPGeoSource = nil, want wrapped source") } + if cfg.TOS != 0 { + t.Fatalf("buildTraceConfig TOS = %d, want 0", cfg.TOS) + } +} + +func TestBuildTraceConfig_PreservesNegativePacketSizeAndTOS(t *testing.T) { + packetSize := -123 + tos := 255 + cfg, err := buildTraceConfig(traceRequest{ + PacketSize: &packetSize, + TOS: &tos, + }, trace.ICMPTrace, net.ParseIP("1.1.1.1"), "disable-geoip", 80) + if err != nil { + t.Fatalf("buildTraceConfig returned error: %v", err) + } + if !cfg.RandomPacketSize { + t.Fatal("buildTraceConfig RandomPacketSize = false, want true") + } + if cfg.TOS != 255 { + t.Fatalf("buildTraceConfig TOS = %d, want 255", cfg.TOS) + } +} + +func TestNormalizeTraceRequest_RejectsInvalidTOS(t *testing.T) { + tos := 256 + statusCode, err := normalizeTraceRequest(&traceRequest{TOS: &tos}) + if err == nil { + t.Fatal("normalizeTraceRequest should reject invalid tos") + } + if statusCode != http.StatusBadRequest { + t.Fatalf("statusCode = %d, want %d", statusCode, http.StatusBadRequest) + } } func TestPrepareTrace_RejectsUnknownSourceDevice(t *testing.T) { diff --git a/server/web/assets/app.js b/server/web/assets/app.js index ee81609..31bc22f 100644 --- a/server/web/assets/app.js +++ b/server/web/assets/app.js @@ -7,6 +7,7 @@ const disableMaptraceInput = document.getElementById('disable-maptrace'); const dstPortHint = document.getElementById('dst-port-hint'); const dstPortInput = document.getElementById('dst-port'); const payloadSizeInput = document.getElementById('payload-size'); +const tosInput = document.getElementById('tos'); const modeSelect = document.getElementById('mode'); const statusNode = document.getElementById('status'); const resultNode = document.getElementById('result'); @@ -26,6 +27,7 @@ const labelMaxHops = document.getElementById('label-maxhops'); const labelDisableMap = document.getElementById('label-disable-map'); const labelDstPort = document.getElementById('label-dst-port'); const labelPSize = document.getElementById('label-psize'); +const labelTOS = document.getElementById('label-tos'); const labelMode = document.getElementById('label-mode'); const targetInput = document.getElementById('target'); const groupBasicParams = document.getElementById('group-basic-params'); @@ -52,6 +54,7 @@ let mtrRenderTimer = null; let mtrRenderRAF = null; let mtrRenderLastAt = 0; let mtrRawKnownFinalTTL = Infinity; +const traceFormHelpers = globalThis.NextTraceForm || {}; const uiText = { cn: { @@ -65,7 +68,8 @@ const uiText = { labelMaxHops: '最大跳数', labelDisableMap: '禁用地图生成', labelDstPort: '目的端口', - labelPSize: '负载大小', + labelPSize: '探测包大小', + labelTOS: 'TOS', labelMode: '探测模式', buttonStartSingle: '开始探测', buttonStartMtr: '开始持续探测', @@ -130,7 +134,8 @@ const uiText = { labelMaxHops: 'Max hops', labelDisableMap: 'Disable map generation', labelDstPort: 'Destination Port', - labelPSize: 'Payload Size', + labelPSize: 'Probe Packet Size', + labelTOS: 'TOS', labelMode: 'Mode', buttonStartSingle: 'Start Trace', buttonStartMtr: 'Start Continuous Trace', @@ -227,7 +232,9 @@ async function loadOptions() { queriesInput.dataset.defaultValue = queriesInput.value; maxHopsInput.value = data.defaultOptions.max_hops; disableMaptraceInput.checked = data.defaultOptions.disable_maptrace; - payloadSizeInput.value = data.defaultOptions.packet_size || payloadSizeInput.value || 52; + const defaultOptionValue = traceFormHelpers.defaultOptionValue || ((opts, key, fallback) => (opts && Object.prototype.hasOwnProperty.call(opts, key) ? opts[key] : fallback)); + payloadSizeInput.value = defaultOptionValue(data.defaultOptions, 'packet_size', payloadSizeInput.value || 52); + tosInput.value = defaultOptionValue(data.defaultOptions, 'tos', tosInput.value || 0); dstPortInput.value = data.defaultOptions.port || dstPortInput.value || ''; updateDstPortState(); updateModeUI(); @@ -604,47 +611,23 @@ function createMetaItem(label, value, allowHTML = false) { } function buildPayload() { - const payload = { - target: form.target.value.trim(), + const buildTracePayload = traceFormHelpers.buildTracePayload || ((values) => values); + const payload = buildTracePayload({ + target: form.target.value, protocol: protocolSelect.value, - data_provider: providerSelect.value, - disable_maptrace: disableMaptraceInput.checked, + dataProvider: providerSelect.value, + disableMaptrace: disableMaptraceInput.checked, language: currentLang, mode: modeSelect.value || 'single', - }; - - const isMtrMode = payload.mode === 'mtr'; - if (isMtrMode) { - payload.queries = 10; - if (queriesInput.value !== '10') { - queriesInput.value = '10'; - } - } else { - const queries = readNumericValue(queriesInput); - if (queries !== undefined) { - payload.queries = Math.max(1, Math.min(63, queries)); - } + queries: queriesInput.value, + maxHops: maxHopsInput.value, + dstPort: dstPortInput.value, + packetSize: payloadSizeInput.value, + tos: tosInput.value, + }); + if (payload.mode === 'mtr' && queriesInput.value !== '10') { + queriesInput.value = '10'; } - - const maxHops = readNumericValue(maxHopsInput); - if (maxHops !== undefined) { - payload.max_hops = maxHops; - } - - if (payload.mode === 'mtr') { - payload.hop_interval_ms = 1000; - payload.max_rounds = 0; - } - const dstPort = readNumericValue(dstPortInput); - if (dstPort !== undefined) { - payload.port = dstPort; - } - - const psize = readNumericValue(payloadSizeInput); - if (psize !== undefined) { - payload.packet_size = psize; - } - return payload; } @@ -945,6 +928,7 @@ function applyTranslations() { labelDisableMap.textContent = t('labelDisableMap'); labelDstPort.textContent = t('labelDstPort'); labelPSize.textContent = t('labelPSize'); + labelTOS.textContent = t('labelTOS'); labelMode.textContent = t('labelMode'); dstPortHint.textContent = t('hintDstPort'); targetInput.placeholder = t('placeholderTarget'); diff --git a/server/web/assets/trace_form.js b/server/web/assets/trace_form.js new file mode 100644 index 0000000..f3203d0 --- /dev/null +++ b/server/web/assets/trace_form.js @@ -0,0 +1,74 @@ +(function (root, factory) { + const api = factory(); + if (typeof module !== 'undefined' && module.exports) { + module.exports = api; + } + root.NextTraceForm = api; +})(typeof globalThis !== 'undefined' ? globalThis : this, function () { + function readNumericValueFromRaw(raw) { + const text = String(raw ?? '').trim(); + if (text === '') { + return undefined; + } + const num = Number(text); + return Number.isFinite(num) ? num : undefined; + } + + function defaultOptionValue(defaultOptions, key, fallback) { + if (defaultOptions && Object.prototype.hasOwnProperty.call(defaultOptions, key)) { + return defaultOptions[key]; + } + return fallback; + } + + function buildTracePayload(values) { + const payload = { + target: String(values.target || '').trim(), + protocol: values.protocol, + data_provider: values.dataProvider, + disable_maptrace: Boolean(values.disableMaptrace), + language: values.language, + mode: values.mode || 'single', + }; + + const isMtrMode = payload.mode === 'mtr'; + if (isMtrMode) { + payload.queries = 10; + payload.hop_interval_ms = 1000; + payload.max_rounds = 0; + } else { + const queries = readNumericValueFromRaw(values.queries); + if (queries !== undefined) { + payload.queries = Math.max(1, Math.min(63, queries)); + } + } + + const maxHops = readNumericValueFromRaw(values.maxHops); + if (maxHops !== undefined) { + payload.max_hops = maxHops; + } + + const dstPort = readNumericValueFromRaw(values.dstPort); + if (dstPort !== undefined) { + payload.port = dstPort; + } + + const packetSize = readNumericValueFromRaw(values.packetSize); + if (packetSize !== undefined) { + payload.packet_size = packetSize; + } + + const tos = readNumericValueFromRaw(values.tos); + if (tos !== undefined) { + payload.tos = tos; + } + + return payload; + } + + return { + buildTracePayload, + defaultOptionValue, + readNumericValueFromRaw, + }; +}); diff --git a/server/web/assets/trace_form.test.cjs b/server/web/assets/trace_form.test.cjs new file mode 100644 index 0000000..d991c70 --- /dev/null +++ b/server/web/assets/trace_form.test.cjs @@ -0,0 +1,52 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { buildTracePayload, defaultOptionValue } = require('./trace_form.js'); + +test('buildTracePayload preserves negative packet_size and zero tos', () => { + const payload = buildTracePayload({ + target: '1.1.1.1', + protocol: 'icmp', + dataProvider: 'LeoMoeAPI', + disableMaptrace: false, + language: 'cn', + mode: 'single', + queries: '3', + maxHops: '30', + dstPort: '', + packetSize: '-123', + tos: '0', + }); + + assert.equal(payload.packet_size, -123); + assert.equal(payload.tos, 0); + assert.equal(payload.queries, 3); +}); + +test('buildTracePayload carries packet_size and tos in mtr mode', () => { + const payload = buildTracePayload({ + target: 'example.com', + protocol: 'udp', + dataProvider: 'disable-geoip', + disableMaptrace: true, + language: 'en', + mode: 'mtr', + queries: '5', + maxHops: '20', + dstPort: '33494', + packetSize: '80', + tos: '255', + }); + + assert.equal(payload.mode, 'mtr'); + assert.equal(payload.queries, 10); + assert.equal(payload.hop_interval_ms, 1000); + assert.equal(payload.max_rounds, 0); + assert.equal(payload.packet_size, 80); + assert.equal(payload.tos, 255); +}); + +test('defaultOptionValue keeps explicit zero', () => { + assert.equal(defaultOptionValue({ tos: 0 }, 'tos', 5), 0); + assert.equal(defaultOptionValue({}, 'tos', 5), 5); +}); diff --git a/server/web/index.html b/server/web/index.html index d5725ec..f09a130 100644 --- a/server/web/index.html +++ b/server/web/index.html @@ -65,8 +65,15 @@ 仅 TCP/UDP 模式有效