forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loop.go
345 lines (287 loc) · 6.41 KB
/
loop.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
package icmp
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math/rand"
"net"
"sync"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
"github.com/elastic/beats/libbeat/logp"
)
type icmpLoop struct {
conn4, conn6 *icmp.PacketConn
recv chan packet
mutex sync.Mutex
requests map[requestID]*requestContext
}
type timeoutError struct {
}
const (
// iana types
protocolICMP = 1
protocolIPv6ICMP = 58
)
type packet struct {
ts time.Time
addr net.Addr
Type icmp.Type // type, either ipv4.ICMPType or ipv6.ICMPType
Code int // code
Checksum int // checksum
Echo icmp.Echo
}
type requestID struct {
addr string
proto int
id int
seq int
}
type requestContext struct {
l *icmpLoop
id requestID
ts time.Time
result chan requestResult
}
type requestResult struct {
packet packet
err error
}
var (
loopInit sync.Once
loop *icmpLoop
)
func newICMPLoop() (*icmpLoop, error) {
// Log errors at info level, as the loop is setup globally when ICMP module is loaded
// first (not yet configured).
// With multiple configurations using the icmp loop, we have to postpose
// IPv4/IPv6 checking
conn4 := createListener("IPv4", "ip4:icmp")
conn6 := createListener("IPv6", "ip6:ipv6-icmp")
l := &icmpLoop{
conn4: conn4,
conn6: conn6,
recv: make(chan packet, 16),
requests: map[requestID]*requestContext{},
}
if conn4 != nil {
go l.runICMPRecv(conn4, protocolICMP)
}
if conn6 != nil {
go l.runICMPRecv(conn6, protocolIPv6ICMP)
}
return l, nil
}
func (l *icmpLoop) checkNetworkMode(mode string) error {
ip4, ip6 := false, false
switch mode {
case "ip4":
ip4 = true
case "ip6":
ip6 = true
case "ip":
ip4, ip6 = true, true
default:
return fmt.Errorf("'%v' is not supported", mode)
}
if ip4 && l.conn4 == nil {
return errors.New("failed to initiate IPv4 support")
}
if ip6 && l.conn6 == nil {
return errors.New("failed to initiate IPv6 support")
}
return nil
}
func (l *icmpLoop) runICMPRecv(conn *icmp.PacketConn, proto int) {
for {
bytes := make([]byte, 512)
conn.SetReadDeadline(time.Now().Add(1 * time.Second))
_, addr, err := conn.ReadFrom(bytes)
if err != nil {
if neterr, ok := err.(*net.OpError); ok {
if neterr.Timeout() {
continue
} else {
// TODO: report error and quit loop?
return
}
}
}
ts := time.Now()
m, err := icmp.ParseMessage(proto, bytes)
if err != nil {
continue
}
// process echo reply only
if m.Type != ipv4.ICMPTypeEchoReply && m.Type != ipv6.ICMPTypeEchoReply {
continue
}
echo, ok := m.Body.(*icmp.Echo)
if !ok {
continue
}
id := requestID{
addr: addr.String(),
proto: proto,
id: echo.ID,
seq: echo.Seq,
}
l.mutex.Lock()
ctx := l.requests[id]
if ctx != nil {
delete(l.requests, id)
}
l.mutex.Unlock()
// no return context available for echo reply -> handle next message
if ctx == nil {
continue
}
ctx.result <- requestResult{
packet: packet{
ts: ts,
addr: addr,
Type: m.Type,
Code: m.Code,
Checksum: m.Checksum,
Echo: *echo,
},
}
}
}
func (l *icmpLoop) ping(
addr *net.IPAddr,
timeout time.Duration,
interval time.Duration,
) (time.Duration, int, error) {
var err error
toTimer := time.NewTimer(timeout)
defer toTimer.Stop()
ticker := time.NewTicker(interval)
defer ticker.Stop()
done := false
doneSignal := make(chan struct{})
success := false
var rtt time.Duration
// results accepts first response received only
results := make(chan time.Duration, 1)
requests := 0
awaitResponse := func(ctx *requestContext) {
select {
case <-doneSignal:
ctx.Stop()
case r := <-ctx.result:
// ctx is removed from request tables automatically a response is
// received. No need to stop it.
// try to push RTT. The first result available will be reported
select {
case results <- r.packet.ts.Sub(ctx.ts):
default:
}
}
}
for !done {
var ctx *requestContext
ctx, err = l.sendEchoRequest(addr)
if err != nil {
close(doneSignal)
break
}
go awaitResponse(ctx)
requests++
select {
case <-toTimer.C:
// no response for any active request received. Finish loop
// and remove all requests from request table.
done = true
close(doneSignal)
case <-ticker.C:
// No response yet. Send another request with every tick
case rtt = <-results:
success = true
done = true
close(doneSignal)
}
}
if err != nil {
return 0, 0, err
}
if !success {
return 0, 0, timeoutError{}
}
return rtt, requests, nil
}
func (l *icmpLoop) sendEchoRequest(addr *net.IPAddr) (*requestContext, error) {
var conn *icmp.PacketConn
var proto int
var typ icmp.Type
if l == nil {
panic("icmp loop not initialized")
}
if isIPv4(addr.IP) {
conn = l.conn4
proto = protocolICMP
typ = ipv4.ICMPTypeEcho
} else if isIPv6(addr.IP) {
conn = l.conn6
proto = protocolIPv6ICMP
typ = ipv6.ICMPTypeEchoRequest
} else {
return nil, fmt.Errorf("%v is unknown ip address", addr)
}
id := requestID{
addr: addr.String(),
proto: proto,
id: rand.Intn(0xffff),
seq: rand.Intn(0xffff),
}
ctx := &requestContext{
l: l,
id: id,
result: make(chan requestResult, 1),
}
l.mutex.Lock()
l.requests[id] = ctx
l.mutex.Unlock()
payloadBuf := make([]byte, 0, 8)
payload := bytes.NewBuffer(payloadBuf)
ts := time.Now()
binary.Write(payload, binary.BigEndian, ts.UnixNano())
msg := &icmp.Message{
Type: typ,
Body: &icmp.Echo{
ID: id.id,
Seq: id.seq,
Data: payload.Bytes(),
},
}
encoded, _ := msg.Marshal(nil)
_, err := conn.WriteTo(encoded, addr)
if err != nil {
return nil, err
}
ctx.ts = ts
return ctx, nil
}
func createListener(name, network string) *icmp.PacketConn {
conn, err := icmp.ListenPacket(network, "")
// XXX: need to check for conn == nil, as 'err != nil' seems always to be
// true, even if error value itself is `nil`. Checking for conn suppresses
// missleading log message.
if conn == nil && err != nil {
logp.Info("%v ICMP not supported: %v", name, err)
return nil
}
return conn
}
// timeoutError implements net.Error interface
func (timeoutError) Error() string { return "ping timeout" }
func (timeoutError) Timeout() bool { return true }
func (timeoutError) Temporary() bool { return true }
func (r *requestContext) Stop() {
r.l.mutex.Lock()
delete(r.l.requests, r.id)
r.l.mutex.Unlock()
}