-
Notifications
You must be signed in to change notification settings - Fork 12
/
discovery.go
258 lines (204 loc) · 5.78 KB
/
discovery.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
package networkwebsockets
import (
"encoding/base64"
"errors"
"fmt"
"log"
"net"
"strings"
"time"
"github.com/richtr/bcrypt"
"github.com/richtr/mdns"
)
const (
ipv4mdns = "224.0.0.251"
ipv6mdns = "ff02::fb"
mdnsPort = 5406 // operate on our own multicast port (standard mDNS port is 5353)
)
var (
network_ipv4Addr = &net.UDPAddr{
IP: net.ParseIP(ipv4mdns),
Port: mdnsPort,
}
network_ipv6Addr = &net.UDPAddr{
IP: net.ParseIP(ipv6mdns),
Port: mdnsPort,
}
)
/** Network Web Socket DNS-SD Discovery Client interface **/
type DiscoveryService struct {
Name string
Hash string
Path string
Port int
server *mdns.Server
}
func NewDiscoveryService(name, hash, path string, port int) *DiscoveryService {
discoveryService := &DiscoveryService{
Name: name,
Hash: hash,
Path: path,
Port: port,
}
return discoveryService
}
func (dc *DiscoveryService) Register(domain string) {
dnssdServiceId := GenerateId()
s := &mdns.MDNSService{
Instance: dnssdServiceId,
Service: "_nws._tcp",
Domain: domain,
Port: dc.Port,
Info: fmt.Sprintf("hash=%s,path=%s", dc.Hash, dc.Path),
}
if err := s.Init(); err != nil {
log.Printf("Could not register service on network. %v", err)
return
}
var mdnsClientConfig *mdns.Config
// Advertise service to the correct endpoint (local or network)
mdnsClientConfig = &mdns.Config{
IPv4Addr: network_ipv4Addr,
IPv6Addr: network_ipv6Addr,
}
// Add the DNS zone record to advertise
mdnsClientConfig.Zone = s
serv, err := mdns.NewServer(mdnsClientConfig)
if err != nil {
log.Printf("Failed to create new mDNS server. %v", err)
return
}
dc.server = serv
log.Printf("New '%s' channel advertised as '%s' in %s network", dc.Name, fmt.Sprintf("%s._nws._tcp", dnssdServiceId), domain)
}
func (dc *DiscoveryService) Shutdown() {
if dc.server != nil {
dc.server.Shutdown()
}
}
/** Network Web Socket DNS-SD Discovery Server interface **/
type DiscoveryBrowser struct {
// Network Web Socket DNS-SD records currently unresolved by this proxy instance
cachedDNSRecords map[string]*DNSRecord
closed bool
}
func NewDiscoveryBrowser() *DiscoveryBrowser {
discoveryBrowser := &DiscoveryBrowser{
cachedDNSRecords: make(map[string]*DNSRecord, 255),
closed: false,
}
return discoveryBrowser
}
func (ds *DiscoveryBrowser) Browse(service *Service, timeoutSeconds int) {
entries := make(chan *mdns.ServiceEntry, 255)
recordsCache := make(map[string]*DNSRecord, 255)
timeout := time.Duration(timeoutSeconds) * time.Second
var targetIPv4 *net.UDPAddr
var targetIPv6 *net.UDPAddr
targetIPv4 = network_ipv4Addr
targetIPv6 = network_ipv6Addr
// Only look for Network Web Socket DNS-SD services
params := &mdns.QueryParam{
Service: "_nws._tcp",
Domain: "local",
Timeout: timeout,
Entries: entries,
IPv4mdns: targetIPv4,
IPv6mdns: targetIPv6,
}
go func() {
complete := false
timeoutFinish := time.After(timeout)
// Wait for responses until timeout
for !complete {
select {
case discoveredService, ok := <-entries:
if !ok {
continue
}
serviceRecord, err := NewServiceRecordFromDNSRecord(discoveredService)
if err != nil {
log.Printf("err: %v", err)
continue
}
// Ignore our own Channel services
if service.isOwnProxyService(serviceRecord) {
continue
}
// Ignore previously discovered Channel proxy services
if service.isActiveProxyService(serviceRecord) {
continue
}
// Resolve discovered service hash provided against available services
var channel *Channel
for _, knownService := range service.Channels {
if bcrypt.Match(knownService.serviceName, serviceRecord.Hash_BCrypt) {
channel = knownService
break
}
}
if channel != nil {
// Create new web socket connection toward discovered proxy
if dErr := dialProxyFromDNSRecord(serviceRecord, channel); dErr != nil {
log.Printf("err: %v", dErr)
continue
}
} else {
// Store as an unresolved DNS-SD record
recordsCache[serviceRecord.Hash_Base64] = serviceRecord
continue
}
case <-timeoutFinish:
// Replace unresolved DNS records cache
ds.cachedDNSRecords = recordsCache
complete = true
}
}
}()
// Run the mDNS/DNS-SD query
err := mdns.Query(params)
if err != nil {
log.Printf("Could not perform mDNS/DNS-SD query. %v", err)
return
}
}
func (ds *DiscoveryBrowser) Shutdown() {
ds.closed = true
}
/** Network Web Socket DNS Record interface **/
type DNSRecord struct {
*mdns.ServiceEntry
Path string
Hash_Base64 string
Hash_BCrypt string
}
func NewServiceRecordFromDNSRecord(serviceEntry *mdns.ServiceEntry) (*DNSRecord, error) {
servicePath := ""
serviceHash_Base64 := ""
serviceHash_BCrypt := ""
if serviceEntry.Info == "" {
return nil, errors.New("Could not find associated TXT record for advertised Network Web Socket service")
}
serviceParts := strings.FieldsFunc(serviceEntry.Info, func(r rune) bool {
return r == '=' || r == ',' || r == ';' || r == ' '
})
if len(serviceParts) > 1 {
for i := 0; i < len(serviceParts); i += 2 {
if strings.ToLower(serviceParts[i]) == "path" {
servicePath = serviceParts[i+1]
}
if strings.ToLower(serviceParts[i]) == "hash" {
serviceHash_Base64 = serviceParts[i+1]
if res, err := base64.StdEncoding.DecodeString(serviceHash_Base64); err == nil {
serviceHash_BCrypt = string(res)
}
}
}
}
if servicePath == "" || serviceHash_Base64 == "" || serviceHash_BCrypt == "" {
return nil, errors.New("Could not resolve the provided Network Web Socket DNS Record")
}
// Create and return a new Network Web Socket DNS Record with the parsed information
newServiceDNSRecord := &DNSRecord{serviceEntry, servicePath, serviceHash_Base64, serviceHash_BCrypt}
return newServiceDNSRecord, nil
}