forked from eaglesunshine/trace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrace.go
272 lines (223 loc) · 5.29 KB
/
trace.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package ztrace
import (
"fmt"
"net"
"runtime"
"sync"
"time"
"github.com/eaglesunshine/trace/tsyncmap"
"github.com/sirupsen/logrus"
)
type SendMetric struct {
FlowKey string
ID uint32
TTL uint8
TimeStamp time.Time
}
type RecvMetric struct {
FlowKey string
ID uint32
RespAddr string
TimeStamp time.Time
}
type TraceRoute struct {
SrcAddr string
Dest string
TCPDPort uint16
TCPProbePorts []uint16
MaxPath int
MaxTTL uint8
Protocol string
PacketRate float32
WideMode bool
PortOffset int32
NetSrcAddr net.IP
NetDstAddr net.IP
Af string
recvICMPConn *net.IPConn
recvTCPConn *net.IPConn
DB sync.Map
Metric []map[string][]*ServerRecord
LastMetric []map[string][]*ServerRecord
Latitude float64
Longitude float64
Lock *sync.RWMutex
Timeout time.Duration
LastArrived int
Hops []HopData
StartTime time.Time
RecordLock sync.Mutex
SendMap map[string]*SendMetric
}
type StatsDB struct {
Cache *tsyncmap.Map
SendCnt *uint64
}
func NewStatsDB(key string) *StatsDB {
cacheTimeout := 6 * time.Second
checkFreq := 1 * time.Second
var cnt uint64
px := &StatsDB{
Cache: tsyncmap.NewMap(key, cacheTimeout, checkFreq, false),
SendCnt: &cnt,
}
return px
}
func (t *TraceRoute) validateSrcAddress() error {
if t.SrcAddr != "" {
addr, err := net.ResolveIPAddr(t.Af, t.SrcAddr)
if err != nil {
return err
}
t.NetSrcAddr = addr.IP
return nil
}
if t.Af == "ip6" {
t.SrcAddr = "::"
return nil
}
//if config does not specify address, fetch local address
conn, err := net.Dial("udp", "8.8.8.8:53")
if err != nil {
logrus.Error(err)
return nil
}
defer conn.Close()
result := conn.LocalAddr().(*net.UDPAddr)
t.NetSrcAddr = result.IP
return nil
}
func (t *TraceRoute) VerifyCfg() error {
var dst net.IPAddr
rAddr, err := t.dnsResolve(t.Dest, &dst)
if err != nil {
logrus.Error("dst address validation:", err)
return err
}
t.NetDstAddr = rAddr
err = t.validateSrcAddress()
if err != nil {
logrus.Error(err)
return err
}
if t.MaxPath > 32 {
logrus.Error("Only support max ECMP = 32")
return fmt.Errorf("Only support max ECMP = 32")
}
if t.MaxTTL > 64 {
logrus.Warn("Large TTL may cause low performance")
return fmt.Errorf("Large TTL may cause low performance")
}
return nil
}
func New(protocol string, dest string, src string, af string, maxPath int64, maxTtl int64, timeout int64) (result *TraceRoute, err error) {
defer func() {
if e := recover(); e != nil {
logrus.Error(e)
buf := make([]byte, 64<<10) //64*2^10, 64KB
buf = buf[:runtime.Stack(buf, false)]
err = fmt.Errorf("panic recovered: %s\n %s", e, buf)
}
}()
result = &TraceRoute{
SrcAddr: src,
Dest: dest,
Af: af,
TCPDPort: 443,
TCPProbePorts: []uint16{80, 8080, 443, 8443},
Protocol: protocol,
MaxPath: int(maxPath),
MaxTTL: uint8(maxTtl),
PacketRate: 1,
WideMode: true,
PortOffset: 0,
Timeout: time.Duration(timeout) * time.Second,
}
if err := result.VerifyCfg(); err != nil {
logrus.Error("VerifyCfg failed: ", err)
return nil, err
}
result.Lock = &sync.RWMutex{}
//logrus.Info("VerifyCfg passed: ", result.netSrcAddr, " -> ", result.netDstAddr)
result.Metric = make([]map[string][]*ServerRecord, int(maxTtl)+1)
result.LastMetric = make([]map[string][]*ServerRecord, int(maxTtl)+1)
for i := 0; i < len(result.Metric); i++ {
result.Metric[i] = make(map[string][]*ServerRecord)
result.LastMetric[i] = make(map[string][]*ServerRecord)
}
return result, nil
}
func (t *TraceRoute) TraceUDP() (err error) {
var handlers []func() error
for i := 0; i < t.MaxPath; i++ {
handlers = append(handlers, func() error {
return t.SendIPv4UDP()
})
}
handlers = append(handlers, func() error {
return t.ListenIPv4ICMP()
})
return GoroutineNotPanic(handlers...)
}
func (t *TraceRoute) TraceTCP() (err error) {
var handlers []func() error
for i := 0; i < t.MaxPath; i++ {
handlers = append(handlers, func() error {
return t.SendIPv4TCP()
})
}
handlers = append(handlers, func() error {
return t.ListenIPv4ICMP()
})
return GoroutineNotPanic(handlers...)
}
func (t *TraceRoute) TraceICMP() (err error) {
var handlers []func() error
for i := 0; i < t.MaxPath; i++ {
handlers = append(handlers, func() error {
return t.SendIPv4ICMP()
})
}
handlers = append(handlers, func() error {
return t.ListenIPv4ICMP()
})
return GoroutineNotPanic(handlers...)
}
func (t *TraceRoute) Run() error {
if t.Af == "ip6" {
return t.TraceIpv6ICMP()
}
switch t.Protocol {
case "tcp":
return t.TraceTCP()
case "udp":
return t.TraceUDP()
case "icmp":
return t.TraceICMP()
default:
return fmt.Errorf("unsupported protocol: only support tcp/udp/icmp")
}
}
func GoroutineNotPanic(handlers ...func() error) (err error) {
var wg sync.WaitGroup
for _, f := range handlers {
wg.Add(1)
go func(handler func() error) {
defer func() {
if e := recover(); e != nil {
logrus.Error(e)
buf := make([]byte, 64<<10) //64*2^10, 64KB
buf = buf[:runtime.Stack(buf, false)]
err = fmt.Errorf("panic recovered: %s\n %s", e, buf)
}
wg.Done()
}()
e := handler()
if err == nil && e != nil {
err = e
}
}(f)
}
wg.Wait()
return
}