-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathtrace.go
488 lines (448 loc) · 9.09 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package main
import (
"context"
"errors"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
"net"
"sort"
"sync"
"sync/atomic"
"syscall"
"time"
)
// DefaultConfig is the default configuration for Tracer.
var DefaultConfig = Config{
Delay: 50 * time.Millisecond,
Timeout: 500 * time.Millisecond,
MaxHops: 15,
Count: 1,
Networks: []string{"ip4:icmp", "ip4:ip"},
}
// DefaultTracer is a tracer with DefaultConfig.
var DefaultTracer = &Tracer{
Config: DefaultConfig,
}
// Config is a configuration for Tracer.
type Config struct {
Delay time.Duration
Timeout time.Duration
MaxHops int
Count int
Networks []string
Addr *net.IPAddr
}
// Tracer is a traceroute tool based on raw IP packets.
// It can handle multiple sessions simultaneously.
type Tracer struct {
Config
once sync.Once
conn *net.IPConn
err error
mu sync.RWMutex
sess map[string][]*Session
seq uint32
}
// Trace starts sending IP packets increasing TTL until MaxHops and calls h for each reply.
func (t *Tracer) Trace(ctx context.Context, ip net.IP, h func(reply *Reply)) error {
sess, err := t.NewSession(ip)
if err != nil {
return err
}
defer sess.Close()
delay := time.NewTicker(t.Delay)
defer delay.Stop()
max := t.MaxHops
for n := 0; n < t.Count; n++ {
for ttl := 1; ttl <= t.MaxHops && ttl <= max; ttl++ {
err = sess.Ping(ttl)
if err != nil {
return err
}
select {
case <-delay.C:
case r := <-sess.Receive():
if max > r.Hops && ip.Equal(r.IP) {
max = r.Hops
}
h(r)
case <-ctx.Done():
return ctx.Err()
}
}
}
if sess.isDone(max) {
return nil
}
deadline := time.After(t.Timeout)
for {
select {
case r := <-sess.Receive():
if max > r.Hops && ip.Equal(r.IP) {
max = r.Hops
}
h(r)
if sess.isDone(max) {
return nil
}
case <-deadline:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
}
// NewSession returns new tracer session.
func (t *Tracer) NewSession(ip net.IP) (*Session, error) {
t.once.Do(t.init)
if t.err != nil {
return nil, t.err
}
return newSession(t, shortIP(ip)), nil
}
func (t *Tracer) init() {
for _, network := range t.Networks {
t.conn, t.err = t.listen(network, t.Addr)
if t.err != nil {
continue
}
go t.serve(t.conn)
return
}
}
func (t *Tracer) listen(network string, laddr *net.IPAddr) (*net.IPConn, error) {
conn, err := net.ListenIP(network, laddr)
if err != nil {
return nil, err
}
raw, err := conn.SyscallConn()
if err != nil {
conn.Close()
return nil, err
}
_ = raw.Control(func(fd uintptr) {
err = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_HDRINCL, 1)
})
if err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
// Close closes listening socket.
// Tracer can not be used after Close is called.
func (t *Tracer) Close() {
t.mu.Lock()
defer t.mu.Unlock()
if t.conn != nil {
t.conn.Close()
}
}
func (t *Tracer) serve(conn *net.IPConn) error {
defer conn.Close()
buf := make([]byte, 1500)
for {
n, from, err := conn.ReadFromIP(buf)
if err != nil {
return err
}
err = t.serveData(from.IP, buf[:n])
if err != nil {
continue
}
}
}
func (t *Tracer) serveData(from net.IP, b []byte) error {
if from.To4() == nil {
// TODO: implement ProtocolIPv6ICMP
return errUnsupportedProtocol
}
now := time.Now()
msg, err := icmp.ParseMessage(ProtocolICMP, b)
if err != nil {
return err
}
if msg.Type == ipv4.ICMPTypeEchoReply {
echo := msg.Body.(*icmp.Echo)
return t.serveReply(from, &packet{from, uint16(echo.ID), 1, now})
}
b = getReplyData(msg)
if len(b) < ipv4.HeaderLen {
return errMessageTooShort
}
switch b[0] >> 4 {
case ipv4.Version:
ip, err := ipv4.ParseHeader(b)
if err != nil {
return err
}
return t.serveReply(ip.Dst, &packet{from, uint16(ip.ID), ip.TTL, now})
case ipv6.Version:
ip, err := ipv6.ParseHeader(b)
if err != nil {
return err
}
return t.serveReply(ip.Dst, &packet{from, uint16(ip.FlowLabel), ip.HopLimit, now})
default:
return errUnsupportedProtocol
}
}
func (t *Tracer) sendRequest(dst net.IP, ttl int) (*packet, error) {
id := uint16(atomic.AddUint32(&t.seq, 1))
b := newPacket(id, dst, ttl)
req := &packet{dst, id, ttl, time.Now()}
_, err := t.conn.WriteToIP(b, &net.IPAddr{IP: dst})
if err != nil {
return nil, err
}
return req, nil
}
func (t *Tracer) addSession(s *Session) {
t.mu.Lock()
defer t.mu.Unlock()
if t.sess == nil {
t.sess = make(map[string][]*Session)
}
t.sess[string(s.ip)] = append(t.sess[string(s.ip)], s)
}
func (t *Tracer) removeSession(s *Session) {
t.mu.Lock()
defer t.mu.Unlock()
a := t.sess[string(s.ip)]
for i, it := range a {
if it == s {
t.sess[string(s.ip)] = append(a[:i], a[i+1:]...)
return
}
}
}
func (t *Tracer) serveReply(dst net.IP, res *packet) error {
t.mu.RLock()
defer t.mu.RUnlock()
a := t.sess[string(shortIP(dst))]
for _, s := range a {
s.handle(res)
}
return nil
}
// Session is a tracer session.
type Session struct {
t *Tracer
ip net.IP
ch chan *Reply
mu sync.RWMutex
probes []*packet
}
// NewSession returns new session.
func NewSession(ip net.IP) (*Session, error) {
return DefaultTracer.NewSession(ip)
}
func newSession(t *Tracer, ip net.IP) *Session {
s := &Session{
t: t,
ip: ip,
ch: make(chan *Reply, 64),
}
t.addSession(s)
return s
}
// Ping sends single ICMP packet with specified TTL.
func (s *Session) Ping(ttl int) error {
req, err := s.t.sendRequest(s.ip, ttl+1)
if err != nil {
return err
}
s.mu.Lock()
s.probes = append(s.probes, req)
s.mu.Unlock()
return nil
}
// Receive returns channel to receive ICMP replies.
func (s *Session) Receive() <-chan *Reply {
return s.ch
}
// isDone returns true if session does not have unresponsed requests with TTL <= ttl.
func (s *Session) isDone(ttl int) bool {
s.mu.RLock()
defer s.mu.RUnlock()
for _, r := range s.probes {
if r.TTL <= ttl {
return false
}
}
return true
}
func (s *Session) handle(res *packet) {
now := res.Time
n := 0
var req *packet
s.mu.Lock()
for _, r := range s.probes {
if now.Sub(r.Time) > s.t.Timeout {
continue
}
if r.ID == res.ID {
req = r
continue
}
s.probes[n] = r
n++
}
s.probes = s.probes[:n]
s.mu.Unlock()
if req == nil {
return
}
hops := req.TTL - res.TTL + 1
if hops < 1 {
hops = 1
}
select {
case s.ch <- &Reply{
IP: res.IP,
RTT: res.Time.Sub(req.Time),
Hops: hops,
}:
default:
}
}
// Close closes tracer session.
func (s *Session) Close() {
s.t.removeSession(s)
}
type packet struct {
IP net.IP
ID uint16
TTL int
Time time.Time
}
func shortIP(ip net.IP) net.IP {
if v := ip.To4(); v != nil {
return v
}
return ip
}
func getReplyData(msg *icmp.Message) []byte {
switch b := msg.Body.(type) {
case *icmp.TimeExceeded:
return b.Data
case *icmp.DstUnreach:
return b.Data
case *icmp.ParamProb:
return b.Data
}
return nil
}
var (
errMessageTooShort = errors.New("message too short")
errUnsupportedProtocol = errors.New("unsupported protocol")
errNoReplyData = errors.New("no reply data")
)
func newPacket(id uint16, dst net.IP, ttl int) []byte {
// TODO: reuse buffers...
msg := icmp.Message{
Type: ipv4.ICMPTypeEcho,
Body: &icmp.Echo{
ID: int(id),
Seq: int(id),
},
}
p, _ := msg.Marshal(nil)
ip := &ipv4.Header{
Version: ipv4.Version,
Len: ipv4.HeaderLen,
TotalLen: ipv4.HeaderLen + len(p),
TOS: 16,
ID: int(id),
Dst: dst,
Protocol: ProtocolICMP,
TTL: ttl,
}
buf, err := ip.Marshal()
if err != nil {
return nil
}
return append(buf, p...)
}
// IANA Assigned Internet Protocol Numbers
const (
ProtocolICMP = 1
ProtocolTCP = 6
ProtocolUDP = 17
ProtocolIPv6ICMP = 58
)
// Reply is a reply packet.
type Reply struct {
IP net.IP
RTT time.Duration
Hops int
}
// Node is a detected network node.
type Node struct {
IP net.IP
RTT []time.Duration
}
// Hop is a set of detected nodes.
type Hop struct {
Nodes []*Node
Distance int
}
// Add adds node from r.
func (h *Hop) Add(r *Reply) *Node {
var node *Node
for _, it := range h.Nodes {
if it.IP.Equal(r.IP) {
node = it
break
}
}
if node == nil {
node = &Node{IP: r.IP}
h.Nodes = append(h.Nodes, node)
}
node.RTT = append(node.RTT, r.RTT)
return node
}
// Trace is a simple traceroute tool using DefaultTracer.
func Trace(ip net.IP) ([]*Hop, error) {
hops := make([]*Hop, 0, DefaultTracer.MaxHops)
touch := func(dist int) *Hop {
for _, h := range hops {
if h.Distance == dist {
return h
}
}
h := &Hop{Distance: dist}
hops = append(hops, h)
return h
}
err := DefaultTracer.Trace(context.Background(), ip, func(r *Reply) {
touch(r.Hops).Add(r)
})
if err != nil && err != context.DeadlineExceeded {
return nil, err
}
sort.Slice(hops, func(i, j int) bool {
return hops[i].Distance < hops[j].Distance
})
last := len(hops) - 1
for i := last; i >= 0; i-- {
h := hops[i]
if len(h.Nodes) == 1 && ip.Equal(h.Nodes[0].IP) {
continue
}
if i == last {
break
}
i++
node := hops[i].Nodes[0]
i++
for _, it := range hops[i:] {
node.RTT = append(node.RTT, it.Nodes[0].RTT...)
}
hops = hops[:i]
break
}
return hops, nil
}