generated from djthorpe/goapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
274 lines (233 loc) · 5.76 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
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
package mdns
import (
"context"
"fmt"
"net"
"strings"
"sync"
"time"
// Modules
. "github.com/djthorpe/go-server"
multierror "github.com/hashicorp/go-multierror"
dns "github.com/miekg/dns"
ipv4 "golang.org/x/net/ipv4"
ipv6 "golang.org/x/net/ipv6"
)
///////////////////////////////////////////////////////////////////////////////
// TYPES
type listener struct {
sync.WaitGroup
// Domain for mDNS
domain string
// Interfaces for listener
ifaces []net.Interface
// Bound listeners
ip4 *ipv4.PacketConn
ip6 *ipv6.PacketConn
// Channel to send messages to
c chan<- message
}
////////////////////////////////////////////////////////////////////////////////
// GLOBALS
const (
emitRetryCount = 3
emitRetryDuration = 100 * time.Millisecond
defaultDomain = "local."
)
var (
MULTICAST_ADDR_IPV4 = &net.UDPAddr{IP: net.ParseIP("224.0.0.251"), Port: 5353}
MULTICAST_ADDR_IPV6 = &net.UDPAddr{IP: net.ParseIP("ff02::fb"), Port: 5353}
)
////////////////////////////////////////////////////////////////////////////////
// LIFECYCLE
func NewListener(domain, iface string, c chan<- message) (*listener, error) {
this := new(listener)
// Fully qualify domain (remove dots and add one to end)
if domain = strings.Trim(domain, ".") + "."; domain == "." {
this.domain = defaultDomain
} else {
this.domain = domain
}
// Obtain the interfaces for listening
if iface, err := interfaceForName(iface); err != nil {
return nil, err
} else if ifaces, err := multicastInterfaces(iface); err != nil {
return nil, err
} else if len(ifaces) == 0 {
return nil, ErrBadParameter.With("No interfaces defined for listening")
} else {
this.ifaces = ifaces
}
// Join IP4
if ip4, err := bindUdp4(this.ifaces, MULTICAST_ADDR_IPV4); err != nil {
return nil, err
} else {
this.ip4 = ip4
}
// Join IP6
if ip6, err := bindUdp6(this.ifaces, MULTICAST_ADDR_IPV6); err != nil {
return nil, err
} else {
this.ip6 = ip6
}
// Set channel
this.c = c
// Return success
return this, nil
}
///////////////////////////////////////////////////////////////////////////////
// STRINGIFY
func (this *listener) String() string {
str := "<listener"
str += fmt.Sprintf(" domain=%q", this.domain)
str += " ifaces="
for i, iface := range this.ifaces {
if i > 0 {
str += ","
}
str += iface.Name
}
return str + ">"
}
///////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
func (this *listener) Run(ctx context.Context) error {
var result error
// Run4
if this.ip4 != nil {
this.WaitGroup.Add(1)
go this.run4(ctx, this.ip4)
}
// Run6
if this.ip6 != nil {
this.WaitGroup.Add(1)
go this.run6(ctx, this.ip6)
}
// Wait for cancels
<-ctx.Done()
// Close connections
if this.ip4 != nil {
if err := this.ip4.Close(); err != nil {
result = multierror.Append(result, err)
}
}
if this.ip6 != nil {
if err := this.ip6.Close(); err != nil {
result = multierror.Append(result, err)
}
}
// Wait until receive loops have completed
this.WaitGroup.Wait()
// Return any errors
return result
}
// Send a single DNS message to a particular interface or all interfaces if 0
func (this *listener) Send(msg *dns.Msg, ifIndex int) error {
var buf []byte
var result error
if buf_, err := msg.Pack(); err != nil {
return err
} else {
buf = buf_
}
/*for i, q := range msg.Question {
this.Debug(" ", i, " Send: ", q.Name, " type=", qTypeString(q.Qtype), " ifIndex=", ifIndex)
}
*/
if this.ip4 != nil {
var cm ipv4.ControlMessage
if ifIndex != 0 {
cm.IfIndex = ifIndex
if _, err := this.ip4.WriteTo(buf, &cm, MULTICAST_ADDR_IPV4); err != nil {
result = multierror.Append(result, err)
}
} else {
for _, intf := range this.ifaces {
cm.IfIndex = intf.Index
if intf.Flags&net.FlagUp != 0 {
this.ip4.WriteTo(buf, &cm, MULTICAST_ADDR_IPV4)
}
}
}
}
if this.ip6 != nil {
var cm ipv6.ControlMessage
if ifIndex != 0 {
cm.IfIndex = ifIndex
if _, err := this.ip6.WriteTo(buf, &cm, MULTICAST_ADDR_IPV6); err != nil {
result = multierror.Append(result, err)
}
} else {
for _, intf := range this.ifaces {
cm.IfIndex = intf.Index
if intf.Flags&net.FlagUp != 0 {
this.ip6.WriteTo(buf, &cm, MULTICAST_ADDR_IPV6)
}
}
}
}
// Return any errors
return result
}
// Query by sending multiple messages to interfaces
func (this *listener) Query(ctx context.Context, msg *dns.Msg, iface int) error {
timer := time.NewTimer(1 * time.Nanosecond)
defer timer.Stop()
c := 0
for {
c++
select {
case <-timer.C:
if err := this.Send(msg, iface); err != nil {
return err
} else if c >= emitRetryCount {
return nil
}
timer.Reset(emitRetryDuration * time.Duration(c))
case <-ctx.Done():
return ctx.Err()
}
}
}
///////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
func (this *listener) run4(ctx context.Context, conn *ipv4.PacketConn) {
defer this.WaitGroup.Done()
buf := make([]byte, 65536)
for {
select {
case <-ctx.Done():
return
default:
if n, cm, from, err := conn.ReadFrom(buf); err != nil {
continue
} else if cm == nil {
continue
} else if msg, err := parseDnsPacket(buf[:n]); err != nil {
this.c <- message{Err: err}
} else {
this.c <- message{msg, from, cm.IfIndex, this.domain, nil}
}
}
}
}
func (this *listener) run6(ctx context.Context, conn *ipv6.PacketConn) {
defer this.WaitGroup.Done()
buf := make([]byte, 65536)
for {
select {
case <-ctx.Done():
return
default:
if n, cm, from, err := conn.ReadFrom(buf); err != nil {
continue
} else if cm == nil {
continue
} else if msg, err := parseDnsPacket(buf[:n]); err != nil {
this.c <- message{Err: err}
} else {
this.c <- message{msg, from, cm.IfIndex, this.domain, nil}
}
}
}
}