-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdns-server.js
51 lines (49 loc) · 1.46 KB
/
dns-server.js
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
const dns = require('dns2')
const { Packet } = dns
module.exports = async function createServer (entries) {
const lookup = {}
for (const domain in entries) {
lookup[toCharCodes(domain)] = entries[domain]
}
const server = dns.createServer({
udp: true,
tcp: true,
doh: true,
handle: (request, send) => {
const response = Packet.createResponseFromRequest(request)
// Note: common public DNS servers only support single requests
const [question] = request.questions
const { name, type, class: clazz } = question
let answers = lookup[name] && lookup[name][type]
if (answers) {
if (!Array.isArray(answers)) {
answers = [answers]
}
response.answers = answers.map((entry) => {
return {
name,
type,
class: clazz || Packet.CLASS.IN,
ttl: entry.ttl,
data: entry.data
}
})
} else {
const rcode = lookup[name] && lookup[name].DNS_RCODE && lookup[name].DNS_RCODE[0] && entries[name].DNS_RCODE[0].data
// In case no answer is given and no error is provided, we use the rcode === 3 aka unknown domain.
response.header.rcode = rcode || 3
}
send(response)
}
})
await server.listen()
return server
}
function toCharCodes (testDomain) {
const buff = Buffer.from(testDomain)
let string = ''
for (const i of buff) {
string += String.fromCharCode(i)
}
return string
}