-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathstdloop.go
410 lines (347 loc) · 9 KB
/
stdloop.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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package icmp
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math/rand"
"net"
"os"
"runtime"
"sync"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
type stdICMPLoop 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 *stdICMPLoop
id requestID
ts time.Time
result chan requestResult
}
type requestResult struct {
packet packet
err error
}
// stdLoop is a singleton for our main ICMP loop since it doesn't
// make sense to have multiples. While having a singleton is ugly
// is mandatory for the ICMP interface in go, where all monitors
// must share a single loop.
// These vars should not be used directly, but rather getStdLoop
// should be invoked to initialize and return stdLoop.
var (
stdICMPLoopInit sync.Mutex
stdICMPLoopSingleton *stdICMPLoop
)
func getStdLoop() (*stdICMPLoop, error) {
stdICMPLoopInit.Lock()
defer stdICMPLoopInit.Unlock()
if stdICMPLoopSingleton == nil {
debugf("initializing ICMP loop")
singleton, err := newICMPLoop()
if err != nil {
return nil, err
}
stdICMPLoopSingleton = singleton
debugf("ICMP loop successfully initialized")
}
return stdICMPLoopSingleton, nil
}
func noPingCapabilityError(message string) error {
return fmt.Errorf(fmt.Sprintf("Insufficient privileges to perform ICMP ping. %s", message))
}
func newICMPLoop() (*stdICMPLoop, 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")
unprivilegedPossible := false
l := &stdICMPLoop{
conn4: conn4,
conn6: conn6,
recv: make(chan packet, 16),
requests: map[requestID]*requestContext{},
}
if l.conn4 == nil && l.conn6 == nil {
switch runtime.GOOS {
case "linux", "darwin":
unprivilegedPossible = true
//This is non-privileged ICMP, not udp
l.conn4 = createListener("Unprivileged IPv4", "udp4")
l.conn6 = createListener("Unprivileged IPv6", "udp6")
}
}
if l.conn4 != nil {
go l.runICMPRecv(l.conn4, protocolICMP)
}
if l.conn6 != nil {
go l.runICMPRecv(l.conn6, protocolIPv6ICMP)
}
if l.conn4 == nil && l.conn6 == nil {
if unprivilegedPossible {
var buffer bytes.Buffer
path, _ := os.Executable()
buffer.WriteString("You can run without root by setting cap_net_raw:\n sudo setcap cap_net_raw+eip ")
buffer.WriteString(path + " \n")
buffer.WriteString("Your system allows the use of unprivileged ping by setting net.ipv4.ping_group_range \n sysctl -w net.ipv4.ping_group_range='<min-uid> <max-uid>' ")
return nil, noPingCapabilityError(buffer.String())
}
return nil, noPingCapabilityError("You must provide the appropriate permissions to this executable")
}
return l, nil
}
func (l *stdICMPLoop) 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. Check log details for permission configuration")
}
if ip6 && l.conn6 == nil {
return errors.New("failed to initiate IPv6 support. Check log details for permission configuration")
}
return nil
}
func (l *stdICMPLoop) 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 *stdICMPLoop) 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 pingRequests 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, requests, timeoutError{}
}
return rtt, requests, nil
}
func (l *stdICMPLoop) 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
// misleading log message.
if conn == nil && err != nil {
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()
}