-
Notifications
You must be signed in to change notification settings - Fork 55
/
listener.go
169 lines (145 loc) · 3.54 KB
/
listener.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
package peerdiscovery
import (
"net"
"sync"
"time"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
const (
// https://en.wikipedia.org/wiki/User_Datagram_Protocol#Packet_structure
maxDatagramSize = 66507
)
// PeerState is the state of a peer that has been discovered.
// It contains the address of the peer, the last time it was seen,
// the last payload it sent, and the metadata associated with it.
// To update the metadata, assign your own metadata to the Metadata.Data field.
// The metadata is not protected by a mutex, so you must do this yourself.
type PeerState struct {
Address string
lastSeen time.Time
lastPayload []byte
metadata *Metadata
}
type LostPeer struct {
Address string
LastSeen time.Time
LastPayload []byte
Metadata *Metadata
}
func (p *PeerDiscovery) gc() {
ticker := time.NewTicker(p.settings.Delay * 2)
defer ticker.Stop()
for range ticker.C {
p.Lock()
for ip, peerState := range p.received {
if time.Since(peerState.lastSeen) > p.settings.Delay*4 {
if p.settings.NotifyLost != nil {
p.settings.NotifyLost(LostPeer{
Address: ip,
LastSeen: peerState.lastSeen,
LastPayload: peerState.lastPayload,
Metadata: peerState.metadata,
})
}
delete(p.received, ip)
}
}
p.Unlock()
}
}
// PeerDiscovery is the object that can do the discovery for finding LAN peers.
type PeerDiscovery struct {
settings Settings
received map[string]*PeerState
sync.RWMutex
exit bool
}
func (p *PeerDiscovery) Shutdown() {
p.exit = true
}
func (p *PeerDiscovery) ActivePeers() (peers []*PeerState) {
p.RLock()
defer p.RUnlock()
for _, peerState := range p.received {
peers = append(peers, peerState)
}
return
}
// Listen binds to the UDP address and port given and writes packets received
// from that address to a buffer which is passed to a hander
func (p *PeerDiscovery) listen(c net.PacketConn) (recievedBytes []byte, err error) {
p.RLock()
portNum := p.settings.portNum
allowSelf := p.settings.AllowSelf
timeLimit := p.settings.TimeLimit
notify := p.settings.Notify
p.RUnlock()
localIPs := getLocalIPs()
// get interfaces
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
// log.Println(ifaces)
group := p.settings.multicastAddressNumbers
var p2 NetPacketConn
if p.settings.IPVersion == IPv4 {
p2 = PacketConn4{ipv4.NewPacketConn(c)}
} else {
p2 = PacketConn6{ipv6.NewPacketConn(c)}
}
for i := range ifaces {
p2.JoinGroup(&ifaces[i], &net.UDPAddr{IP: group, Port: portNum})
}
start := time.Now()
// Loop forever reading from the socket
for {
buffer := make([]byte, maxDatagramSize)
var (
n int
src net.Addr
errRead error
)
n, src, errRead = p2.ReadFrom(buffer)
if errRead != nil {
err = errRead
return
}
srcHost, _, _ := net.SplitHostPort(src.String())
if _, ok := localIPs[srcHost]; ok && !allowSelf {
continue
}
// log.Println(src, hex.Dump(buffer[:n]))
p.Lock()
if peer, ok := p.received[srcHost]; ok {
peer.lastSeen = time.Now()
peer.lastPayload = buffer[:n]
} else {
p.received[srcHost] = &PeerState{
Address: srcHost,
lastPayload: buffer[:n],
lastSeen: time.Now(),
metadata: &Metadata{},
}
}
p.Unlock()
if notify != nil {
notify(Discovered{
Address: srcHost,
Payload: buffer[:n],
})
}
p.RLock()
if len(p.received) >= p.settings.Limit && p.settings.Limit > 0 {
p.RUnlock()
break
}
if p.exit || timeLimit > 0 && time.Since(start) > timeLimit {
p.RUnlock()
break
}
p.RUnlock()
}
return
}