/
pinger.go
489 lines (399 loc) · 8.95 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
477
478
479
480
481
482
483
484
485
486
487
488
489
// go-parallel-pinger is a easy and thread-safe way to send ping in Go.
package pinger
import (
"context"
"encoding/binary"
"errors"
"math/rand"
"net"
"runtime"
"sync"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
const (
// DEFAULT_PRIVILEGED is the default value of Pinger.Privileged/Pinger.SetPrivileged.
DEFAULT_PRIVILEGED = runtime.GOOS == "windows"
)
var (
// ErrAlreadyStarted is the error if the pinger is already started.
ErrAlreadyStarted = errors.New("Pinger is already started")
// ErrNotStarted is the error if call Pinger.Ping before start the pinger.
ErrNotStarted = errors.New("Pinger is not started yet")
errInvalidTracker = errors.New("Invalid Tracker")
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// tracker is a value for tracking echo reply.
type tracker struct {
ProbeID uint32
MessageID uint32
}
func newTracker(probeID uint32) tracker {
return tracker{
ProbeID: probeID,
MessageID: rand.Uint32(),
}
}
func (t *tracker) Unmarshal(raw []byte) error {
if len(raw) != 8 {
return errInvalidTracker
}
t.ProbeID = binary.BigEndian.Uint32(raw[:4])
t.MessageID = binary.BigEndian.Uint32(raw[4:])
return nil
}
func (t tracker) Marshal() []byte {
var result [8]byte
binary.BigEndian.PutUint32(result[:4], t.ProbeID)
binary.BigEndian.PutUint32(result[4:], t.MessageID)
return result[:]
}
// reply is a echo reply event from target hos.
type reply struct {
ReceivedAt int64
Tracker tracker
}
// handlerRegistry manage handlers set.
type handlerRegistry struct {
sync.RWMutex
handlers map[uint32]chan reply
}
func newHandlerRegistry() *handlerRegistry {
return &handlerRegistry{
handlers: make(map[uint32]chan reply),
}
}
func (h *handlerRegistry) Register(probeID uint32, ch chan reply) {
h.Lock()
defer h.Unlock()
h.handlers[probeID] = ch
}
func (h *handlerRegistry) Unregister(probeID uint32) {
h.Lock()
defer h.Unlock()
delete(h.handlers, probeID)
}
func (h *handlerRegistry) Handle(r reply) {
h.RLock()
defer h.RUnlock()
if handler, ok := h.handlers[r.Tracker.ProbeID]; ok {
handler <- r
}
}
func (h *handlerRegistry) Clear() {
h.Lock()
defer h.Unlock()
h.handlers = make(map[uint32]chan reply)
}
// Pinger is the ping sender and receiver.
type Pinger struct {
lock sync.Mutex
id int
protocol byte
privileged bool
started bool
stop func()
stopped chan struct{}
conn *icmp.PacketConn
handler *handlerRegistry
}
func newPinger(protocol byte) *Pinger {
return &Pinger{
id: rand.Intn(0xffff + 1),
protocol: protocol,
privileged: DEFAULT_PRIVILEGED,
handler: newHandlerRegistry(),
}
}
// NewIPv4 makes new Pinger for IPv4 protocol.
func NewIPv4() *Pinger {
return newPinger('4')
}
// NewIPv6 makes new Pinger for IPv6 protocol.
func NewIPv6() *Pinger {
return newPinger('6')
}
// Protocol returns "v4" if it's a Pinger for IPv4, otherwise returns "v6".
func (p *Pinger) Protocol() string {
if p.protocol == '4' {
return "v4"
}
return "v6"
}
// SetPrivileged sets privileged mode.
//
// It should set as true if runs on Windows, and the default value in Windows is true.
//
// In Linux or Darwin(mac os), you have to run as root if use privileged mode. and the default is false.
//
// You can't call it after call Start method.
// It will returns ErrAlreadyStarted if call it after Pinger started.
func (p *Pinger) SetPrivileged(b bool) error {
if p.Started() {
return ErrAlreadyStarted
}
p.lock.Lock()
defer p.lock.Unlock()
p.privileged = b
return nil
}
// Privileged returns current privileged mode.
//
// Please seealso SetPrivileged.
func (p *Pinger) Privileged() bool {
p.lock.Lock()
defer p.lock.Unlock()
return p.privileged
}
// Started returns true if this Pinger is started, otherwise returns false.
func (p *Pinger) Started() bool {
p.lock.Lock()
defer p.lock.Unlock()
return p.started
}
// Stop will stop this Pinger and block for stopped it completely.
//
// It returns ErrNotStarted if call this before call Start.
func (p *Pinger) Stop() error {
p.lock.Lock()
if !p.started {
p.lock.Unlock()
return ErrNotStarted
}
p.stop()
p.lock.Unlock()
<-p.stopped
return nil
}
func (p *Pinger) close() {
p.lock.Lock()
defer p.lock.Unlock()
p.conn.Close()
p.handler.Clear()
p.started = false
p.stop()
close(p.stopped)
}
func (p *Pinger) listen() error {
p.lock.Lock()
defer p.lock.Unlock()
if p.started {
return ErrAlreadyStarted
}
var err error
p.conn, err = icmp.ListenPacket(p.protoName(), p.listenAddr())
if err != nil {
p.conn = nil
return err
}
p.started = true
return nil
}
func (p *Pinger) runHandler(ctx context.Context) {
defer p.close()
var buf [1500]byte
for {
select {
case <-ctx.Done():
return
default:
}
p.conn.SetReadDeadline(time.Now().Add(10 * time.Millisecond))
if n, _, err := p.conn.ReadFrom(buf[:]); err == nil {
p.onReceiveMessage(buf[:n])
}
}
}
// Start is starts this Pinger for send and receive ping in new goroutine.
//
// It returns ErrAlreadyStarted if the Pinger already started.
func (p *Pinger) Start(ctx context.Context) error {
if err := p.listen(); err != nil {
return err
}
ctx, p.stop = context.WithCancel(ctx)
p.stopped = make(chan struct{})
go p.runHandler(ctx)
return nil
}
func (p *Pinger) onReceiveMessage(raw []byte) {
reply := reply{ReceivedAt: time.Now().UnixNano()}
msg, err := icmp.ParseMessage(p.protoNum(), raw)
if err != nil {
return
}
if msg.Type != p.replyType() {
return
}
if body, ok := msg.Body.(*icmp.Echo); !ok {
return
} else if err = reply.Tracker.Unmarshal(body.Data); err == nil {
p.handler.Handle(reply)
}
}
func (p *Pinger) listenAddr() string {
if p.protocol == '4' {
return "0.0.0.0"
} else {
return "::"
}
}
func (p *Pinger) protoName() string {
if p.privileged {
if p.protocol == '4' {
return "ip4:icmp"
} else {
return "ip6:ipv6-icmp"
}
} else {
if p.protocol == '4' {
return "udp4"
} else {
return "udp6"
}
}
}
func (p *Pinger) protoNum() int {
if p.protocol == '4' {
return 1
} else {
return 58
}
}
func (p *Pinger) requestType() icmp.Type {
if p.protocol == '4' {
return ipv4.ICMPTypeEcho
} else {
return ipv6.ICMPTypeEchoRequest
}
}
func (p *Pinger) replyType() icmp.Type {
if p.protocol == '4' {
return ipv4.ICMPTypeEchoReply
} else {
return ipv6.ICMPTypeEchoReply
}
}
func (p *Pinger) send(dst net.Addr, seq int, t tracker) error {
p.lock.Lock()
conn := p.conn
p.lock.Unlock()
msg := icmp.Message{
Type: p.requestType(),
Body: &icmp.Echo{
ID: p.id,
Seq: seq,
Data: t.Marshal(),
},
}
if b, err := msg.Marshal(nil); err != nil {
return err
} else if _, err = conn.WriteTo(b, dst); err != nil {
return err
}
return nil
}
func (p *Pinger) convertTarget(target *net.IPAddr) net.Addr {
if p.Privileged() {
return target
} else {
return &net.UDPAddr{IP: target.IP, Zone: target.Zone}
}
}
// Ping sends ping to target, and wait for reply.
//
// It returns ErrNotStarted if call this before call Start.
func (p *Pinger) Ping(ctx context.Context, target *net.IPAddr, count int, interval time.Duration) (Result, error) {
result := newResult(target, count)
if !p.Started() {
return result, ErrNotStarted
}
if count <= 0 {
return result, nil
}
targetAddr := p.convertTarget(target)
probeID := rand.Uint32()
recv := make(chan reply, count+1)
defer close(recv)
p.handler.Register(probeID, recv)
defer p.handler.Unregister(probeID)
tick := time.NewTicker(interval)
defer tick.Stop()
result.Sent++
t := newTracker(probeID)
sent := map[uint32]int64{
t.MessageID: time.Now().UnixNano(),
}
if err := p.send(targetAddr, result.Sent, t); err != nil {
return result, err
}
for {
select {
case <-ctx.Done():
return result.calculate(), nil
case <-tick.C:
if result.Sent < count {
result.Sent++
t = newTracker(probeID)
sent[t.MessageID] = time.Now().UnixNano()
if err := p.send(targetAddr, result.Sent, t); err != nil {
return result.calculate(), err
}
}
case r := <-recv:
if sentAt, ok := sent[r.Tracker.MessageID]; ok {
delete(sent, r.Tracker.MessageID)
(&result).onRecv(time.Duration(r.ReceivedAt-sentAt) * time.Nanosecond)
if result.Recv >= count {
return result.calculate(), nil
}
}
}
}
}
// Result is a result of Ping.
type Result struct {
Target *net.IPAddr
Sent int
Recv int
Loss int
RTTs []time.Duration
MinRTT time.Duration
MaxRTT time.Duration
AvgRTT time.Duration
}
func newResult(target *net.IPAddr, total int) Result {
return Result{
Target: target,
Loss: total,
RTTs: make([]time.Duration, 0, total),
}
}
func (r *Result) onRecv(rtt time.Duration) {
r.Recv++
r.Loss--
r.RTTs = append(r.RTTs, rtt)
}
func (r Result) calculate() Result {
if len(r.RTTs) == 0 {
return r
}
r.MinRTT = r.RTTs[0]
r.MaxRTT = r.RTTs[0]
r.AvgRTT = r.RTTs[0]
for _, x := range r.RTTs[1:] {
if x < r.MinRTT {
r.MinRTT = x
}
if x > r.MaxRTT {
r.MaxRTT = x
}
r.AvgRTT += x
}
r.AvgRTT /= time.Duration(len(r.RTTs))
return r
}