-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
84 lines (73 loc) · 2.44 KB
/
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
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
'use strict';
const dns = require('native-dns');
const config = require('./src/config');
require('dotenv').config();
const ScraperSerivce = require('./src/scraperService');
const DnsProxyService = require('./src/dnsProxyService');
// TODO: make this a config setting
// TODO: replace console statements with log calls
// TODO; figure out the recursion requested error in responses
// TODO: we should stop trying a plugin if login fails.
const targetDomainExpression = /\.local$/i;
const scraperSerivce = new ScraperSerivce(config);
const dnsProxySerivce = new DnsProxyService(config);
const server = dns.createServer();
server.on('request', (request, response) => {
// to keep things simple, assume one question per request
const questionName = request.question[0].name;
console.log(`${new Date()} request for ${questionName} ->`);
if (!targetDomainExpression.test(questionName)) {
// make a request to our fallback server
console.log('Not in target domain.');
dnsProxySerivce.makeRequest(request)
.then(proxyAnswer => {
console.log('Got response from proxy service.');
response.answer = proxyAnswer.answer;
response.send();
console.log('<--request');
})
.catch(err => {
console.error('Proxied Request Error!');
console.error(err);
});
return;
}
const editedQuestionName =
questionName.toLowerCase().replace(/\.local/, '');
scraperSerivce.getAddress(editedQuestionName)
.then(matchingClient => {
if (matchingClient) {
console.log('matched ', questionName);
response.answer.push(dns.A({
name: questionName,
address: matchingClient.ipv4,
// TODO: ipv6
// TODO: don't hardcode
ttl: 600,
}));
} else {
console.log('didn\'t match ', questionName);
}
response.send();
console.log('<--request');
})
.catch(err => {
console.log('Scraper Error!');
console.error(err);
});
});
server.on('listening', () => console.log('server listening:', server.address()));
server.on('close', () => console.log('server closed'));
server.on('socketError', err => {
console.error('Socket error!');
console.error(err);
});
server.on('error', err => {
// TODO: exit the process
console.error('Unhandled Error!');
console.error(err);
console.log(err.stack);
});
// TODO: make this configurable
// TODO: need to run with sudo for such a low port
server.serve(53);