forked from fazalmajid/pingwatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pinger.go
476 lines (417 loc) · 9.61 KB
/
pinger.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
package main
import (
"bytes"
"database/sql"
"encoding/binary"
"fmt"
"log"
"math"
"math/rand"
"net"
"sync"
"syscall"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
const (
szLen = 8
tsLen = 8
protocolICMP = 1
protocolIPv6ICMP = 58
)
var (
ipv4Proto = map[string]string{"ip": "ip4:icmp", "udp": "udp4"}
ipv6Proto = map[string]string{"ip": "ip6:ipv6-icmp", "udp": "udp6"}
pingers map[string]*Pinger
)
type in_flight struct {
timer *time.Timer
pinger *Pinger
results chan *Result
Result
}
type Pinger struct {
Host string
// Interval is the wait time between each packet send. Default is 1s.
Interval time.Duration
// ICMP timeout
Timeout time.Duration
// Size of packet being sent
Size int
// stop chan bool
done chan bool
conn_ipv4 *icmp.PacketConn
done_ipv4 chan bool
conn_ipv6 *icmp.PacketConn
done_ipv6 chan bool
recv chan *packet
size int
id int
sequence int
network string
wg sync.WaitGroup
pending map[int]in_flight // sequence -> start time
results chan *Result
}
func NewPinger(host string, interval time.Duration, results chan *Result) (*Pinger, error) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return &Pinger{
Host: host,
Interval: interval,
Timeout: 5 * time.Second,
id: r.Intn(math.MaxInt16),
network: "udp",
Size: 128,
done: make(chan bool),
done_ipv4: make(chan bool),
done_ipv6: make(chan bool),
pending: make(map[int]in_flight, 1),
results: results,
}, nil
}
type packet struct {
ipv4 bool
bytes []byte
nbytes int
ttl int
}
type Result = struct {
TS time.Time
Host string
IP string
Rtt time.Duration
}
// SetPrivileged sets the type of ping pinger will send.
// false means pinger will send an "unprivileged" UDP ping.
// true means pinger will send a "privileged" raw ICMP ping.
// NOTE: setting to true requires that it be run with super-user privileges.
func (p *Pinger) SetPrivileged(privileged bool) {
if privileged {
p.network = "ip"
} else {
p.network = "udp"
}
}
// Privileged returns whether pinger is running in privileged mode.
func (p *Pinger) Privileged() bool {
return p.network == "ip"
}
func (p *Pinger) start_listener(use_ipv4 bool) (conn *icmp.PacketConn) {
if use_ipv4 {
conn = p.listen(ipv4Proto[p.network])
if conn == nil {
log.Fatal("could not start IPv4 listener")
}
conn.IPv4PacketConn().SetControlMessage(ipv4.FlagTTL, true)
} else {
if conn = p.listen(ipv6Proto[p.network]); conn == nil {
log.Fatal("could not start IPv6 listener")
}
conn.IPv6PacketConn().SetControlMessage(ipv6.FlagHopLimit, true)
}
go p.recvICMP(conn, use_ipv4)
return conn
}
func (p *Pinger) recvICMP(conn *icmp.PacketConn, use_ipv4 bool) {
defer conn.Close()
defer p.wg.Done()
var done chan bool
if use_ipv4 {
done = p.done_ipv4
} else {
done = p.done_ipv6
}
for {
select {
case <-done:
return
default:
bytes := make([]byte, 512)
conn.SetReadDeadline(time.Now().Add(time.Millisecond * 100))
var n, ttl int
var err error
if use_ipv4 {
var cm *ipv4.ControlMessage
n, cm, _, err = conn.IPv4PacketConn().ReadFrom(bytes)
if cm != nil {
ttl = cm.TTL
}
} else {
var cm *ipv6.ControlMessage
n, cm, _, err = conn.IPv6PacketConn().ReadFrom(bytes)
if cm != nil {
ttl = cm.HopLimit
}
}
if err != nil {
if neterr, ok := err.(*net.OpError); ok {
if neterr.Timeout() {
// Read timeout
continue
} else {
close(p.done)
return
}
}
}
p.recv <- &packet{
ipv4: use_ipv4,
bytes: bytes,
nbytes: n,
ttl: ttl,
}
}
}
}
func (p *Pinger) Run() {
p.recv = make(chan *packet, 5)
defer close(p.recv)
p.wg.Add(1)
if *verbose {
log.Println("starting pinger", p.Host, "interval", p.Interval)
}
err := p.sendICMP()
if err != nil {
fmt.Println(err.Error())
}
interval := time.NewTicker(p.Interval)
defer interval.Stop()
for {
select {
case <-p.done:
p.Stop()
return
case <-interval.C:
err = p.sendICMP()
if err != nil {
fmt.Println("FATAL: ", err.Error())
}
case r := <-p.recv:
err := p.processPacket(r, p.results)
if err != nil {
fmt.Println("FATAL: ", err.Error())
}
}
}
}
func (p *Pinger) Stop() {
close(p.done)
p.done_ipv4 <- true
p.done_ipv6 <- true
p.wg.Wait()
}
func (p *Pinger) sendICMP() error {
var typ icmp.Type
var conn *icmp.PacketConn
// this lookup could take longer than the actual ping itself
ipaddr, err := net.ResolveIPAddr("ip", p.Host)
if err != nil {
return err
}
addr_string := ipaddr.String()
if isIPv4(ipaddr.IP) {
if p.conn_ipv4 == nil {
p.conn_ipv4 = p.start_listener(true)
}
conn = p.conn_ipv4
typ = ipv4.ICMPTypeEcho
} else if isIPv6(ipaddr.IP) {
if p.conn_ipv6 == nil {
p.conn_ipv6 = p.start_listener(false)
}
conn = p.conn_ipv6
typ = ipv6.ICMPTypeEchoRequest
}
var dst net.Addr = ipaddr
if p.network == "udp" {
dst = &net.UDPAddr{IP: ipaddr.IP, Zone: ipaddr.Zone}
}
now := time.Now()
payload := bytes.Join(
[][]byte{
timeToBytes(now),
intToBytes(int64(len(p.Host))),
[]byte(p.Host),
intToBytes(int64(len(addr_string))),
[]byte(addr_string),
},
[]byte{},
)
padding := p.Size - szLen - len(payload)
if padding > 0 {
payload = append(payload, bytes.Repeat([]byte{1}, padding)...)
}
payload = append(intToBytes(int64(len(payload))), payload...)
body := &icmp.Echo{
ID: p.id,
Seq: p.sequence,
Data: payload,
}
msg := &icmp.Message{
Type: typ,
Code: 0,
Body: body,
}
msgBytes, err := msg.Marshal(nil)
if err != nil {
return err
}
for {
if _, err := conn.WriteTo(msgBytes, dst); err != nil {
if neterr, ok := err.(*net.OpError); ok {
if neterr.Err == syscall.ENOBUFS {
continue
}
}
}
timer := in_flight{
Result: Result{
TS: now,
Host: p.Host,
IP: addr_string,
Rtt: -1 * time.Hour,
},
}
timer.timer = time.AfterFunc(p.Timeout, timer.doTimeout)
timer.pinger = p
p.pending[p.sequence] = timer
p.sequence++
break
}
return nil
}
func (t *in_flight) doTimeout() {
t.pinger.results <- &t.Result
}
func (p *Pinger) processPacket(recv *packet, results chan *Result) error {
receivedAt := time.Now()
var proto int
if recv.ipv4 {
proto = protocolICMP
} else {
proto = protocolIPv6ICMP
}
var m *icmp.Message
var err error
if m, err = icmp.ParseMessage(proto, recv.bytes); err != nil {
return fmt.Errorf("error parsing icmp message: %s", err.Error())
}
if m.Type != ipv4.ICMPTypeEchoReply && m.Type != ipv6.ICMPTypeEchoReply {
// Not an echo reply, ignore it
return nil
}
r := &Result{}
switch pkt := m.Body.(type) {
case *icmp.Echo:
// If we are privileged, we can match icmp.ID
if p.network == "ip" {
// Check if reply from same ID
if pkt.ID != p.id {
return nil
}
}
// XXX should lock p.pending
timeout, ok := p.pending[pkt.Seq]
if ok {
timeout.timer.Stop()
}
if len(pkt.Data) < szLen+tsLen {
return fmt.Errorf("insufficient data received; got: %d %v",
len(pkt.Data), pkt.Data)
}
size := bytesToInt(pkt.Data[0:szLen])
if int64(len(pkt.Data)) < szLen+size {
return fmt.Errorf("payload size mismatch; got: %d, expected %d %v",
len(pkt.Data), size, pkt.Data)
}
offset := int64(szLen)
r.TS = bytesToTime(pkt.Data[offset : offset+tsLen])
r.Rtt = receivedAt.Sub(r.TS)
offset += tsLen
hostLen := bytesToInt(pkt.Data[offset : offset+szLen])
if hostLen <= 0 || offset+szLen+hostLen > int64(len(pkt.Data)) {
return fmt.Errorf("invalid hostlen: %d %v", hostLen, pkt.Data)
}
offset += szLen
r.Host = string(pkt.Data[offset : offset+hostLen])
if r.Host != p.Host {
return fmt.Errorf("hostname mismatch, expected %s, got %s %v",
p.Host, r.Host, pkt.Data)
}
offset += hostLen
addrLen := bytesToInt(pkt.Data[offset : offset+szLen])
if offset+szLen+addrLen > int64(len(pkt.Data)) {
return fmt.Errorf("invalid addr len: %d %v", addrLen, pkt.Data)
}
offset += szLen
r.IP = string(pkt.Data[offset : offset+addrLen])
default:
// Very bad, not sure how this can happen
return fmt.Errorf(
"invalid ICMP echo reply; type: '%T', '%v'", pkt, pkt)
}
results <- r
return nil
}
func (p *Pinger) listen(netProto string) *icmp.PacketConn {
conn, err := icmp.ListenPacket(netProto, "")
if err != nil {
fmt.Printf("Error listening for ICMP packets: %s\n", err.Error())
close(p.done)
return nil
}
return conn
}
func bytesToTime(b []byte) time.Time {
var nsec int64
for i := uint8(0); i < 8; i++ {
nsec += int64(b[i]) << ((7 - i) * 8)
}
return time.Unix(nsec/1000000000, nsec%1000000000)
}
func isIPv4(ip net.IP) bool {
return len(ip.To4()) == net.IPv4len
}
func isIPv6(ip net.IP) bool {
return len(ip) == net.IPv6len
}
func timeToBytes(t time.Time) []byte {
nsec := t.UnixNano()
b := make([]byte, 8)
for i := uint8(0); i < 8; i++ {
b[i] = byte((nsec >> ((7 - i) * 8)) & 0xff)
}
return b
}
func bytesToInt(b []byte) int64 {
return int64(binary.BigEndian.Uint64(b))
}
func intToBytes(tracker int64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(tracker))
return b
}
func start_pinger(db *sql.DB, interval time.Duration) {
results := ResultWorker(db)
pingers = make(map[string]*Pinger, 0)
hosts := get_dests(db)
for _, host := range hosts {
pinger, err := NewPinger(host, interval, results)
if err != nil {
log.Fatal("could not start pinger for", host, err)
}
pinger.SetPrivileged(*privileged)
pingers[host] = pinger
go pinger.Run()
}
}
func stop_pingers() {
for host, pinger := range pingers {
pinger.Stop()
if *verbose {
log.Println("stopped pinger for", host)
}
}
}