diff --git a/README.md b/README.md index c36467d..1ca5de1 100644 --- a/README.md +++ b/README.md @@ -404,7 +404,7 @@ 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` | Probe packet size | `52` bytes | Inclusive IP + probe headers; negative values randomize each probe up to `abs(value)`; sizes above the egress/path MTU may fragment on wire | +| `--psize` | Probe packet size | Protocol/IP-family minimum | Inclusive IP + probe headers; negative values randomize each probe up to `abs(value)`; sizes above the egress/path MTU may fragment on wire | | `-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. @@ -744,11 +744,11 @@ Arguments: on slow intercontinental or high-loss paths. Default: 1000 --psize Probe packet size in bytes, inclusive IP - and active probe headers. Keep 52 for - normal routing checks; raise for MTU or + and active probe headers. Default is the + minimum legal size for the chosen + protocol and IP family; 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, diff --git a/README_zh_CN.md b/README_zh_CN.md index 16fa32e..ad063b4 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -400,7 +400,7 @@ 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` 字节 | 含 IP + 探测协议头;负值表示每个 probe 在 `abs(value)` 内随机;超过出接口/路径 MTU 时,链路上可能看到分片 | +| `--psize` | 探测包大小 | 按协议/IP 族自动取最小合法值 | 含 IP + 探测协议头;负值表示每个 probe 在 `abs(value)` 内随机;超过出接口/路径 MTU 时,链路上可能看到分片 | | `-Q`, `--tos` | IP TOS / traffic class | `0` | 设置 IP 头里的 TOS / traffic class | 这些探测参数目前仍是 CLI 级配置,`nt_config.yaml` 还不能直接保存它们。若要复用一组调优参数,建议写成 shell alias 或小脚本。 @@ -724,11 +724,11 @@ Arguments: on slow intercontinental or high-loss paths. Default: 1000 --psize Probe packet size in bytes, inclusive IP - and active probe headers. Keep 52 for - normal routing checks; raise for MTU or + and active probe headers. Default is the + minimum legal size for the chosen + protocol and IP family; 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, diff --git a/cmd/cmd.go b/cmd/cmd.go index 61b6299..0abecdb 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -363,7 +363,7 @@ func buildTimeoutHelp() string { } func buildPayloadSizeHelp() string { - 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)" + return "Probe packet size in bytes, inclusive IP and active probe headers. Default is the minimum legal size for the chosen protocol and IP family; raise for MTU or large-packet testing. Negative values randomize each probe up to abs(value)" } func buildTOSHelp() string { @@ -531,6 +531,13 @@ func detectExplicitProbeFlags(parser *argparse.Parser) (queriesExplicit, ttlTime return queriesExplicit, ttlTimeExplicit, packetSizeExplicit, tosExplicit } +func resolvePacketSizeArg(packetSize int, explicit bool, method trace.Method, dstIP net.IP) int { + if explicit { + return packetSize + } + return trace.DefaultPacketSize(method, dstIP) +} + func applyColorMode(noColor bool) { color.NoColor = noColor } @@ -1064,7 +1071,7 @@ func Execute() { packetInterval := registerPacketIntervalFlag(parser) ttlInterval := registerTTLIntervalFlag(parser) timeout := parser.Int("", "timeout", &argparse.Options{Default: 1000, Help: buildTimeoutHelp()}) - packetSize := parser.Int("", "psize", &argparse.Options{Default: 52, Help: buildPayloadSizeHelp()}) + packetSize := parser.Int("", "psize", &argparse.Options{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]"}) @@ -1215,6 +1222,7 @@ func Execute() { AlwaysWaitRDNS: *alwaysrDNS, Lang: *lang, PktSize: *packetSize, + PacketSizeSet: packetSizeExplicit, TOS: *tos, Timeout: time.Duration(*timeout) * time.Millisecond, File: *file, @@ -1281,9 +1289,10 @@ func Execute() { ip := lookupTargetIPOrExit(domain, *ipv4Only, *ipv6Only, *dot, *jsonPrint) applySourceDevice(*srcDev, ip, srcAddr) - printTraceNav(*jsonPrint, mtrModes.mtr, ip, domain, *dataOrigin, *maxHops, *packetSize, *srcAddr, method) + effectivePacketSize := resolvePacketSizeArg(*packetSize, packetSizeExplicit, method, ip) + printTraceNav(*jsonPrint, mtrModes.mtr, ip, domain, *dataOrigin, *maxHops, effectivePacketSize, *srcAddr, method) - packetSizeSpec, packetSizeErr := trace.NormalizePacketSize(method, ip, *packetSize) + packetSizeSpec, packetSizeErr := trace.NormalizePacketSize(method, ip, effectivePacketSize) if packetSizeErr != nil { fmt.Println(packetSizeErr) os.Exit(1) diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index dd0e317..a1d8255 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -1,10 +1,12 @@ package cmd import ( + "net" "strings" "testing" "github.com/akamensky/argparse" + "github.com/nxtrace/NTrace-core/trace" ) func TestRegisterGlobalpingFlagWithAvailability_DisabledStillParses(t *testing.T) { @@ -70,14 +72,14 @@ func TestAdvancedHelpTextMentionsTuningGuidance(t *testing.T) { parser.Int("", "max-attempts", &argparse.Options{Help: buildMaxAttemptsHelp()}) parser.Int("", "parallel-requests", &argparse.Options{Default: 18, Help: buildParallelRequestsHelp()}) parser.Int("", "timeout", &argparse.Options{Default: 1000, Help: buildTimeoutHelp()}) - parser.Int("", "psize", &argparse.Options{Default: 52, Help: buildPayloadSizeHelp()}) + parser.Int("", "psize", &argparse.Options{Help: buildPayloadSizeHelp()}) usage := parser.Usage(nil) for _, want := range []string{ "load-balanced paths", "rate-limited links", "intercontinental", - "MTU or large-packet", + "raise for MTU or", } { if !strings.Contains(usage, want) { t.Fatalf("usage missing tuning guidance %q:\n%s", want, usage) @@ -87,7 +89,7 @@ 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("", "psize", &argparse.Options{Help: buildPayloadSizeHelp()}) parser.Int("Q", "tos", &argparse.Options{Default: 0, Help: buildTOSHelp()}) usage := parser.Usage(nil) @@ -105,7 +107,7 @@ 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("", "psize", &argparse.Options{}) parser.Int("Q", "tos", &argparse.Options{Default: 0}) if err := parser.Parse([]string{"ntr", "--psize", "-123", "-Q", "46", "-q", "5"}); err != nil { @@ -144,7 +146,7 @@ func TestNormalizeNegativePacketSizeArgs(t *testing.T) { func TestNegativePacketSizeParsesBeforeTarget(t *testing.T) { parser := argparse.NewParser("ntr", "") - packetSize := parser.Int("", "psize", &argparse.Options{Default: 52}) + packetSize := parser.Int("", "psize", &argparse.Options{}) ipv6Only := parser.Flag("6", "ipv6", &argparse.Options{}) target := parser.StringPositional(&argparse.Options{}) @@ -162,3 +164,10 @@ func TestNegativePacketSizeParsesBeforeTarget(t *testing.T) { t.Fatalf("target = %q, want 2606:4700:4700::1111", *target) } } + +func TestResolvePacketSizeArg_DefaultsToProtocolMinimum(t *testing.T) { + got := resolvePacketSizeArg(0, false, trace.TCPTrace, net.ParseIP("2a00:1450:4009:81a::200e")) + if got != 64 { + t.Fatalf("resolvePacketSizeArg() = %d, want 64", got) + } +} diff --git a/fast_trace/fast_trace ipv6.go b/fast_trace/fast_trace ipv6.go index 6c2c722..0f34b6b 100644 --- a/fast_trace/fast_trace ipv6.go +++ b/fast_trace/fast_trace ipv6.go @@ -3,6 +3,7 @@ package fastTrace import ( "fmt" "log" + "net" "os" "os/signal" "strings" @@ -21,14 +22,22 @@ 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, %s, %s mode\n", ispCollection.IPv6, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(f.ParamsFastTrace.PktSize), strings.ToUpper(string(f.TracerouteMethod))) + displayPacketSize := f.ParamsFastTrace.PktSize + if !f.ParamsFastTrace.PacketSizeSet { + displayPacketSize = trace.DefaultPacketSize(f.TracerouteMethod, net.ParseIP(ispCollection.IPv6)) + } + fmt.Printf("traceroute to %s, %d hops max, %s, %s mode\n", ispCollection.IPv6, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(displayPacketSize), 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) + packetSize := f.ParamsFastTrace.PktSize + if !f.ParamsFastTrace.PacketSizeSet { + packetSize = trace.DefaultPacketSize(f.TracerouteMethod, ip) + } + packetSizeSpec, err := trace.NormalizePacketSize(f.TracerouteMethod, ip, packetSize) if err != nil { log.Fatal(err) } @@ -69,7 +78,11 @@ 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, %s, %s mode\n", ispCollection.IPv6, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(f.ParamsFastTrace.PktSize), strings.ToUpper(string(f.TracerouteMethod))) + displayPacketSize := f.ParamsFastTrace.PktSize + if !f.ParamsFastTrace.PacketSizeSet { + displayPacketSize = trace.DefaultPacketSize(f.TracerouteMethod, net.ParseIP(ispCollection.IPv6)) + } + log.Printf("traceroute to %s, %d hops max, %s, %s mode\n", ispCollection.IPv6, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(displayPacketSize), strings.ToUpper(string(f.TracerouteMethod))) conf.RealtimePrinter = tracelog.RealtimePrinter } else { conf.RealtimePrinter = printer.RealtimePrinter diff --git a/fast_trace/fast_trace.go b/fast_trace/fast_trace.go index 1c3d2b2..ad3756a 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 + PacketSizeSet bool TOS int Timeout time.Duration File string @@ -216,12 +217,20 @@ func printFileTraceHeader(ip IpListElement, params ParamsFastTrace, tracerouteMe if util.EnableHidDstIP { dst = util.HideIPPart(ip.Ip) } - fmt.Printf("traceroute to %s, %d hops max, %s, %s mode\n", dst, params.MaxHops, trace.FormatPacketSizeLabel(params.PktSize), strings.ToUpper(string(tracerouteMethod))) + displayPacketSize := params.PktSize + if !params.PacketSizeSet { + displayPacketSize = trace.DefaultPacketSize(tracerouteMethod, net.ParseIP(ip.Ip)) + } + fmt.Printf("traceroute to %s, %d hops max, %s, %s mode\n", dst, params.MaxHops, trace.FormatPacketSizeLabel(displayPacketSize), 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) + packetSize := params.PktSize + if !params.PacketSizeSet { + packetSize = trace.DefaultPacketSize(tracerouteMethod, dstIP) + } + packetSizeSpec, err := trace.NormalizePacketSize(tracerouteMethod, dstIP, packetSize) if err != nil { log.Fatal(err) } @@ -272,7 +281,11 @@ 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, %s, %s mode\n", ip.Desc, ip.Ip, params.MaxHops, trace.FormatPacketSizeLabel(params.PktSize), strings.ToUpper(string(tracerouteMethod))) + displayPacketSize := params.PktSize + if !params.PacketSizeSet { + displayPacketSize = trace.DefaultPacketSize(tracerouteMethod, net.ParseIP(ip.Ip)) + } + header := fmt.Sprintf("『%s』\ntraceroute to %s, %d hops max, %s, %s mode\n", ip.Desc, ip.Ip, params.MaxHops, trace.FormatPacketSizeLabel(displayPacketSize), strings.ToUpper(string(tracerouteMethod))) if err := configureFastTraceRealtimePrinter(&conf, header); err != nil { return } @@ -285,14 +298,22 @@ 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, %s, %s mode\n", ispCollection.IP, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(f.ParamsFastTrace.PktSize), strings.ToUpper(string(f.TracerouteMethod))) + displayPacketSize := f.ParamsFastTrace.PktSize + if !f.ParamsFastTrace.PacketSizeSet { + displayPacketSize = trace.DefaultPacketSize(f.TracerouteMethod, net.ParseIP(ispCollection.IP)) + } + fmt.Printf("traceroute to %s, %d hops max, %s, %s mode\n", ispCollection.IP, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(displayPacketSize), 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) + packetSize := f.ParamsFastTrace.PktSize + if !f.ParamsFastTrace.PacketSizeSet { + packetSize = trace.DefaultPacketSize(f.TracerouteMethod, ip) + } + packetSizeSpec, err := trace.NormalizePacketSize(f.TracerouteMethod, ip, packetSize) if err != nil { log.Fatal(err) } @@ -334,7 +355,11 @@ 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, %s, %s mode\n", ispCollection.IP, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(f.ParamsFastTrace.PktSize), strings.ToUpper(string(f.TracerouteMethod))) + displayPacketSize := f.ParamsFastTrace.PktSize + if !f.ParamsFastTrace.PacketSizeSet { + displayPacketSize = trace.DefaultPacketSize(f.TracerouteMethod, net.ParseIP(ispCollection.IP)) + } + log.Printf("traceroute to %s, %d hops max, %s, %s mode\n", ispCollection.IP, f.ParamsFastTrace.MaxHops, trace.FormatPacketSizeLabel(displayPacketSize), strings.ToUpper(string(f.TracerouteMethod))) conf.RealtimePrinter = tracelog.RealtimePrinter } else { conf.RealtimePrinter = printer.RealtimePrinter diff --git a/server/handlers.go b/server/handlers.go index d3dd7ae..044746e 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -25,7 +25,7 @@ var ( "queries": 3, "max_hops": 30, "timeout_ms": 1000, - "packet_size": 52, + "packet_size": nil, "tos": 0, "parallel_requests": 18, "begin_hop": 1, diff --git a/server/trace_handler.go b/server/trace_handler.go index 4a2a757..996bd1c 100644 --- a/server/trace_handler.go +++ b/server/trace_handler.go @@ -334,7 +334,7 @@ func buildTraceConfig(req traceRequest, method trace.Method, ip net.IP, dataProv timeout = defaults["timeout_ms"].(int) } - packetSize := defaults["packet_size"].(int) + packetSize := trace.DefaultPacketSize(method, ip) if req.PacketSize != nil { packetSize = *req.PacketSize } diff --git a/server/trace_handler_test.go b/server/trace_handler_test.go index 2932d11..9e4e146 100644 --- a/server/trace_handler_test.go +++ b/server/trace_handler_test.go @@ -89,6 +89,19 @@ func TestBuildTraceConfig_PreservesNegativePacketSizeAndTOS(t *testing.T) { } } +func TestBuildTraceConfig_DefaultsPacketSizeByProtocolAndFamily(t *testing.T) { + cfg, err := buildTraceConfig(traceRequest{}, trace.TCPTrace, net.ParseIP("2a00:1450:4009:81a::200e"), "disable-geoip", 80) + if err != nil { + t.Fatalf("buildTraceConfig returned error: %v", err) + } + if cfg.PktSize != 0 { + t.Fatalf("buildTraceConfig PktSize = %d, want 0 payload bytes for default TCP/IPv6 minimum", cfg.PktSize) + } + if cfg.RandomPacketSize { + t.Fatal("buildTraceConfig RandomPacketSize = true, want false") + } +} + func TestNormalizeTraceRequest_RejectsInvalidTOS(t *testing.T) { tos := 256 statusCode, err := normalizeTraceRequest(&traceRequest{TOS: &tos}) diff --git a/server/web/assets/app.js b/server/web/assets/app.js index 31bc22f..5241135 100644 --- a/server/web/assets/app.js +++ b/server/web/assets/app.js @@ -233,7 +233,7 @@ async function loadOptions() { maxHopsInput.value = data.defaultOptions.max_hops; disableMaptraceInput.checked = data.defaultOptions.disable_maptrace; 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); + payloadSizeInput.value = defaultOptionValue(data.defaultOptions, 'packet_size', payloadSizeInput.value || '') ?? ''; tosInput.value = defaultOptionValue(data.defaultOptions, 'tos', tosInput.value || 0); dstPortInput.value = data.defaultOptions.port || dstPortInput.value || ''; updateDstPortState(); diff --git a/server/web/assets/trace_form.test.cjs b/server/web/assets/trace_form.test.cjs index d991c70..fc03cd9 100644 --- a/server/web/assets/trace_form.test.cjs +++ b/server/web/assets/trace_form.test.cjs @@ -50,3 +50,7 @@ test('defaultOptionValue keeps explicit zero', () => { assert.equal(defaultOptionValue({ tos: 0 }, 'tos', 5), 0); assert.equal(defaultOptionValue({}, 'tos', 5), 5); }); + +test('defaultOptionValue preserves explicit null for auto packet size', () => { + assert.equal(defaultOptionValue({ packet_size: null }, 'packet_size', 52), null); +}); diff --git a/trace/packet_size.go b/trace/packet_size.go index 40930af..303848f 100644 --- a/trace/packet_size.go +++ b/trace/packet_size.go @@ -22,6 +22,10 @@ type PacketSizeSpec struct { Random bool } +func DefaultPacketSize(method Method, dstIP net.IP) int { + return MinPacketSize(method, dstIP) +} + func packetSizeIPHeaderBytes(dstIP net.IP) int { if util.IsIPv6(dstIP) { return ipv6HeaderBytes diff --git a/trace/packet_size_test.go b/trace/packet_size_test.go index f9e4681..8b3c3aa 100644 --- a/trace/packet_size_test.go +++ b/trace/packet_size_test.go @@ -82,3 +82,10 @@ func TestMinPacketSize(t *testing.T) { } } } + +func TestDefaultPacketSizeMatchesMinimum(t *testing.T) { + ip := net.ParseIP("2a00:1450:4009:81a::200e") + if got := DefaultPacketSize(TCPTrace, ip); got != 64 { + t.Fatalf("DefaultPacketSize(TCPTrace, %v) = %d, want 64", ip, got) + } +}