-
Notifications
You must be signed in to change notification settings - Fork 2
/
fwdns
executable file
·305 lines (273 loc) · 7.96 KB
/
fwdns
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
302
303
304
305
#!/usr/bin/env node
'use strict';
if (process.env.NODE_ENV !== 'production'){
try { require('longjohn'); } catch (e) {} }
const debug = require('debug')('fwdns:server');
const dnsd = require('./dnsd/named');
const dns = require('./dns/dns');
const Zone = require('./zone');
const consts = require('./packet/').consts;
const ip6 = require('ip6');
const NodeCache = require('node-cache');
const cache = new NodeCache({ useClones: false });
const race = require('async').race;
const platform = require('./dns/lib/platform');
function collectZone(zone, zones) {
if (zone.endsWith('.json')) {
zone = require(zone);
if (zone && Array.isArray(zone.hosts) && Array.isArray(zone.names)) {
zones.push(new Zone(zone.hosts, zone.names));
}
} else {
zones.push(zone);
}
return zones;
}
function collectLocalZone(zone, zones) {
if (zone.endsWith('.json')) {
zone = require(zone);
if (zone) {
Object.assign(zones, zone);
}
}
return zones;
}
const option = require('commander')
.version(require('./package.json').version)
.option('-p, --port [6666]', 'Port to bind', val => parseInt(val), 6666)
.option('-l, --listen [127.0.0.1]', 'Address to listen', '127.0.0.1')
.option('-z, --zone [8.8.8.8]',
'Default zone, use system by default',
collectZone, [])
.option('-t, --timeout [5000]',
'Timeout forwarding requests',
val => parseInt(val), 5000)
.option('--renew-timeout [3600]',
'Timeout of auto renewal',
val => parseInt(val), 600)
.option('-f, --forward-zone [/path/to/forward/zone.json]',
'Forward zone setting, {"hosts": ["8.8.8.8"], "names": ["google.com"]}',
collectZone, [])
.option('-s, --local-zone [/path/to/local/zone.json]',
'Local zone setting, {"abc.com": "127.0.0.1"}',
collectLocalZone, [])
.parse(process.argv);
const SupportTypes = [
'A', 'MX', 'CNAME', 'TXT', 'PTR',
'AAAA', 'NS', 'SOA', 'SRV'
//, 'DS' // unsupported by native-dns-packet
];
const lastQuery = {};
const server = dnsd.createServer((req, res) => {
const question = req.question[0], hostname = question.name;
const start = Date.now();
const tag = `[${pad(5, req.id)}/${pad(4, req.connection.type, ' ')}]`;
let timeStamp = [
tag, req.opcode, hostname, question.class, question.type].join(' ');
question.class = consts.NAME_TO_QCLASS[question.class] || 1;
// TODO unsupported due to dnsd's broken implementation.
if (SupportTypes.indexOf(question.type) === -1) {
debug(timeStamp + ` +${Date.now() - start}ms`);
res.responseCode = 2;
return res.end();
}
lastQuery[question.name] = start;
const cached = get(question);
if (cached != null) {
const time = Math.max(0, parseInt((ttl(question) - Date.now()) / 1000));
debug(timeStamp + ` via cache (ttl: ${time}) +${Date.now() - start}ms`);
copy(cached, res, ['authority', 'answer'], (rec) => {
rec.ttl = time;
return rec;
});
return res.end();
}
let local = option.localZone[question.name];
if (local) {
if (!Array.isArray(local)) local = [local];
res.answer = local.map(val => {
return {
name: question.name,
type: 'A',
class: 'IN',
data: val,
ttl: 3600
}
});
debug(timeStamp + ` via local +${Date.now() - start}ms`);
return res.end();
}
let server = [];
for (let fwz of option.forwardZone) {
if (fwz.match(question.name)) {
server = fwz.hosts;
break;
}
}
if (server.length === 0) server = option.zone;
timeStamp += ' via ' + server.length === 0 ? 'system' : server.join(',');
doMultiQuery(question, server, (err, data) => {
if (err) {
res.responseCode = 2;
} else {
copy(data, res);
}
debug(timeStamp + ` +${Date.now() - start}ms`);
res.end();
return process.nextTick(() => {
if (!data) data = { authority: [], answer: [] };
data.server = server;
save(question, data);
});
});
});
function pad(n, m, holder = '0') {
return String(Array(n + 1).join(holder) + m).slice(-n);
}
// convert from node-dns to dnsd
function convert(rec) {
rec.type = consts.qtypeToName(rec.type);
rec.class = consts.QCLASS_TO_NAME[rec.class] || 'IN';
switch (rec.type) {
case 'A':
rec.data = rec.address;
break;
case 'AAAA':
rec.data = ip6.normalize(rec.address);
break;
case 'CNAME':
rec.data = rec.data || [
rec.primary,
rec.admin,
rec.serial,
rec.refresh,
rec.retry,
rec.expiration,
rec.minimum
];
break;
case 'MX':
rec.data = [rec.priority, rec.exchange];
break;
case 'TXT':
case 'SPF':
rec.data = rec.data;
break;
case 'SOA':
rec.data = {
rname: rec.admin,
mname: rec.primary,
serial: rec.serial,
refresh: rec.refresh,
retry: rec.retry,
expire: rec.expiration,
ttl: rec.minimum
};
break;
case 'SRV':
rec.data = {};
['priority', 'weight', 'port', 'target'].forEach(key => {
rec.data[key] = rec[key];
});
break;
}
return rec;
}
const pending = {};
function save(question, res) {
const key = `${question.name} ${question.type}`;
const o = res.answer.length > 0 ? res.answer : res.authority;
const ttls = o.map(v => v.ttl);
const ttl = ttls.length > 0 ? ttls[0] : 600;
cache.set(key, copy(res), ttl);
if (lastQuery[question.name] && ttl > 10 &&
pending[question.name] !== question.type &&
(Date.now() - lastQuery[question.name]) / 1000 < option.renewTimeout) {
pending[question.name] = question.type;
setTimeout(() => {
doMultiQuery(question, res.server, (err, data) => {
delete pending[question.name];
if (err) return;
debug(`renew ${key}`);
data.server = res.server;
save(question, data);
});
}, (ttl * 1000) * 0.8);
}
}
function get(question) {
const key = `${question.name} ${question.type}`;
return cache.get(key);
}
function ttl(question) {
const key = `${question.name} ${question.type}`;
return cache.getTtl(key);
}
function doMultiQuery(question, server, callback) {
if (server.length === 0) {
const time = Date.now();
return dns.resolve(question.name, question.type, (err, ret, message) => {
if (err) return callback(err);
debug(`querying ${question.name} via system +${Date.now() - time}ms`);
const data = { server: server };
copy(message, data, ['authority', 'answer'], convert);
callback(null, data);
});
}
race(server.map(s => {
let address = s.split(':');
s = {};
s.address = address[0];
if (address.length > 1) {
s.port = address[1];
}
return (callback) => {
const time = Date.now();
doQuery(question, s, (err, rep) => {
debug(`querying ${question.name}` +
` via ${s.address}:${s.port} +${Date.now() - time}ms`);
callback(err, rep);
});
};
}), callback);
}
function doQuery(question, server, callback) {
const data = { server: server };
const forwardReq = dns.Request({
question: dns.Question(question),
server: server,
timeout: option.timeout,
});
forwardReq.on('timeout', () => {
callback(new Error('timeout'));
debug(`querying ${question.name}` +
` via ${server.address}:${server.port} timeout`);
});
forwardReq.on('error', err => {
callback(err);
debug('forward error', err);
});
forwardReq.on('message', (err, message) => {
if (err) {
debug('forward error', err);
return;
}
copy(message, data, ['authority', 'answer'], convert);
callback(null, data);
});
forwardReq.on('end', () => {
//
});
forwardReq.send();
}
function copy(from, to = {}, keys = ['authority', 'answer', 'server'], mapper) {
keys.forEach(k => {
if (from[k]) {
to[k] = mapper ? from[k].map(v => mapper(v)) : from[k];
}
});
return to;
}
server.listen(option.port, option.address, () => {
debug(`start listening to ${option.address || ''}:${option.port}.`)
});