-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdnsname.go
86 lines (67 loc) · 1.5 KB
/
dnsname.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
package dnsname
import (
"errors"
"strings"
)
func Decode(encoded []byte) (string, error) {
size := len(encoded)
offset := 0
var decoded string
for {
// read length
l := int(encoded[offset])
// length must be less than 64
if l > 63 {
return "", errors.New("label too long")
}
offset++
// if null-zero is found
if l == 0 {
if offset == size {
// we're done
break
} else {
return "", errors.New("unexpected terminator")
}
}
// after reading this label, there should be at least one byte left
// for the terminator
if size-offset-l < 1 {
return "", errors.New("out of bounds")
}
// read the label
label := string(encoded[offset : offset+l])
// the label should not contain a null-zero character
if strings.ContainsRune(label, rune(0)) {
return "", errors.New("unexpected null-zero")
}
decoded += label
offset += l
// if we are not at the end of the name, append a period
if size-offset > 1 {
decoded += "."
}
}
return decoded, nil
}
func Encode(name string) ([]byte, error) {
name = strings.Trim(name, ".")
encoded := make([]byte, len(name)+2)
offset := 0
// split name into labels
labels := strings.Split(name, ".")
for _, label := range labels {
l := len(label)
// length must be less than 64
if l > 63 {
return nil, errors.New("label too long")
}
// write length
encoded[offset] = byte(l)
offset++
// write label
copy(encoded[offset:offset+l], []byte(label))
offset += l
}
return encoded, nil
}