-
Notifications
You must be signed in to change notification settings - Fork 3
/
h2dns
executable file
·200 lines (180 loc) · 6.21 KB
/
h2dns
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
#!/usr/bin/env node
'use strict';
if (process.env.NODE_ENV !== 'production'){
try { require('longjohn'); } catch (e) {} }
const debug = require('debug')('h2dns:server');
const dnsd = require('./dnsd/named');
const randomstring = require("randomstring");
const shuffle = require('shuffle-array');
const option = require('commander')
.version(require('./package.json').version)
.option('-i, --edns-client-subnet [subnet]', 'EDNS Client Subnet')
.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('-t, --timeout [5000]', 'Default Http2 Request Timeout',
val => parseInt(val), 5000)
.option('-c, --pool [2]', 'Concurrent Connections of Pool Size',
val => Math.max(1, val), 2)
.option('--ping-interval [60000]', 'Interval of ping to keepAlive.',
val => Math.max(500, parseInt(val)), 60000) // at least 500ms?
.option('-v, --family [4|6]',
'Force Resolver Internet Protocol Version priority',
val => parseInt(val), 0)
.option('-r, --retries [3]',
'The maximum amount of times to retry',
val => parseInt(val), 3)
.parse(process.argv);
const defaultOptions = {
json: true,
timeout: option.timeout,
gzip: true,
agent: true, // a holder for proxy
};
const forwardUrl = 'https://dns.google.com:443/resolve';
const url = require('url');
const resolver = url.parse(forwardUrl);
resolver.family = option.family;
const agentPool = require('./pool')(resolver, option.pool);
const retry = require('retry');
const request = require('request')
.defaults(new Proxy(defaultOptions, {
get: (target, name) => {
if (name === 'agent') {
return agentPool.aquire();
}
return defaultOptions[name];
}
}));
const Constants = require('./dnsd/constants');
const ip6 = require('ip6');
const subnet = option.ednsClientSubnet;
const SupportTypes = [
'A', 'MX', 'CNAME', 'TXT', 'PTR',
'AAAA', 'NS', 'SOA', 'SRV', 'DS'
];
const server = dnsd.createServer((req, res) => {
const question = req.question[0], hostname = question.name;
const time = new Date().getTime();
const tag = `[${pad(5, req.id)}/${pad(4, req.connection.type, ' ')}]`;
const timeStamp = [
tag, req.opcode, hostname, question.class, question.type].join(' ');
// TODO unsupported due to dnsd's broken implementation.
if (SupportTypes.indexOf(question.type) === -1) {
debug(timeStamp + ` +${new Date().getTime() - time}ms`);
res.responseCode = 2;
return res.end();
}
let query = { name: hostname }
let type = Constants.type_to_number(question.type);
if (question.type != 'A') {
query.type = type; // Type defaults 1
// API clients concerned about possible side-channel privacy attacks
// using the packet sizes of HTTPS GET requests can use this to make all
// requests exactly the same size by padding requests with random data.
query.random_padding= randomstring.generate({ // 253 maximum dnslength
// +'&type=type'.length minus current Name for equal query length url
length: 253 - question.name.length - type.toString().length,
charset: 'alphanumeric' // safe but can be more extended chars-_
});
} else {
query.random_padding= randomstring.generate({
length: 259 - question.name.length,
charset: 'alphanumeric'
});
}
if (subnet) {
query.edns_client_subnet = subnet;
}
const operation = retry.operation({
retries: option.retries,
maxTimeout: option.timeout,
minTimeout: Math.min(option.timeout, 1000)
});
operation.attempt(current => {
const http2Req = request({
url: forwardUrl,
qs: query
}, (err, response, output) => {
if (operation.retry(err)) {
debug(`${tag} retrying ${operation.attempts()}/${option.retries}`);
return;
}
if (err) {
debug(`give up retry after ${option.retries} attempts`);
err = operation.mainError();
}
if (!err) agentPool.release(http2Req.agent);
debug(timeStamp + ` +${new Date().getTime() - time}ms`);
if (output && output.Answer) {
// https://en.wikipedia.org/wiki/Round-robin_DNS
if (output.Answer.length > 1) {
shuffle(output.Answer);
}
res.recursion_available = output.RA;
res.recursion_desired = output.RD;
res.answer = output.Answer.map(rec => {
rec.ttl = rec.TTL;
rec.type = Constants.type_to_label(rec.type);
switch (rec.type) {
case 'MX':
rec.data = rec.data.split(/\s+/);
break;
case 'TXT':
case 'SPF':
rec.data = rec.data.slice(1, -1);
break;
case 'AAAA':
// dnsd is expecting long IPVersion 6 format
rec.data = ip6.normalize(rec.data);
break;
case 'SOA':
rec.data = arr2map(rec.data.split(/\s+/), [
'mname', 'rname', 'serial', 'refresh', 'retry', 'expire', 'ttl'
]);
break;
case 'SRV':
rec.data = arr2map(rec.data.split(/\s+/), [
'priority', 'weight', 'port', 'target'
]);
break;
case 'DS':
rec.data = arr2map(rec.data.split(/\s+/), [
'key_tag', 'algorithm', 'digest_type', 'digest'
]);
break;
}
return rec;
});
} else if (err) {
res.responseCode = 2;
debug('request error', err);
}
res.end();
});
http2Req.on('error', err => {
debug('request error', err);
});
});
});
function arr2map(arr, keys, data = {}) {
keys.forEach((key, idx) => data[key] = arr[idx]);
return data;
}
function pad(n, m, holder = '0') {
return String(Array(n + 1).join(holder) + m).slice(-n);
}
const devnull = require('dev-null');
setInterval(() => {
const req = request({
url: forwardUrl,
qs: { name: resolver.hostname }
}, (err) => {
if (!err) agentPool.release(req.agent);
});
req.on('error', err => {
debug('ping error', err);
}).pipe(devnull());
}, option.pingInterval);
server.listen(option.port, option.address, () => {
debug(`start listening to ${option.address || ''}:${option.port}.`)
});