forked from bortzmeyer/grong
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
301 lines (287 loc) · 8.97 KB
/
server.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
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
/* Main program for the GRONG authoritative name server
Stephane Bortzmeyer <[email protected]>
*/
package main
import (
"bytes"
"encoding/binary"
"flag"
"fmt"
"net"
"os"
"./responder"
"strings"
"./types"
)
var debug int
func serializeSection(section []types.RR, buffer []byte, end int) int {
for i := 0; i < len(section); i++ {
rr := section[i]
encoded_qname := types.Encode(rr.Name)
end += copy(buffer[end:], encoded_qname)
binary.BigEndian.PutUint16(buffer[end:], rr.Type)
end += 2
binary.BigEndian.PutUint16(buffer[end:], rr.Class)
end += 2
binary.BigEndian.PutUint32(buffer[end:], rr.TTL)
end += 4
binary.BigEndian.PutUint16(buffer[end:], uint16(len(rr.Data)))
end += 2
end += copy(buffer[end:], rr.Data)
}
return end
}
func serialize(packet types.DNSpacket) []byte {
result := make([]byte, 512)
// ID
binary.BigEndian.PutUint16(result[0:2], packet.Id)
// Misc flags...
result[2] = 0x80 // TODO: why this value?
result[3] = byte(packet.Rcode)
binary.BigEndian.PutUint16(result[4:6], packet.Qdcount)
// Ancount
binary.BigEndian.PutUint16(result[6:8], packet.Ancount)
// Nscount
binary.BigEndian.PutUint16(result[8:], packet.Nscount)
// Arcount
result[10] = 0
result[11] = 0
if len(packet.Qsection) != 1 {
fmt.Printf("Fatal: Qsection's length is not 1: %d\n", len(packet.Qsection))
os.Exit(1) // TODO: better handling
}
encoded_qname := types.Encode(packet.Qsection[0].Qname)
last := 12
last += copy(result[last:], encoded_qname)
binary.BigEndian.PutUint16(result[last:], packet.Qsection[0].Qtype)
last += 2
binary.BigEndian.PutUint16(result[last:], packet.Qsection[0].Qclass)
last += 2
last = serializeSection(packet.Asection, result, last)
last = serializeSection(packet.Nssection, result, last)
return result[0:last]
}
func readShortInteger(buf *bytes.Buffer) uint16 {
slice := make([]byte, 2)
n, error := buf.Read(slice[0:2])
if error != nil || n != 2 {
fmt.Printf("Error in Read of an int16: %s (%d bytes read)\n", error, n)
os.Exit(1) // TODO: should handle it better?
}
return binary.BigEndian.Uint16(slice[0:2])
}
func parse(buf *bytes.Buffer) types.DNSpacket {
var packet types.DNSpacket
packet.Valid = false
packet.Id = readShortInteger(buf)
dnsmisc := readShortInteger(buf)
qr := (dnsmisc & 0x8000) >> 15
packet.Query = false
if qr == 0 {
packet.Query = true
}
packet.Opcode = uint((dnsmisc >> 11) & 0x000F)
rd := (dnsmisc & 0x0100) >> 8
packet.Recursion = false
if rd == 1 {
packet.Recursion = true
}
packet.Rcode = uint(dnsmisc & 0x000F)
packet.Qdcount = readShortInteger(buf)
packet.Ancount = readShortInteger(buf)
packet.Nscount = readShortInteger(buf)
packet.Arcount = readShortInteger(buf)
over := false
labels_max := make([]string, 63)
labels := labels_max[0:0]
nlabels := 0
for !over {
labelsize, error := buf.ReadByte()
if error != nil {
if error == os.EOF {
return packet
} else {
fmt.Printf("Error in ReadByte: %s\n", error)
os.Exit(1) // TODO: should handle it better
}
}
if labelsize == 0 {
over = true
break
}
label := make([]byte, labelsize)
n, error := buf.Read(label)
if error != nil || n != int(labelsize) {
if error == nil {
// Client left after leaving only a few bytes
return packet
} else {
fmt.Printf("Error in Read %d bytes: %s\n", n, error)
os.Exit(1) // TODO: should handle it better
}
}
nlabels += 1
labels = labels[0:nlabels]
labels[nlabels-1] = string(label)
}
packet.Qsection = make([]types.Qentry, packet.Qdcount)
packet.Qsection[0].Qname = strings.Join(labels, ".")
packet.Qsection[0].Qtype = readShortInteger(buf)
packet.Qsection[0].Qclass = readShortInteger(buf)
packet.Valid = true
return packet
}
func generichandle(buf *bytes.Buffer, remaddr net.Addr) (response types.DNSpacket, noresponse bool) {
var query types.DNSquery
noresponse = true
packet := parse(buf)
if !packet.Valid { // Invalid packet or client too impatient
return
}
if debug > 2 {
fmt.Printf("Query is %t, Opcode is %d, Recursion is %t, Rcode is %d\n",
packet.Query, packet.Opcode, packet.Recursion, packet.Rcode)
fmt.Printf("FQDN is %s, type is %d, class is %d\n", packet.Qsection[0].Qname, packet.Qsection[0].Qtype, packet.Qsection[0].Qclass)
}
if packet.Query && packet.Opcode == types.STDQUERY {
if debug > 2 {
fmt.Printf("Replying with ID %d...\n", packet.Id)
}
noresponse = false
response.Id = packet.Id
response.Query = false
response.Opcode = packet.Opcode
response.Qdcount = 1 // Or packet.Qdcount ?
response.Qsection = make([]types.Qentry, response.Qdcount)
response.Qsection[0].Qname = packet.Qsection[0].Qname
response.Qsection[0].Qclass = packet.Qsection[0].Qclass
response.Qsection[0].Qtype = packet.Qsection[0].Qtype
query.Client = remaddr
query.Qname = packet.Qsection[0].Qname
query.Qclass = packet.Qsection[0].Qclass
query.Qtype = packet.Qsection[0].Qtype
desiredresponse := responder.Respond(query)
response.Rcode = desiredresponse.Responsecode
response.Ancount = uint16(len(desiredresponse.Asection))
response.Asection = desiredresponse.Asection
response.Nscount = uint16(len(desiredresponse.Nssection))
response.Nssection = desiredresponse.Nssection
return
}
// Else, ignore the incoming query. May be we should reply REFUSED instead?
noresponse = true
return
}
func udphandle(conn *net.UDPConn, remaddr net.Addr, buf *bytes.Buffer) {
var response types.DNSpacket
if debug > 1 {
fmt.Printf("%d bytes packet from %s\n", buf.Len(), remaddr)
}
response, noresponse := generichandle(buf, remaddr)
if !noresponse {
binaryresponse := serialize(response)
_, error := conn.WriteTo(binaryresponse, remaddr)
if error != nil {
fmt.Printf("Error in Write: %s\n", error)
os.Exit(1) // TODO: should handle it better
}
}
// Else, ignore the incoming packet. May be we should reply REFUSED instead?
}
func tcphandle(connection net.Conn) {
if debug > 1 {
fmt.Printf("TCP connection accepted from %s\n", connection.RemoteAddr())
}
smallbuf := make([]byte, 2)
n, error := connection.Read(smallbuf)
if error != nil {
fmt.Printf("Cannot read message length from TCP connection: %s\n", error)
os.Exit(1) // TODO: should handle it better
}
msglength := binary.BigEndian.Uint16(smallbuf) // RFC 1035, section 4.2.2 "TCP usage"
message := make([]byte, msglength)
n, error = connection.Read(message)
if error != nil {
fmt.Printf("Cannot read message from TCP connection with %s: %s\n", connection.RemoteAddr(), error)
os.Exit(1) // TODO: should handle it better
}
if debug > 1 {
fmt.Printf("%d bytes read from %s\n", n, connection.RemoteAddr())
}
response, noresponse := generichandle(bytes.NewBuffer(message), connection.RemoteAddr())
if !noresponse {
binaryresponse := serialize(response)
shortbuf := make([]byte, 2)
binary.BigEndian.PutUint16(shortbuf, uint16(len(binaryresponse)))
n, error := connection.Write(shortbuf)
if n != 2 || error != nil {
fmt.Printf("Error in TCP message length Write: %s\n", error)
os.Exit(1) // TODO: should handle it better
}
n, error = connection.Write(binaryresponse)
if error != nil {
fmt.Printf("Error in TCP message Write: %s\n", error)
os.Exit(1) // TODO: should handle it better
}
}
connection.Close() // In theory, we may have other requests. We clearly violate the RFC by not waiting for them. TODO
}
func tcpListener(address *net.TCPAddr, comm chan bool) {
listener, error := net.ListenTCP("udp", address)
if error != nil {
fmt.Printf("Cannot listen: %s\n", error)
os.Exit(1)
}
for {
connection, error := listener.Accept()
if error != nil {
fmt.Printf("Cannot accept TCP connection: %s\n", error)
os.Exit(1) // TODO: should handle it better
}
go tcphandle(connection)
}
listener.Close()
comm <- true
}
func udpListener(address *net.UDPAddr, comm chan bool) {
listener, error := net.ListenUDP("udp", address)
if error != nil {
fmt.Printf("Cannot listen: %s\n", error)
os.Exit(1)
}
for {
message := make([]byte, 512) // 512 is a reasonable upper limit
// for *incoming* queries
n, remaddr, error := listener.ReadFrom(message)
if error != nil {
fmt.Printf("Cannot read UDP from %s: %s\n", remaddr.String(), error)
os.Exit(1) // TODO: should handle it better
}
buf := bytes.NewBuffer(message[0:n])
go udphandle(listener, remaddr, buf)
}
listener.Close()
comm <- true
}
func main() {
debugptr := flag.Int("debug", 0, "Set the debug level, the higher, the more verbose")
listen := flag.String("address", ":8053", "Set the port (+optional address) to listen at")
flag.Parse()
debug = *debugptr
udpaddr, error := net.ResolveUDPAddr(*listen)
if error != nil {
fmt.Printf("Cannot parse \"%s\": %s\n", *listen, error)
os.Exit(1)
}
tcpaddr, error := net.ResolveTCPAddr(*listen)
if error != nil {
fmt.Printf("Cannot parse \"%s\": %s\n", *listen, error)
os.Exit(1)
}
udpchan := make(chan bool)
go udpListener(udpaddr, udpchan)
tcpchan := make(chan bool)
go tcpListener(tcpaddr, tcpchan)
<-udpchan // Just to wait the listener, otherwise, the Go runtime ends even if there are live goroutines
<-tcpchan
}