mirror of
https://github.com/nxtrace/NTrace-core.git
synced 2026-12-05 10:47:35 +00:00
30 files changed
+2067
-1144
No files matched your search
+13
-19
@@ -44,11 +44,12 @@ func PrepareWinDivertRuntime() error {
|
||||
}
|
||||
|
||||
// DLL
|
||||
if err := writeIfChecksumDiff(filepath.Join(exeDir, "WinDivert.dll"), dllBytes); err != nil {
|
||||
if err = writeIfChecksumDiff(filepath.Join(exeDir, "WinDivert.dll"), dllBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// SYS
|
||||
if err := writeIfChecksumDiff(filepath.Join(exeDir, sysName), sysBytes); err != nil {
|
||||
if err = writeIfChecksumDiff(filepath.Join(exeDir, sysName), sysBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -56,29 +57,22 @@ func PrepareWinDivertRuntime() error {
|
||||
|
||||
// writeIfChecksumDiff 通过比较 SHA-256 来判断是否覆写目标文件
|
||||
func writeIfChecksumDiff(dst string, data []byte) error {
|
||||
f, err := os.Open(dst)
|
||||
file, err := os.Open(dst)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return os.WriteFile(dst, data, 0o644)
|
||||
}
|
||||
// 读失败,则尝试覆盖
|
||||
return os.WriteFile(dst, data, 0o644)
|
||||
return os.WriteFile(dst, data, 0o644) // 读失败,则尝试覆盖
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
// 读失败,则尝试覆盖
|
||||
return os.WriteFile(dst, data, 0o644)
|
||||
hash := sha256.New()
|
||||
if _, err = io.Copy(hash, file); err != nil {
|
||||
_ = file.Close() // 先关再写,避免 Windows 共享冲突
|
||||
return os.WriteFile(dst, data, 0o644) // 读失败,则尝试覆盖
|
||||
}
|
||||
sumFile := h.Sum(nil)
|
||||
|
||||
sumFile := hash.Sum(nil)
|
||||
_ = file.Close() // 先关再写,避免 Windows 共享冲突
|
||||
sumMem := sha256.Sum256(data)
|
||||
|
||||
if bytes.Equal(sumFile, sumMem[:]) {
|
||||
return nil // 一致,跳过
|
||||
}
|
||||
// 不一致,则尝试覆盖
|
||||
return os.WriteFile(dst, data, 0o644)
|
||||
return os.WriteFile(dst, data, 0o644) // 不一致,则尝试覆盖
|
||||
}
|
||||
+10
-7
@@ -40,6 +40,7 @@ func Execute() {
|
||||
udp := parser.Flag("U", "udp", &argparse.Options{Help: "Use UDP SYN for tracerouting (default port is 33494)"})
|
||||
fast_trace := parser.Flag("F", "fast-trace", &argparse.Options{Help: "One-Key Fast Trace to China ISPs"})
|
||||
port := parser.Int("p", "port", &argparse.Options{Help: "Set the destination port to use. With default of 80 for \"tcp\", 33494 for \"udp\"", Default: 0})
|
||||
icmpMode := parser.Int("", "icmp-mode", &argparse.Options{Help: "Choose the method to listen for ICMP packets (1=Socket, 2=PCAP; 0=Auto)"})
|
||||
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)"})
|
||||
@@ -61,7 +62,7 @@ func Execute() {
|
||||
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"})
|
||||
ver := parser.Flag("V", "version", &argparse.Options{Help: "Print version info and exit"})
|
||||
srcAddr := parser.String("s", "source", &argparse.Options{Help: "Use source address src_addr for outgoing packets"})
|
||||
srcPort := parser.Int("", "source-port", &argparse.Options{Help: "Use source port src_port for outgoing packets"})
|
||||
srcDev := parser.String("D", "dev", &argparse.Options{Help: "Use the following Network Devices as the source address in outgoing packets"})
|
||||
@@ -101,15 +102,15 @@ func Execute() {
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
OSKind := 3
|
||||
OSType := 3
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
OSKind = 1
|
||||
OSType = 1
|
||||
case "windows":
|
||||
OSKind = 2
|
||||
OSType = 2
|
||||
}
|
||||
|
||||
if *init && OSKind == 2 {
|
||||
if *init && OSType == 2 {
|
||||
if err := windivert.PrepareWinDivertRuntime(); err != nil {
|
||||
if util.EnvDevMode {
|
||||
panic(err)
|
||||
@@ -153,7 +154,8 @@ func Execute() {
|
||||
|
||||
if *fast_trace || *file != "" {
|
||||
var paramsFastTrace = fastTrace.ParamsFastTrace{
|
||||
OSKind: OSKind,
|
||||
OSType: OSType,
|
||||
ICMPMode: *icmpMode,
|
||||
SrcDev: *srcDev,
|
||||
SrcAddr: *srcAddr,
|
||||
DstPort: *port,
|
||||
@@ -282,7 +284,8 @@ func Execute() {
|
||||
util.SrcPort = *srcPort
|
||||
util.DstIP = ip.String()
|
||||
var conf = trace.Config{
|
||||
OSKind: OSKind,
|
||||
OSType: OSType,
|
||||
ICMPMode: *icmpMode,
|
||||
DN42: *dn42,
|
||||
SrcAddr: *srcAddr,
|
||||
SrcPort: *srcPort,
|
||||
|
||||
@@ -29,7 +29,8 @@ func (f *FastTracer) tracert_v6(location string, ispCollection ISPCollection) {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var conf = trace.Config{
|
||||
OSKind: f.ParamsFastTrace.OSKind,
|
||||
OSType: f.ParamsFastTrace.OSType,
|
||||
ICMPMode: f.ParamsFastTrace.ICMPMode,
|
||||
BeginHop: f.ParamsFastTrace.BeginHop,
|
||||
DstIP: ip,
|
||||
DstPort: f.ParamsFastTrace.DstPort,
|
||||
|
||||
@@ -26,7 +26,8 @@ type FastTracer struct {
|
||||
}
|
||||
|
||||
type ParamsFastTrace struct {
|
||||
OSKind int
|
||||
OSType int
|
||||
ICMPMode int
|
||||
SrcDev string
|
||||
SrcAddr string
|
||||
DstPort int
|
||||
@@ -59,7 +60,8 @@ func (f *FastTracer) tracert(location string, ispCollection ISPCollection) {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var conf = trace.Config{
|
||||
OSKind: f.ParamsFastTrace.OSKind,
|
||||
OSType: f.ParamsFastTrace.OSType,
|
||||
ICMPMode: f.ParamsFastTrace.ICMPMode,
|
||||
BeginHop: f.ParamsFastTrace.BeginHop,
|
||||
DstIP: ip,
|
||||
DstPort: f.ParamsFastTrace.DstPort,
|
||||
@@ -340,7 +342,8 @@ func testFile(paramsFastTrace ParamsFastTrace, traceMode trace.Method) {
|
||||
}
|
||||
|
||||
var conf = trace.Config{
|
||||
OSKind: paramsFastTrace.OSKind,
|
||||
OSType: paramsFastTrace.OSType,
|
||||
ICMPMode: paramsFastTrace.ICMPMode,
|
||||
BeginHop: paramsFastTrace.BeginHop,
|
||||
DstIP: net.ParseIP(ip.Ip),
|
||||
DstPort: paramsFastTrace.DstPort,
|
||||
|
||||
@@ -18,6 +18,7 @@ require (
|
||||
github.com/xjasonlyu/windivert-go v0.0.0-20201010013527-4239d0afa76f
|
||||
golang.org/x/net v0.44.0
|
||||
golang.org/x/sync v0.17.0
|
||||
golang.org/x/sys v0.36.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -37,7 +38,6 @@ require (
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
+2
-2
@@ -107,8 +107,8 @@ var receiveParseOnce sync.Once
|
||||
func LeoIP(ip string, timeout time.Duration, lang string, maptrace bool) (*IPGeoData, error) {
|
||||
// TODO: 根据lang的值请求中文/英文API
|
||||
// TODO: 根据maptrace的值决定是否请求经纬度信息
|
||||
if timeout < 5*time.Second {
|
||||
timeout = 5 * time.Second
|
||||
if timeout < 2*time.Second {
|
||||
timeout = 2 * time.Second
|
||||
}
|
||||
|
||||
// 确保对应 IP 的通道已存在(读锁快速路径 + 写锁惰性创建)
|
||||
|
||||
+251
-231
@@ -1,9 +1,7 @@
|
||||
package trace
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"log"
|
||||
"math/rand"
|
||||
@@ -15,8 +13,7 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace/internal"
|
||||
@@ -25,17 +22,34 @@ import (
|
||||
|
||||
type ICMPTracer struct {
|
||||
Config
|
||||
wg sync.WaitGroup
|
||||
res Result
|
||||
echoIDTag uint8
|
||||
pidLow uint8
|
||||
inflightRequest map[int]chan Hop
|
||||
inflightRequestLock sync.RWMutex
|
||||
icmp net.PacketConn
|
||||
icmpConn *ipv4.PacketConn
|
||||
hopLimitLock sync.Mutex
|
||||
final atomic.Int32
|
||||
sem *semaphore.Weighted
|
||||
wg sync.WaitGroup
|
||||
res Result
|
||||
echoID int
|
||||
pending map[int]struct{}
|
||||
pendingMu sync.Mutex
|
||||
sentAt map[int]time.Time
|
||||
sentMu sync.RWMutex
|
||||
SrcIP net.IP
|
||||
final atomic.Int32
|
||||
sem *semaphore.Weighted
|
||||
matchQ chan matchTask
|
||||
readyICMP chan struct{}
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) waitAllReady(ctx context.Context) {
|
||||
timeout := time.After(5 * time.Second)
|
||||
waiting := 1
|
||||
for waiting > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.readyICMP:
|
||||
waiting--
|
||||
case <-timeout:
|
||||
return
|
||||
}
|
||||
}
|
||||
<-time.After(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) ttlComp(ttl int) bool {
|
||||
@@ -77,7 +91,7 @@ func (t *ICMPTracer) PrintFunc(ctx context.Context, cancel context.CancelCauseFu
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) launchTTL(ctx context.Context, ttl int) {
|
||||
func (t *ICMPTracer) launchTTL(ctx context.Context, s *internal.ICMPSpec, ttl int) {
|
||||
go func(ttl int) {
|
||||
for i := 0; i < t.MaxAttempts; i++ {
|
||||
// 若此 TTL 已完成或 ctx 已取消,则不再发起新的尝试
|
||||
@@ -87,7 +101,7 @@ func (t *ICMPTracer) launchTTL(ctx context.Context, ttl int) {
|
||||
|
||||
t.wg.Add(1)
|
||||
go func(ttl, i int) {
|
||||
if err := t.send(ctx, ttl, i); err != nil && !errors.Is(err, context.Canceled) {
|
||||
if err := t.send(ctx, s, ttl, i); err != nil && !errors.Is(err, context.Canceled) {
|
||||
if util.EnvDevMode {
|
||||
panic(err)
|
||||
}
|
||||
@@ -105,23 +119,148 @@ func (t *ICMPTracer) launchTTL(ctx context.Context, ttl int) {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
// 生成一个 8 位的随机 tag
|
||||
echoIDTag := r.Intn(256)
|
||||
|
||||
// 获取当前进程的 pid
|
||||
pid := os.Getpid()
|
||||
|
||||
// 将随机 tag 编码到高 8 位;将 pid 的低 8 位编码到低 8 位
|
||||
t.echoID = (echoIDTag << 8) | (pid & 0xFF)
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) markPending(seq int) {
|
||||
t.pendingMu.Lock()
|
||||
defer t.pendingMu.Unlock()
|
||||
t.pending[seq] = struct{}{}
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) clearPending(seq int) bool {
|
||||
t.pendingMu.Lock()
|
||||
defer t.pendingMu.Unlock()
|
||||
_, ok := t.pending[seq]
|
||||
delete(t.pending, seq)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) storeSent(seq int, start time.Time) {
|
||||
t.sentMu.Lock()
|
||||
defer t.sentMu.Unlock()
|
||||
t.sentAt[seq] = start
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) lookupSent(seq int) (start time.Time, ok bool) {
|
||||
t.sentMu.RLock()
|
||||
defer t.sentMu.RUnlock()
|
||||
start, ok = t.sentAt[seq]
|
||||
if !ok {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return start, true
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) dropSent(seq int) {
|
||||
t.sentMu.Lock()
|
||||
defer t.sentMu.Unlock()
|
||||
delete(t.sentAt, seq)
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) addHopWithIndex(peer net.Addr, ttl, i int, rtt time.Duration, mpls []string) {
|
||||
if f := t.final.Load(); f != -1 && ttl > int(f) {
|
||||
return
|
||||
}
|
||||
|
||||
if ip := util.AddrIP(peer); ip != nil && ip.Equal(t.DstIP) {
|
||||
for {
|
||||
old := t.final.Load()
|
||||
if old != -1 && ttl >= int(old) {
|
||||
break
|
||||
}
|
||||
if t.final.CompareAndSwap(old, int32(ttl)) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
h := Hop{
|
||||
Success: true,
|
||||
Address: peer,
|
||||
TTL: ttl,
|
||||
RTT: rtt,
|
||||
MPLS: mpls,
|
||||
}
|
||||
|
||||
_ = h.fetchIPData(t.Config) // 忽略错误,继续添加结果
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) matchWorker(ctx context.Context) {
|
||||
defer t.wg.Done()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case task, ok := <-t.matchQ:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// 固定等待 10ms,缓解登记竞态
|
||||
timer := time.NewTimer(10 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
timer.Stop()
|
||||
|
||||
// 尝试一次匹配
|
||||
start, ok := t.lookupSent(task.seq)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
// 将 task.seq 转为 16 位无符号数
|
||||
u := uint16(task.seq)
|
||||
|
||||
// 高 8 位是 TTL
|
||||
ttl := int((u >> 8) & 0xFF)
|
||||
|
||||
// 低 8 位是索引 i
|
||||
i := int(u & 0xFF)
|
||||
|
||||
if t.clearPending(task.seq) {
|
||||
rtt := task.finish.Sub(start)
|
||||
t.addHopWithIndex(task.peer, ttl, i, rtt, task.mpls)
|
||||
}
|
||||
t.dropSent(task.seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) Execute() (res *Result, err error) {
|
||||
// 初始化 Echo.ID
|
||||
t.initEchoID()
|
||||
|
||||
// 初始化 inflightRequest map
|
||||
t.inflightRequest = make(map[int]chan Hop)
|
||||
// 初始化 pending、sentAt 和 matchQ
|
||||
t.pending = make(map[int]struct{})
|
||||
t.sentAt = make(map[int]time.Time)
|
||||
t.matchQ = make(chan matchTask, 60)
|
||||
|
||||
// 创建就绪通道
|
||||
t.readyICMP = make(chan struct{})
|
||||
|
||||
if len(t.res.Hops) > 0 {
|
||||
return &t.res, errTracerouteExecuted
|
||||
}
|
||||
|
||||
// 初始化 Result.Hops,并预分配到 MaxHops
|
||||
// 初始化 res.Hops 和 res.tailDone,并预分配到 MaxHops
|
||||
t.res.Hops = make([][]Hop, t.MaxHops)
|
||||
t.res.tailDone = make([]bool, t.MaxHops)
|
||||
|
||||
@@ -130,28 +269,40 @@ func (t *ICMPTracer) Execute() (res *Result, err error) {
|
||||
if t.SrcAddr != "" && SrcAddr == nil {
|
||||
return nil, errors.New("invalid IPv4 SrcAddr:" + t.SrcAddr)
|
||||
}
|
||||
SrcIP := ""
|
||||
if SrcAddr != nil {
|
||||
SrcIP = SrcAddr.String()
|
||||
t.SrcIP, _ = util.LocalIPPort(t.DstIP, SrcAddr, "icmp")
|
||||
if t.SrcIP == nil {
|
||||
return nil, errors.New("cannot determine local IPv4 address")
|
||||
}
|
||||
|
||||
t.icmp, err = internal.ListenPacket("ip4:icmp", SrcIP)
|
||||
if err != nil {
|
||||
return &t.res, err
|
||||
}
|
||||
defer func() {
|
||||
if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
t.icmpConn = ipv4.NewPacketConn(t.icmp)
|
||||
s := internal.NewICMPSpec(
|
||||
4,
|
||||
t.ICMPMode,
|
||||
t.echoID,
|
||||
t.SrcIP,
|
||||
t.DstIP,
|
||||
)
|
||||
|
||||
s.InitICMP()
|
||||
defer s.Close()
|
||||
|
||||
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
ctx, cancel := context.WithCancelCause(sigCtx)
|
||||
t.final.Store(-1)
|
||||
|
||||
workerN := 16
|
||||
for i := 0; i < workerN; i++ {
|
||||
t.wg.Add(1)
|
||||
go t.matchWorker(ctx)
|
||||
}
|
||||
t.wg.Add(1)
|
||||
go t.listenICMP(ctx)
|
||||
go func() {
|
||||
defer t.wg.Done()
|
||||
s.ListenICMP(ctx, t.readyICMP, func(msg internal.ReceivedMessage, finish time.Time, seq int) {
|
||||
t.handleICMPMessage(msg, finish, seq)
|
||||
},
|
||||
)
|
||||
}()
|
||||
t.waitAllReady(ctx)
|
||||
t.wg.Add(1)
|
||||
go t.PrintFunc(ctx, cancel)
|
||||
|
||||
@@ -161,7 +312,7 @@ func (t *ICMPTracer) Execute() (res *Result, err error) {
|
||||
go func() {
|
||||
defer t.wg.Done()
|
||||
// 立即启动 BeginHop 对应的 TTL 组
|
||||
t.launchTTL(ctx, t.BeginHop)
|
||||
t.launchTTL(ctx, s, t.BeginHop)
|
||||
|
||||
for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ {
|
||||
// 之后按 TTLInterval 周期启动后续 TTL 组
|
||||
@@ -177,7 +328,7 @@ func (t *ICMPTracer) Execute() (res *Result, err error) {
|
||||
}
|
||||
|
||||
// 并发启动这个 TTL 的所有测量
|
||||
t.launchTTL(ctx, ttl)
|
||||
t.launchTTL(ctx, s, ttl)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -185,11 +336,11 @@ func (t *ICMPTracer) Execute() (res *Result, err error) {
|
||||
stop()
|
||||
t.wg.Wait()
|
||||
|
||||
bound := int(t.final.Load())
|
||||
if bound == -1 {
|
||||
bound = t.MaxHops
|
||||
final := int(t.final.Load())
|
||||
if final == -1 {
|
||||
final = t.MaxHops
|
||||
}
|
||||
t.res.reduce(bound)
|
||||
t.res.reduce(final)
|
||||
|
||||
if cause := context.Cause(ctx); !errors.Is(cause, errNaturalDone) {
|
||||
return &t.res, cause
|
||||
@@ -197,120 +348,20 @@ func (t *ICMPTracer) Execute() (res *Result, err error) {
|
||||
return &t.res, nil
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) listenICMP(ctx context.Context) {
|
||||
defer t.wg.Done()
|
||||
lc := internal.NewPacketListener(t.icmp)
|
||||
go lc.Start(ctx)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case msg, ok := <-lc.Messages:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
rm, err := icmp.ParseMessage(1, msg.Msg)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
var (
|
||||
data []byte
|
||||
)
|
||||
switch rm.Type {
|
||||
case ipv4.ICMPTypeEchoReply:
|
||||
echo, ok := rm.Body.(*icmp.Echo)
|
||||
if !ok || echo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// 只在 Peer 是目的地址时分发,用 seq 作为通道 key
|
||||
if ip := util.AddrIP(msg.Peer); ip != nil && ip.Equal(t.DstIP) {
|
||||
id := uint16(echo.ID)
|
||||
if uint8(id>>8) != t.echoIDTag || uint8(id&0xFF) != t.pidLow {
|
||||
continue
|
||||
}
|
||||
// 从 Echo.Seq 恢复出先前编码的 (ttl<<8)|index
|
||||
seq := echo.Seq
|
||||
// 高 8 位是真正的 TTL
|
||||
ttl := seq >> 8
|
||||
// TTL 越界时舍弃
|
||||
if ttl < t.BeginHop || ttl > t.MaxHops {
|
||||
continue
|
||||
}
|
||||
t.handleICMPMessage(msg, seq)
|
||||
}
|
||||
continue
|
||||
case ipv4.ICMPTypeTimeExceeded:
|
||||
body, ok := rm.Body.(*icmp.TimeExceeded)
|
||||
if !ok || body == nil {
|
||||
continue
|
||||
}
|
||||
data = body.Data
|
||||
case ipv4.ICMPTypeDestinationUnreachable:
|
||||
body, ok := rm.Body.(*icmp.DstUnreach)
|
||||
if !ok || body == nil {
|
||||
continue
|
||||
}
|
||||
data = body.Data
|
||||
default:
|
||||
continue
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstip := net.IP(data[16:20])
|
||||
if dstip.Equal(t.DstIP) || dstip.Equal(net.IPv4zero) {
|
||||
inner, err := util.GetICMPResponsePayload(data)
|
||||
if err != nil || len(inner) < 8 {
|
||||
continue
|
||||
}
|
||||
id := binary.BigEndian.Uint16(inner[4:6])
|
||||
if uint8(id>>8) != t.echoIDTag || uint8(id&0xFF) != t.pidLow {
|
||||
continue
|
||||
}
|
||||
seq := int(binary.BigEndian.Uint16(inner[6:8]))
|
||||
t.handleICMPMessage(msg, seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) handleICMPMessage(msg internal.ReceivedMessage, seq int) {
|
||||
func (t *ICMPTracer) handleICMPMessage(msg internal.ReceivedMessage, finish time.Time, seq int) {
|
||||
mpls := extractMPLS(msg)
|
||||
|
||||
// 取出通道后立刻解锁
|
||||
t.inflightRequestLock.RLock()
|
||||
ch, ok := t.inflightRequest[seq]
|
||||
t.inflightRequestLock.RUnlock()
|
||||
if !ok || ch == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h := Hop{
|
||||
Success: true,
|
||||
Address: msg.Peer,
|
||||
MPLS: mpls,
|
||||
}
|
||||
|
||||
// 非阻塞发送,避免重复回包把缓冲塞满导致阻塞
|
||||
// 非阻塞投递;如果队列已满则直接丢弃该任务
|
||||
select {
|
||||
case ch <- h:
|
||||
case t.matchQ <- matchTask{
|
||||
seq: seq, peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
}:
|
||||
default:
|
||||
// 丢弃重复/迟到的相同 seq 回包,避免阻塞
|
||||
// 丢弃以避免阻塞抓包循环
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ICMPTracer) send(ctx context.Context, ttl, i int) error {
|
||||
func (t *ICMPTracer) send(ctx context.Context, s *internal.ICMPSpec, ttl, i int) error {
|
||||
defer t.wg.Done()
|
||||
|
||||
if t.ttlComp(ttl) {
|
||||
@@ -335,97 +386,66 @@ func (t *ICMPTracer) send(ctx context.Context, ttl, i int) error {
|
||||
// 将 TTL 编码到高 8 位;将索引 i 编码到低 8 位
|
||||
seq := (ttl << 8) | (i & 0xFF)
|
||||
|
||||
t.inflightRequestLock.Lock()
|
||||
hopCh := make(chan Hop, 1)
|
||||
t.inflightRequest[seq] = hopCh
|
||||
t.inflightRequestLock.Unlock()
|
||||
defer func() {
|
||||
t.inflightRequestLock.Lock()
|
||||
delete(t.inflightRequest, seq)
|
||||
t.inflightRequestLock.Unlock()
|
||||
}()
|
||||
|
||||
// 将随机 tag 编码到高 8 位;将 pid 的低 8 位编码到低 8 位
|
||||
id := int(uint16(t.echoIDTag)<<8 | uint16(t.pidLow))
|
||||
|
||||
var data []byte
|
||||
if t.PktSize < 3 {
|
||||
data = bytes.Repeat([]byte{0}, t.PktSize)
|
||||
} else {
|
||||
data = bytes.Repeat([]byte{0}, t.PktSize-3)
|
||||
data = append(data, 0x6e, 0x74, 0x72) // "ntr" 作为标识
|
||||
ipHeader := &layers.IPv4{
|
||||
Version: 4,
|
||||
SrcIP: t.SrcIP,
|
||||
DstIP: t.DstIP,
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
TTL: uint8(ttl),
|
||||
}
|
||||
|
||||
icmpHeader := icmp.Message{
|
||||
Type: ipv4.ICMPTypeEcho,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: id,
|
||||
Data: data,
|
||||
Seq: seq,
|
||||
},
|
||||
icmpHeader := &layers.ICMPv4{
|
||||
TypeCode: layers.CreateICMPv4TypeCode(layers.ICMPv4TypeEchoRequest, 0),
|
||||
Id: uint16(t.echoID),
|
||||
Seq: uint16(seq),
|
||||
}
|
||||
|
||||
// 串行设置 TTL + 发送,放在同一把锁里保证并发安全
|
||||
t.hopLimitLock.Lock()
|
||||
if err := t.icmpConn.SetTTL(ttl); err != nil {
|
||||
t.hopLimitLock.Unlock()
|
||||
return err
|
||||
}
|
||||
wb, err := icmpHeader.Marshal(nil)
|
||||
if err != nil {
|
||||
t.hopLimitLock.Unlock()
|
||||
return err
|
||||
}
|
||||
start := time.Now()
|
||||
if _, err := t.icmp.WriteTo(wb, &net.IPAddr{IP: t.DstIP}); err != nil {
|
||||
t.hopLimitLock.Unlock()
|
||||
return err
|
||||
}
|
||||
t.hopLimitLock.Unlock()
|
||||
desiredPayloadSize := t.PktSize
|
||||
payload := make([]byte, desiredPayloadSize)
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return context.Canceled
|
||||
case h := <-hopCh:
|
||||
rtt := time.Since(start)
|
||||
if desiredPayloadSize >= 3 {
|
||||
copy(payload[desiredPayloadSize-3:], []byte{'n', 't', 'r'}) // "ntr" 作为标识
|
||||
}
|
||||
|
||||
if f := t.final.Load(); f != -1 && ttl > int(f) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if ip := util.AddrIP(h.Address); ip != nil && ip.Equal(t.DstIP) {
|
||||
for {
|
||||
old := t.final.Load()
|
||||
if old != -1 && ttl >= int(old) {
|
||||
break
|
||||
}
|
||||
if t.final.CompareAndSwap(old, int32(ttl)) {
|
||||
break
|
||||
}
|
||||
// 登记 pending,并启动超时守护
|
||||
t.markPending(seq)
|
||||
go func(seq, ttl, i int) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = t.clearPending(seq)
|
||||
return
|
||||
case <-time.After(t.Timeout):
|
||||
// 仍未完成且未超出 final/未达成 ttlComp 才补位
|
||||
if !t.clearPending(seq) {
|
||||
return
|
||||
}
|
||||
|
||||
if f := t.final.Load(); f != -1 && ttl > int(f) {
|
||||
return
|
||||
}
|
||||
|
||||
if t.ttlComp(ttl) {
|
||||
return
|
||||
}
|
||||
|
||||
h := Hop{
|
||||
Success: false,
|
||||
Address: nil,
|
||||
TTL: ttl,
|
||||
RTT: 0,
|
||||
Error: errHopLimitTimeout,
|
||||
}
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
t.dropSent(seq)
|
||||
}
|
||||
}(seq, ttl, i)
|
||||
|
||||
h.TTL = ttl
|
||||
h.RTT = rtt
|
||||
|
||||
_ = h.fetchIPData(t.Config) // 忽略错误,继续添加结果
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
case <-time.After(t.Timeout):
|
||||
if f := t.final.Load(); f != -1 && ttl > int(f) {
|
||||
return nil
|
||||
}
|
||||
|
||||
h := Hop{
|
||||
Success: false,
|
||||
Address: nil,
|
||||
TTL: ttl,
|
||||
RTT: 0,
|
||||
Error: errHopLimitTimeout,
|
||||
}
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
start, err := s.SendICMP(ctx, ipHeader, icmpHeader, nil, payload)
|
||||
if err != nil {
|
||||
_ = t.clearPending(seq)
|
||||
return err
|
||||
}
|
||||
t.storeSent(seq, start)
|
||||
return nil
|
||||
}
|
||||
+253
-230
@@ -1,9 +1,7 @@
|
||||
package trace
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"log"
|
||||
"math/rand"
|
||||
@@ -15,8 +13,7 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv6"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace/internal"
|
||||
@@ -25,17 +22,34 @@ import (
|
||||
|
||||
type ICMPTracerv6 struct {
|
||||
Config
|
||||
wg sync.WaitGroup
|
||||
res Result
|
||||
echoIDTag uint8
|
||||
pidLow uint8
|
||||
inflightRequest map[int]chan Hop
|
||||
inflightRequestLock sync.RWMutex
|
||||
icmp net.PacketConn
|
||||
icmpConn *ipv6.PacketConn
|
||||
hopLimitLock sync.Mutex
|
||||
final atomic.Int32
|
||||
sem *semaphore.Weighted
|
||||
wg sync.WaitGroup
|
||||
res Result
|
||||
echoID int
|
||||
pending map[int]struct{}
|
||||
pendingMu sync.Mutex
|
||||
sentAt map[int]time.Time
|
||||
sentMu sync.RWMutex
|
||||
SrcIP net.IP
|
||||
final atomic.Int32
|
||||
sem *semaphore.Weighted
|
||||
matchQ chan matchTask
|
||||
readyICMP chan struct{}
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) waitAllReady(ctx context.Context) {
|
||||
timeout := time.After(5 * time.Second)
|
||||
waiting := 1
|
||||
for waiting > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.readyICMP:
|
||||
waiting--
|
||||
case <-timeout:
|
||||
return
|
||||
}
|
||||
}
|
||||
<-time.After(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) ttlComp(ttl int) bool {
|
||||
@@ -77,7 +91,7 @@ func (t *ICMPTracerv6) PrintFunc(ctx context.Context, cancel context.CancelCause
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) launchTTL(ctx context.Context, ttl int) {
|
||||
func (t *ICMPTracerv6) launchTTL(ctx context.Context, s *internal.ICMPSpec, ttl int) {
|
||||
go func(ttl int) {
|
||||
for i := 0; i < t.MaxAttempts; i++ {
|
||||
// 若此 TTL 已完成或 ctx 已取消,则不再发起新的尝试
|
||||
@@ -87,7 +101,7 @@ func (t *ICMPTracerv6) launchTTL(ctx context.Context, ttl int) {
|
||||
|
||||
t.wg.Add(1)
|
||||
go func(ttl, i int) {
|
||||
if err := t.send(ctx, ttl, i); err != nil && !errors.Is(err, context.Canceled) {
|
||||
if err := t.send(ctx, s, ttl, i); err != nil && !errors.Is(err, context.Canceled) {
|
||||
if util.EnvDevMode {
|
||||
panic(err)
|
||||
}
|
||||
@@ -105,23 +119,148 @@ func (t *ICMPTracerv6) launchTTL(ctx context.Context, ttl int) {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
// 生成一个 8 位的随机 tag
|
||||
echoIDTag := r.Intn(256)
|
||||
|
||||
// 获取当前进程的 pid
|
||||
pid := os.Getpid()
|
||||
|
||||
// 将随机 tag 编码到高 8 位;将 pid 的低 8 位编码到低 8 位
|
||||
t.echoID = (echoIDTag << 8) | (pid & 0xFF)
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) markPending(seq int) {
|
||||
t.pendingMu.Lock()
|
||||
defer t.pendingMu.Unlock()
|
||||
t.pending[seq] = struct{}{}
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) clearPending(seq int) bool {
|
||||
t.pendingMu.Lock()
|
||||
defer t.pendingMu.Unlock()
|
||||
_, ok := t.pending[seq]
|
||||
delete(t.pending, seq)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) storeSent(seq int, start time.Time) {
|
||||
t.sentMu.Lock()
|
||||
defer t.sentMu.Unlock()
|
||||
t.sentAt[seq] = start
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) lookupSent(seq int) (start time.Time, ok bool) {
|
||||
t.sentMu.RLock()
|
||||
defer t.sentMu.RUnlock()
|
||||
start, ok = t.sentAt[seq]
|
||||
if !ok {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return start, true
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) dropSent(seq int) {
|
||||
t.sentMu.Lock()
|
||||
defer t.sentMu.Unlock()
|
||||
delete(t.sentAt, seq)
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) addHopWithIndex(peer net.Addr, ttl, i int, rtt time.Duration, mpls []string) {
|
||||
if f := t.final.Load(); f != -1 && ttl > int(f) {
|
||||
return
|
||||
}
|
||||
|
||||
if ip := util.AddrIP(peer); ip != nil && ip.Equal(t.DstIP) {
|
||||
for {
|
||||
old := t.final.Load()
|
||||
if old != -1 && ttl >= int(old) {
|
||||
break
|
||||
}
|
||||
if t.final.CompareAndSwap(old, int32(ttl)) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
h := Hop{
|
||||
Success: true,
|
||||
Address: peer,
|
||||
TTL: ttl,
|
||||
RTT: rtt,
|
||||
MPLS: mpls,
|
||||
}
|
||||
|
||||
_ = h.fetchIPData(t.Config) // 忽略错误,继续添加结果
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) matchWorker(ctx context.Context) {
|
||||
defer t.wg.Done()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case task, ok := <-t.matchQ:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// 固定等待 10ms,缓解登记竞态
|
||||
timer := time.NewTimer(10 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
timer.Stop()
|
||||
|
||||
// 尝试一次匹配
|
||||
start, ok := t.lookupSent(task.seq)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
// 将 task.seq 转为 16 位无符号数
|
||||
u := uint16(task.seq)
|
||||
|
||||
// 高 8 位是 TTL
|
||||
ttl := int((u >> 8) & 0xFF)
|
||||
|
||||
// 低 8 位是索引 i
|
||||
i := int(u & 0xFF)
|
||||
|
||||
if t.clearPending(task.seq) {
|
||||
rtt := task.finish.Sub(start)
|
||||
t.addHopWithIndex(task.peer, ttl, i, rtt, task.mpls)
|
||||
}
|
||||
t.dropSent(task.seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) Execute() (res *Result, err error) {
|
||||
// 初始化 Echo.ID
|
||||
t.initEchoID()
|
||||
|
||||
// 初始化 inflightRequest map
|
||||
t.inflightRequest = make(map[int]chan Hop)
|
||||
// 初始化 pending、sentAt 和 matchQ
|
||||
t.pending = make(map[int]struct{})
|
||||
t.sentAt = make(map[int]time.Time)
|
||||
t.matchQ = make(chan matchTask, 60)
|
||||
|
||||
// 创建就绪通道
|
||||
t.readyICMP = make(chan struct{})
|
||||
|
||||
if len(t.res.Hops) > 0 {
|
||||
return &t.res, errTracerouteExecuted
|
||||
}
|
||||
|
||||
// 初始化 Result.Hops,并预分配到 MaxHops
|
||||
// 初始化 res.Hops 和 res.tailDone,并预分配到 MaxHops
|
||||
t.res.Hops = make([][]Hop, t.MaxHops)
|
||||
t.res.tailDone = make([]bool, t.MaxHops)
|
||||
|
||||
@@ -130,28 +269,40 @@ func (t *ICMPTracerv6) Execute() (res *Result, err error) {
|
||||
if t.SrcAddr != "" && !util.IsIPv6(SrcAddr) {
|
||||
return nil, errors.New("invalid IPv6 SrcAddr: " + t.SrcAddr)
|
||||
}
|
||||
SrcIP := ""
|
||||
if SrcAddr != nil {
|
||||
SrcIP = SrcAddr.String()
|
||||
t.SrcIP, _ = util.LocalIPPortv6(t.DstIP, SrcAddr, "icmp6")
|
||||
if t.SrcIP == nil {
|
||||
return nil, errors.New("cannot determine local IPv6 address")
|
||||
}
|
||||
|
||||
t.icmp, err = internal.ListenPacket("ip6:ipv6-icmp", SrcIP)
|
||||
if err != nil {
|
||||
return &t.res, err
|
||||
}
|
||||
defer func() {
|
||||
if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
t.icmpConn = ipv6.NewPacketConn(t.icmp)
|
||||
s := internal.NewICMPSpec(
|
||||
6,
|
||||
t.ICMPMode,
|
||||
t.echoID,
|
||||
t.SrcIP,
|
||||
t.DstIP,
|
||||
)
|
||||
|
||||
s.InitICMP()
|
||||
defer s.Close()
|
||||
|
||||
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
ctx, cancel := context.WithCancelCause(sigCtx)
|
||||
t.final.Store(-1)
|
||||
|
||||
workerN := 16
|
||||
for i := 0; i < workerN; i++ {
|
||||
t.wg.Add(1)
|
||||
go t.matchWorker(ctx)
|
||||
}
|
||||
t.wg.Add(1)
|
||||
go t.listenICMP(ctx)
|
||||
go func() {
|
||||
defer t.wg.Done()
|
||||
s.ListenICMP(ctx, t.readyICMP, func(msg internal.ReceivedMessage, finish time.Time, seq int) {
|
||||
t.handleICMPMessage(msg, finish, seq)
|
||||
},
|
||||
)
|
||||
}()
|
||||
t.waitAllReady(ctx)
|
||||
t.wg.Add(1)
|
||||
go t.PrintFunc(ctx, cancel)
|
||||
|
||||
@@ -161,7 +312,7 @@ func (t *ICMPTracerv6) Execute() (res *Result, err error) {
|
||||
go func() {
|
||||
defer t.wg.Done()
|
||||
// 立即启动 BeginHop 对应的 TTL 组
|
||||
t.launchTTL(ctx, t.BeginHop)
|
||||
t.launchTTL(ctx, s, t.BeginHop)
|
||||
|
||||
for ttl := t.BeginHop + 1; ttl <= t.MaxHops; ttl++ {
|
||||
// 之后按 TTLInterval 周期启动后续 TTL 组
|
||||
@@ -177,7 +328,7 @@ func (t *ICMPTracerv6) Execute() (res *Result, err error) {
|
||||
}
|
||||
|
||||
// 并发启动这个 TTL 的所有测量
|
||||
t.launchTTL(ctx, ttl)
|
||||
t.launchTTL(ctx, s, ttl)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -185,11 +336,11 @@ func (t *ICMPTracerv6) Execute() (res *Result, err error) {
|
||||
stop()
|
||||
t.wg.Wait()
|
||||
|
||||
bound := int(t.final.Load())
|
||||
if bound == -1 {
|
||||
bound = t.MaxHops
|
||||
final := int(t.final.Load())
|
||||
if final == -1 {
|
||||
final = t.MaxHops
|
||||
}
|
||||
t.res.reduce(bound)
|
||||
t.res.reduce(final)
|
||||
|
||||
if cause := context.Cause(ctx); !errors.Is(cause, errNaturalDone) {
|
||||
return &t.res, cause
|
||||
@@ -197,120 +348,20 @@ func (t *ICMPTracerv6) Execute() (res *Result, err error) {
|
||||
return &t.res, nil
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) listenICMP(ctx context.Context) {
|
||||
defer t.wg.Done()
|
||||
lc := internal.NewPacketListener(t.icmp)
|
||||
go lc.Start(ctx)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case msg, ok := <-lc.Messages:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
rm, err := icmp.ParseMessage(58, msg.Msg)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
var (
|
||||
data []byte
|
||||
)
|
||||
switch rm.Type {
|
||||
case ipv6.ICMPTypeEchoReply:
|
||||
echo, ok := rm.Body.(*icmp.Echo)
|
||||
if !ok || echo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// 只在 Peer 是目的地址时分发,用 seq 作为通道 key
|
||||
if ip := util.AddrIP(msg.Peer); ip != nil && ip.Equal(t.DstIP) {
|
||||
id := uint16(echo.ID)
|
||||
if uint8(id>>8) != t.echoIDTag || uint8(id&0xFF) != t.pidLow {
|
||||
continue
|
||||
}
|
||||
// 从 Echo.Seq 恢复出先前编码的 (ttl<<8)|index
|
||||
seq := echo.Seq
|
||||
// 高 8 位是真正的 TTL
|
||||
ttl := seq >> 8
|
||||
// TTL 越界时舍弃
|
||||
if ttl < t.BeginHop || ttl > t.MaxHops {
|
||||
continue
|
||||
}
|
||||
t.handleICMPMessage(msg, seq)
|
||||
}
|
||||
continue
|
||||
case ipv6.ICMPTypeTimeExceeded:
|
||||
body, ok := rm.Body.(*icmp.TimeExceeded)
|
||||
if !ok || body == nil {
|
||||
continue
|
||||
}
|
||||
data = body.Data
|
||||
case ipv6.ICMPTypeDestinationUnreachable:
|
||||
body, ok := rm.Body.(*icmp.DstUnreach)
|
||||
if !ok || body == nil {
|
||||
continue
|
||||
}
|
||||
data = body.Data
|
||||
default:
|
||||
continue
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstip := net.IP(data[24:40])
|
||||
if dstip.Equal(t.DstIP) || dstip.Equal(net.IPv6zero) {
|
||||
inner, err := util.GetICMPResponsePayload(data)
|
||||
if err != nil || len(inner) < 8 {
|
||||
continue
|
||||
}
|
||||
id := binary.BigEndian.Uint16(inner[4:6])
|
||||
if uint8(id>>8) != t.echoIDTag || uint8(id&0xFF) != t.pidLow {
|
||||
continue
|
||||
}
|
||||
seq := int(binary.BigEndian.Uint16(inner[6:8]))
|
||||
t.handleICMPMessage(msg, seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) handleICMPMessage(msg internal.ReceivedMessage, seq int) {
|
||||
func (t *ICMPTracerv6) handleICMPMessage(msg internal.ReceivedMessage, finish time.Time, seq int) {
|
||||
mpls := extractMPLS(msg)
|
||||
|
||||
// 取出通道后立刻解锁
|
||||
t.inflightRequestLock.RLock()
|
||||
ch, ok := t.inflightRequest[seq]
|
||||
t.inflightRequestLock.RUnlock()
|
||||
if !ok || ch == nil {
|
||||
return
|
||||
}
|
||||
|
||||
h := Hop{
|
||||
Success: true,
|
||||
Address: msg.Peer,
|
||||
MPLS: mpls,
|
||||
}
|
||||
|
||||
// 非阻塞发送,避免重复回包把缓冲塞满导致阻塞
|
||||
// 非阻塞投递;如果队列已满则直接丢弃该任务
|
||||
select {
|
||||
case ch <- h:
|
||||
case t.matchQ <- matchTask{
|
||||
seq: seq, peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
}:
|
||||
default:
|
||||
// 丢弃重复/迟到的相同 seq 回包,避免阻塞
|
||||
// 丢弃以避免阻塞抓包循环
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ICMPTracerv6) send(ctx context.Context, ttl, i int) error {
|
||||
func (t *ICMPTracerv6) send(ctx context.Context, s *internal.ICMPSpec, ttl, i int) error {
|
||||
defer t.wg.Done()
|
||||
|
||||
if t.ttlComp(ttl) {
|
||||
@@ -335,97 +386,69 @@ func (t *ICMPTracerv6) send(ctx context.Context, ttl, i int) error {
|
||||
// 将 TTL 编码到高 8 位;将索引 i 编码到低 8 位
|
||||
seq := (ttl << 8) | (i & 0xFF)
|
||||
|
||||
t.inflightRequestLock.Lock()
|
||||
hopCh := make(chan Hop, 1)
|
||||
t.inflightRequest[seq] = hopCh
|
||||
t.inflightRequestLock.Unlock()
|
||||
defer func() {
|
||||
t.inflightRequestLock.Lock()
|
||||
delete(t.inflightRequest, seq)
|
||||
t.inflightRequestLock.Unlock()
|
||||
}()
|
||||
|
||||
// 将随机 tag 编码到高 8 位;将 pid 的低 8 位编码到低 8 位
|
||||
id := int(uint16(t.echoIDTag)<<8 | uint16(t.pidLow))
|
||||
|
||||
var data []byte
|
||||
if t.PktSize < 3 {
|
||||
data = bytes.Repeat([]byte{0}, t.PktSize)
|
||||
} else {
|
||||
data = bytes.Repeat([]byte{0}, t.PktSize-3)
|
||||
data = append(data, 0x6e, 0x74, 0x72) // "ntr" 作为标识
|
||||
ipHeader := &layers.IPv6{
|
||||
Version: 6,
|
||||
SrcIP: t.SrcIP,
|
||||
DstIP: t.DstIP,
|
||||
NextHeader: layers.IPProtocolICMPv6,
|
||||
HopLimit: uint8(ttl),
|
||||
}
|
||||
|
||||
icmpHeader := icmp.Message{
|
||||
Type: ipv6.ICMPTypeEchoRequest,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: id,
|
||||
Data: data,
|
||||
Seq: seq,
|
||||
},
|
||||
icmpHeader := &layers.ICMPv6{
|
||||
TypeCode: layers.CreateICMPv6TypeCode(layers.ICMPv6TypeEchoRequest, 0),
|
||||
}
|
||||
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
t.hopLimitLock.Lock()
|
||||
if err := t.icmpConn.SetHopLimit(ttl); err != nil {
|
||||
t.hopLimitLock.Unlock()
|
||||
return err
|
||||
icmpEcho := &layers.ICMPv6Echo{
|
||||
Identifier: uint16(t.echoID),
|
||||
SeqNumber: uint16(seq),
|
||||
}
|
||||
wb, err := icmpHeader.Marshal(nil)
|
||||
if err != nil {
|
||||
t.hopLimitLock.Unlock()
|
||||
return err
|
||||
|
||||
desiredPayloadSize := t.PktSize
|
||||
payload := make([]byte, desiredPayloadSize)
|
||||
|
||||
if desiredPayloadSize >= 3 {
|
||||
copy(payload[desiredPayloadSize-3:], []byte{'n', 't', 'r'}) // "ntr" 作为标识
|
||||
}
|
||||
start := time.Now()
|
||||
if _, err := t.icmp.WriteTo(wb, &net.IPAddr{IP: t.DstIP}); err != nil {
|
||||
t.hopLimitLock.Unlock()
|
||||
return err
|
||||
}
|
||||
t.hopLimitLock.Unlock()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return context.Canceled
|
||||
case h := <-hopCh:
|
||||
rtt := time.Since(start)
|
||||
|
||||
if f := t.final.Load(); f != -1 && ttl > int(f) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if ip := util.AddrIP(h.Address); ip != nil && ip.Equal(t.DstIP) {
|
||||
for {
|
||||
old := t.final.Load()
|
||||
if old != -1 && ttl >= int(old) {
|
||||
break
|
||||
}
|
||||
if t.final.CompareAndSwap(old, int32(ttl)) {
|
||||
break
|
||||
}
|
||||
// 登记 pending,并启动超时守护
|
||||
t.markPending(seq)
|
||||
go func(seq, ttl, i int) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = t.clearPending(seq)
|
||||
return
|
||||
case <-time.After(t.Timeout):
|
||||
// 仍未完成且未超出 final/未达成 ttlComp 才补位
|
||||
if !t.clearPending(seq) {
|
||||
return
|
||||
}
|
||||
|
||||
if f := t.final.Load(); f != -1 && ttl > int(f) {
|
||||
return
|
||||
}
|
||||
|
||||
if t.ttlComp(ttl) {
|
||||
return
|
||||
}
|
||||
|
||||
h := Hop{
|
||||
Success: false,
|
||||
Address: nil,
|
||||
TTL: ttl,
|
||||
RTT: 0,
|
||||
Error: errHopLimitTimeout,
|
||||
}
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
t.dropSent(seq)
|
||||
}
|
||||
}(seq, ttl, i)
|
||||
|
||||
h.TTL = ttl
|
||||
h.RTT = rtt
|
||||
|
||||
_ = h.fetchIPData(t.Config) // 忽略错误,继续添加结果
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
case <-time.After(t.Timeout):
|
||||
if f := t.final.Load(); f != -1 && ttl > int(f) {
|
||||
return nil
|
||||
}
|
||||
|
||||
h := Hop{
|
||||
Success: false,
|
||||
Address: nil,
|
||||
TTL: ttl,
|
||||
RTT: 0,
|
||||
Error: errHopLimitTimeout,
|
||||
}
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
start, err := s.SendICMP(ctx, ipHeader, icmpHeader, icmpEcho, payload)
|
||||
if err != nil {
|
||||
_ = t.clearPending(seq)
|
||||
return err
|
||||
}
|
||||
t.storeSent(seq, start)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/util"
|
||||
)
|
||||
|
||||
type ipLayer interface {
|
||||
gopacket.NetworkLayer
|
||||
gopacket.SerializableLayer
|
||||
}
|
||||
|
||||
func NewICMPSpec(IPVersion, ICMPMode, echoID int, srcIP, dstIP net.IP) *ICMPSpec {
|
||||
return &ICMPSpec{IPVersion: IPVersion, ICMPMode: ICMPMode, EchoID: echoID, SrcIP: srcIP, DstIP: dstIP}
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) InitICMP() {
|
||||
network := "ip4:icmp"
|
||||
if s.IPVersion == 6 {
|
||||
network = "ip6:ipv6-icmp"
|
||||
}
|
||||
|
||||
icmpConn, err := 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
|
||||
|
||||
if s.IPVersion == 4 {
|
||||
s.icmp4 = ipv4.NewPacketConn(s.icmp)
|
||||
} else {
|
||||
s.icmp6 = ipv6.NewPacketConn(s.icmp)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) listenICMPSock(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, seq int)) {
|
||||
lc := NewPacketListener(s.icmp)
|
||||
go lc.Start(ctx)
|
||||
close(ready)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case msg, ok := <-lc.Messages:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
finish := time.Now()
|
||||
|
||||
var data []byte // 提取 ICMP 的负载
|
||||
if s.IPVersion == 4 {
|
||||
rm, err := icmp.ParseMessage(1, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv4.ICMPTypeEchoReply:
|
||||
echo, ok := rm.Body.(*icmp.Echo)
|
||||
if !ok || echo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if ip := util.AddrIP(msg.Peer); ip == nil || !ip.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
|
||||
id := echo.ID
|
||||
if id != s.EchoID {
|
||||
continue
|
||||
}
|
||||
|
||||
seq := echo.Seq
|
||||
onICMP(msg, finish, seq)
|
||||
continue
|
||||
case ipv4.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv4.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
rm, err := icmp.ParseMessage(58, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv6.ICMPTypeEchoReply:
|
||||
echo, ok := rm.Body.(*icmp.Echo)
|
||||
if !ok || echo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if ip := util.AddrIP(msg.Peer); ip == nil || !ip.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
|
||||
id := echo.ID
|
||||
if id != s.EchoID {
|
||||
continue
|
||||
}
|
||||
|
||||
seq := echo.Seq
|
||||
onICMP(msg, finish, seq)
|
||||
continue
|
||||
case ipv6.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypePacketTooBig:
|
||||
if body, ok := rm.Body.(*icmp.PacketTooBig); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
header, err := util.GetICMPResponsePayload(data)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
id, err := util.GetICMPID(header)
|
||||
if err != nil || id != s.EchoID {
|
||||
continue
|
||||
}
|
||||
|
||||
seq, err := util.GetICMPSeq(header)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
onICMP(msg, finish, seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,21 +6,39 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
type ICMPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
EchoID int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
icmp net.PacketConn
|
||||
icmp4 *ipv4.PacketConn
|
||||
icmp6 *ipv6.PacketConn
|
||||
hopLimitLock sync.Mutex
|
||||
}
|
||||
|
||||
//go:linkname internetSocket net.internetSocket
|
||||
func internetSocket(ctx context.Context, net string, laddr, raddr any, sotype, proto int, mode string, ctrlCtxFn func(context.Context, string, string, syscall.RawConn) error) (fd unsafe.Pointer, err error)
|
||||
func internetSocket(_ context.Context, _ string, _, _ any, _, _ int, _ string, _ func(context.Context, string, string, syscall.RawConn) error) (fd unsafe.Pointer, err error)
|
||||
|
||||
//go:linkname newIPConn net.newIPConn
|
||||
func newIPConn(fd unsafe.Pointer) *net.IPConn
|
||||
func newIPConn(_ unsafe.Pointer) *net.IPConn
|
||||
|
||||
var (
|
||||
errUnknownNetwork = errors.New("unknown network type")
|
||||
errUnknownIface = errors.New("unknown network interface")
|
||||
|
||||
networkMap = map[string]string{
|
||||
networkMap = map[string]string{
|
||||
"ip4:icmp": "udp4",
|
||||
"ip4:1": "udp4",
|
||||
"ip6:ipv6-icmp": "udp6",
|
||||
@@ -94,3 +112,92 @@ func ListenPacket(network string, laddr string) (net.PacketConn, error) {
|
||||
return nil, errUnknownNetwork
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, seq int)) {
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) SendICMP(ctx context.Context, ipHdr gopacket.NetworkLayer, icmpHdr, icmpEcho gopacket.SerializableLayer, payload []byte) (time.Time, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return time.Time{}, context.Canceled
|
||||
default:
|
||||
}
|
||||
|
||||
if s.IPVersion == 4 {
|
||||
ip4, ok := ipHdr.(*layers.IPv4)
|
||||
if !ok || ip4 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.IPv4 when s.IPVersion==4")
|
||||
}
|
||||
ttl := int(ip4.TTL)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
|
||||
// 序列化 ICMP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, icmpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.icmp4.SetTTL(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.icmp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
}
|
||||
ttl := int(ip6.HopLimit)
|
||||
|
||||
ic6, ok := icmpHdr.(*layers.ICMPv6)
|
||||
if !ok || ic6 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.ICMPv6 when s.IPVersion==6")
|
||||
}
|
||||
|
||||
_ = ic6.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
|
||||
// 序列化 ICMP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, icmpHdr, icmpEcho, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.icmp6.SetHopLimit(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.icmp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
//go:build !darwin
|
||||
|
||||
package internal
|
||||
|
||||
import "net"
|
||||
|
||||
func ListenPacket(network string, laddr string) (net.PacketConn, error) {
|
||||
return net.ListenPacket(network, laddr)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//go:build !darwin && !(windows && amd64)
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
type ICMPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
EchoID int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
icmp net.PacketConn
|
||||
icmp4 *ipv4.PacketConn
|
||||
icmp6 *ipv6.PacketConn
|
||||
hopLimitLock sync.Mutex
|
||||
}
|
||||
|
||||
func ListenPacket(network string, laddr string) (net.PacketConn, error) {
|
||||
return net.ListenPacket(network, laddr)
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, seq int)) {
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) SendICMP(ctx context.Context, ipHdr gopacket.NetworkLayer, icmpHdr, icmpEcho gopacket.SerializableLayer, payload []byte) (time.Time, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return time.Time{}, context.Canceled
|
||||
default:
|
||||
}
|
||||
|
||||
if s.IPVersion == 4 {
|
||||
ip4, ok := ipHdr.(*layers.IPv4)
|
||||
if !ok || ip4 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.IPv4 when s.IPVersion==4")
|
||||
}
|
||||
ttl := int(ip4.TTL)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
|
||||
// 序列化 ICMP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, icmpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.icmp4.SetTTL(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.icmp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
}
|
||||
ttl := int(ip6.HopLimit)
|
||||
|
||||
ic6, ok := icmpHdr.(*layers.ICMPv6)
|
||||
if !ok || ic6 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.ICMPv6 when s.IPVersion==6")
|
||||
}
|
||||
|
||||
_ = ic6.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
|
||||
// 序列化 ICMP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, icmpHdr, icmpEcho, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.icmp6.SetHopLimit(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.icmp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
//go:build windows && amd64
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/google/gopacket/pcap"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
"golang.org/x/sys/windows"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/util"
|
||||
)
|
||||
|
||||
type ICMPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
EchoID int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
icmp net.PacketConn
|
||||
icmp4 *ipv4.PacketConn
|
||||
icmp6 *ipv6.PacketConn
|
||||
hopLimitLock sync.Mutex
|
||||
}
|
||||
|
||||
func ListenPacket(network string, laddr string) (net.PacketConn, error) {
|
||||
return net.ListenPacket(network, laddr)
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
}
|
||||
|
||||
// isAdmin 判断当前进程是否具有管理员权限
|
||||
func isAdmin() bool {
|
||||
var token windows.Token
|
||||
if err := windows.OpenProcessToken(windows.CurrentProcess(), windows.TOKEN_QUERY, &token); err != nil {
|
||||
return false
|
||||
}
|
||||
defer func() {
|
||||
_ = token.Close()
|
||||
}()
|
||||
|
||||
type tokenElevation struct {
|
||||
TokenIsElevated uint32
|
||||
}
|
||||
var elev tokenElevation
|
||||
var outLen uint32
|
||||
|
||||
if err := windows.GetTokenInformation(
|
||||
token,
|
||||
windows.TokenElevation,
|
||||
(*byte)(unsafe.Pointer(&elev)),
|
||||
uint32(unsafe.Sizeof(elev)),
|
||||
&outLen,
|
||||
); err != nil {
|
||||
return false
|
||||
}
|
||||
return elev.TokenIsElevated != 0
|
||||
}
|
||||
|
||||
// pcapAvailable 判断 Npcap 是否可用
|
||||
func pcapAvailable() (bool, error) {
|
||||
devs, err := pcap.FindAllDevs()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if len(devs) == 0 {
|
||||
return false, fmt.Errorf("no pcap devices found")
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// resolveICMPMode 进行最终模式判定
|
||||
func (s *ICMPSpec) resolveICMPMode() int {
|
||||
icmpMode := s.ICMPMode
|
||||
if icmpMode != 1 && icmpMode != 2 {
|
||||
icmpMode = 0 // 统一成 Auto
|
||||
}
|
||||
|
||||
// 指定 1=Socket:直接返回
|
||||
if icmpMode == 1 {
|
||||
return 1
|
||||
}
|
||||
|
||||
// Auto(0) 或强制 PCAP(2) → 尝试 PCAP
|
||||
if !isAdmin() {
|
||||
if icmpMode == 2 {
|
||||
log.Printf("PCAP mode requested, but administrator privilege is required; falling back to Socket mode.")
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
ok, err := pcapAvailable()
|
||||
if !ok {
|
||||
if icmpMode == 2 {
|
||||
log.Printf("PCAP mode requested, but Npcap is not available: %v; falling back to Socket mode.", err)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, seq int)) {
|
||||
switch s.resolveICMPMode() {
|
||||
case 1:
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
case 2:
|
||||
s.listenICMPPcap(ctx, ready, onICMP)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) listenICMPPcap(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, seq int)) {
|
||||
// 选择捕获设备与本地接口
|
||||
dev, err := util.PcapDeviceByIP(s.SrcIP)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
ipPrefix := "ip"
|
||||
proto := "icmp"
|
||||
if s.IPVersion == 6 {
|
||||
ipPrefix = "ip6"
|
||||
proto = "icmp6"
|
||||
}
|
||||
|
||||
// 以“立即模式”打开 pcap,降低首包丢失概率
|
||||
handle, err := util.OpenLiveImmediate(dev, 65535, true, 4<<20)
|
||||
if err != nil {
|
||||
if util.EnvDevMode {
|
||||
panic(fmt.Errorf("(ListenICMP) pcap open failed on %s: %v", dev, err))
|
||||
}
|
||||
log.Fatalf("(ListenICMP) pcap open failed on %s: %v", dev, err)
|
||||
}
|
||||
defer handle.Close()
|
||||
|
||||
// 过滤:只抓 {ip/ip6} + {icmp/icmp6},且目标为本机 s.SrcIP
|
||||
filter := fmt.Sprintf("%s and %s and dst host %s",
|
||||
ipPrefix, proto, s.SrcIP.String())
|
||||
|
||||
if err := handle.SetBPFFilter(filter); err != nil {
|
||||
if util.EnvDevMode {
|
||||
panic(fmt.Errorf("(ListenICMP) set BPF failed: %v (filter=%q)", err, filter))
|
||||
}
|
||||
log.Fatalf("(ListenICMP) set BPF failed: %v (filter=%q)", err, filter)
|
||||
}
|
||||
|
||||
src := gopacket.NewPacketSource(handle, handle.LinkType())
|
||||
pktCh := src.Packets()
|
||||
close(ready)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case pkt, ok := <-pktCh:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// 解包
|
||||
packet := pkt.NetworkLayer()
|
||||
if packet == nil {
|
||||
continue
|
||||
}
|
||||
finish := pkt.Metadata().Timestamp
|
||||
|
||||
// outer = IP 头 + 负载
|
||||
outer := make([]byte, 0, len(packet.LayerContents())+len(packet.LayerPayload()))
|
||||
outer = append(outer, packet.LayerContents()...)
|
||||
outer = append(outer, packet.LayerPayload()...)
|
||||
|
||||
var peerIP net.IP // 提取对端 IP(按族别)
|
||||
var data []byte // 提取 ICMP 的负载
|
||||
if s.IPVersion == 4 {
|
||||
// 从包中获取 IPv4 层信息
|
||||
ip4, ok := pkt.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
|
||||
if !ok || ip4 == nil {
|
||||
continue
|
||||
}
|
||||
peerIP = ip4.SrcIP
|
||||
|
||||
// 从包中获取 ICMPv4 层信息
|
||||
ic4, ok := pkt.Layer(layers.LayerTypeICMPv4).(*layers.ICMPv4)
|
||||
if !ok || ic4 == nil {
|
||||
continue
|
||||
}
|
||||
data = ic4.Payload
|
||||
|
||||
switch ic4.TypeCode.Type() {
|
||||
case layers.ICMPv4TypeEchoReply:
|
||||
if !peerIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
|
||||
id := int(ic4.Id)
|
||||
if id != s.EchoID {
|
||||
continue
|
||||
}
|
||||
peer := &net.IPAddr{IP: peerIP}
|
||||
|
||||
// outer:外层 IP 报文字节
|
||||
msg := ReceivedMessage{
|
||||
Peer: peer,
|
||||
Msg: outer,
|
||||
}
|
||||
seq := int(ic4.Seq)
|
||||
onICMP(msg, finish, seq)
|
||||
continue
|
||||
case layers.ICMPv4TypeTimeExceeded:
|
||||
case layers.ICMPv4TypeDestinationUnreachable:
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", ic4.TypeCode.Type())
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
// 从包中获取 IPv6 层信息
|
||||
ip6, ok := pkt.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
continue
|
||||
}
|
||||
peerIP = ip6.SrcIP
|
||||
|
||||
// 从包中获取 ICMPv6 层信息
|
||||
ic6, ok := pkt.Layer(layers.LayerTypeICMPv6).(*layers.ICMPv6)
|
||||
if !ok || ic6 == nil {
|
||||
continue
|
||||
}
|
||||
data = ic6.Payload[4:]
|
||||
|
||||
switch ic6.TypeCode.Type() {
|
||||
case layers.ICMPv6TypeEchoReply:
|
||||
// 从包中获取 ICMPv6 的 Echo 层信息
|
||||
echo, ok := pkt.Layer(layers.LayerTypeICMPv6Echo).(*layers.ICMPv6Echo)
|
||||
if !ok || echo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if !peerIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
|
||||
id := int(echo.Identifier)
|
||||
if id != s.EchoID {
|
||||
continue
|
||||
}
|
||||
peer := &net.IPAddr{IP: peerIP}
|
||||
|
||||
// outer:外层 IP 报文字节
|
||||
msg := ReceivedMessage{
|
||||
Peer: peer,
|
||||
Msg: outer,
|
||||
}
|
||||
seq := int(echo.SeqNumber)
|
||||
onICMP(msg, finish, seq)
|
||||
continue
|
||||
case layers.ICMPv6TypeTimeExceeded:
|
||||
case layers.ICMPv6TypePacketTooBig:
|
||||
case layers.ICMPv6TypeDestinationUnreachable:
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", ic6.TypeCode.Type())
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
peer := &net.IPAddr{IP: peerIP}
|
||||
|
||||
// outer:外层 IP 报文字节
|
||||
msg := ReceivedMessage{
|
||||
Peer: peer,
|
||||
Msg: outer,
|
||||
}
|
||||
|
||||
header, err := util.GetICMPResponsePayload(data)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
id, err := util.GetICMPID(header)
|
||||
if err != nil || id != s.EchoID {
|
||||
continue
|
||||
}
|
||||
|
||||
seq, err := util.GetICMPSeq(header)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
onICMP(msg, finish, seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ICMPSpec) SendICMP(ctx context.Context, ipHdr gopacket.NetworkLayer, icmpHdr, icmpEcho gopacket.SerializableLayer, payload []byte) (time.Time, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return time.Time{}, context.Canceled
|
||||
default:
|
||||
}
|
||||
|
||||
if s.IPVersion == 4 {
|
||||
ip4, ok := ipHdr.(*layers.IPv4)
|
||||
if !ok || ip4 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.IPv4 when s.IPVersion==4")
|
||||
}
|
||||
ttl := int(ip4.TTL)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
|
||||
// 序列化 ICMP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, icmpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.icmp4.SetTTL(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.icmp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
}
|
||||
ttl := int(ip6.HopLimit)
|
||||
|
||||
ic6, ok := icmpHdr.(*layers.ICMPv6)
|
||||
if !ok || ic6 == nil {
|
||||
return time.Time{}, errors.New("SendICMP: expect *layers.ICMPv6 when s.IPVersion==6")
|
||||
}
|
||||
|
||||
_ = ic6.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
|
||||
// 序列化 ICMP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, icmpHdr, icmpEcho, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.icmp6.SetHopLimit(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.icmp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/util"
|
||||
)
|
||||
|
||||
func NewTCPSpec(IPVersion, ICMPMode int, srcIP, dstIP net.IP, dstPort int, pktSize int) *TCPSpec {
|
||||
return &TCPSpec{IPVersion: IPVersion, ICMPMode: ICMPMode, SrcIP: srcIP, DstIP: dstIP, DstPort: dstPort, PktSize: pktSize}
|
||||
}
|
||||
|
||||
func (s *TCPSpec) 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 *TCPSpec) 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
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
finish := time.Now()
|
||||
|
||||
var data []byte // 提取 ICMP 的负载
|
||||
if s.IPVersion == 4 {
|
||||
rm, err := icmp.ParseMessage(1, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv4.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv4.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
rm, err := icmp.ParseMessage(58, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv6.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypePacketTooBig:
|
||||
if body, ok := rm.Body.(*icmp.PacketTooBig); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
onICMP(msg, finish, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
-110
@@ -13,7 +13,6 @@ import (
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
@@ -22,6 +21,7 @@ import (
|
||||
|
||||
type TCPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
DstPort int
|
||||
@@ -33,10 +33,6 @@ type TCPSpec struct {
|
||||
hopLimitLock sync.Mutex
|
||||
}
|
||||
|
||||
func NewTCPSpec(IPVersion int, srcIP, dstIP net.IP, dstPort int, icmp net.PacketConn, pktSize int) *TCPSpec {
|
||||
return &TCPSpec{IPVersion: IPVersion, SrcIP: srcIP, DstIP: dstIP, DstPort: dstPort, icmp: icmp, PktSize: pktSize}
|
||||
}
|
||||
|
||||
func (s *TCPSpec) InitTCP() {
|
||||
network := "ip4:tcp"
|
||||
if s.IPVersion == 6 {
|
||||
@@ -53,100 +49,19 @@ func (s *TCPSpec) InitTCP() {
|
||||
s.tcp = tcp
|
||||
|
||||
if s.IPVersion == 4 {
|
||||
s.tcp4 = ipv4.NewPacketConn(tcp)
|
||||
s.tcp4 = ipv4.NewPacketConn(s.tcp)
|
||||
} else {
|
||||
s.tcp6 = ipv6.NewPacketConn(tcp)
|
||||
s.tcp6 = ipv6.NewPacketConn(s.tcp)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TCPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
_ = s.tcp.Close()
|
||||
}
|
||||
|
||||
func (s *TCPSpec) ListenICMP(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
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
finish := time.Now()
|
||||
|
||||
var data []byte // 提取 ICMP 负载
|
||||
if s.IPVersion == 4 {
|
||||
rm, err := icmp.ParseMessage(1, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv4.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv4.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv4zero)) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
rm, err := icmp.ParseMessage(58, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv6.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypePacketTooBig:
|
||||
if body, ok := rm.Body.(*icmp.PacketTooBig); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv6zero)) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
onICMP(msg, finish, data)
|
||||
}
|
||||
}
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
}
|
||||
|
||||
func (s *TCPSpec) ListenTCP(ctx context.Context, ready chan struct{}, onTCP func(srcPort, seq int, peer net.Addr, finish time.Time)) {
|
||||
@@ -256,21 +171,48 @@ func (s *TCPSpec) SendTCP(ctx context.Context, ipHdr gopacket.NetworkLayer, tcpH
|
||||
default:
|
||||
}
|
||||
|
||||
var ttl int // 提取 IP 头中的 TTL(按族别)
|
||||
if s.IPVersion == 4 {
|
||||
ip4, ok := ipHdr.(*layers.IPv4)
|
||||
if !ok || ip4 == nil {
|
||||
return time.Time{}, errors.New("SendTCP: expect *layers.IPv4 when s.IPVersion==4")
|
||||
}
|
||||
ttl = int(ip4.TTL)
|
||||
} else {
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendTCP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
ttl := int(ip4.TTL)
|
||||
|
||||
_ = tcpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
ttl = int(ip6.HopLimit)
|
||||
|
||||
// 序列化 TCP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, tcpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.tcp4.SetTTL(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.tcp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendTCP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
}
|
||||
ttl := int(ip6.HopLimit)
|
||||
|
||||
_ = tcpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
@@ -284,26 +226,18 @@ func (s *TCPSpec) SendTCP(ctx context.Context, ipHdr gopacket.NetworkLayer, tcpH
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL/HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
if s.IPVersion == 4 {
|
||||
if err := s.tcp4.SetTTL(ttl); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
} else {
|
||||
if err := s.tcp6.SetHopLimit(ttl); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.tcp6.SetHopLimit(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.tcp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
s.hopLimitLock.Unlock()
|
||||
return start, nil
|
||||
}
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
@@ -22,6 +21,7 @@ import (
|
||||
|
||||
type TCPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
DstPort int
|
||||
@@ -33,10 +33,6 @@ type TCPSpec struct {
|
||||
hopLimitLock sync.Mutex
|
||||
}
|
||||
|
||||
func NewTCPSpec(IPVersion int, srcIP, dstIP net.IP, dstPort int, icmp net.PacketConn, pktSize int) *TCPSpec {
|
||||
return &TCPSpec{IPVersion: IPVersion, SrcIP: srcIP, DstIP: dstIP, DstPort: dstPort, icmp: icmp, PktSize: pktSize}
|
||||
}
|
||||
|
||||
func (s *TCPSpec) InitTCP() {
|
||||
network := "ip4:tcp"
|
||||
if s.IPVersion == 6 {
|
||||
@@ -53,100 +49,19 @@ func (s *TCPSpec) InitTCP() {
|
||||
s.tcp = tcp
|
||||
|
||||
if s.IPVersion == 4 {
|
||||
s.tcp4 = ipv4.NewPacketConn(tcp)
|
||||
s.tcp4 = ipv4.NewPacketConn(s.tcp)
|
||||
} else {
|
||||
s.tcp6 = ipv6.NewPacketConn(tcp)
|
||||
s.tcp6 = ipv6.NewPacketConn(s.tcp)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TCPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
_ = s.tcp.Close()
|
||||
}
|
||||
|
||||
func (s *TCPSpec) ListenICMP(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
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
finish := time.Now()
|
||||
|
||||
var data []byte // 提取 ICMP 负载
|
||||
if s.IPVersion == 4 {
|
||||
rm, err := icmp.ParseMessage(1, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv4.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv4.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv4zero)) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
rm, err := icmp.ParseMessage(58, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv6.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypePacketTooBig:
|
||||
if body, ok := rm.Body.(*icmp.PacketTooBig); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv6zero)) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
onICMP(msg, finish, data)
|
||||
}
|
||||
}
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
}
|
||||
|
||||
func (s *TCPSpec) ListenTCP(ctx context.Context, ready chan struct{}, onTCP func(srcPort, seq int, peer net.Addr, finish time.Time)) {
|
||||
@@ -210,21 +125,48 @@ func (s *TCPSpec) SendTCP(ctx context.Context, ipHdr gopacket.NetworkLayer, tcpH
|
||||
default:
|
||||
}
|
||||
|
||||
var ttl int // 提取 IP 头中的 TTL(按族别)
|
||||
if s.IPVersion == 4 {
|
||||
ip4, ok := ipHdr.(*layers.IPv4)
|
||||
if !ok || ip4 == nil {
|
||||
return time.Time{}, errors.New("SendTCP: expect *layers.IPv4 when s.IPVersion==4")
|
||||
}
|
||||
ttl = int(ip4.TTL)
|
||||
} else {
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendTCP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
ttl := int(ip4.TTL)
|
||||
|
||||
_ = tcpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
ttl = int(ip6.HopLimit)
|
||||
|
||||
// 序列化 TCP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, tcpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.tcp4.SetTTL(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.tcp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendTCP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
}
|
||||
ttl := int(ip6.HopLimit)
|
||||
|
||||
_ = tcpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
@@ -238,26 +180,18 @@ func (s *TCPSpec) SendTCP(ctx context.Context, ipHdr gopacket.NetworkLayer, tcpH
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL/HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
if s.IPVersion == 4 {
|
||||
if err := s.tcp4.SetTTL(ttl); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
} else {
|
||||
if err := s.tcp6.SetHopLimit(ttl); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.tcp6.SetHopLimit(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.tcp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
s.hopLimitLock.Unlock()
|
||||
return start, nil
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
|
||||
type TCPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
DstPort int
|
||||
@@ -27,15 +28,6 @@ type TCPSpec struct {
|
||||
handle wd.Handle
|
||||
}
|
||||
|
||||
type ipLayer interface {
|
||||
gopacket.NetworkLayer
|
||||
gopacket.SerializableLayer
|
||||
}
|
||||
|
||||
func NewTCPSpec(IPVersion int, srcIP, dstIP net.IP, dstPort int, icmp net.PacketConn, pktSize int) *TCPSpec {
|
||||
return &TCPSpec{IPVersion: IPVersion, SrcIP: srcIP, DstIP: dstIP, DstPort: dstPort, icmp: icmp, PktSize: pktSize}
|
||||
}
|
||||
|
||||
func (s *TCPSpec) InitTCP() {
|
||||
handle, err := wd.Open("false", wd.LayerNetwork, 0, 0)
|
||||
if err != nil {
|
||||
@@ -53,10 +45,43 @@ func (s *TCPSpec) InitTCP() {
|
||||
}
|
||||
|
||||
func (s *TCPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
_ = s.handle.Close()
|
||||
}
|
||||
|
||||
// resolveICMPMode 进行最终模式判定
|
||||
func (s *TCPSpec) resolveICMPMode() int {
|
||||
icmpMode := s.ICMPMode
|
||||
if icmpMode != 1 && icmpMode != 2 {
|
||||
icmpMode = 0 // 统一成 Auto
|
||||
}
|
||||
|
||||
// 指定 1=Socket:直接返回
|
||||
if icmpMode == 1 {
|
||||
return 1
|
||||
}
|
||||
|
||||
// Auto(0) 或强制 PCAP(2) → 尝试 PCAP
|
||||
ok, err := pcapAvailable()
|
||||
if !ok {
|
||||
if icmpMode == 2 {
|
||||
log.Printf("PCAP mode requested, but Npcap is not available: %v; falling back to Socket mode.", err)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
}
|
||||
|
||||
func (s *TCPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, data []byte)) {
|
||||
switch s.resolveICMPMode() {
|
||||
case 1:
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
case 2:
|
||||
s.listenICMPPcap(ctx, ready, onICMP)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TCPSpec) listenICMPPcap(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, data []byte)) {
|
||||
// 选择捕获设备与本地接口
|
||||
dev, err := util.PcapDeviceByIP(s.SrcIP)
|
||||
if err != nil {
|
||||
@@ -117,7 +142,7 @@ func (s *TCPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP fu
|
||||
outer = append(outer, packet.LayerPayload()...)
|
||||
|
||||
var peerIP net.IP // 提取对端 IP(按族别)
|
||||
var data []byte // 提取 ICMP 负载
|
||||
var data []byte // 提取 ICMP 的负载
|
||||
if s.IPVersion == 4 {
|
||||
// 从包中获取 IPv4 层信息
|
||||
ip4, ok := pkt.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
|
||||
@@ -146,7 +171,7 @@ func (s *TCPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP fu
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv4zero)) {
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
@@ -178,7 +203,7 @@ func (s *TCPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP fu
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv6zero)) {
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
"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
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
finish := time.Now()
|
||||
|
||||
var data []byte // 提取 ICMP 的负载
|
||||
if s.IPVersion == 4 {
|
||||
rm, err := icmp.ParseMessage(1, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv4.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv4.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
rm, err := icmp.ParseMessage(58, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv6.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypePacketTooBig:
|
||||
if body, ok := rm.Body.(*icmp.PacketTooBig); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
onICMP(msg, finish, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
-110
@@ -13,7 +13,6 @@ import (
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
@@ -22,6 +21,7 @@ import (
|
||||
|
||||
type UDPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
DstPort int
|
||||
@@ -32,10 +32,6 @@ type UDPSpec struct {
|
||||
hopLimitLock sync.Mutex
|
||||
}
|
||||
|
||||
func NewUDPSpec(IPVersion int, srcIP, dstIP net.IP, dstPort int, icmp net.PacketConn) *UDPSpec {
|
||||
return &UDPSpec{IPVersion: IPVersion, SrcIP: srcIP, DstIP: dstIP, DstPort: dstPort, icmp: icmp}
|
||||
}
|
||||
|
||||
func (s *UDPSpec) InitUDP() {
|
||||
network := "ip4:udp"
|
||||
if s.IPVersion == 6 {
|
||||
@@ -52,13 +48,14 @@ func (s *UDPSpec) InitUDP() {
|
||||
s.udp = udp
|
||||
|
||||
if s.IPVersion == 4 {
|
||||
s.udp4 = ipv4.NewPacketConn(udp)
|
||||
s.udp4 = ipv4.NewPacketConn(s.udp)
|
||||
} else {
|
||||
s.udp6 = ipv6.NewPacketConn(udp)
|
||||
s.udp6 = ipv6.NewPacketConn(s.udp)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UDPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
_ = s.udp.Close()
|
||||
}
|
||||
|
||||
@@ -135,89 +132,7 @@ func (s *UDPSpec) ListenOut(ctx context.Context, ready chan struct{}, onOut func
|
||||
}
|
||||
|
||||
func (s *UDPSpec) ListenICMP(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
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
finish := time.Now()
|
||||
|
||||
var data []byte // 提取 ICMP 负载
|
||||
if s.IPVersion == 4 {
|
||||
rm, err := icmp.ParseMessage(1, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv4.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv4.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv4zero)) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
rm, err := icmp.ParseMessage(58, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv6.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypePacketTooBig:
|
||||
if body, ok := rm.Body.(*icmp.PacketTooBig); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv6zero)) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
onICMP(msg, finish, data)
|
||||
}
|
||||
}
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
}
|
||||
|
||||
func (s *UDPSpec) SendUDP(ctx context.Context, ipHdr gopacket.NetworkLayer, udpHdr *layers.UDP, payload []byte) (time.Time, error) {
|
||||
@@ -227,21 +142,48 @@ func (s *UDPSpec) SendUDP(ctx context.Context, ipHdr gopacket.NetworkLayer, udpH
|
||||
default:
|
||||
}
|
||||
|
||||
var ttl int // 提取 IP 头中的 TTL(按族别)
|
||||
if s.IPVersion == 4 {
|
||||
ip4, ok := ipHdr.(*layers.IPv4)
|
||||
if !ok || ip4 == nil {
|
||||
return time.Time{}, errors.New("SendUDP: expect *layers.IPv4 when s.IPVersion==4")
|
||||
}
|
||||
ttl = int(ip4.TTL)
|
||||
} else {
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendUDP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
ttl := int(ip4.TTL)
|
||||
|
||||
_ = udpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
ttl = int(ip6.HopLimit)
|
||||
|
||||
// 序列化 UDP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, udpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.udp4.SetTTL(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.udp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendUDP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
}
|
||||
ttl := int(ip6.HopLimit)
|
||||
|
||||
_ = udpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
@@ -255,26 +197,18 @@ func (s *UDPSpec) SendUDP(ctx context.Context, ipHdr gopacket.NetworkLayer, udpH
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 TTL/HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
if s.IPVersion == 4 {
|
||||
if err := s.udp4.SetTTL(ttl); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
} else {
|
||||
if err := s.udp6.SetHopLimit(ttl); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.udp6.SetHopLimit(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.udp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
s.hopLimitLock.Unlock()
|
||||
return start, nil
|
||||
}
|
||||
@@ -13,20 +13,15 @@ import (
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/util"
|
||||
)
|
||||
|
||||
type ipLayer interface {
|
||||
gopacket.NetworkLayer
|
||||
gopacket.SerializableLayer
|
||||
}
|
||||
|
||||
type UDPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
DstPort int
|
||||
@@ -38,10 +33,6 @@ type UDPSpec struct {
|
||||
mtu int
|
||||
}
|
||||
|
||||
func NewUDPSpec(IPVersion int, srcIP, dstIP net.IP, dstPort int, icmp net.PacketConn) *UDPSpec {
|
||||
return &UDPSpec{IPVersion: IPVersion, SrcIP: srcIP, DstIP: dstIP, DstPort: dstPort, icmp: icmp}
|
||||
}
|
||||
|
||||
func (s *UDPSpec) InitUDP() {
|
||||
network := "ip4:udp"
|
||||
if s.IPVersion == 6 {
|
||||
@@ -58,7 +49,7 @@ func (s *UDPSpec) InitUDP() {
|
||||
s.udp = udp
|
||||
|
||||
if s.IPVersion == 4 {
|
||||
s.udp4, err = ipv4.NewRawConn(udp)
|
||||
s.udp4, err = ipv4.NewRawConn(s.udp)
|
||||
if err != nil {
|
||||
s.Close()
|
||||
if util.EnvDevMode {
|
||||
@@ -74,11 +65,12 @@ func (s *UDPSpec) InitUDP() {
|
||||
}
|
||||
s.mtu = mtu
|
||||
} else {
|
||||
s.udp6 = ipv6.NewPacketConn(udp)
|
||||
s.udp6 = ipv6.NewPacketConn(s.udp)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UDPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
_ = s.udp.Close()
|
||||
}
|
||||
|
||||
@@ -86,89 +78,7 @@ func (s *UDPSpec) ListenOut(_ context.Context, _ chan struct{}, _ func(srcPort,
|
||||
}
|
||||
|
||||
func (s *UDPSpec) ListenICMP(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
|
||||
}
|
||||
|
||||
if msg.Err != nil {
|
||||
continue
|
||||
}
|
||||
finish := time.Now()
|
||||
|
||||
var data []byte // 提取 ICMP 负载
|
||||
if s.IPVersion == 4 {
|
||||
rm, err := icmp.ParseMessage(1, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv4.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv4.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 20 || data[0]>>4 != 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv4zero)) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
rm, err := icmp.ParseMessage(58, msg.Msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch rm.Type {
|
||||
case ipv6.ICMPTypeTimeExceeded:
|
||||
if body, ok := rm.Body.(*icmp.TimeExceeded); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypePacketTooBig:
|
||||
if body, ok := rm.Body.(*icmp.PacketTooBig); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
case ipv6.ICMPTypeDestinationUnreachable:
|
||||
if body, ok := rm.Body.(*icmp.DstUnreach); ok && body != nil {
|
||||
data = body.Data
|
||||
}
|
||||
default:
|
||||
//log.Println("received icmp message of unknown type", rm.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(data) < 40 || data[0]>>4 != 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv6zero)) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
onICMP(msg, finish, data)
|
||||
}
|
||||
}
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
}
|
||||
|
||||
func (s *UDPSpec) SendUDP(ctx context.Context, ipHdr ipLayer, udpHdr *layers.UDP, payload []byte) (time.Time, error) {
|
||||
@@ -178,30 +88,20 @@ func (s *UDPSpec) SendUDP(ctx context.Context, ipHdr ipLayer, udpHdr *layers.UDP
|
||||
default:
|
||||
}
|
||||
|
||||
var ttl int // 提取 IP 头中的 TTL
|
||||
if s.IPVersion == 4 {
|
||||
ip4, ok := ipHdr.(*layers.IPv4)
|
||||
if !ok || ip4 == nil {
|
||||
return time.Time{}, errors.New("SendUDP: expect *layers.IPv4 when s.IPVersion==4")
|
||||
}
|
||||
} else {
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendUDP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
|
||||
_ = udpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
ttl = int(ip6.HopLimit)
|
||||
}
|
||||
|
||||
_ = udpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
|
||||
var start time.Time
|
||||
if s.IPVersion == 4 {
|
||||
// 序列化 IP 与 UDP 头以及 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, ipHdr, udpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
@@ -221,6 +121,7 @@ func (s *UDPSpec) SendUDP(ctx context.Context, ipHdr ipLayer, udpHdr *layers.UDP
|
||||
}
|
||||
body := packet[ihl:]
|
||||
|
||||
var start time.Time // 记录起始时间
|
||||
if total <= s.mtu {
|
||||
// (1) 不分片:总长 ≤ MTU,直接发送
|
||||
start = time.Now()
|
||||
@@ -236,31 +137,45 @@ func (s *UDPSpec) SendUDP(ctx context.Context, ipHdr ipLayer, udpHdr *layers.UDP
|
||||
|
||||
start = time.Now()
|
||||
for _, fr := range frags {
|
||||
if err := s.udp4.WriteTo(fr.Hdr, fr.Body, nil); err != nil {
|
||||
if err := s.udp4.WriteTo(&fr.Hdr, fr.Body, nil); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 序列化 UDP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, udpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
if err := s.udp6.SetHopLimit(ttl); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
ip6, ok := ipHdr.(*layers.IPv6)
|
||||
if !ok || ip6 == nil {
|
||||
return time.Time{}, errors.New("SendUDP: expect *layers.IPv6 when s.IPVersion==6")
|
||||
}
|
||||
ttl := int(ip6.HopLimit)
|
||||
|
||||
start = time.Now()
|
||||
_ = udpHdr.SetNetworkLayerForChecksum(ipHdr)
|
||||
|
||||
if _, err := s.udp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
s.hopLimitLock.Unlock()
|
||||
return time.Time{}, err
|
||||
}
|
||||
s.hopLimitLock.Unlock()
|
||||
buf := gopacket.NewSerializeBuffer()
|
||||
opts := gopacket.SerializeOptions{
|
||||
ComputeChecksums: true,
|
||||
FixLengths: true,
|
||||
}
|
||||
|
||||
// 序列化 UDP 头与 payload 到缓冲区
|
||||
if err := gopacket.SerializeLayers(buf, opts, udpHdr, gopacket.Payload(payload)); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
// 串行设置 HopLimit + 发送,放在同一把锁里保证并发安全
|
||||
s.hopLimitLock.Lock()
|
||||
defer s.hopLimitLock.Unlock()
|
||||
|
||||
if err := s.udp6.SetHopLimit(ttl); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
|
||||
if _, err := s.udp.WriteTo(buf.Bytes(), &net.IPAddr{IP: s.DstIP}); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return start, nil
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
|
||||
type UDPSpec struct {
|
||||
IPVersion int
|
||||
ICMPMode int
|
||||
SrcIP net.IP
|
||||
DstIP net.IP
|
||||
DstPort int
|
||||
@@ -26,10 +27,6 @@ type UDPSpec struct {
|
||||
handle wd.Handle
|
||||
}
|
||||
|
||||
func NewUDPSpec(IPVersion int, srcIP, dstIP net.IP, dstPort int, icmp net.PacketConn) *UDPSpec {
|
||||
return &UDPSpec{IPVersion: IPVersion, SrcIP: srcIP, DstIP: dstIP, DstPort: dstPort, icmp: icmp}
|
||||
}
|
||||
|
||||
func (s *UDPSpec) InitUDP() {
|
||||
handle, err := wd.Open("false", wd.LayerNetwork, 0, 0)
|
||||
if err != nil {
|
||||
@@ -47,13 +44,46 @@ func (s *UDPSpec) InitUDP() {
|
||||
}
|
||||
|
||||
func (s *UDPSpec) Close() {
|
||||
_ = s.icmp.Close()
|
||||
_ = s.handle.Close()
|
||||
}
|
||||
|
||||
func (s *UDPSpec) ListenOut(_ context.Context, _ chan struct{}, _ func(srcPort, seq, ttl int, start time.Time)) {
|
||||
}
|
||||
|
||||
// resolveICMPMode 进行最终模式判定
|
||||
func (s *UDPSpec) resolveICMPMode() int {
|
||||
icmpMode := s.ICMPMode
|
||||
if icmpMode != 1 && icmpMode != 2 {
|
||||
icmpMode = 0 // 统一成 Auto
|
||||
}
|
||||
|
||||
// 指定 1=Socket:直接返回
|
||||
if icmpMode == 1 {
|
||||
return 1
|
||||
}
|
||||
|
||||
// Auto(0) 或强制 PCAP(2) → 尝试 PCAP
|
||||
ok, err := pcapAvailable()
|
||||
if !ok {
|
||||
if icmpMode == 2 {
|
||||
log.Printf("PCAP mode requested, but Npcap is not available: %v; falling back to Socket mode.", err)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return 2
|
||||
}
|
||||
|
||||
func (s *UDPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, data []byte)) {
|
||||
switch s.resolveICMPMode() {
|
||||
case 1:
|
||||
s.listenICMPSock(ctx, ready, onICMP)
|
||||
case 2:
|
||||
s.listenICMPPcap(ctx, ready, onICMP)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UDPSpec) listenICMPPcap(ctx context.Context, ready chan struct{}, onICMP func(msg ReceivedMessage, finish time.Time, data []byte)) {
|
||||
// 选择捕获设备与本地接口
|
||||
dev, err := util.PcapDeviceByIP(s.SrcIP)
|
||||
if err != nil {
|
||||
@@ -114,7 +144,7 @@ func (s *UDPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP fu
|
||||
outer = append(outer, packet.LayerPayload()...)
|
||||
|
||||
var peerIP net.IP // 提取对端 IP(按族别)
|
||||
var data []byte // 提取 ICMP 负载
|
||||
var data []byte // 提取 ICMP 的负载
|
||||
if s.IPVersion == 4 {
|
||||
// 从包中获取 IPv4 层信息
|
||||
ip4, ok := pkt.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
|
||||
@@ -143,7 +173,7 @@ func (s *UDPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP fu
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[16:20])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv4zero)) {
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
@@ -175,7 +205,7 @@ func (s *UDPSpec) ListenICMP(ctx context.Context, ready chan struct{}, onICMP fu
|
||||
}
|
||||
|
||||
dstIP := net.IP(data[24:40])
|
||||
if !(dstIP.Equal(s.DstIP) || dstIP.Equal(net.IPv6zero)) {
|
||||
if !dstIP.Equal(s.DstIP) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
+11
-23
@@ -14,7 +14,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace/internal"
|
||||
@@ -25,12 +24,11 @@ type TCPTracer struct {
|
||||
Config
|
||||
wg sync.WaitGroup
|
||||
res Result
|
||||
pendingMu sync.Mutex
|
||||
pending map[int]struct{}
|
||||
sentMu sync.RWMutex
|
||||
pendingMu sync.Mutex
|
||||
sentAt map[int]sentInfo
|
||||
sentMu sync.RWMutex
|
||||
SrcIP net.IP
|
||||
icmp net.PacketConn
|
||||
final atomic.Int32
|
||||
sem *semaphore.Weighted
|
||||
matchQ chan matchTask
|
||||
@@ -252,7 +250,7 @@ func (t *TCPTracer) Execute() (res *Result, err error) {
|
||||
return &t.res, errTracerouteExecuted
|
||||
}
|
||||
|
||||
// 初始化 Result.Hops,并预分配到 MaxHops
|
||||
// 初始化 res.Hops 和 res.tailDone,并预分配到 MaxHops
|
||||
t.res.Hops = make([][]Hop, t.MaxHops)
|
||||
t.res.tailDone = make([]bool, t.MaxHops)
|
||||
|
||||
@@ -266,25 +264,16 @@ func (t *TCPTracer) Execute() (res *Result, err error) {
|
||||
return nil, errors.New("cannot determine local IPv4 address")
|
||||
}
|
||||
|
||||
t.icmp, err = icmp.ListenPacket("ip4:icmp", t.SrcIP.String())
|
||||
if err != nil {
|
||||
return &t.res, err
|
||||
}
|
||||
defer func() {
|
||||
if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
s := internal.NewTCPSpec(
|
||||
4,
|
||||
t.ICMPMode,
|
||||
t.SrcIP,
|
||||
t.DstIP,
|
||||
t.DstPort,
|
||||
t.icmp,
|
||||
t.PktSize,
|
||||
)
|
||||
|
||||
s.InitICMP()
|
||||
s.InitTCP()
|
||||
defer s.Close()
|
||||
|
||||
@@ -353,11 +342,11 @@ func (t *TCPTracer) Execute() (res *Result, err error) {
|
||||
stop()
|
||||
t.wg.Wait()
|
||||
|
||||
bound := int(t.final.Load())
|
||||
if bound == -1 {
|
||||
bound = t.MaxHops
|
||||
final := int(t.final.Load())
|
||||
if final == -1 {
|
||||
final = t.MaxHops
|
||||
}
|
||||
t.res.reduce(bound)
|
||||
t.res.reduce(final)
|
||||
|
||||
if cause := context.Cause(ctx); !errors.Is(cause, errNaturalDone) {
|
||||
return &t.res, cause
|
||||
@@ -390,7 +379,7 @@ func (t *TCPTracer) handleICMPMessage(msg internal.ReceivedMessage, finish time.
|
||||
// 非阻塞投递;如果队列已满则直接丢弃该任务
|
||||
select {
|
||||
case t.matchQ <- matchTask{
|
||||
srcPort: srcPort, seq: int(seq), peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
srcPort: srcPort, seq: seq, peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
}:
|
||||
default:
|
||||
// 丢弃以避免阻塞抓包循环
|
||||
@@ -431,7 +420,6 @@ func (t *TCPTracer) send(ctx context.Context, s *internal.TCPSpec, ttl, i int) e
|
||||
|
||||
ipHeader := &layers.IPv4{
|
||||
Version: 4,
|
||||
IHL: 5,
|
||||
SrcIP: t.SrcIP,
|
||||
DstIP: t.DstIP,
|
||||
Protocol: layers.IPProtocolTCP,
|
||||
@@ -443,7 +431,7 @@ func (t *TCPTracer) send(ctx context.Context, s *internal.TCPSpec, ttl, i int) e
|
||||
DstPort: layers.TCPPort(t.DstPort),
|
||||
Seq: uint32(seq),
|
||||
SYN: true,
|
||||
Window: 14600,
|
||||
Window: 65535,
|
||||
Options: []layers.TCPOption{
|
||||
{OptionType: layers.TCPOptionKindMSS, OptionLength: 4, OptionData: []byte{0x05, 0xb4}}, // MSS=1460
|
||||
},
|
||||
|
||||
+11
-22
@@ -14,7 +14,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace/internal"
|
||||
@@ -25,12 +24,11 @@ type TCPTracerIPv6 struct {
|
||||
Config
|
||||
wg sync.WaitGroup
|
||||
res Result
|
||||
pendingMu sync.Mutex
|
||||
pending map[int]struct{}
|
||||
sentMu sync.RWMutex
|
||||
pendingMu sync.Mutex
|
||||
sentAt map[int]sentInfo
|
||||
sentMu sync.RWMutex
|
||||
SrcIP net.IP
|
||||
icmp net.PacketConn
|
||||
final atomic.Int32
|
||||
sem *semaphore.Weighted
|
||||
matchQ chan matchTask
|
||||
@@ -252,7 +250,7 @@ func (t *TCPTracerIPv6) Execute() (res *Result, err error) {
|
||||
return &t.res, errTracerouteExecuted
|
||||
}
|
||||
|
||||
// 初始化 Result.Hops,并预分配到 MaxHops
|
||||
// 初始化 res.Hops 和 res.tailDone,并预分配到 MaxHops
|
||||
t.res.Hops = make([][]Hop, t.MaxHops)
|
||||
t.res.tailDone = make([]bool, t.MaxHops)
|
||||
|
||||
@@ -266,25 +264,16 @@ func (t *TCPTracerIPv6) Execute() (res *Result, err error) {
|
||||
return nil, errors.New("cannot determine local IPv6 address")
|
||||
}
|
||||
|
||||
t.icmp, err = icmp.ListenPacket("ip6:ipv6-icmp", t.SrcIP.String())
|
||||
if err != nil {
|
||||
return &t.res, err
|
||||
}
|
||||
defer func() {
|
||||
if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
s := internal.NewTCPSpec(
|
||||
6,
|
||||
t.ICMPMode,
|
||||
t.SrcIP,
|
||||
t.DstIP,
|
||||
t.DstPort,
|
||||
t.icmp,
|
||||
t.PktSize,
|
||||
)
|
||||
|
||||
s.InitICMP()
|
||||
s.InitTCP()
|
||||
defer s.Close()
|
||||
|
||||
@@ -353,11 +342,11 @@ func (t *TCPTracerIPv6) Execute() (res *Result, err error) {
|
||||
stop()
|
||||
t.wg.Wait()
|
||||
|
||||
bound := int(t.final.Load())
|
||||
if bound == -1 {
|
||||
bound = t.MaxHops
|
||||
final := int(t.final.Load())
|
||||
if final == -1 {
|
||||
final = t.MaxHops
|
||||
}
|
||||
t.res.reduce(bound)
|
||||
t.res.reduce(final)
|
||||
|
||||
if cause := context.Cause(ctx); !errors.Is(cause, errNaturalDone) {
|
||||
return &t.res, cause
|
||||
@@ -390,7 +379,7 @@ func (t *TCPTracerIPv6) handleICMPMessage(msg internal.ReceivedMessage, finish t
|
||||
// 非阻塞投递;如果队列已满则直接丢弃该任务
|
||||
select {
|
||||
case t.matchQ <- matchTask{
|
||||
srcPort: srcPort, seq: int(seq), peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
srcPort: srcPort, seq: seq, peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
}:
|
||||
default:
|
||||
// 丢弃以避免阻塞抓包循环
|
||||
@@ -442,7 +431,7 @@ func (t *TCPTracerIPv6) send(ctx context.Context, s *internal.TCPSpec, ttl, i in
|
||||
DstPort: layers.TCPPort(t.DstPort),
|
||||
Seq: uint32(seq),
|
||||
SYN: true,
|
||||
Window: 14600,
|
||||
Window: 65535,
|
||||
Options: []layers.TCPOption{
|
||||
{OptionType: layers.TCPOptionKindMSS, OptionLength: 4, OptionData: []byte{0x05, 0xA0}}, // MSS=1440
|
||||
},
|
||||
|
||||
+95
-38
@@ -11,11 +11,11 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace/internal"
|
||||
"golang.org/x/net/idna"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/ipgeo"
|
||||
"github.com/nxtrace/NTrace-core/trace/internal"
|
||||
"github.com/nxtrace/NTrace-core/util"
|
||||
)
|
||||
|
||||
@@ -24,13 +24,15 @@ var (
|
||||
errInvalidMethod = errors.New("invalid method")
|
||||
errNaturalDone = errors.New("trace natural done")
|
||||
errTracerouteExecuted = errors.New("traceroute already executed")
|
||||
lastErr error
|
||||
geoCache = sync.Map{}
|
||||
ipGeoSF singleflight.Group
|
||||
rDNSSF singleflight.Group
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
OSKind int
|
||||
OSType int
|
||||
ICMPMode int
|
||||
SrcAddr string
|
||||
SrcPort int
|
||||
BeginHop int
|
||||
@@ -107,6 +109,19 @@ func Traceroute(method Method, config Config) (*Result, error) {
|
||||
config.ParallelRequests = config.NumMeasurements * 5
|
||||
}
|
||||
|
||||
// 若 CLI 未给或给了非正数,则尝试用环境变量
|
||||
if config.ICMPMode <= 0 && util.EnvICMPMode > 0 {
|
||||
config.ICMPMode = util.EnvICMPMode
|
||||
}
|
||||
|
||||
switch config.ICMPMode {
|
||||
case 0, 1, 2:
|
||||
// 合法,保持不变
|
||||
default:
|
||||
// 非法输入一律回退到 Auto
|
||||
config.ICMPMode = 0
|
||||
}
|
||||
|
||||
// 若 CLI 未给或给了非正数,则尝试用环境变量
|
||||
if config.MaxAttempts <= 0 && util.EnvMaxAttempts > 0 {
|
||||
config.MaxAttempts = util.EnvMaxAttempts
|
||||
@@ -146,6 +161,7 @@ func Traceroute(method Method, config Config) (*Result, error) {
|
||||
default:
|
||||
return &Result{}, errInvalidMethod
|
||||
}
|
||||
|
||||
result, err := tracer.Execute()
|
||||
if err != nil && errors.Is(err, syscall.EPERM) {
|
||||
err = fmt.Errorf("%w, please run as root", err)
|
||||
@@ -271,7 +287,7 @@ func CanonicalHostname(s string) string {
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
func (h *Hop) fetchIPData(c Config) (err error) {
|
||||
func (h *Hop) fetchIPData(c Config) error {
|
||||
ipStr := h.Address.String()
|
||||
// DN42
|
||||
if c.DN42 {
|
||||
@@ -299,23 +315,42 @@ func (h *Hop) fetchIPData(c Config) (err error) {
|
||||
}
|
||||
}
|
||||
// singleflight 合并相同 key 的并发查询
|
||||
v, err, _ := ipGeoSF.Do(combined, func() (any, error) {
|
||||
timeout := c.Timeout
|
||||
if timeout < 2*time.Second {
|
||||
timeout = 2 * time.Second
|
||||
maxRetries := c.NumMeasurements - 1
|
||||
if maxRetries < 0 {
|
||||
maxRetries = 0
|
||||
}
|
||||
if maxRetries > 5 {
|
||||
maxRetries = 5
|
||||
}
|
||||
|
||||
for attempt := 0; attempt <= maxRetries; attempt++ {
|
||||
// 超时:2s 起,每次 +1s,上限 6s
|
||||
timeout := time.Duration(2+attempt) * time.Second
|
||||
if timeout > 6*time.Second {
|
||||
timeout = 6 * time.Second
|
||||
}
|
||||
return c.IPGeoSource(combined, timeout, c.Lang, c.Maptrace)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
v, err, _ := ipGeoSF.Do(combined, func() (any, error) {
|
||||
return c.IPGeoSource(combined, timeout, c.Lang, c.Maptrace)
|
||||
})
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
geo, ok := v.(*ipgeo.IPGeoData)
|
||||
if !ok || geo == nil {
|
||||
lastErr = errors.New("ipgeo: nil or bad type from singleflight (DN42)")
|
||||
continue
|
||||
}
|
||||
|
||||
// 成功:写入结果与缓存,结束
|
||||
h.Geo = geo
|
||||
geoCache.Store(combined, h.Geo)
|
||||
return nil
|
||||
}
|
||||
geo, ok := v.(*ipgeo.IPGeoData)
|
||||
if !ok || geo == nil {
|
||||
return errors.New("ipgeo: nil or bad type from singleflight (DN42)")
|
||||
}
|
||||
h.Geo = geo
|
||||
// 如果缓存中无结果,进行查询并将结果存入缓存
|
||||
geoCache.Store(combined, h.Geo)
|
||||
// 所有尝试均失败
|
||||
return lastErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -342,25 +377,43 @@ func (h *Hop) fetchIPData(c Config) (err error) {
|
||||
}
|
||||
}
|
||||
// (3) singleflight 去重
|
||||
timeout := c.Timeout
|
||||
if timeout < 2*time.Second {
|
||||
timeout = 2 * time.Second
|
||||
maxRetries := c.NumMeasurements - 1
|
||||
if maxRetries < 0 {
|
||||
maxRetries = 0
|
||||
}
|
||||
v, err, _ := ipGeoSF.Do(ipStr, func() (any, error) {
|
||||
return c.IPGeoSource(ipStr, timeout, c.Lang, c.Maptrace)
|
||||
})
|
||||
if err != nil {
|
||||
ipGeoCh <- err
|
||||
if maxRetries > 5 {
|
||||
maxRetries = 5
|
||||
}
|
||||
|
||||
for attempt := 0; attempt <= maxRetries; attempt++ {
|
||||
// 超时:2s 起,每次 +1s,上限 6s
|
||||
timeout := time.Duration(2+attempt) * time.Second
|
||||
if timeout > 6*time.Second {
|
||||
timeout = 6 * time.Second
|
||||
}
|
||||
|
||||
v, err, _ := ipGeoSF.Do(ipStr, func() (any, error) {
|
||||
return c.IPGeoSource(ipStr, timeout, c.Lang, c.Maptrace)
|
||||
})
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
geo, ok := v.(*ipgeo.IPGeoData)
|
||||
if !ok || geo == nil {
|
||||
lastErr = errors.New("ipgeo: nil or bad type from singleflight")
|
||||
continue
|
||||
}
|
||||
|
||||
// 成功:写入结果与缓存,结束
|
||||
h.Geo = geo
|
||||
geoCache.Store(ipStr, h.Geo)
|
||||
ipGeoCh <- nil
|
||||
return
|
||||
}
|
||||
geo, ok := v.(*ipgeo.IPGeoData)
|
||||
if !ok || geo == nil {
|
||||
ipGeoCh <- errors.New("ipgeo: nil or bad type from singleflight")
|
||||
return
|
||||
}
|
||||
h.Geo = geo
|
||||
geoCache.Store(ipStr, h.Geo)
|
||||
ipGeoCh <- nil
|
||||
// 所有尝试均失败
|
||||
ipGeoCh <- lastErr
|
||||
}()
|
||||
|
||||
rDNSStarted := c.RDNS && h.Hostname == ""
|
||||
@@ -370,10 +423,14 @@ func (h *Hop) fetchIPData(c Config) (err error) {
|
||||
v, _, _ := rDNSSF.Do(ipStr, func() (any, error) {
|
||||
return util.LookupAddr(ipStr)
|
||||
})
|
||||
if ptrs, _ := v.([]string); len(ptrs) > 0 {
|
||||
rDNSCh <- ptrs
|
||||
} else {
|
||||
rDNSCh <- nil
|
||||
var ptrs []string
|
||||
if p, _ := v.([]string); len(p) > 0 {
|
||||
ptrs = p
|
||||
}
|
||||
// 非阻塞发送:没人收或通道已满就丢弃,保证不阻塞
|
||||
select {
|
||||
case rDNSCh <- ptrs:
|
||||
default:
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
+20
-30
@@ -14,7 +14,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace/internal"
|
||||
@@ -25,14 +24,13 @@ type UDPTracer struct {
|
||||
Config
|
||||
wg sync.WaitGroup
|
||||
res Result
|
||||
ttlQMu sync.Mutex
|
||||
ttlQueues map[int][]attemptPort
|
||||
pendingMu sync.Mutex
|
||||
ttlQMu sync.Mutex
|
||||
pending map[attemptKey]struct{}
|
||||
sentMu sync.RWMutex
|
||||
pendingMu sync.Mutex
|
||||
sentAt map[int]sentInfo
|
||||
sentMu sync.RWMutex
|
||||
SrcIP net.IP
|
||||
icmp net.PacketConn
|
||||
final atomic.Int32
|
||||
sem *semaphore.Weighted
|
||||
matchQ chan matchTask
|
||||
@@ -168,7 +166,7 @@ func (t *UDPTracer) clearPending(ttl, i int) bool {
|
||||
func (t *UDPTracer) storeSent(seq, ttl, i, srcPort int, start time.Time) {
|
||||
t.sentMu.Lock()
|
||||
defer t.sentMu.Unlock()
|
||||
if t.OSKind != 1 {
|
||||
if t.OSType != 1 {
|
||||
t.sentAt[seq] = sentInfo{srcPort: srcPort, start: start}
|
||||
} else {
|
||||
t.sentAt[seq] = sentInfo{ttl: ttl, i: i, srcPort: srcPort, start: start}
|
||||
@@ -264,7 +262,7 @@ func (t *UDPTracer) matchWorker(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
|
||||
if t.OSKind != 1 {
|
||||
if t.OSType != 1 {
|
||||
// 将 task.seq 转为 16 位无符号数
|
||||
u := uint16(task.seq)
|
||||
|
||||
@@ -300,7 +298,7 @@ func (t *UDPTracer) Execute() (res *Result, err error) {
|
||||
return &t.res, errTracerouteExecuted
|
||||
}
|
||||
|
||||
// 初始化 Result.Hops,并预分配到 MaxHops
|
||||
// 初始化 res.Hops 和 res.tailDone,并预分配到 MaxHops
|
||||
t.res.Hops = make([][]Hop, t.MaxHops)
|
||||
t.res.tailDone = make([]bool, t.MaxHops)
|
||||
|
||||
@@ -314,24 +312,15 @@ func (t *UDPTracer) Execute() (res *Result, err error) {
|
||||
return nil, errors.New("cannot determine local IPv4 address")
|
||||
}
|
||||
|
||||
t.icmp, err = icmp.ListenPacket("ip4:icmp", t.SrcIP.String())
|
||||
if err != nil {
|
||||
return &t.res, err
|
||||
}
|
||||
defer func() {
|
||||
if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
s := internal.NewUDPSpec(
|
||||
4,
|
||||
t.ICMPMode,
|
||||
t.SrcIP,
|
||||
t.DstIP,
|
||||
t.DstPort,
|
||||
t.icmp,
|
||||
)
|
||||
|
||||
s.InitICMP()
|
||||
s.InitUDP()
|
||||
defer s.Close()
|
||||
|
||||
@@ -344,7 +333,7 @@ func (t *UDPTracer) Execute() (res *Result, err error) {
|
||||
t.wg.Add(1)
|
||||
go t.matchWorker(ctx)
|
||||
}
|
||||
if t.OSKind == 1 {
|
||||
if t.OSType == 1 {
|
||||
t.wg.Add(1)
|
||||
go func() {
|
||||
defer t.wg.Done()
|
||||
@@ -402,11 +391,11 @@ func (t *UDPTracer) Execute() (res *Result, err error) {
|
||||
stop()
|
||||
t.wg.Wait()
|
||||
|
||||
bound := int(t.final.Load())
|
||||
if bound == -1 {
|
||||
bound = t.MaxHops
|
||||
final := int(t.final.Load())
|
||||
if final == -1 {
|
||||
final = t.MaxHops
|
||||
}
|
||||
t.res.reduce(bound)
|
||||
t.res.reduce(final)
|
||||
|
||||
if cause := context.Cause(ctx); !errors.Is(cause, errNaturalDone) {
|
||||
return &t.res, cause
|
||||
@@ -439,7 +428,7 @@ func (t *UDPTracer) handleICMPMessage(msg internal.ReceivedMessage, finish time.
|
||||
// 非阻塞投递;如果队列已满则直接丢弃该任务
|
||||
select {
|
||||
case t.matchQ <- matchTask{
|
||||
srcPort: srcPort, seq: int(seq), peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
srcPort: srcPort, seq: seq, peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
}:
|
||||
default:
|
||||
// 丢弃以避免阻塞抓包循环
|
||||
@@ -480,7 +469,6 @@ func (t *UDPTracer) send(ctx context.Context, s *internal.UDPSpec, ttl, i int) e
|
||||
|
||||
ipHeader := &layers.IPv4{
|
||||
Version: 4,
|
||||
IHL: 5,
|
||||
Id: uint16(seq),
|
||||
SrcIP: t.SrcIP,
|
||||
DstIP: t.DstIP,
|
||||
@@ -502,8 +490,10 @@ func (t *UDPTracer) send(ctx context.Context, s *internal.UDPSpec, ttl, i int) e
|
||||
payload[k] = byte(r.Intn(256))
|
||||
}
|
||||
|
||||
// 记录 TTL 队列
|
||||
t.enqueueTTLPort(ttl, i, SrcPort)
|
||||
if t.OSType == 1 {
|
||||
// 记录 TTL 队列
|
||||
t.enqueueTTLPort(ttl, i, SrcPort)
|
||||
}
|
||||
|
||||
// 登记 pending,并启动超时守护
|
||||
t.markPending(ttl, i)
|
||||
@@ -535,7 +525,7 @@ func (t *UDPTracer) send(ctx context.Context, s *internal.UDPSpec, ttl, i int) e
|
||||
}
|
||||
|
||||
t.res.add(h, i, t.NumMeasurements, t.MaxAttempts)
|
||||
if t.OSKind != 1 {
|
||||
if t.OSType != 1 {
|
||||
t.dropSent(seq)
|
||||
} else {
|
||||
t.dropByAttempt(ttl, i)
|
||||
@@ -549,7 +539,7 @@ func (t *UDPTracer) send(ctx context.Context, s *internal.UDPSpec, ttl, i int) e
|
||||
return err
|
||||
}
|
||||
|
||||
if t.OSKind != 1 {
|
||||
if t.OSType != 1 {
|
||||
t.storeSent(seq, 0, 0, SrcPort, start)
|
||||
}
|
||||
return nil
|
||||
|
||||
+10
-21
@@ -14,7 +14,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/trace/internal"
|
||||
@@ -25,12 +24,11 @@ type UDPTracerIPv6 struct {
|
||||
Config
|
||||
wg sync.WaitGroup
|
||||
res Result
|
||||
pendingMu sync.Mutex
|
||||
pending map[int]struct{}
|
||||
sentMu sync.RWMutex
|
||||
pendingMu sync.Mutex
|
||||
sentAt map[int]sentInfo
|
||||
sentMu sync.RWMutex
|
||||
SrcIP net.IP
|
||||
icmp net.PacketConn
|
||||
final atomic.Int32
|
||||
sem *semaphore.Weighted
|
||||
matchQ chan matchTask
|
||||
@@ -252,7 +250,7 @@ func (t *UDPTracerIPv6) Execute() (res *Result, err error) {
|
||||
return &t.res, errTracerouteExecuted
|
||||
}
|
||||
|
||||
// 初始化 Result.Hops,并预分配到 MaxHops
|
||||
// 初始化 res.Hops 和 res.tailDone,并预分配到 MaxHops
|
||||
t.res.Hops = make([][]Hop, t.MaxHops)
|
||||
t.res.tailDone = make([]bool, t.MaxHops)
|
||||
|
||||
@@ -266,24 +264,15 @@ func (t *UDPTracerIPv6) Execute() (res *Result, err error) {
|
||||
return nil, errors.New("cannot determine local IPv6 address")
|
||||
}
|
||||
|
||||
t.icmp, err = icmp.ListenPacket("ip6:ipv6-icmp", t.SrcIP.String())
|
||||
if err != nil {
|
||||
return &t.res, err
|
||||
}
|
||||
defer func() {
|
||||
if c := t.icmp; c != nil { // 先拷一份引用,避免 defer 执行时 t.icmp 已被并发改写
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
s := internal.NewUDPSpec(
|
||||
6,
|
||||
t.ICMPMode,
|
||||
t.SrcIP,
|
||||
t.DstIP,
|
||||
t.DstPort,
|
||||
t.icmp,
|
||||
)
|
||||
|
||||
s.InitICMP()
|
||||
s.InitUDP()
|
||||
defer s.Close()
|
||||
|
||||
@@ -338,11 +327,11 @@ func (t *UDPTracerIPv6) Execute() (res *Result, err error) {
|
||||
stop()
|
||||
t.wg.Wait()
|
||||
|
||||
bound := int(t.final.Load())
|
||||
if bound == -1 {
|
||||
bound = t.MaxHops
|
||||
final := int(t.final.Load())
|
||||
if final == -1 {
|
||||
final = t.MaxHops
|
||||
}
|
||||
t.res.reduce(bound)
|
||||
t.res.reduce(final)
|
||||
|
||||
if cause := context.Cause(ctx); !errors.Is(cause, errNaturalDone) {
|
||||
return &t.res, cause
|
||||
@@ -375,7 +364,7 @@ func (t *UDPTracerIPv6) handleICMPMessage(msg internal.ReceivedMessage, finish t
|
||||
// 非阻塞投递;如果队列已满则直接丢弃该任务
|
||||
select {
|
||||
case t.matchQ <- matchTask{
|
||||
srcPort: srcPort, seq: int(seq), peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
srcPort: srcPort, seq: seq, peer: msg.Peer, finish: finish, mpls: mpls,
|
||||
}:
|
||||
default:
|
||||
// 丢弃以避免阻塞抓包循环
|
||||
|
||||
@@ -19,6 +19,7 @@ var (
|
||||
EnvHostPort = GetEnvDefault("NEXTTRACE_HOSTPORT", "api.nxtrace.org")
|
||||
EnvPowProvider = GetEnvDefault("NEXTTRACE_POWPROVIDER", "api.nxtrace.org")
|
||||
EnvMaxAttempts = GetEnvInt("NEXTTRACE_MAXATTEMPTS", 0)
|
||||
EnvICMPMode = GetEnvInt("NEXTTRACE_ICMPMODE", 0)
|
||||
)
|
||||
|
||||
func GetEnvTrimmed(key string) (string, bool) {
|
||||
|
||||
+36
-15
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
type IPv4Fragment struct {
|
||||
Hdr *ipv4.Header
|
||||
Hdr ipv4.Header
|
||||
Body []byte
|
||||
}
|
||||
|
||||
@@ -65,39 +65,60 @@ func GetMTUByIP(srcIP net.IP) int {
|
||||
|
||||
// IPv4Fragmentize 将 base(IPv4 头)与 body(IPv4 负载:传输层头+数据)按 mtu 进行 IP 层分片
|
||||
func IPv4Fragmentize(base *ipv4.Header, body []byte, mtu int) ([]IPv4Fragment, error) {
|
||||
const (
|
||||
ipFlagMoreFragments = 0x2000
|
||||
ipOffsetMask = 0x1FFF
|
||||
)
|
||||
// 低 13 位为分片偏移(单位 8 字节)
|
||||
const ipOffsetMask = 0x1FFF
|
||||
|
||||
// 提取 IPv4 头长度 ihl
|
||||
ihl := base.Len
|
||||
|
||||
// MTU 至少要容纳一个完整 IPv4 头
|
||||
if mtu <= ihl {
|
||||
return nil, errors.New("IPv4Fragmentize: MTU too small (<= IHL)")
|
||||
}
|
||||
maxFragBody := mtu - ihl
|
||||
aligned := (maxFragBody / 8) * 8
|
||||
frags := make([]IPv4Fragment, 0, (len(body)+aligned-1)/aligned)
|
||||
|
||||
// 假如已经置位 DF=1,则直接报错并返回 nil
|
||||
if (base.Flags & ipv4.DontFragment) != 0 {
|
||||
return nil, errors.New("IPv4Fragmentize: DF set while fragmentation required")
|
||||
}
|
||||
|
||||
// 非最后片的片内负载长度按 8 字节对齐
|
||||
aligned := (maxFragBody / 8) * 8
|
||||
|
||||
// 预分配结果切片的容量
|
||||
capacity := (len(body) + aligned - 1) / aligned
|
||||
frags := make([]IPv4Fragment, 0, capacity)
|
||||
|
||||
// 按 aligned 切出所有的分片(最后片承载所有剩余字节)
|
||||
for off := 0; off < len(body); {
|
||||
remain := len(body) - off
|
||||
fragLen, more := remain, false
|
||||
if remain > aligned {
|
||||
fragLen, more = aligned, true
|
||||
more := off+aligned < len(body)
|
||||
fragLen := len(body) - off
|
||||
if more {
|
||||
fragLen = aligned
|
||||
}
|
||||
|
||||
// 为每片拷贝出独立头部
|
||||
h := *base
|
||||
h.Len = ihl
|
||||
h.TotalLen = ihl + fragLen
|
||||
|
||||
// 偏移单位:8 字节;设置 MF/offset
|
||||
h.FragOff &^= ipFlagMoreFragments | ipOffsetMask
|
||||
// 先清除已有的 MF 标志
|
||||
h.Flags &^= ipv4.MoreFragments
|
||||
|
||||
// 写入分片偏移(仅低 13 位,单位 8 字节)
|
||||
h.FragOff &^= ipOffsetMask
|
||||
h.FragOff |= (off / 8) & ipOffsetMask
|
||||
|
||||
// 非最后片,则置位 MF=1 到 Flags 字段中
|
||||
if more {
|
||||
h.FragOff |= ipFlagMoreFragments
|
||||
h.Flags |= ipv4.MoreFragments
|
||||
}
|
||||
|
||||
// 置 0 使 Marshal 重算 IPv4 头校验和
|
||||
h.Checksum = 0
|
||||
|
||||
frags = append(frags, IPv4Fragment{
|
||||
Hdr: &h,
|
||||
Hdr: h,
|
||||
Body: body[off : off+fragLen],
|
||||
})
|
||||
off += fragLen
|
||||
|
||||
+23
-7
@@ -90,6 +90,22 @@ func GetICMPResponsePayload(data []byte) ([]byte, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func GetICMPID(data []byte) (int, error) {
|
||||
if len(data) < 6 {
|
||||
return 0, errors.New("length of icmp header too short for ID")
|
||||
}
|
||||
seqBytes := data[4:6]
|
||||
return int(binary.BigEndian.Uint16(seqBytes)), nil
|
||||
}
|
||||
|
||||
func GetICMPSeq(data []byte) (int, error) {
|
||||
if len(data) < 8 {
|
||||
return 0, errors.New("length of icmp header too short for seq")
|
||||
}
|
||||
seqBytes := data[6:8]
|
||||
return int(binary.BigEndian.Uint16(seqBytes)), nil
|
||||
}
|
||||
|
||||
func GetTCPPorts(data []byte) (int, int, error) {
|
||||
if len(data) < 4 {
|
||||
return 0, 0, errors.New("length of tcp header too short for ports")
|
||||
@@ -99,12 +115,12 @@ func GetTCPPorts(data []byte) (int, int, error) {
|
||||
return srcPort, dstPort, nil
|
||||
}
|
||||
|
||||
func GetTCPSeq(data []byte) (uint32, error) {
|
||||
func GetTCPSeq(data []byte) (int, error) {
|
||||
if len(data) < 8 {
|
||||
return 0, errors.New("length of tcp header too short for seq")
|
||||
}
|
||||
seqBytes := data[4:8]
|
||||
return binary.BigEndian.Uint32(seqBytes), nil
|
||||
return int(binary.BigEndian.Uint32(seqBytes)), nil
|
||||
}
|
||||
|
||||
func GetUDPPorts(data []byte) (int, int, error) {
|
||||
@@ -116,9 +132,9 @@ func GetUDPPorts(data []byte) (int, int, error) {
|
||||
return srcPort, dstPort, nil
|
||||
}
|
||||
|
||||
func GetUDPSeq(data []byte) (uint16, error) {
|
||||
func GetUDPSeq(data []byte) (int, error) {
|
||||
if len(data) < 1 {
|
||||
return 0, errors.New("received invalid IP header")
|
||||
return 0, errors.New("received invalid IPv4 header")
|
||||
}
|
||||
hdrLen, err := GetIPHeaderLength(data)
|
||||
if err != nil {
|
||||
@@ -128,13 +144,13 @@ func GetUDPSeq(data []byte) (uint16, error) {
|
||||
return 0, errors.New("length of IPv4 header too short for seq")
|
||||
}
|
||||
seqBytes := data[4:6]
|
||||
return binary.BigEndian.Uint16(seqBytes), nil
|
||||
return int(binary.BigEndian.Uint16(seqBytes)), nil
|
||||
}
|
||||
|
||||
func GetUDPSeqv6(data []byte) (uint16, error) {
|
||||
func GetUDPSeqv6(data []byte) (int, error) {
|
||||
if len(data) < 8 {
|
||||
return 0, errors.New("length of udp header too short for seq")
|
||||
}
|
||||
seqBytes := data[6:8]
|
||||
return binary.BigEndian.Uint16(seqBytes), nil
|
||||
return int(binary.BigEndian.Uint16(seqBytes)), nil
|
||||
}
|
||||
+14
-2
@@ -75,7 +75,11 @@ func LookupAddr(addr string) ([]string, error) {
|
||||
|
||||
// getLocalIPPort(仅用于 IPv4):
|
||||
// (1) 若 srcIP 非空,则以其为绑定源 IP;否则先通过 DialUDP 到 dstIP 获取实际出站源 IP
|
||||
// (2) 根据 proto("tcp"/"udp") 做一次本地端口可用性测试(Listen* 绑定 Port=0,让内核挑一个可用端口)
|
||||
// (2) 根据 proto:
|
||||
//
|
||||
// "icmp" :直接返回 bindIP,bindPort=0(表示“无端口”);
|
||||
// "tcp"/"udp":使用 Listen* 以 Port=0 做一次本地绑定测试,让内核分配可用端口,并在记录后立即关闭
|
||||
//
|
||||
// (3) 立即关闭监听并返回 (bindIP, bindPort),若出错则返回 (nil, -1)
|
||||
func getLocalIPPort(dstIP net.IP, srcIP net.IP, proto string) (net.IP, int) {
|
||||
if dstIP == nil || dstIP.To4() == nil {
|
||||
@@ -102,6 +106,8 @@ func getLocalIPPort(dstIP net.IP, srcIP net.IP, proto string) (net.IP, int) {
|
||||
|
||||
// (2) 按需求测试端口可用性(仅本地 bind,不做网络握手)
|
||||
switch proto {
|
||||
case "icmp":
|
||||
return bindIP, 0
|
||||
case "tcp":
|
||||
ln, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: bindIP, Port: 0})
|
||||
if err != nil {
|
||||
@@ -124,7 +130,11 @@ func getLocalIPPort(dstIP net.IP, srcIP net.IP, proto string) (net.IP, int) {
|
||||
|
||||
// getLocalIPPortv6(仅用于 IPv6):
|
||||
// (1) 若 srcIP 非空,则以其为绑定源 IP;否则先通过 DialUDP 到 dstIP 获取实际出站源 IP
|
||||
// (2) 根据 proto("tcp6"/"udp6") 做一次本地端口可用性测试(Listen* 绑定 Port=0,让内核挑一个可用端口)
|
||||
// (2) 根据 proto:
|
||||
//
|
||||
// "icmp6" :直接返回 bindIP,bindPort=0(表示“无端口”);
|
||||
// "tcp6"/"udp6":使用 Listen* 以 Port=0 做一次本地绑定测试,让内核分配可用端口,并在记录后立即关闭
|
||||
//
|
||||
// (3) 立即关闭监听并返回 (bindIP, bindPort),若出错则返回 (nil, -1)
|
||||
func getLocalIPPortv6(dstIP net.IP, srcIP net.IP, proto string) (net.IP, int) {
|
||||
if !IsIPv6(dstIP) {
|
||||
@@ -151,6 +161,8 @@ func getLocalIPPortv6(dstIP net.IP, srcIP net.IP, proto string) (net.IP, int) {
|
||||
|
||||
// (2) 按需求测试端口可用性(仅本地 bind,不做网络握手)
|
||||
switch proto {
|
||||
case "icmp6":
|
||||
return bindIP, 0
|
||||
case "tcp6":
|
||||
ln, err := net.ListenTCP("tcp6", &net.TCPAddr{IP: bindIP, Port: 0})
|
||||
if err != nil {
|
||||
|
||||
Reference in new issue
Block a user