This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pinger.go
287 lines (271 loc) · 6.91 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
// Pinger implements a utility object for testing whether a remote
// system is alive based on whether it can respond to ICMP echo
// requests or not. It currently only handles IPv4.
package pinger
import (
"bytes"
"fmt"
"net"
"sync"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
// Pinger tests to see if a system or service is alive and responding
// to requests according to whatever metric makes the most sense for
// the system or service.
type Pinger interface {
// Close closes the Pinger, cancelling any outstanding InUse calls.
Close()
// InUse has the Pinger test to see if a system is alive within a
// specified timeframe.
//
// If the result channel yields true, the remote system or service
// responded to the request within the appropriate timeframe. If
// the result channel yields false, either the remote system or
// service failed to respond within the specified time frame or we
// recieve positive confirmation that the system or service is not
// able to answer requests.
//
// You are not responsible for closing the returned channel, the
// Pinger will close it either after sending an appropriate response
// or if the Pinger is closed. You must use the two-operand recieve
// operator to distinguish between the channel closing and the
// systrem or service not responding.
InUse(string, time.Duration) <-chan bool
}
type pinger struct {
*sync.Mutex
closed bool
probes map[string][]chan<- bool
timeouts map[string]time.Time
conn4, conn6 *icmp.PacketConn
}
func (p *pinger) msgBody(addr string) []byte {
return []byte(fmt.Sprintf("Rebar DHCP Address Probe %s", addr))
}
func (p *pinger) Close() {
p.Lock()
p.closed = true
for _, probe := range p.probes {
for _, c := range probe {
close(c)
}
}
p.probes = nil
p.timeouts = nil
p.Unlock()
}
func (p *pinger) InUse(ip string, timeout time.Duration) <-chan bool {
p.Lock()
defer p.Unlock()
res := make(chan bool)
if p.closed {
close(res)
return res
}
addr := net.ParseIP(ip)
if probes, ok := p.probes[ip]; ok {
probes = append(probes, res)
} else {
p.probes[ip] = []chan<- bool{res}
go func() {
for i := 1; i <= 3; i++ {
tgtAddr := &net.IPAddr{IP: addr}
msgBody := p.msgBody(tgtAddr.IP.String())
msg := icmp.Message{
Code: 0,
Body: &icmp.Echo{
Data: msgBody,
Seq: i,
},
}
msg.Type = ipv6.ICMPTypeEchoRequest
if addr.To4() != nil {
msg.Type = ipv4.ICMPTypeEcho
}
msgBytes, err := msg.Marshal(nil)
if err == nil {
if msg.Type == ipv4.ICMPTypeEcho {
_, err = p.conn4.WriteTo(msgBytes, tgtAddr)
} else {
_, err = p.conn4.WriteTo(msgBytes, tgtAddr)
}
if err != nil && !err.(net.Error).Temporary() {
return
}
}
time.Sleep(1 * time.Second)
}
}()
}
p.timeouts[ip] = time.Now().Add(timeout)
return res
}
func (p *pinger) runTimeouts() ([]chan<- bool, bool) {
p.Lock()
defer p.Unlock()
res := []chan<- bool{}
cTime := time.Now()
toKill := []string{}
for k, v := range p.timeouts {
if cTime.After(v) {
toKill = append(toKill, k)
}
}
if len(toKill) > 0 {
for _, v := range toKill {
delete(p.timeouts, v)
res = append(res, p.probes[v]...)
delete(p.probes, v)
}
}
return res, false
}
func (p *pinger) runMessage(peer net.Addr, pktLen int, buf []byte) ([]chan<- bool, bool) {
res := []chan<- bool{}
retVal := false
toKill := ""
var resp *icmp.Message
resp, err := icmp.ParseMessage(1, buf[:pktLen])
if err != nil {
return res, false
}
// No read error, so see what kind of ICMP packet we recieved.
tgtAddr := peer.String()
p.Lock()
defer p.Unlock()
switch resp.Type {
case ipv4.ICMPTypeDestinationUnreachable, ipv6.ICMPTypeDestinationUnreachable:
// DestinationUnreachable will not come from our target, so we
// have to test its body against all our potential targets.
body, ok := resp.Body.(*icmp.DstUnreach)
if ok {
for k := range p.probes {
msgBody := p.msgBody(k)
if bytes.Contains(body.Data, msgBody) {
res = p.probes[k]
toKill = k
break
}
}
}
case ipv4.ICMPTypeEchoReply, ipv6.ICMPTypeEchoReply:
_, ok := p.probes[tgtAddr]
if ok {
res = p.probes[tgtAddr]
toKill = tgtAddr
retVal = true
}
}
if toKill != "" {
delete(p.timeouts, toKill)
delete(p.probes, toKill)
}
return res, retVal
}
func (p *pinger) mainLoop(conn *icmp.PacketConn) {
buf := make([]byte, 1500)
for {
p.Lock()
if p.closed {
conn.Close()
p.Unlock()
return
}
p.Unlock()
err := conn.SetReadDeadline(time.Now().Add(1 * time.Second))
if err != nil {
conn.Close()
p.Close()
return
}
chansToSend := []chan<- bool{}
valToSend := false
n, peer, err := conn.ReadFrom(buf)
if err == nil {
// We recieved a message. Process it.
chansToSend, valToSend = p.runMessage(peer, n, buf)
} else if err.(net.Error).Timeout() {
// Our read timed out. Process the appropriate timeouts
chansToSend, valToSend = p.runTimeouts()
} else if err.(net.Error).Temporary() {
// Transient error, sleep a bit and try again.
time.Sleep(1 * time.Second)
continue
} else {
// Permanent error, we are done here
p.Close()
continue
}
for _, ch := range chansToSend {
ch <- valToSend
close(ch)
}
}
}
// ICMP creates a new Pinger that tests system aliveness via ICMPv4 or
// ICMPv6. It will return an error if we are unable to open a
// privileged ICMP packet sockets or if we are not able to set a read
// timeout on the sockets.
//
// The InUse method on the Pinter returned by ICMP accepts raw IPv4 or
// IPv6 addresses.
func ICMP() (Pinger, error) {
return ICMPSelectOptions(true, true)
}
func ICMPv4Only() (Pinger, error) {
return ICMPSelectOptions(true, false)
}
func ICMPv6Only() (Pinger, error) {
return ICMPSelectOptions(false, true)
}
func ICMPSelectOptions(ipv4On, ipv6On bool) (Pinger, error) {
if !ipv4On && !ipv6On {
return nil, fmt.Errorf("Must specify something to listen on.")
}
res := &pinger{
Mutex: &sync.Mutex{},
probes: map[string][]chan<- bool{},
timeouts: map[string]time.Time{},
}
if ipv4On {
conn4, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
return nil, err
}
if err := conn4.SetReadDeadline(time.Now().Add(1 * time.Second)); err != nil {
return nil, err
}
res.conn4 = conn4
go res.mainLoop(conn4)
}
if ipv6On {
conn6, err := icmp.ListenPacket("ip6:ipv6-icmp", "::")
if err != nil {
return nil, err
}
if err := conn6.SetReadDeadline(time.Now().Add(1 * time.Second)); err != nil {
return nil, err
}
res.conn6 = conn6
go res.mainLoop(conn6)
}
return res, nil
}
type fake bool
func (f fake) Close() {}
func (f fake) InUse(string, time.Duration) <-chan bool {
res := make(chan bool)
go func() {
res <- bool(f)
close(res)
}()
return res
}
// Fake returns a Pinger that always returns whatever is passed in for
// ret. It is intended for use in unit tests.
func Fake(ret bool) Pinger {
return fake(ret)
}