-
Notifications
You must be signed in to change notification settings - Fork 2
/
deserialization.go
61 lines (52 loc) · 1.13 KB
/
deserialization.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
package nameserver
import (
"encoding/binary"
"errors"
)
func (m *message) deserialize(b []byte) error {
rem, err := extractHeaders(b)
if err != nil {
return err
}
m.header = &header{}
m.header.deserialize(b)
m.query = &query{}
err = m.query.deserialize(rem)
if err != nil {
return err
}
return nil
}
func (h *header) deserialize(b []byte) {
h.id = binary.BigEndian.Uint16(b[:2])
h.qdCount = binary.BigEndian.Uint16(b[4:6])
}
func (q *query) deserialize(b []byte) error {
labels, _, err := extractLabels(b)
if err != nil {
return err
}
q.qname = labels
q.qtype = qtypeA
q.qclass = qclassIN
return nil
}
func extractLabels(b []byte) (l []label, remaining []byte, err error) {
if b[0] == 0 {
return nil, nil, errors.New("no question to extract")
}
for b[0] != 0 {
length := b[0]
lab := label(string(b[1 : length+1]))
l = append(l, lab)
b = b[length+1:]
}
l = append(l, label(""))
return l, b[1:], nil // don't return the remaining null byte
}
func extractHeaders(in []byte) ([]byte, error) {
if len(in) < headerLength {
return nil, errors.New("missing header fields")
}
return in[headerLength:], nil
}