-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
73 lines (66 loc) · 1.67 KB
/
index.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
var dnsd = require('dnsd');
var dns = require('dns');
var port = 53;
var ttl = 60;
var parse_rule = function(str) {
var pattern_result = str.split(/,/);
if(pattern_result.length != 2) {
throw 'Wrong format';
}
return { pattern: new RegExp(pattern_result[0]), replace: pattern_result[1] };
};
var rules = [ ];
var as_daemon = false;
var args = process.argv.slice(2);
while(0 < args.length && args[0].match(/^-/)) {
var opt = args.shift();
if(opt == '-p') {
port = args.shift();
} else if(opt == '-d') {
as_daemon = true;
} else if(opt == '-s') {
rules.push(parse_rule(args.shift()));
} else {
throw 'Unknown parameter';
}
}
if(as_daemon) {
require('daemon')();
};
var server = dnsd.createServer(handler)
.listen(port, '127.0.0.1')
console.log('Server running at 127.0.0.1:'+port);
function handler(req, res) {
console.log('%s:%s/%s %j', req.connection.remoteAddress, req.connection.remotePort, req.connection.type, req)
var question = res.question[0];
var name = res.question[0].name;
for(var i=0 ; i<rules.length ; i++) {
if(rules[i].pattern.exec(name)) {
name = rules[i].replace;
console.log(' -> ' + name);
break;
}
}
dns.resolve4(name, function (err, addresses) {
console.log(`addresses: ${JSON.stringify(addresses)}`);
if(err && err.code == 'ENOTFOUND') {
// TODO: return soa of zone
res.end();
return;
}
if(err) {
console.log(err);
res.end();
return;
}
while(0 < addresses.length) {
var a = addresses.shift();
res.answer.push({
name: res.question[0].name,
type: 'A', data: a,
ttl: ttl
});
}
res.end();
});
}