mirror of
https://github.com/nxtrace/NTrace-core.git
synced 2026-12-01 17:02:33 +00:00
Use ICMP response semantics instead of source-address equality to detect transit, destination, and unreachable replies. Keep tracing when any ECMP path returns a transit response, expose structured stop reasons, and preserve raw and JSON output behavior.
69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package internal
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"net"
|
|
"time"
|
|
|
|
"github.com/nxtrace/NTrace-core/util"
|
|
)
|
|
|
|
func NewUDPSpec(IPVersion, ICMPMode int, srcIP, dstIP net.IP, dstPort int) *UDPSpec {
|
|
return &UDPSpec{IPVersion: IPVersion, ICMPMode: ICMPMode, SrcIP: srcIP, DstIP: dstIP, DstPort: dstPort}
|
|
}
|
|
|
|
func (s *UDPSpec) InitICMP() {
|
|
network := "ip4:icmp"
|
|
if s.IPVersion == 6 {
|
|
network = "ip6:ipv6-icmp"
|
|
}
|
|
|
|
icmpConn, err := net.ListenPacket(network, s.SrcIP.String())
|
|
if err != nil {
|
|
if util.EnvDevMode {
|
|
panic(fmt.Errorf("(InitICMP) ListenPacket(%s, %s) failed: %v", network, s.SrcIP, err))
|
|
}
|
|
log.Fatalf("(InitICMP) ListenPacket(%s, %s) failed: %v", network, s.SrcIP, err)
|
|
}
|
|
s.icmp = icmpConn
|
|
}
|
|
|
|
func (s *UDPSpec) listenICMPSock(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, data []byte)) {
|
|
lc := NewPacketListener(s.icmp)
|
|
go lc.Start(ctx)
|
|
close(ready)
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case msg, ok := <-lc.Messages:
|
|
if !ok {
|
|
return
|
|
}
|
|
finish, data, response, ok := s.decodeICMPSocketMessage(msg)
|
|
if ok {
|
|
msg.ICMP = response
|
|
onICMP(msg, finish, data)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *UDPSpec) decodeICMPSocketMessage(msg ReceivedMessage) (time.Time, []byte, ICMPResponse, bool) {
|
|
if msg.Err != nil {
|
|
return time.Time{}, nil, ICMPResponse{}, false
|
|
}
|
|
|
|
finish := time.Now()
|
|
rm, ok := parseSocketICMPMessage(s.IPVersion, msg.Msg)
|
|
if !ok {
|
|
return finish, nil, ICMPResponse{}, false
|
|
}
|
|
|
|
data, ok := extractSocketICMPPayload(s.IPVersion, rm, s.DstIP)
|
|
return finish, data, classifySocketICMPResponse(s.IPVersion, rm, msg.Msg), ok
|
|
}
|