-
Notifications
You must be signed in to change notification settings - Fork 0
/
header.go
119 lines (98 loc) · 2.51 KB
/
header.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
package main
type DnsHeader struct {
id uint16 // identification number
recursionDesired bool
truncatedMessage bool
authoritativeAnswer bool
opcode uint8 // purpose of the message
response bool // query/response
resCode ResultCode // response code
checkingDisabled bool
authedData bool
z bool
recursionAvailable bool
questions uint16
answers uint16
authoritativeEntries uint16
resourceEntries uint16
}
// NewDnsHeader creates a new DnsHeader
func NewDnsHeader() *DnsHeader {
return &DnsHeader{}
}
func (d *DnsHeader) read(buf *BytePacketBuffer) error {
id, err := buf.read2Byte()
if err != nil {
return err
}
d.id = id
flags, err := buf.read2Byte()
if err != nil {
return err
}
a := uint8(flags >> 8)
b := uint8(flags & 0xFF)
d.recursionDesired = (a & (1 << 0)) > 0
d.truncatedMessage = (a & (1 << 1)) > 0
d.authoritativeAnswer = (a & (1 << 2)) > 0
d.opcode = (a >> 3) & 0x0F
d.response = (a & (1 << 7)) > 0
d.resCode = ResultCode(b & 0x0F)
d.recursionAvailable = (b & (1 << 7)) > 0
d.checkingDisabled = (b & (1 << 4)) > 0
d.authedData = (b & (1 << 5)) > 0
d.z = (b & (1 << 6)) > 0
questions, err := buf.read2Byte()
if err != nil {
return err
}
d.questions = questions
answers, err := buf.read2Byte()
if err != nil {
return err
}
d.answers = answers
authoritativeEntries, err := buf.read2Byte()
if err != nil {
return err
}
d.authoritativeEntries = authoritativeEntries
resourceEntries, err := buf.read2Byte()
if err != nil {
return err
}
d.resourceEntries = resourceEntries
return nil
}
func (d *DnsHeader) write(buf *BytePacketBuffer) error {
if err := buf.write2Byte(d.id); err != nil {
return err
}
flags := b2i(d.recursionDesired) | (b2i(d.truncatedMessage) << 1) | (b2i(d.authoritativeAnswer) << 2) | (d.opcode << 3) | (b2i(d.response) << 7)
if err := buf.write(flags); err != nil {
return err
}
flags = (uint8(d.resCode)) | (b2i(d.checkingDisabled) << 4) | (b2i(d.authedData) << 5) | (b2i(d.z) << 6) | (b2i(d.recursionAvailable) >> 7)
if err := buf.write(flags); err != nil {
return err
}
if err := buf.write2Byte(d.questions); err != nil {
return err
}
if err := buf.write2Byte(d.answers); err != nil {
return err
}
if err := buf.write2Byte(d.authoritativeEntries); err != nil {
return err
}
if err := buf.write2Byte(d.resourceEntries); err != nil {
return err
}
return nil
}
func b2i(b bool) uint8 {
if b {
return 1
}
return 0
}