diff --git a/README.md b/README.md index ce3c83b..291e1a1 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ nexttrace --udp 1.0.0.1 nexttrace --udp --port 5353 1.0.0.1 # For TCP/UDP Trace, you can specify the source port; by default, a fixed random port is used -# (if you need to use a different random source port for each packet, please set the ENV variable NEXTTRACE_RANDOMPORT) +# (If you need to use a different random source port for each packet, please set the ENV variable NEXTTRACE_RANDOMPORT) nexttrace --tcp --source-port 14514 www.bing.com ``` @@ -236,6 +236,11 @@ nexttrace --tcp --source-port 14514 www.bing.com # Send 2 probe packets per hop nexttrace --queries 2 www.hkix.net +# Set the maximum attempts per TTL +nexttrace --max-attempts 5 www.hkix.net +# or use the ENV variable NEXTTRACE_MAXATTEMPTS to persist across runs +export NEXTTRACE_MAXATTEMPTS=5 + # No concurrent probe packets, only one probe packet is sent at a time nexttrace --parallel-requests 1 www.hkix.net @@ -328,18 +333,19 @@ All NextTrace IP geolocation `API DEMO` can refer to [here](https://github.com/n Usage: nexttrace [-h|--help] [-4|--ipv4] [-6|--ipv6] [-T|--tcp] [-U|--udp] [-F|--fast-trace] [-p|--port ] [-q|--queries ] [--parallel-requests ] [-m|--max-hops - ] [-d|--data-provider - (Ip2region|ip2region|IP.SB|ip.sb|IPInfo|ipinfo|IPInsight|ipinsight|IPAPI.com|ip-api.com|IPInfoLocal|ipinfolocal|chunzhen|LeoMoeAPI|leomoeapi|disable-geoip)] + ] [--max-attempts ] [-d|--data-provider + (Ip2region|ip2region|IP.SB|ip.sb|IPInfo|ipinfo|IPInsight|ipinsight|IPAPI.com|ip-api.com|IPInfoLocal|ipinfolocal|chunzhen|LeoMoeAPI|leomoeapi|ipdb.one|disable-geoip)] [--pow-provider (api.nxtrace.org|sakura)] [-n|--no-rdns] [-a|--always-rdns] [-P|--route-path] [-r|--report] [--dn42] [-o|--output] [-t|--table] [--raw] [-j|--json] [-c|--classic] [-f|--first ] [-M|--map] [-e|--disable-mpls] - [-v|--version] [-s|--source ""] [-D|--dev ""] - [-z|--send-time ] [-i|--ttl-time ] - [--timeout ] [--psize ] - [_positionalArg_nexttrace_32 ""] [--dot-server - (dnssb|aliyun|dnspod|google|cloudflare)] [-g|--language - (en|cn)] [--file ""] [-C|--nocolor] + [-v|--version] [-s|--source ""] [--source-port + ] [-D|--dev ""] [-z|--send-time ] + [-i|--ttl-time ] [--timeout ] [--psize + ] [_positionalArg_nexttrace_34 ""] + [--dot-server (dnssb|aliyun|dnspod|google|cloudflare)] + [-g|--language (en|cn)] [--file ""] [-C|--nocolor] + [--dont-fragment] Arguments: @@ -352,7 +358,8 @@ Arguments: is 33494) -F --fast-trace One-Key Fast Trace to China ISPs -p --port Set the destination port to use. With - default of 80 for "tcp", 33494 for "udp" + default of 80 for "tcp", 33494 for "udp". + Default: 80 -q --queries Set the number of probes per each hop. Default: 3 --parallel-requests Set ParallelRequests number. It should be @@ -360,6 +367,8 @@ Arguments: 18 -m --max-hops Set the max number of hops (max TTL to be reached). Default: 30 + --max-attempts Set the max number of attempts per TTL + (instead of a fixed auto value) -d --data-provider Choose IP Geograph Data Provider [IP.SB, IPInfo, IPInsight, IP-API.com, Ip2region, IPInfoLocal, CHUNZHEN, disable-geoip]. @@ -382,18 +391,19 @@ Arguments: -j --json Output trace results as JSON -c --classic Classic Output trace results like BestTrace - -f --first Start from the first_ttl hop (instead from + -f --first Start from the first_ttl hop (instead of 1). Default: 1 -M --map Disable Print Trace Map -e --disable-mpls Disable MPLS -v --version Print version info and exit - -s --source Use source src_addr for outgoing packets + -s --source Use source address src_addr for outgoing + packets --source-port Use source port src_port for outgoing packets -D --dev Use the following Network Devices as the source address in outgoing packets -z --send-time Set how many [milliseconds] between - sending each packet.. Useful when some + sending each packet. Useful when some routers use rate-limit for ICMP messages. Default: 50 -i --ttl-time Set how many [milliseconds] between @@ -402,9 +412,9 @@ Arguments: messages. Default: 50 --timeout The number of [milliseconds] to keep probe sockets open before giving up on the - connection.. Default: 1000 + connection. Default: 1000 --psize Set the payload size. Default: 52 - --_positionalArg_nexttrace_32 IP Address or domain name + --_positionalArg_nexttrace_34 IP Address or domain name --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 133c228..69c93a9 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -27,7 +27,7 @@ import ( "github.com/syndtr/gocapability/capability" ) -func Excute() { +func Execute() { parser := argparse.NewParser("nexttrace", "An open source visual route tracking CLI tool") // Create string flag ipv4Only := parser.Flag("4", "ipv4", &argparse.Options{Help: "Use IPv4 only"}) @@ -39,6 +39,7 @@ func Excute() { numMeasurements := parser.Int("q", "queries", &argparse.Options{Default: 3, Help: "Set the number of probes per each hop"}) parallelRequests := parser.Int("", "parallel-requests", &argparse.Options{Default: 18, Help: "Set ParallelRequests number. It should be 1 when there is a multi-routing"}) maxHops := parser.Int("m", "max-hops", &argparse.Options{Default: 30, Help: "Set the max number of hops (max TTL to be reached)"}) + maxAttempts := parser.Int("", "max-attempts", &argparse.Options{Help: "Set the max number of attempts per TTL (instead of a fixed auto value)"}) dataOrigin := parser.Selector("d", "data-provider", []string{"Ip2region", "ip2region", "IP.SB", "ip.sb", "IPInfo", "ipinfo", "IPInsight", "ipinsight", "IPAPI.com", "ip-api.com", "IPInfoLocal", "ipinfolocal", "chunzhen", "LeoMoeAPI", "leomoeapi", "ipdb.one", "disable-geoip"}, &argparse.Options{Default: "LeoMoeAPI", Help: "Choose IP Geograph Data Provider [IP.SB, IPInfo, IPInsight, IP-API.com, Ip2region, IPInfoLocal, CHUNZHEN, disable-geoip]"}) powProvider := parser.Selector("", "pow-provider", []string{"api.nxtrace.org", "sakura"}, &argparse.Options{Default: "api.nxtrace.org", @@ -53,7 +54,7 @@ func Excute() { rawPrint := parser.Flag("", "raw", &argparse.Options{Help: "An Output Easy to Parse"}) jsonPrint := parser.Flag("j", "json", &argparse.Options{Help: "Output trace results as JSON"}) classicPrint := parser.Flag("c", "classic", &argparse.Options{Help: "Classic Output trace results like BestTrace"}) - beginHop := parser.Int("f", "first", &argparse.Options{Default: 1, Help: "Start from the first_ttl hop (instead from 1)"}) + beginHop := parser.Int("f", "first", &argparse.Options{Default: 1, Help: "Start from the first_ttl hop (instead of 1)"}) disableMaptrace := parser.Flag("M", "map", &argparse.Options{Help: "Disable Print Trace Map"}) disableMPLS := parser.Flag("e", "disable-mpls", &argparse.Options{Help: "Disable MPLS"}) ver := parser.Flag("v", "version", &argparse.Options{Help: "Print version info and exit"}) @@ -264,6 +265,7 @@ func Excute() { PacketInterval: *packetInterval, TTLInterval: *ttlInterval, NumMeasurements: *numMeasurements, + MaxAttempts: *maxAttempts, ParallelRequests: *parallelRequests, Lang: *lang, RDns: !*noRdns, @@ -358,7 +360,6 @@ func Excute() { } func capabilitiesCheck() { - // Windows 判断放在前面,防止遇到一些奇奇怪怪的问题 if runtime.GOOS == "windows" { // Running on Windows, skip checking capabilities diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index 93fd8d7..d742f75 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -3,5 +3,5 @@ package cmd import "testing" func TestCMD(t *testing.T) { - Excute() + Execute() } diff --git a/main.go b/main.go index 9f23ba9..e24e4d7 100644 --- a/main.go +++ b/main.go @@ -5,5 +5,5 @@ import ( ) func main() { - cmd.Excute() + cmd.Execute() } diff --git a/printer/tableprinter.go b/printer/tableprinter.go index cd50057..6006f8b 100644 --- a/printer/tableprinter.go +++ b/printer/tableprinter.go @@ -57,7 +57,7 @@ func New() table.Table { headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc() columnFmt := color.New(color.FgYellow).SprintfFunc() - tbl := table.New("Hop", "IP", "Lantency", "ASN", "Location", "Owner") + tbl := table.New("Hop", "IP", "Latency", "ASN", "Location", "Owner") tbl.WithHeaderFormatter(headerFmt).WithFirstColumnFormatter(columnFmt) return tbl } @@ -69,14 +69,14 @@ func tableDataGenerator(h trace.Hop) *rowData { IP: "*", } } else { - lantency := fmt.Sprintf("%.2fms", h.RTT.Seconds()*1000) + latency := fmt.Sprintf("%.2fms", h.RTT.Seconds()*1000) IP := h.Address.String() if strings.HasPrefix(IP, "9.") { return &rowData{ Hop: fmt.Sprint(h.TTL), IP: IP, - Latency: lantency, + Latency: latency, Country: "LAN Address", Prov: "", Owner: "", @@ -85,7 +85,7 @@ func tableDataGenerator(h trace.Hop) *rowData { return &rowData{ Hop: fmt.Sprint(h.TTL), IP: IP, - Latency: lantency, + Latency: latency, Country: "LAN Address", Prov: "", Owner: "", @@ -103,7 +103,7 @@ func tableDataGenerator(h trace.Hop) *rowData { r := &rowData{ Hop: fmt.Sprint(h.TTL), IP: IP, - Latency: lantency, + Latency: latency, Asnumber: h.Geo.Asnumber, Country: h.Geo.CountryEn, Prov: h.Geo.ProvEn, diff --git a/trace/icmp_ipv4.go b/trace/icmp_ipv4.go index be2cb00..4747786 100644 --- a/trace/icmp_ipv4.go +++ b/trace/icmp_ipv4.go @@ -3,6 +3,7 @@ package trace import ( "bytes" "encoding/binary" + "errors" "log" "math/rand" "net" @@ -62,13 +63,38 @@ func (t *ICMPTracer) PrintFunc() { } } +func (t *ICMPTracer) ttlComp(ttl int) bool { + idx := ttl - 1 + t.res.lock.Lock() + defer t.res.lock.Unlock() + return idx < len(t.res.Hops) && len(t.res.Hops[idx]) >= t.NumMeasurements +} + +func (t *ICMPTracer) launchTTL(ttl int) { + go func(ttl int) { + for i := 0; i < t.MaxAttempts; i++ { + // 若此 TTL 已完成,则不再发起新的尝试 + if t.ttlComp(ttl) { + return + } + t.wg.Add(1) + go func(ttl, i int) { + if err := t.send(ttl, i); err != nil { + log.Printf("send failed: ttl=%d i=%d: %v", ttl, i, err) + } + }(ttl, i) + <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) + } + }(ttl) +} + func (t *ICMPTracer) initEchoID() { r := rand.New(rand.NewSource(time.Now().UnixNano())) t.echoIDTag = uint8(r.Intn(256)) // 高 8 位随机 tag t.pidLow = uint8(os.Getpid() & 0xFF) // 低 8 位为 pid } -func (t *ICMPTracer) Execute() (*Result, error) { +func (t *ICMPTracer) Execute() (res *Result, err error) { // 初始化 inflightRequest map t.inflightRequestLock.Lock() t.inflightRequest = make(map[int]chan Hop) @@ -80,13 +106,15 @@ func (t *ICMPTracer) Execute() (*Result, error) { return &t.res, ErrTracerouteExecuted } - var err error - t.icmp, err = internal.ListenICMP("ip4:icmp", t.SrcAddr) if err != nil { return &t.res, err } - defer t.icmp.Close() + defer func() { + if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() t.icmpConn = ipv4.NewPacketConn(t.icmp) @@ -102,21 +130,23 @@ func (t *ICMPTracer) Execute() (*Result, error) { t.sem = semaphore.NewWeighted(int64(t.ParallelRequests)) - for ttl := t.BeginHop; ttl <= t.MaxHops; ttl++ { - // 如果到达最终跳,则退出 - if t.final != -1 && ttl > t.final { - break - } - for i := 0; i < t.NumMeasurements; i++ { - // 将 TTL 编码到高 8 位;将索引 i 编码到低 8 位 - seq := (ttl << 8) | (i & 0xFF) + go func() { + // 立即启动 BeginHop 对应的 TTL 组 + t.launchTTL(t.BeginHop) + // 之后按 TTLInterval 周期启动后续 TTL 组 + ticker := time.NewTicker(time.Millisecond * time.Duration(t.Config.TTLInterval)) + defer ticker.Stop() - t.wg.Add(1) - go t.send(ttl, seq) - <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) + for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ { + <-ticker.C + // 如果到达最终跳,则退出 + if t.final != -1 && ttl > t.final { + break + } + // 并发启动这个 TTL 的所有测量 + t.launchTTL(ttl) } - <-time.After(time.Millisecond * time.Duration(t.Config.TTLInterval)) - } + }() t.wg.Wait() t.res.reduce(t.final) @@ -144,7 +174,7 @@ func (t *ICMPTracer) listenICMP() { echo := rm.Body.(*icmp.Echo) data := echo.Data // 只在 Peer 是目的地址时分发,用 seq 作为通道 key - if ip, ok := msg.Peer.(*net.IPAddr); ok && ip.IP.Equal(t.DestIP) { + if msg.Peer.String() == t.DestIP.String() { id := uint16(echo.ID) if uint8(id>>8) != t.echoIDTag || uint8(id&0xFF) != t.pidLow { continue @@ -205,28 +235,40 @@ func (t *ICMPTracer) listenICMP() { } func (t *ICMPTracer) handleICMPMessage(msg ReceivedMessage, icmpType int8, data []byte, seq int) { - if icmpType == 2 { - if t.DestIP.String() != msg.Peer.String() { - return - } + if icmpType == 2 && msg.Peer.String() != t.DestIP.String() { + return } - t.inflightRequestLock.Lock() - defer t.inflightRequestLock.Unlock() - mpls := extractMPLS(msg, data) - if _, ok := t.inflightRequest[seq]; ok { - t.inflightRequest[seq] <- Hop{ - Success: true, - Address: msg.Peer, - MPLS: mpls, - } + // 取出通道后立刻解锁 + t.inflightRequestLock.Lock() + ch, ok := t.inflightRequest[seq] + t.inflightRequestLock.Unlock() + if !ok || ch == nil { + return + } + + h := Hop{ + Success: true, + Address: msg.Peer, + MPLS: mpls, + } + // 非阻塞发送,避免重复回包把缓冲塞满导致阻塞 + select { + case ch <- h: + default: + // 丢弃重复/迟到的相同 seq 回包,避免阻塞 } } -func (t *ICMPTracer) send(ttl, seq int) error { +func (t *ICMPTracer) send(ttl, i int) error { defer t.wg.Done() + if t.ttlComp(ttl) { + // 快路径短路:若该 TTL 已完成,直接返回避免竞争信号量与无谓发包 + return nil + } + if err := t.sem.Acquire(t.ctx, 1); err != nil { return err } @@ -236,6 +278,13 @@ func (t *ICMPTracer) send(ttl, seq int) error { return nil } + if t.ttlComp(ttl) { + // 竞态兜底:获取信号量期间可能已完成,再次检查以避免冗余发包 + return nil + } + // 将 TTL 编码到高 8 位;将索引 i 编码到低 8 位 + seq := (ttl << 8) | (i & 0xFF) + t.inflightRequestLock.Lock() hopCh := make(chan Hop, 1) t.inflightRequest[seq] = hopCh @@ -314,20 +363,20 @@ func (t *ICMPTracer) send(ttl, seq int) error { return err } - t.res.add(h) + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) case <-time.After(t.Timeout): if t.final != -1 && ttl > t.final { return nil } - t.res.add(Hop{ + h := Hop{ Success: false, Address: nil, TTL: ttl, RTT: 0, Error: ErrHopLimitTimeout, - }) - + } + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) } return nil } diff --git a/trace/icmp_ipv6.go b/trace/icmp_ipv6.go index 444f939..0d30eae 100644 --- a/trace/icmp_ipv6.go +++ b/trace/icmp_ipv6.go @@ -3,6 +3,7 @@ package trace import ( "bytes" "encoding/binary" + "errors" "log" "math/rand" "net" @@ -40,36 +41,58 @@ type ICMPTracerv6 struct { func (t *ICMPTracerv6) PrintFunc() { defer t.wg.Done() - var ttl = t.Config.BeginHop - 1 + ttl := t.Config.BeginHop - 1 for { if t.AsyncPrinter != nil { t.AsyncPrinter(&t.res) } - // 接收的时候检查一下是不是 3 跳都齐了 - if len(t.res.Hops) > ttl { - if len(t.res.Hops[ttl]) == t.NumMeasurements { - if t.RealtimePrinter != nil { - t.RealtimePrinter(&t.res, ttl) - } - ttl++ - - if ttl == t.final || ttl >= t.MaxHops { - return - } + if ttl < len(t.res.Hops) && + len(t.res.Hops[ttl]) == t.NumMeasurements { + if t.RealtimePrinter != nil { + t.RealtimePrinter(&t.res, ttl) + } + ttl++ + if ttl == t.final || ttl >= t.MaxHops { + return } } <-time.After(200 * time.Millisecond) } } +func (t *ICMPTracerv6) ttlComp(ttl int) bool { + idx := ttl - 1 + t.res.lock.Lock() + defer t.res.lock.Unlock() + return idx < len(t.res.Hops) && len(t.res.Hops[idx]) >= t.NumMeasurements +} + +func (t *ICMPTracerv6) launchTTL(ttl int) { + go func(ttl int) { + for i := 0; i < t.MaxAttempts; i++ { + // 若此 TTL 已完成,则不再发起新的尝试 + if t.ttlComp(ttl) { + return + } + t.wg.Add(1) + go func(ttl, i int) { + if err := t.send(ttl, i); err != nil { + log.Printf("send failed: ttl=%d i=%d: %v", ttl, i, err) + } + }(ttl, i) + <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) + } + }(ttl) +} + func (t *ICMPTracerv6) initEchoID() { r := rand.New(rand.NewSource(time.Now().UnixNano())) t.echoIDTag = uint8(r.Intn(256)) // 高 8 位随机 tag t.pidLow = uint8(os.Getpid() & 0xFF) // 低 8 位为 pid } -func (t *ICMPTracerv6) Execute() (*Result, error) { +func (t *ICMPTracerv6) Execute() (res *Result, err error) { // 初始化 inflightRequest map t.inflightRequestLock.Lock() t.inflightRequest = make(map[int]chan Hop) @@ -81,13 +104,15 @@ func (t *ICMPTracerv6) Execute() (*Result, error) { return &t.res, ErrTracerouteExecuted } - var err error - t.icmp, err = internal.ListenICMP("ip6:ipv6-icmp", t.SrcAddr) if err != nil { return &t.res, err } - defer t.icmp.Close() + defer func() { + if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() t.icmpConn = ipv6.NewPacketConn(t.icmp) @@ -103,21 +128,23 @@ func (t *ICMPTracerv6) Execute() (*Result, error) { t.sem = semaphore.NewWeighted(int64(t.ParallelRequests)) - for ttl := t.BeginHop; ttl <= t.MaxHops; ttl++ { - // 如果到达最终跳,则退出 - if t.final != -1 && ttl > t.final { - break - } - for i := 0; i < t.NumMeasurements; i++ { - // 将 TTL 编码到高 8 位;将索引 i 编码到低 8 位 - seq := (ttl << 8) | (i & 0xFF) + go func() { + // 立即启动 BeginHop 对应的 TTL 组 + t.launchTTL(t.BeginHop) + // 之后按 TTLInterval 周期启动后续 TTL 组 + ticker := time.NewTicker(time.Millisecond * time.Duration(t.Config.TTLInterval)) + defer ticker.Stop() - t.wg.Add(1) - go t.send(ttl, seq) - <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) + for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ { + <-ticker.C + // 如果到达最终跳,则退出 + if t.final != -1 && ttl > t.final { + break + } + // 并发启动这个 TTL 的所有测量 + t.launchTTL(ttl) } - <-time.After(time.Millisecond * time.Duration(t.Config.TTLInterval)) - } + }() // for ttl := t.BeginHop; ttl <= t.MaxHops; ttl++ { // if t.final != -1 && ttl > t.final { // break @@ -163,7 +190,7 @@ func (t *ICMPTracerv6) listenICMP() { echo := rm.Body.(*icmp.Echo) data := echo.Data // 只在 Peer 是目的地址时分发,用 seq 作为通道 key - if ip, ok := msg.Peer.(*net.IPAddr); ok && ip.IP.Equal(t.DestIP) { + if msg.Peer.String() == t.DestIP.String() { id := uint16(echo.ID) if uint8(id>>8) != t.echoIDTag || uint8(id&0xFF) != t.pidLow { continue @@ -264,27 +291,40 @@ func (t *ICMPTracerv6) listenICMP() { } func (t *ICMPTracerv6) handleICMPMessage(msg ReceivedMessage, icmpType int8, data []byte, seq int) { - if icmpType == 2 { - if t.DestIP.String() != msg.Peer.String() { - return - } + if icmpType == 2 && msg.Peer.String() != t.DestIP.String() { + return } - t.inflightRequestLock.Lock() - defer t.inflightRequestLock.Unlock() mpls := extractMPLS(msg, data) - if _, ok := t.inflightRequest[seq]; ok { - t.inflightRequest[seq] <- Hop{ - Success: true, - Address: msg.Peer, - MPLS: mpls, - } + // 取出通道后立刻解锁 + t.inflightRequestLock.Lock() + ch, ok := t.inflightRequest[seq] + t.inflightRequestLock.Unlock() + if !ok || ch == nil { + return + } + + h := Hop{ + Success: true, + Address: msg.Peer, + MPLS: mpls, + } + // 非阻塞发送,避免重复回包把缓冲塞满导致阻塞 + select { + case ch <- h: + default: + // 丢弃重复/迟到的相同 seq 回包,避免阻塞 } } -func (t *ICMPTracerv6) send(ttl, seq int) error { +func (t *ICMPTracerv6) send(ttl, i int) error { defer t.wg.Done() + if t.ttlComp(ttl) { + // 快路径短路:若该 TTL 已完成,直接返回避免竞争信号量与无谓发包 + return nil + } + if err := t.sem.Acquire(t.ctx, 1); err != nil { return err } @@ -294,6 +334,13 @@ func (t *ICMPTracerv6) send(ttl, seq int) error { return nil } + if t.ttlComp(ttl) { + // 竞态兜底:获取信号量期间可能已完成,再次检查以避免冗余发包 + return nil + } + // 将 TTL 编码到高 8 位;将索引 i 编码到低 8 位 + seq := (ttl << 8) | (i & 0xFF) + t.inflightRequestLock.Lock() hopCh := make(chan Hop, 1) t.inflightRequest[seq] = hopCh @@ -372,20 +419,20 @@ func (t *ICMPTracerv6) send(ttl, seq int) error { return err } - t.res.add(h) - + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) case <-time.After(t.Timeout): if t.final != -1 && ttl > t.final { return nil } - t.res.add(Hop{ + h := Hop{ Success: false, Address: nil, TTL: ttl, RTT: 0, Error: ErrHopLimitTimeout, - }) + } + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) } return nil } diff --git a/trace/internal/icmp_darwin.go b/trace/internal/icmp_darwin.go index ab39e6c..9befcf5 100644 --- a/trace/internal/icmp_darwin.go +++ b/trace/internal/icmp_darwin.go @@ -21,10 +21,10 @@ var ( errUnknownIface = errors.New("unknown network interface") networkMap = map[string]string{ - "ip4:icmp": "udp4", - "ip4:1": "udp4", - "ip6:icmp": "udp6", - "ip6:58": "udp6", + "ip4:icmp": "udp4", + "ip4:1": "udp4", + "ip6:ipv6-icmp": "udp6", + "ip6:58": "udp6", } ) @@ -93,5 +93,4 @@ func ListenICMP(network string, laddr string) (net.PacketConn, error) { } else { return nil, errUnknownNetwork } - //} } diff --git a/trace/tcp_ipv4.go b/trace/tcp_ipv4.go index c7cd600..3a6cce2 100644 --- a/trace/tcp_ipv4.go +++ b/trace/tcp_ipv4.go @@ -1,6 +1,7 @@ package trace import ( + "errors" "log" "math/rand" "net" @@ -36,7 +37,54 @@ type TCPTracer struct { fetchLock sync.Mutex } -func (t *TCPTracer) Execute() (*Result, error) { +func (t *TCPTracer) PrintFunc() { + defer t.wg.Done() + ttl := t.Config.BeginHop - 1 + for { + if t.AsyncPrinter != nil { + t.AsyncPrinter(&t.res) + } + // 接收的时候检查一下是不是 3 跳都齐了 + if ttl < len(t.res.Hops) && + len(t.res.Hops[ttl]) == t.NumMeasurements { + if t.RealtimePrinter != nil { + t.RealtimePrinter(&t.res, ttl) + } + ttl++ + if ttl == t.final || ttl >= t.MaxHops { + return + } + } + <-time.After(200 * time.Millisecond) + } +} + +func (t *TCPTracer) ttlComp(ttl int) bool { + idx := ttl - 1 + t.res.lock.Lock() + defer t.res.lock.Unlock() + return idx < len(t.res.Hops) && len(t.res.Hops[idx]) >= t.NumMeasurements +} + +func (t *TCPTracer) launchTTL(ttl int) { + go func(ttl int) { + for i := 0; i < t.MaxAttempts; i++ { + // 若此 TTL 已完成,则不再发起新的尝试 + if t.ttlComp(ttl) { + return + } + t.wg.Add(1) + go func(ttl, i int) { + if err := t.send(ttl, i); err != nil { + log.Printf("send failed: ttl=%d i=%d: %v", ttl, i, err) + } + }(ttl, i) + <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) + } + }(ttl) +} + +func (t *TCPTracer) Execute() (res *Result, err error) { // 初始化 inflightRequest map t.inflightRequestLock.Lock() t.inflightRequest = make(map[int]chan Hop) @@ -48,8 +96,6 @@ func (t *TCPTracer) Execute() (*Result, error) { t.SrcIP, _ = util.LocalIPPort(t.DestIP) - var err error - if t.SrcAddr != "" { t.tcp, err = net.ListenPacket("ip4:tcp", t.SrcAddr) } else { @@ -58,7 +104,11 @@ func (t *TCPTracer) Execute() (*Result, error) { if err != nil { return nil, err } - defer t.tcp.Close() + defer func() { + if c := t.tcp; c != nil { // 先拷一份引用,避免 defer 执行时 t.tcp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() t.tcpConn = ipv4.NewPacketConn(t.tcp) @@ -66,7 +116,11 @@ func (t *TCPTracer) Execute() (*Result, error) { if err != nil { return &t.res, err } - defer t.icmp.Close() + defer func() { + if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() var cancel context.CancelFunc t.ctx, cancel = context.WithCancel(context.Background()) @@ -76,41 +130,29 @@ func (t *TCPTracer) Execute() (*Result, error) { go t.listenICMP() go t.listenTCP() + t.wg.Add(1) + go t.PrintFunc() t.sem = semaphore.NewWeighted(int64(t.ParallelRequests)) - for ttl := t.BeginHop; ttl <= t.MaxHops; ttl++ { - // 如果到达最终跳,则退出 - if t.final != -1 && ttl > t.final { - break - } - for i := 0; i < t.NumMeasurements; i++ { - // 将 TTL 编码到高 8 位;将索引 i 编码到低 24 位 - seq := (ttl << 24) | (i & 0xFFFFFF) - - t.wg.Add(1) - go t.send(ttl, seq) - <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) - } - if t.RealtimePrinter != nil { - // 对于实时模式,应该按照TTL进行并发请求 - t.wg.Wait() - t.RealtimePrinter(&t.res, ttl-1) - } - <-time.After(time.Millisecond * time.Duration(t.Config.TTLInterval)) - } go func() { - if t.AsyncPrinter != nil { - for { - t.AsyncPrinter(&t.res) - time.Sleep(200 * time.Millisecond) + // 立即启动 BeginHop 对应的 TTL 组 + t.launchTTL(t.BeginHop) + // 之后按 TTLInterval 周期启动后续 TTL 组 + ticker := time.NewTicker(time.Millisecond * time.Duration(t.Config.TTLInterval)) + defer ticker.Stop() + + for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ { + <-ticker.C + // 如果到达最终跳,则退出 + if t.final != -1 && ttl > t.final { + break } + // 并发启动这个 TTL 的所有测量 + t.launchTTL(ttl) } }() - // 如果是表格模式,则一次性并发请求 - if t.RealtimePrinter == nil { - t.wg.Wait() - } + t.wg.Wait() t.res.reduce(t.final) return &t.res, nil @@ -182,16 +224,26 @@ func (t *TCPTracer) listenTCP() { // 从包中获取TCP layer信息 if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil { tcp, _ := tcpLayer.(*layers.TCP) + // 从对端返回的 ACK-1 恢复出原始探测包的 seq + seq := int(tcp.Ack - 1) + // 取出通道后立刻解锁 t.inflightRequestLock.Lock() - // 从对端返回的 ACK - 1 恢复出原始探测包的 Sequence - if ch, ok := t.inflightRequest[int(tcp.Ack-1)]; ok { - // 最后一跳 - ch <- Hop{ - Success: true, - Address: msg.Peer, - } - } + ch, ok := t.inflightRequest[seq] t.inflightRequestLock.Unlock() + if !ok || ch == nil { + continue + } + + h := Hop{ + Success: true, + Address: msg.Peer, + } + // 非阻塞发送,避免重复回包把缓冲塞满导致阻塞 + select { + case ch <- h: + default: + // 丢弃重复/迟到的相同 seq 回包,避免阻塞 + } } } } @@ -207,24 +259,34 @@ func (t *TCPTracer) handleICMPMessage(msg ReceivedMessage, data []byte) { if err != nil { return } - + // 取出通道后立刻解锁 t.inflightRequestLock.Lock() - defer t.inflightRequestLock.Unlock() - ch, ok := t.inflightRequest[int(seq)] - if !ok { + t.inflightRequestLock.Unlock() + if !ok || ch == nil { return } - ch <- Hop{ + h := Hop{ Success: true, Address: msg.Peer, } + // 非阻塞发送,避免重复回包把缓冲塞满导致阻塞 + select { + case ch <- h: + default: + // 丢弃重复/迟到的相同 seq 回包,避免阻塞 + } } -func (t *TCPTracer) send(ttl, seq int) error { +func (t *TCPTracer) send(ttl, i int) error { defer t.wg.Done() + if t.ttlComp(ttl) { + // 快路径短路:若该 TTL 已完成,直接返回避免竞争信号量与无谓发包 + return nil + } + if err := t.sem.Acquire(t.ctx, 1); err != nil { return err } @@ -234,6 +296,13 @@ func (t *TCPTracer) send(ttl, seq int) error { return nil } + if t.ttlComp(ttl) { + // 竞态兜底:获取信号量期间可能已完成,再次检查以避免冗余发包 + return nil + } + // 将 TTL 编码到高 8 位;将索引 i 编码到低 24 位 + seq := (ttl << 24) | (i & 0xFFFFFF) + t.inflightRequestLock.Lock() hopCh := make(chan Hop, 1) t.inflightRequest[seq] = hopCh @@ -333,19 +402,20 @@ func (t *TCPTracer) send(ttl, seq int) error { return err } - t.res.add(h) + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) case <-time.After(t.Timeout): if t.final != -1 && ttl > t.final { return nil } - t.res.add(Hop{ + h := Hop{ Success: false, Address: nil, TTL: ttl, RTT: 0, Error: ErrHopLimitTimeout, - }) + } + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) } return nil } diff --git a/trace/tcp_ipv6.go b/trace/tcp_ipv6.go index 9c0e387..7439c0c 100644 --- a/trace/tcp_ipv6.go +++ b/trace/tcp_ipv6.go @@ -1,6 +1,7 @@ package trace import ( + "errors" "log" "math/rand" "net" @@ -36,7 +37,54 @@ type TCPTracerIPv6 struct { fetchLock sync.Mutex } -func (t *TCPTracerIPv6) Execute() (*Result, error) { +func (t *TCPTracerIPv6) PrintFunc() { + defer t.wg.Done() + ttl := t.Config.BeginHop - 1 + for { + if t.AsyncPrinter != nil { + t.AsyncPrinter(&t.res) + } + // 接收的时候检查一下是不是 3 跳都齐了 + if ttl < len(t.res.Hops) && + len(t.res.Hops[ttl]) == t.NumMeasurements { + if t.RealtimePrinter != nil { + t.RealtimePrinter(&t.res, ttl) + } + ttl++ + if ttl == t.final || ttl >= t.MaxHops { + return + } + } + <-time.After(200 * time.Millisecond) + } +} + +func (t *TCPTracerIPv6) ttlComp(ttl int) bool { + idx := ttl - 1 + t.res.lock.Lock() + defer t.res.lock.Unlock() + return idx < len(t.res.Hops) && len(t.res.Hops[idx]) >= t.NumMeasurements +} + +func (t *TCPTracerIPv6) launchTTL(ttl int) { + go func(ttl int) { + for i := 0; i < t.MaxAttempts; i++ { + // 若此 TTL 已完成,则不再发起新的尝试 + if t.ttlComp(ttl) { + return + } + t.wg.Add(1) + go func(ttl, i int) { + if err := t.send(ttl, i); err != nil { + log.Printf("send failed: ttl=%d i=%d: %v", ttl, i, err) + } + }(ttl, i) + <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) + } + }(ttl) +} + +func (t *TCPTracerIPv6) Execute() (res *Result, err error) { // 初始化 inflightRequest map t.inflightRequestLock.Lock() t.inflightRequest = make(map[int]chan Hop) @@ -48,8 +96,6 @@ func (t *TCPTracerIPv6) Execute() (*Result, error) { t.SrcIP, _ = util.LocalIPPortv6(t.DestIP) // log.Println(util.LocalIPPortv6(t.DestIP)) - var err error - if t.SrcAddr != "" { t.tcp, err = net.ListenPacket("ip6:tcp", t.SrcAddr) } else { @@ -58,7 +104,11 @@ func (t *TCPTracerIPv6) Execute() (*Result, error) { if err != nil { return nil, err } - defer t.tcp.Close() + defer func() { + if c := t.tcp; c != nil { // 先拷一份引用,避免 defer 执行时 t.tcp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() t.tcpConn = ipv6.NewPacketConn(t.tcp) @@ -66,7 +116,11 @@ func (t *TCPTracerIPv6) Execute() (*Result, error) { if err != nil { return &t.res, err } - defer t.icmp.Close() + defer func() { + if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() var cancel context.CancelFunc t.ctx, cancel = context.WithCancel(context.Background()) @@ -76,42 +130,29 @@ func (t *TCPTracerIPv6) Execute() (*Result, error) { go t.listenICMP() go t.listenTCP() + t.wg.Add(1) + go t.PrintFunc() t.sem = semaphore.NewWeighted(int64(t.ParallelRequests)) - for ttl := t.BeginHop; ttl <= t.MaxHops; ttl++ { - // 如果到达最终跳,则退出 - if t.final != -1 && ttl > t.final { - break - } - for i := 0; i < t.NumMeasurements; i++ { - // TTL 高 8 位、探测索引占低 24 位 - seq := (ttl << 24) | (i & 0xFFFFFF) - - t.wg.Add(1) - go t.send(ttl, seq) - time.Sleep(time.Millisecond * time.Duration(t.Config.PacketInterval)) - } - if t.RealtimePrinter != nil { - // 对于实时模式,应该按照TTL进行并发请求 - t.wg.Wait() - t.RealtimePrinter(&t.res, ttl-1) - } - <-time.After(time.Millisecond * time.Duration(t.Config.TTLInterval)) - } - go func() { - if t.AsyncPrinter != nil { - for { - t.AsyncPrinter(&t.res) - time.Sleep(200 * time.Millisecond) + // 立即启动 BeginHop 对应的 TTL 组 + t.launchTTL(t.BeginHop) + // 之后按 TTLInterval 周期启动后续 TTL 组 + ticker := time.NewTicker(time.Millisecond * time.Duration(t.Config.TTLInterval)) + defer ticker.Stop() + + for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ { + <-ticker.C + // 如果到达最终跳,则退出 + if t.final != -1 && ttl > t.final { + break } + // 并发启动这个 TTL 的所有测量 + t.launchTTL(ttl) } }() - // 如果是表格模式,则一次性并发请求 - if t.RealtimePrinter == nil { - t.wg.Wait() - } + t.wg.Wait() t.res.reduce(t.final) return &t.res, nil @@ -185,16 +226,26 @@ func (t *TCPTracerIPv6) listenTCP() { // 从包中获取TCP layer信息 if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil { tcp, _ := tcpLayer.(*layers.TCP) + // 从对端返回的 ACK-1 恢复出原始探测包的 seq + seq := int(tcp.Ack - 1) + // 取出通道后立刻解锁 t.inflightRequestLock.Lock() - // 从对端返回的 ACK - 1 恢复出原始探测包的 Sequence - if ch, ok := t.inflightRequest[int(tcp.Ack-1)]; ok { - // 最后一跳 - ch <- Hop{ - Success: true, - Address: msg.Peer, - } - } + ch, ok := t.inflightRequest[seq] t.inflightRequestLock.Unlock() + if !ok || ch == nil { + continue + } + + h := Hop{ + Success: true, + Address: msg.Peer, + } + // 非阻塞发送,避免重复回包把缓冲塞满导致阻塞 + select { + case ch <- h: + default: + // 丢弃重复/迟到的相同 seq 回包,避免阻塞 + } } } } @@ -210,24 +261,34 @@ func (t *TCPTracerIPv6) handleICMPMessage(msg ReceivedMessage, data []byte) { if err != nil { return } - + // 取出通道后立刻解锁 t.inflightRequestLock.Lock() - defer t.inflightRequestLock.Unlock() - ch, ok := t.inflightRequest[int(seq)] - if !ok { + t.inflightRequestLock.Unlock() + if !ok || ch == nil { return } - ch <- Hop{ + h := Hop{ Success: true, Address: msg.Peer, } + // 非阻塞发送,避免重复回包把缓冲塞满导致阻塞 + select { + case ch <- h: + default: + // 丢弃重复/迟到的相同 seq 回包,避免阻塞 + } } -func (t *TCPTracerIPv6) send(ttl, seq int) error { +func (t *TCPTracerIPv6) send(ttl, i int) error { defer t.wg.Done() + if t.ttlComp(ttl) { + // 快路径短路:若该 TTL 已完成,直接返回避免竞争信号量与无谓发包 + return nil + } + if err := t.sem.Acquire(t.ctx, 1); err != nil { return err } @@ -237,6 +298,13 @@ func (t *TCPTracerIPv6) send(ttl, seq int) error { return nil } + if t.ttlComp(ttl) { + // 竞态兜底:获取信号量期间可能已完成,再次检查以避免冗余发包 + return nil + } + // 将 TTL 编码到高 8 位;将索引 i 编码到低 24 位 + seq := (ttl << 24) | (i & 0xFFFFFF) + t.inflightRequestLock.Lock() hopCh := make(chan Hop, 1) t.inflightRequest[seq] = hopCh @@ -332,19 +400,20 @@ func (t *TCPTracerIPv6) send(ttl, seq int) error { return err } - t.res.add(h) + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) case <-time.After(t.Timeout): if t.final != -1 && ttl > t.final { return nil } - t.res.add(Hop{ + h := Hop{ Success: false, Address: nil, TTL: ttl, RTT: 0, Error: ErrHopLimitTimeout, - }) + } + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) } return nil } diff --git a/trace/trace.go b/trace/trace.go index 3df1d2b..25098eb 100644 --- a/trace/trace.go +++ b/trace/trace.go @@ -3,6 +3,7 @@ package trace import ( "errors" "fmt" + "log" "net" "strconv" "strings" @@ -27,6 +28,7 @@ type Config struct { BeginHop int MaxHops int NumMeasurements int + MaxAttempts int ParallelRequests int Timeout time.Duration DestIP net.IP @@ -70,6 +72,26 @@ func Traceroute(method Method, config Config) (*Result, error) { if config.ParallelRequests == 0 { config.ParallelRequests = config.NumMeasurements * 5 } + // 若 CLI 未给或给了非正数,则尝试用环境变量 + if config.MaxAttempts <= 0 && util.EnvMaxAttempts != "" { + if env, err := strconv.Atoi(util.EnvMaxAttempts); err == nil { + config.MaxAttempts = env + } else { + log.Printf("ignore invalid NEXTTRACE_MAXATTEMPTS=%q: %v", util.EnvMaxAttempts, err) + } + } + + if config.MaxAttempts <= 0 || config.MaxAttempts < config.NumMeasurements { + n := config.NumMeasurements + switch { + case n <= 2 || n >= 10: + config.MaxAttempts = n // 1–2 或 ≥10 → 等于 n + case n <= 6: + config.MaxAttempts = n + 3 // 3–6 → n+3 + default: + config.MaxAttempts = 10 // 7–9 → 10 + } + } switch method { case ICMPTrace: @@ -107,15 +129,66 @@ type Result struct { TraceMapUrl string } -func (s *Result) add(hop Hop) { +// 判定 Hop 是否“有效” +func isValidHop(h Hop) bool { + return h.Success && h.Address != nil +} + +// 新版 add:带审计/限容 +// - N = numMeasurements(每个 TTL 组的最小输出条数) +// - M = maxAttempts(每个 TTL 组的最大尝试条数) +// 规则:前 N-1 条无条件放行;第 N 条进行审计(已有有效 / 当次有效 / 达到最后一次尝试 任一成立即放行);超过 N 条一律忽略 +func (s *Result) add(hop Hop, attemptIdx, numMeasurements, maxAttempts int) { s.lock.Lock() defer s.lock.Unlock() + + k := hop.TTL - 1 + for len(s.Hops) <= k { + s.Hops = append(s.Hops, make([]Hop, 0)) + } + bucket := s.Hops[k] + + n := numMeasurements + + switch { + case len(bucket) < n-1: + // 前 N-1:无条件放行 + s.Hops[k] = append(bucket, hop) + return + case len(bucket) == n-1: + // 正在决定第 N 条:审计 + // 放行条件(三选一): + // 1) 前 N-1 中已存在有效值;或 + // 2) 当前 hop 为有效值;或 + // 3) 已到最后一次尝试 + hasValid := false + for _, h := range bucket { + if isValidHop(h) { + hasValid = true + break + } + } + if hasValid || isValidHop(hop) || (attemptIdx+1 >= maxAttempts) { + s.Hops[k] = append(bucket, hop) // 填满第 N 个 + } + // 否则丢弃,等待后续更优候选(长度仍保持 N-1) + return + default: + // 已经有 N 条:忽略后续尝试 + return + } +} + +// 旧版 addLegacy +func (s *Result) addLegacy(hop Hop) { + s.lock.Lock() + defer s.lock.Unlock() + k := hop.TTL - 1 for len(s.Hops) < hop.TTL { s.Hops = append(s.Hops, make([]Hop, 0)) } s.Hops[k] = append(s.Hops[k], hop) - } func (s *Result) reduce(final int) { diff --git a/trace/udp_ipv4.go b/trace/udp_ipv4.go index c2b95b8..bc4a33e 100644 --- a/trace/udp_ipv4.go +++ b/trace/udp_ipv4.go @@ -1,6 +1,7 @@ package trace import ( + "errors" "log" "math/rand" "net" @@ -58,20 +59,32 @@ func (t *UDPTracer) PrintFunc() { } } +func (t *UDPTracer) ttlComp(ttl int) bool { + idx := ttl - 1 + t.res.lock.Lock() + defer t.res.lock.Unlock() + return idx < len(t.res.Hops) && len(t.res.Hops[idx]) >= t.NumMeasurements +} + func (t *UDPTracer) launchTTL(ttl int) { go func(ttl int) { - for i := 0; i < t.NumMeasurements; i++ { - // 将 TTL 编码到高 8 位;将索引 i 编码到低 8 位 - seq := (ttl << 8) | (i & 0xFF) - + for i := 0; i < t.MaxAttempts; i++ { + // 若此 TTL 已完成,则不再发起新的尝试 + if t.ttlComp(ttl) { + return + } t.wg.Add(1) - go t.send(ttl, seq) + go func(ttl, i int) { + if err := t.send(ttl, i); err != nil { + log.Printf("send failed: ttl=%d i=%d: %v", ttl, i, err) + } + }(ttl, i) <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) } }(ttl) } -func (t *UDPTracer) Execute() (*Result, error) { +func (t *UDPTracer) Execute() (res *Result, err error) { // 初始化 inflightRequest map t.inflightRequestLock.Lock() t.inflightRequest = make(map[int]chan Hop) @@ -83,8 +96,6 @@ func (t *UDPTracer) Execute() (*Result, error) { t.SrcIP, _ = util.LocalIPPort(t.DestIP) - var err error - if t.SrcAddr != "" { t.udp, err = net.ListenPacket("ip4:udp", t.SrcAddr) } else { @@ -93,7 +104,11 @@ func (t *UDPTracer) Execute() (*Result, error) { if err != nil { return nil, err } - defer t.udp.Close() + defer func() { + if c := t.udp; c != nil { // 先拷一份引用,避免 defer 执行时 t.udp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() t.udpConn, err = ipv4.NewRawConn(t.udp) if err != nil { @@ -104,7 +119,11 @@ func (t *UDPTracer) Execute() (*Result, error) { if err != nil { return &t.res, err } - defer t.icmp.Close() + defer func() { + if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() var cancel context.CancelFunc t.ctx, cancel = context.WithCancel(context.Background()) @@ -190,24 +209,34 @@ func (t *UDPTracer) handleICMPMessage(msg ReceivedMessage, data []byte) { if err != nil { return } - + // 取出通道后立刻解锁 t.inflightRequestLock.Lock() - defer t.inflightRequestLock.Unlock() - ch, ok := t.inflightRequest[int(seq)] - if !ok { + t.inflightRequestLock.Unlock() + if !ok || ch == nil { return } - ch <- Hop{ + h := Hop{ Success: true, Address: msg.Peer, } + // 非阻塞发送,避免重复回包把缓冲塞满导致阻塞 + select { + case ch <- h: + default: + // 丢弃重复/迟到的相同 seq 回包,避免阻塞 + } } -func (t *UDPTracer) send(ttl, seq int) error { +func (t *UDPTracer) send(ttl, i int) error { defer t.wg.Done() + if t.ttlComp(ttl) { + // 快路径短路:若该 TTL 已完成,直接返回避免竞争信号量与无谓发包 + return nil + } + if err := t.sem.Acquire(t.ctx, 1); err != nil { return err } @@ -217,6 +246,13 @@ func (t *UDPTracer) send(ttl, seq int) error { return nil } + if t.ttlComp(ttl) { + // 竞态兜底:获取信号量期间可能已完成,再次检查以避免冗余发包 + return nil + } + // 将 TTL 编码到高 8 位;将索引 i 编码到低 8 位 + seq := (ttl << 8) | (i & 0xFF) + t.inflightRequestLock.Lock() hopCh := make(chan Hop, 1) t.inflightRequest[seq] = hopCh @@ -322,19 +358,20 @@ func (t *UDPTracer) send(ttl, seq int) error { return err } - t.res.add(h) + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) case <-time.After(t.Timeout): if t.final != -1 && ttl > t.final { return nil } - t.res.add(Hop{ + h := Hop{ Success: false, Address: nil, TTL: ttl, RTT: 0, Error: ErrHopLimitTimeout, - }) + } + t.res.add(h, i, t.NumMeasurements, t.MaxAttempts) } return nil } diff --git a/trace/udp_ipv6.go b/trace/udp_ipv6.go index 146df8d..63c086e 100644 --- a/trace/udp_ipv6.go +++ b/trace/udp_ipv6.go @@ -1,6 +1,7 @@ package trace import ( + "errors" "log" "math/rand" "net" @@ -37,7 +38,29 @@ type UDPTracerIPv6 struct { udpMutex sync.Mutex } -func (t *UDPTracerIPv6) Execute() (*Result, error) { +func (t *UDPTracerIPv6) PrintFunc() { + defer t.wg.Done() + ttl := t.Config.BeginHop - 1 + for { + if t.AsyncPrinter != nil { + t.AsyncPrinter(&t.res) + } + // 接收的时候检查一下是不是 3 跳都齐了 + if ttl < len(t.res.Hops) && + len(t.res.Hops[ttl]) == t.NumMeasurements { + if t.RealtimePrinter != nil { + t.RealtimePrinter(&t.res, ttl) + } + ttl++ + if ttl == t.final || ttl >= t.MaxHops { + return + } + } + <-time.After(200 * time.Millisecond) + } +} + +func (t *UDPTracerIPv6) Execute() (res *Result, err error) { // 初始化 inflightRequest map t.inflightRequestLock.Lock() t.inflightRequest = make(map[int]chan Hop) @@ -49,8 +72,6 @@ func (t *UDPTracerIPv6) Execute() (*Result, error) { t.SrcIP, _ = util.LocalIPPortv6(t.DestIP) - var err error - if t.SrcAddr != "" { t.udp, err = net.ListenPacket("ip6:udp", t.SrcAddr) } else { @@ -59,7 +80,11 @@ func (t *UDPTracerIPv6) Execute() (*Result, error) { if err != nil { return nil, err } - defer t.udp.Close() + defer func() { + if c := t.udp; c != nil { // 先拷一份引用,避免 defer 执行时 t.udp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() t.udpConn = ipv6.NewPacketConn(t.udp) @@ -67,7 +92,11 @@ func (t *UDPTracerIPv6) Execute() (*Result, error) { if err != nil { return &t.res, err } - defer t.icmp.Close() + defer func() { + if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写 + err = errors.Join(err, c.Close()) + } + }() var cancel context.CancelFunc t.ctx, cancel = context.WithCancel(context.Background()) @@ -76,6 +105,8 @@ func (t *UDPTracerIPv6) Execute() (*Result, error) { t.final = -1 go t.listenICMP() + t.wg.Add(1) + go t.PrintFunc() t.sem = semaphore.NewWeighted(int64(t.ParallelRequests)) @@ -86,28 +117,16 @@ func (t *UDPTracerIPv6) Execute() (*Result, error) { } for i := 0; i < t.NumMeasurements; i++ { t.wg.Add(1) - go t.send(ttl) + go func(ttl int) { + if err := t.send(ttl); err != nil { + log.Printf("send failed: ttl=%d: %v", ttl, err) + } + }(ttl) <-time.After(time.Millisecond * time.Duration(t.Config.PacketInterval)) } - if t.RealtimePrinter != nil { - // 对于实时模式,应该按照TTL进行并发请求 - t.wg.Wait() - t.RealtimePrinter(&t.res, ttl-1) - } <-time.After(time.Millisecond * time.Duration(t.Config.TTLInterval)) } - go func() { - if t.AsyncPrinter != nil { - for { - t.AsyncPrinter(&t.res) - time.Sleep(200 * time.Millisecond) - } - } - }() - // 如果是表格模式,则一次性并发请求 - if t.RealtimePrinter == nil { - t.wg.Wait() - } + t.wg.Wait() t.res.reduce(t.final) return &t.res, nil @@ -179,19 +198,24 @@ func (t *UDPTracerIPv6) handleICMPMessage(msg ReceivedMessage) { origUDP := udpLayer.(*layers.UDP) SrcPort := int(origUDP.SrcPort) - + // 取出通道后立刻解锁 t.inflightRequestLock.Lock() - defer t.inflightRequestLock.Unlock() - ch, ok := t.inflightRequest[SrcPort] - if !ok { + t.inflightRequestLock.Unlock() + if !ok || ch == nil { return } - ch <- Hop{ + h := Hop{ Success: true, Address: msg.Peer, } + // 非阻塞发送,避免重复回包把缓冲塞满导致阻塞 + select { + case ch <- h: + default: + // 丢弃重复/迟到的相同 icmp 回包,避免阻塞 + } } func (t *UDPTracerIPv6) send(ttl int) error { @@ -304,19 +328,20 @@ func (t *UDPTracerIPv6) send(ttl int) error { return err } - t.res.add(h) + t.res.addLegacy(h) case <-time.After(t.Timeout): if t.final != -1 && ttl > t.final { return nil } - t.res.add(Hop{ + h := Hop{ Success: false, Address: nil, TTL: ttl, RTT: 0, Error: ErrHopLimitTimeout, - }) + } + t.res.addLegacy(h) } return nil } diff --git a/util/util.go b/util/util.go index 2812581..90b5b7a 100644 --- a/util/util.go +++ b/util/util.go @@ -19,6 +19,7 @@ import ( var DisableMPLS = GetenvDefault("NEXTTRACE_DISABLEMPLS", "") var EnableHidDstIP = GetenvDefault("NEXTTRACE_ENABLEHIDDENDSTIP", "") var EnvIPInfoLocalPath = GetenvDefault("NEXTTRACE_IPINFOLOCALPATH", "") +var EnvMaxAttempts = GetenvDefault("NEXTTRACE_MAXATTEMPTS", "") var EnvRandomPort = GetenvDefault("NEXTTRACE_RANDOMPORT", "") var EnvToken = GetenvDefault("NEXTTRACE_TOKEN", "") var Uninterrupted = GetenvDefault("NEXTTRACE_UNINTERRUPTED", "")