-
Notifications
You must be signed in to change notification settings - Fork 34
/
service.go
530 lines (442 loc) · 11 KB
/
service.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package dnssd
import (
"bytes"
"github.com/brutella/dnssd/log"
"fmt"
"net"
"os"
"strings"
"time"
)
type Config struct {
// Name of the service.
Name string
// Type is the service type, for example "_hap._tcp".
Type string
// Domain is the name of the domain, for example "local".
// If empty, "local" is used.
Domain string
// Host is the name of the host (no trailing dot).
// If empty the local host name is used.
Host string
// Txt records
Text map[string]string
// IP addresses of the service.
// This field is deprecated and should not be used.
IPs []net.IP
// Port is the port of the service.
Port int
// Interfaces at which the service should be registered
Ifaces []string
}
func (c Config) Copy() Config {
return Config{
Name: c.Name,
Type: c.Type,
Domain: c.Domain,
Host: c.Host,
Text: c.Text,
IPs: c.IPs,
Port: c.Port,
Ifaces: c.Ifaces,
}
}
func isDigit(r rune) bool {
return r >= '0' && r <= '9'
}
func isAlpha(r rune) bool {
return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
}
func isWhitespace(r rune) bool {
return r == ' '
}
// validHostname returns a valid hostname as specified in RFC-952 and RFC1123.
func validHostname(host string) string {
result := ""
z := len(host) - 1
for i, r := range host {
if isWhitespace(r) {
r = '-'
}
// hostname must start with an alpha [RFC-952 ASSUMPTIONS] or digit [RFC1123 2.1] character.
if i == 0 && (!isDigit(r) && !isAlpha(r)) {
log.Debug.Printf(`hostname "%s" starts with "%s"`, host, string(r))
continue
}
// [RFC-952 ASSUMPTIONS] The last character must not be a minus sign or period.
if i == z && (r == '-' || r == '.') {
log.Debug.Printf(`hostname "%s" ends with "%s"`, host, string(r))
continue
}
if !isDigit(r) && !isAlpha(r) && r != '-' && r != '.' {
log.Debug.Printf(`hostname "%s" contains "%s"`, host, string(r))
continue
}
result += string(r)
}
return result
}
// Service represents a DNS-SD service instance
type Service struct {
Name string
Type string
Domain string
Host string
Text map[string]string
TTL time.Duration // Original time to live
Port int
IPs []net.IP
Ifaces []string
// stores ips by interface name for caching purposes
ifaceIPs map[string][]net.IP
expiration time.Time
}
// NewService returns a new service for the given config.
func NewService(cfg Config) (s Service, err error) {
name := cfg.Name
typ := cfg.Type
port := cfg.Port
if len(name) == 0 {
err = fmt.Errorf("invalid name \"%s\"", name)
return
}
if len(typ) == 0 {
err = fmt.Errorf("invalid type \"%s\"", typ)
return
}
if port == 0 {
err = fmt.Errorf("invalid port \"%d\"", port)
return
}
domain := cfg.Domain
if len(domain) == 0 {
domain = "local"
}
host := cfg.Host
if len(host) == 0 {
host = hostname()
}
text := cfg.Text
if text == nil {
text = map[string]string{}
}
ips := []net.IP{}
var ifaces []string
if cfg.IPs != nil && len(cfg.IPs) > 0 {
ips = cfg.IPs
}
if cfg.Ifaces != nil && len(cfg.Ifaces) > 0 {
ifaces = cfg.Ifaces
}
return Service{
Name: trimServiceNameSuffixRight(name),
Type: typ,
Domain: domain,
Host: validHostname(host),
Text: text,
Port: port,
IPs: ips,
Ifaces: ifaces,
ifaceIPs: map[string][]net.IP{},
}, nil
}
// Interfaces returns the network interfaces for which the service is registered,
// or all multicast network interfaces, if no IP addresses are specified.
func (s *Service) Interfaces() []*net.Interface {
if len(s.Ifaces) > 0 {
ifis := []*net.Interface{}
for _, name := range s.Ifaces {
if ifi, err := net.InterfaceByName(name); err == nil {
ifis = append(ifis, ifi)
}
}
return ifis
}
return MulticastInterfaces()
}
// IsVisibleAtInterface returns true, if the service is published
// at the network interface with name n.
func (s *Service) IsVisibleAtInterface(n string) bool {
if len(s.Ifaces) == 0 {
return true
}
for _, name := range s.Ifaces {
if name == n {
return true
}
}
return false
}
// IPsAtInterface returns the ip address at a specific interface.
func (s *Service) IPsAtInterface(iface *net.Interface) []net.IP {
if iface == nil {
return []net.IP{}
}
if ips, ok := s.ifaceIPs[iface.Name]; ok {
return ips
}
if len(s.IPs) > 0 {
return s.IPs
}
addrs, err := iface.Addrs()
if err != nil {
return []net.IP{}
}
ips := []net.IP{}
for _, addr := range addrs {
if ip, _, err := net.ParseCIDR(addr.String()); err == nil {
ips = append(ips, ip)
} else {
log.Debug.Println(err)
}
}
return ips
}
// HasIPOnAnyInterface returns true, if the service defines
// the ip address on any network interface.
func (s *Service) HasIPOnAnyInterface(ip net.IP) bool {
for _, iface := range s.Interfaces() {
ips := s.IPsAtInterface(iface)
for _, ifaceIP := range ips {
if ifaceIP.Equal(ip) {
return true
}
}
}
return false
}
// Copy returns a copy of the service.
func (s Service) Copy() *Service {
return &Service{
Name: s.Name,
Type: s.Type,
Domain: s.Domain,
Host: s.Host,
Text: s.Text,
TTL: s.TTL,
IPs: s.IPs,
Port: s.Port,
Ifaces: s.Ifaces,
ifaceIPs: s.ifaceIPs,
expiration: s.expiration,
}
}
func (s Service) EscapedName() string {
return escape.Replace(s.Name)
}
func incrementHostname(name string, count int) string {
return fmt.Sprintf("%s-%d", trimHostNameSuffixRight(name), count)
}
func trimHostNameSuffixRight(name string) string {
minus := strings.LastIndex(name, "-")
if minus == -1 || /* not found*/
minus == len(name)-1 /* at the end */ {
return name
}
// after minus
after := name[minus+1:]
for _, r := range after {
if !isDigit(r) {
return name
}
}
trimmed := name[:minus]
if len(trimmed) == 0 {
return name
}
return trimmed
}
// trimServiceNameSuffixRight removes any suffix with the format " (%d)".
func trimServiceNameSuffixRight(name string) string {
open := strings.LastIndex(name, "(")
close := strings.LastIndex(name, ")")
if open == -1 || close == -1 || /* not found*/
open >= close || /* wrong order */
open == 0 || /* at the beginning */
close != len(name)-1 /* not at the end */ {
return name
}
// between brackets are only numbers
between := name[open+1 : close-1]
for _, r := range between {
if !isDigit(r) {
return name
}
}
// before opening bracket is a whitespace
if name[open-1] != ' ' {
return name
}
trimmed := name[:open]
trimmed = strings.TrimRight(trimmed, " ")
if len(trimmed) == 0 {
return name
}
return trimmed
}
func incrementServiceName(name string, count int) string {
return fmt.Sprintf("%s (%d)", trimServiceNameSuffixRight(name), count)
}
// EscapedServiceInstanceName returns the same as `ServiceInstanceName()`
// but escapes any special characters.
func (s Service) EscapedServiceInstanceName() string {
return fmt.Sprintf("%s.%s.%s.", s.EscapedName(), s.Type, s.Domain)
}
// ServiceInstanceName returns the service instance name
// in the form of <instance name>.<service>.<domain>.
// (Note the trailing dot.)
func (s Service) ServiceInstanceName() string {
return fmt.Sprintf("%s.%s.%s.", s.Name, s.Type, s.Domain)
}
// ServiceName returns the service name in the
// form of "<service>.<domain>."
// (Note the trailing dot.)
func (s Service) ServiceName() string {
return fmt.Sprintf("%s.%s.", s.Type, s.Domain)
}
// Hostname returns the hostname in the
// form of "<hostname>.<domain>."
// (Note the trailing dot.)
func (s Service) Hostname() string {
return fmt.Sprintf("%s.%s.", s.Host, s.Domain)
}
// SetHostname sets the service's host name and
// domain (if specified as "<hostname>.<domain>.").
// (Note the trailing dot.)
func (s *Service) SetHostname(hostname string) {
name, domain := parseHostname(hostname)
if domain == s.Domain {
s.Host = name
}
}
// ServicesMetaQueryName returns the name of the meta query
// for the service domain in the form of "_services._dns-sd._udp.<domain.".
// (Note the trailing dot.)
func (s Service) ServicesMetaQueryName() string {
return fmt.Sprintf("_services._dns-sd._udp.%s.", s.Domain)
}
func (s *Service) addIP(ip net.IP, iface *net.Interface) {
s.IPs = append(s.IPs, ip)
if iface != nil {
ifaceIPs := []net.IP{ip}
if ips, ok := s.ifaceIPs[iface.Name]; ok {
ifaceIPs = append(ips, ip)
}
s.ifaceIPs[iface.Name] = ifaceIPs
}
}
func newService(instance string) *Service {
name, typ, domain := parseServiceInstanceName(instance)
return &Service{
Name: name,
Type: typ,
Domain: domain,
Text: map[string]string{},
IPs: []net.IP{},
Ifaces: []string{},
ifaceIPs: map[string][]net.IP{},
}
}
var unescape = strings.NewReplacer("\\", "")
var escape *strings.Replacer
func init() {
specialChars := []byte{'.', ' ', '\'', '@', ';', '(', ')', '"', '\\'}
replaces := make([]string, 2*len(specialChars))
for i, char := range specialChars {
replaces[2*i] = string(char)
replaces[2*i+1] = "\\" + string(char)
}
escape = strings.NewReplacer(replaces...)
}
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
// parseServiceInstanceName parses str to get the instance, service and domain name.
func parseServiceInstanceName(str string) (name string, service string, domain string) {
r := bytes.NewBufferString(reverse(strings.Trim(str, ".")))
l, err := r.ReadString('.')
if err != nil {
return
}
domain = strings.Trim(l, ".")
domain = reverse(domain)
proto, err := r.ReadString('.')
if err != nil {
return
}
typee, err := r.ReadString('.')
if err != nil {
return
}
service = fmt.Sprintf("%s.%s", strings.Trim(reverse(typee), "."), strings.Trim(reverse(proto), "."))
name = reverse(r.String())
name = unescape.Replace(name)
return
}
// Get Fully Qualified Domain Name
// returns "unknown" or hostanme in case of error
func hostname() string {
hostname, err := os.Hostname()
if err != nil {
return "unknown"
}
name, _ := parseHostname(hostname)
return name
}
func parseHostname(str string) (name string, domain string) {
elems := strings.Split(str, ".")
if len(elems) > 0 {
name = elems[0]
}
if len(elems) > 1 {
domain = elems[1]
}
return
}
// MulticastInterfaces returns a list of all active multicast network interfaces.
func MulticastInterfaces(filters ...string) []*net.Interface {
var tmp []*net.Interface
ifaces, err := net.Interfaces()
if err != nil {
return nil
}
for _, iface := range ifaces {
iface := iface
if (iface.Flags & net.FlagUp) == 0 {
continue
}
if (iface.Flags & net.FlagMulticast) == 0 {
continue
}
if !containsIfaces(iface.Name, filters) {
continue
}
// check for a valid ip at that interface
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
if _, _, err := net.ParseCIDR(addr.String()); err == nil {
tmp = append(tmp, &iface)
break
}
}
}
return tmp
}
func containsIfaces(iface string, filters []string) bool {
if filters == nil || len(filters) <= 0 {
return true
}
for _, ifn := range filters {
if ifn == iface {
return true
}
}
return false
}