-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathdns_sd.go
More file actions
355 lines (296 loc) · 9.49 KB
/
dns_sd.go
File metadata and controls
355 lines (296 loc) · 9.49 KB
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
// SPDX-FileCopyrightText: The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package mdns
import (
"errors"
"net/netip"
"strings"
"unicode/utf8"
)
// serviceTypeEnumerationName is the meta-query name for discovering all
// service types on the network (RFC 6763 §9).
// A PTR query for "_services._dns-sd._udp.<Domain>" yields PTR records
// whose rdata is the two-label <Service> name plus the domain.
const serviceTypeEnumerationName = "_services._dns-sd._udp"
// maxInstanceNameLen is the maximum length of a DNS label (RFC 1035 §2.3.4),
// which constrains the Instance portion of a Service Instance Name.
const maxInstanceNameLen = 63
var (
errInvalidServiceName = errors.New("mDNS: invalid DNS-SD service name")
errInstanceNameTooLong = errors.New("mDNS: service instance name exceeds 63 bytes")
errInstanceNameEmpty = errors.New("mDNS: service instance name must not be empty")
errInstanceNameHasControl = errors.New("mDNS: service instance name contains ASCII control character")
errUnhandledServiceQuestionType = errors.New("mDNS: unhandled DNS-SD question type")
)
// ServiceEvent represents a discovered DNS-SD service instance.
// It is emitted by Browse when a complete service instance has been resolved
// (PTR → SRV + TXT → address).
type ServiceEvent struct {
// Instance is the discovered service.
Instance ServiceInstance
// Addr is the resolved address of the service host.
Addr netip.Addr
}
// ServiceInstance represents a DNS-SD service instance (RFC 6763).
//
// A service instance is identified by:
//
// <Instance>.<Service>.<Domain>
//
// Example:
//
// Instance: "My Web Server"
// Service: "_http._tcp"
// Domain: "local"
// Host: "myhost.local."
// Port: 8080
type ServiceInstance struct {
// Instance is the user-friendly name (UTF-8, max 63 bytes after encoding).
// May contain dots and other punctuation (RFC 6763 §4.1.1).
Instance string
// Service is the service type, e.g. "_http._tcp".
// Must be in the form "_<name>._<proto>" where proto is "tcp" or "udp".
Service string
// Domain is the DNS domain, typically "local" for mDNS.
Domain string
// Host is the target hostname for the SRV record (e.g. "myhost.local.").
Host string
// Port is the TCP or UDP port number.
Port uint16
// Priority is the SRV priority field (lower = preferred). Default 0.
Priority uint16
// Weight is the SRV weight field. Default 0.
Weight uint16
// Text contains the key/value pairs for the TXT record.
Text []TXTEntry
}
// serviceInstanceName returns the fully-qualified DNS name for this instance.
// Dots and backslashes in the Instance portion are escaped per RFC 6763 §4.3:
// - Literal dots become "\."
// - Literal backslashes become "\\"
//
// Example:
//
// Instance="My.Web", Service="_http._tcp", Domain="local"
// → "My\.Web._http._tcp.local."
func (si *ServiceInstance) serviceInstanceName() string {
escaped := escapeInstanceName(si.Instance)
return escaped + "." + si.Service + "." + si.Domain + "."
}
// serviceName returns the <Service>.<Domain> browsing name
// (e.g. "_http._tcp.local.").
func (si *ServiceInstance) serviceName() string {
return si.Service + "." + si.Domain + "."
}
// escapeInstanceName escapes dots and backslashes in an instance name
// for safe concatenation into a DNS name string (RFC 6763 §4.3).
func escapeInstanceName(instance string) string {
// Fast path: no escaping needed
if !strings.ContainsAny(instance, `.\`) {
return instance
}
var buf strings.Builder
buf.Grow(len(instance) + 4) // room for a few escapes
for _, c := range instance {
switch c {
case '.':
buf.WriteString(`\.`)
case '\\':
buf.WriteString(`\\`)
default:
buf.WriteRune(c)
}
}
return buf.String()
}
// unescapeInstanceName reverses the escaping applied by escapeInstanceName.
// It converts "\." back to "." and "\\" back to "\".
func unescapeInstanceName(escaped string) string {
if !strings.ContainsRune(escaped, '\\') {
return escaped
}
var b strings.Builder
b.Grow(len(escaped))
for i := 0; i < len(escaped); i++ {
switch {
case escaped[i] == '\\' && i+1 < len(escaped):
i++
b.WriteByte(escaped[i])
default:
b.WriteByte(escaped[i])
}
}
return b.String()
}
// parseServiceInstanceName splits a fully-qualified DNS name into its
// Instance, Service, and Domain components.
//
// The expected format is:
//
// <Instance>.<_name>.<_proto>.<Domain>.
//
// Dots within the Instance portion must be escaped as "\." (RFC 6763 §4.3).
// The trailing dot is optional.
//
// Examples:
//
// "My Web._http._tcp.local." → ("My Web", "_http._tcp", "local")
// "My\.Web._http._tcp.local." → ("My.Web", "_http._tcp", "local")
func parseServiceInstanceName(name string) (instance, service, domain string, err error) {
// Strip trailing dot
name = strings.TrimSuffix(name, ".")
// Split on unescaped dots. We need at least 4 labels:
// <instance>, <_name>, <_proto>, <domain...>
labels := splitEscapedDots(name)
if len(labels) < 4 {
return "", "", "", errInvalidServiceName
}
// The service is always the two labels starting with underscore.
// Walk from position 1 to find _name._proto pattern.
// The instance is everything before it, the domain is everything after.
serviceIdx := -1
for i := 1; i < len(labels)-1; i++ {
if strings.HasPrefix(labels[i], "_") && strings.HasPrefix(labels[i+1], "_") {
serviceIdx = i
break
}
}
if serviceIdx < 1 || serviceIdx+2 > len(labels) {
return "", "", "", errInvalidServiceName
}
// Instance: rejoin labels before serviceIdx (unescaped)
instanceParts := labels[:serviceIdx]
instance = unescapeInstanceName(strings.Join(instanceParts, "."))
service = labels[serviceIdx] + "." + labels[serviceIdx+1]
domain = strings.Join(labels[serviceIdx+2:], ".")
if instance == "" || service == "" || domain == "" {
return "", "", "", errInvalidServiceName
}
return instance, service, domain, nil
}
// splitEscapedDots splits a string on dots that are NOT preceded by a backslash.
func splitEscapedDots(input string) []string {
var labels []string
var current strings.Builder
for i := 0; i < len(input); i++ {
switch {
case input[i] == '\\' && i+1 < len(input):
// Escaped character: keep both the backslash and the next char
current.WriteByte(input[i])
i++
current.WriteByte(input[i])
case input[i] == '.':
labels = append(labels, current.String())
current.Reset()
default:
current.WriteByte(input[i])
}
}
labels = append(labels, current.String())
return labels
}
// validateServiceName checks that a service string like "_http._tcp" follows
// the DNS-SD service naming rules (RFC 6763 §7, RFC 6335):
// - Format: "_<name>._<proto>"
// - Proto must be "_tcp" or "_udp"
// - Name: 1-15 characters (not counting underscore prefix)
// - Name: letters, digits, hyphens only
// - Name: must begin and end with a letter or digit
// - Name: must not contain consecutive hyphens
// - Name: must contain at least one letter
func validateServiceName(service string) error {
parts := strings.SplitN(service, ".", 2)
if len(parts) != 2 {
return errInvalidServiceName
}
namePart := parts[0] // e.g. "_http"
protoPart := parts[1] // e.g. "_tcp"
if err := validateServiceProto(protoPart); err != nil {
return err
}
return validateServiceLabel(namePart)
}
// validateServiceProto checks that the protocol label is "_tcp" or "_udp".
func validateServiceProto(proto string) error {
if proto != "_tcp" && proto != "_udp" {
return errInvalidServiceName
}
return nil
}
// validateServiceLabel checks the "_<name>" portion of a service name.
func validateServiceLabel(label string) error {
if !strings.HasPrefix(label, "_") {
return errInvalidServiceName
}
name := label[1:] // strip underscore prefix
if len(name) == 0 || len(name) > 15 {
return errInvalidServiceName
}
// Must begin and end with letter or digit
if !isLetterOrDigit(name[0]) || !isLetterOrDigit(name[len(name)-1]) {
return errInvalidServiceName
}
if err := validateServiceNameChars(name); err != nil {
return err
}
return nil
}
// validateServiceNameChars checks individual characters in a service name:
// letters, digits, hyphens only; no consecutive hyphens; at least one letter.
func validateServiceNameChars(name string) error {
hasLetter := false
prevHyphen := false
for i := 0; i < len(name); i++ {
c := name[i]
switch {
case isLetter(c):
hasLetter = true
prevHyphen = false
case isDigit(c):
prevHyphen = false
case c == '-':
if prevHyphen {
return errInvalidServiceName // consecutive hyphens
}
prevHyphen = true
default:
return errInvalidServiceName // invalid character
}
}
if !hasLetter {
return errInvalidServiceName
}
return nil
}
// validateInstanceName checks that an instance name is valid per RFC 6763 §4.1.1:
// - Must not be empty
// - Must not exceed 63 bytes when UTF-8 encoded
// - Must not contain ASCII control characters (0x00-0x1F, 0x7F)
func validateInstanceName(instance string) error {
if instance == "" {
return errInstanceNameEmpty
}
if len(instance) > maxInstanceNameLen {
return errInstanceNameTooLong
}
for i := 0; i < len(instance); i++ {
b := instance[i]
if b <= 0x1F || b == 0x7F {
return errInstanceNameHasControl
}
}
// Verify valid UTF-8
if !utf8.ValidString(instance) {
return errInstanceNameHasControl
}
return nil
}
func isLetter(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
func isDigit(c byte) bool {
return c >= '0' && c <= '9'
}
func isLetterOrDigit(c byte) bool {
return isLetter(c) || isDigit(c)
}