forked from iriscouch/dnsd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
618 lines (506 loc) · 16.7 KB
/
Copy pathserver.js
File metadata and controls
618 lines (506 loc) · 16.7 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Copyright 2012 Iris Couch, all rights reserved.
//
// Server routines
"use strict";
const Net = require( "net" );
const Dgram = require( "dgram" );
const { EventEmitter } = require( "events" );
const { DNSMessage, DNSRecord } = require( "./message" );
const { seconds: asSeconds, serial: asSerial } = require( "./convenient" );
const { RCODE } = require( "./constants" );
const DefaultOptions = {
ttl: 3600,
debug: false,
};
/**
* Implements DNS server.
*
* @property {object} options options customizing selected operations
*/
class DNSServer extends EventEmitter {
/**
* @param {function(Request, Response):void} requestHandler handles single incoming request
* @param {object} options customization options for server instance
*/
constructor( requestHandler, options = {} ) {
super();
this.zones = {};
this.options = Object.assign( {}, DefaultOptions, options );
if ( requestHandler )
this.on( "request", requestHandler );
this.udp = Dgram.createSocket( "udp4" );
this.tcp = Net.createServer();
this.udp.on( "close", () => { this.close(); } );
this.tcp.on( "close", () => { this.close(); } );
this.udp.on( "error", function( er ) { this.emit( "error", er ); } );
this.tcp.on( "error", function( er ) { this.emit( "error", er ); } );
this.tcp.on( "connection", connection => { this.onTcpConnection( connection ); } );
this.udp.on( "message", ( msg, rInfo ) => { this.onUdp( msg, rInfo ); } );
const listening = { tcp: false, udp: false };
this.udp.once( "listening", function() {
listening.udp = true;
if ( listening.tcp )
this.emit( "listening" );
} );
this.tcp.once( "listening", function() {
listening.tcp = true;
if ( listening.udp )
this.emit( "listening" );
} );
}
/**
* Adds another zone to server.
*
* @param {string} domainName domain name of zone (the common suffix of all names in this zone)
* @param {string} primaryNameServer domain name of zone's primary/master name server
* @param {string} adminAddress mail address of zone's administrator
* @param {number} serial serial number identifying current version of zone's definition
* @param {number} refresh number of seconds for a slave to wait before fetching zone from master server again
* @param {number} retry number of seconds for a slave to wait before trying to fetch zone again after failed attempt
* @param {number} expire number of seconds for a slave to wait before considering zone _gone_ while failing to fetch zone from master
* @param {number} ttl negative TTL, number of seconds for resolvers to wait before querying name servers of zone again after failed attempts
* @returns {DNSServer} current server for fluent interface
*/
zone( domainName, primaryNameServer = null, adminAddress = "hostmaster", serial = undefined, refresh = 3600, retry = 1800, expire = 604800, ttl = 300 ) {
const record = new DNSRecord( {
class: "IN",
type: "SOA",
name: domainName,
data: {
mname: primaryNameServer || `ns1.${domainName}`,
rname: adminAddress,
serial: asSerial( serial ),
refresh: asSeconds( refresh ),
retry: asSeconds( retry ),
expire: asSeconds( expire ),
ttl: asSeconds( ttl || 0 ),
}
} );
this.zones[record.name] = record;
return this;
}
/**
* Requests server to start listening on selected port for incoming
* queries.
*
* @param {number} port number of IP port to listen on
* @param {string} ip IP to bind on listening
* @param {function():void} callback function invoked on successfully registering listener
* @returns {DNSServer} current server for fluent interface
*/
listen( port, ip, callback ) {
let fn;
this.port = port;
if ( typeof ip === "function" ) {
this.ip = "0.0.0.0";
fn = ip;
} else {
this.ip = ip || "0.0.0.0";
if ( typeof callback === "function" )
fn = callback;
}
this.udp.bind( this.port, this.ip );
this.tcp.listen( this.port, this.ip );
Promise.all( [
new Promise( ( resolve, reject ) => {
this.udp.once( "listening", resolve );
this.udp.once( "error", reject );
} ),
new Promise( ( resolve, reject ) => {
this.tcp.once( "listening", resolve );
this.tcp.once( "error", reject );
} ),
] )
.then( () => {
if ( fn ) {
process.nextTick( fn );
}
process.nextTick( () => this.emit( "listening" ) );
} )
.catch( error => this.emit( "error", error ) );
return this;
}
/**
* Shuts down running server.
*
* @returns {void}
*/
close() {
if ( !this.$closing ) {
this.$closing = true;
this.udp.close();
this.tcp.close( () => {
this.emit( "close" );
} );
}
}
/**
* Handles new connection established on TCP port of server.
*
* @param {Socket} connection describes established TCP connection
* @returns {void}
* @protected
*/
onTcpConnection( connection ) {
let expecting = -1;
let received = 0;
const chunks = [];
/** @type {ServerSocket} */
const socket = {
type: "tcp",
remoteAddress: connection.remoteAddress,
remotePort: connection.remotePort,
server: this,
send: reply => new Promise( ( resolve, reject ) => {
if ( reply == null ) {
// don't waste a connection on a client asking for data this
// server isn't authoritative for
connection.end();
resolve();
return;
}
if ( !Buffer.isBuffer( reply ) ) {
throw new Error( "invalid response, must be Buffer" );
}
const length = reply.length;
if ( length > 65535 ) {
throw new Error( "TCP responses greater than 65535 bytes not supported" );
}
connection.end( Buffer.concat( [ Buffer.from( [ length >> 8, length & 0xff ] ), reply ] ), error => {
if ( error ) {
reject( error );
} else {
resolve();
}
} );
} ),
};
connection.on( "data", chunk => {
chunks.push( chunk );
received += chunk.length;
if ( expecting < 0 && received >= 2 ) {
while ( chunks[0].length < 2 ) {
chunks.splice( 0, 2, Buffer.concat( chunks.slice( 0, 2 ) ) );
}
expecting = chunks[0].readUInt16BE( 0 );
}
if ( expecting > -1 && received >= 2 + expecting ) {
const buf = Buffer.concat( chunks ).slice( 2 );
const message = buf.slice( 0, expecting );
const request = new DNSRequest( message, socket );
const response = new DNSResponse( message, socket );
if ( this.isValidEDNS( request, response ) ) {
this.emit( "request", request, response );
}
expecting = -1;
received = buf.length - expecting;
if ( received > 0 ) {
chunks.splice( 0, chunks.length, buf.slice( expecting ) );
} else {
chunks.splice( 0 );
}
}
} );
}
/**
* Handles new incoming UDP datagram with DNS query.
*
* @param {Buffer} query payload of received datagram containing DNS query
* @param {{address: string, family: string, port: number, size: number}} info describes context of datagram reception
* @returns {void}
* @protected
*/
onUdp( query, info ) {
let response; // eslint-disable-line prefer-const
/** @type {ServerSocket} */
const socket = {
type: this.udp.type,
remoteAddress: info.address,
remotePort: info.port,
server: this,
send: reply => new Promise( ( resolve, reject ) => {
if ( reply == null ) {
resolve();
return;
}
if ( !Buffer.isBuffer( reply ) ) {
throw new Error( "invalid response, must be Buffer" );
}
const udpLimit = Math.max( 512, ( response.edns || {} ).udpSize || 1 );
if ( reply.length > udpLimit ) {
throw new Error( `UDP reply exceeds limit of ${udpLimit} bytes` );
}
this.udp.send( reply, 0, reply.length, info.port, info.address, error => {
if ( error ) {
reject( error );
} else {
resolve();
}
} );
} ),
};
const request = new DNSRequest( query, socket );
response = new DNSResponse( query, socket );
if ( this.isValidEDNS( request, response ) ) {
this.emit( "request", request, response );
}
}
/**
* Checks if request complies with EDNS requirements in RFC 6891.
*
* @param {DNSRequest} request incoming request to be handled
* @param {DNSResponse} response prepared response
* @returns {boolean} true if request may be handled by server callback, false if response has been transmitted already
*/
isValidEDNS( request, response ) {
const records = request.findEDNSRecords();
if ( records.length > 1 || ( records.length === 1 && records[0].section !== "additional" ) ) {
this.respondOnInvalidEDNS( response, RCODE.FORMERR );
return false;
}
if ( records.length === 1 ) {
const { record: { edns } } = records[0];
if ( edns.version > 0 ) {
this.respondOnInvalidEDNS( response, RCODE.BADVERS );
return false;
}
}
return true;
}
/**
* Responds to request with EDNS error.
*
* @param {DNSResponse} response response EDNS record is added to
* @returns {DNSRecord} EDNS record added to response
*/
addEDNSReply( response ) {
const record = new DNSRecord( {
edns: {
udpSize: Math.max( response.edns ? response.edns.udpSize || 512 : 512, 512 ),
extendedResult: 0,
version: 0,
flagDO: 0,
flags: 0,
options: [],
},
name: "",
class: "IN",
type: "OPT",
} );
response.additional.push( record );
return record;
}
/**
* Responds to request with EDNS error.
*
* @param {DNSResponse} response response to use for replying
* @param {number} resultCode EDNS extended result code to use
* @returns {void}
*/
respondOnInvalidEDNS( response, resultCode ) {
this.addEDNSReply( response );
response.responseCode = resultCode; // eslint-disable-line no-param-reassign
response.end()
.catch( error => {
console.error( `responding on invalid EDNS request failed: ${error.message}` );
} );
}
}
/**
* Implements common description of incoming DNS query in context of DNS
* server.
*/
class DNSRequest extends DNSMessage {
/**
* @param {Buffer} query describes DNS message received as query
* @param {ServerSocket} connection describes socket used to receive the request
*/
constructor( query, connection ) {
super( query );
this.connection = connection;
}
/**
* Prepares request for JSON serialization.
*
* @returns {object} description of current request as plain object
*/
toJSON() {
const obj = {};
Object.keys( this ).forEach( key => {
if ( key !== "connection" )
obj[key] = this[key];
} );
return obj;
}
}
/**
* Implements common manager of response to incoming DNS query in context of
* DNS server.
*
* @property {?RawEDNSResourceRecord} edns data of first encountered OPT RR in additional section of related request
*/
class DNSResponse extends DNSMessage {
/**
* @param {Buffer} data describes querying DNS message to respond to
* @param {ServerSocket} connection describes socket used to receive the query
*/
constructor( data, connection ) {
super( data );
this.question = this.question || [];
this.answer = [];
this.authority = [];
this.additional = [];
this.connection = connection;
this.type = "response";
this.ignoreEmpty = false;
}
/**
* Prepares response for JSON serialization.
*
* @returns {object} description of current response as plain object
*/
toJSON() {
const obj = {};
Object.keys( this ).forEach( key => {
if ( key !== "connection" )
obj[key] = this[key];
} );
return obj;
}
/**
* Compiles described response and sends it to querying peer.
*
* @param {*} value value to be included with response, deprecated in favor of more explicit use of API
* @returns {Promise<void>} promises response sent
*/
end( value = undefined ) {
let that = this;
if ( Array.isArray( value ) ) {
this.answer = ( this.answer || [] ).concat( value );
value = undefined; // eslint-disable-line no-param-reassign
} else if ( value && typeof value == "object" ) {
// eslint-disable-next-line consistent-this
that = new DNSResponse( value, this.connection );
value = undefined; // eslint-disable-line no-param-reassign
}
const questions = that.question = that.question || [];
const answer = that.answer = that.answer || [];
const authority = that.authority = that.authority || [];
const additional = that.additional = that.additional || [];
that.recursionAvailable = false;
that.authoritative = true;
if ( !this.responseCode ) {
for ( const question of questions ) {
const soaRecord = this.findZoneForName( question.name );
if ( !soaRecord ) {
// don't respond to questions regarding zones we aren't authoritative for
continue;
}
switch ( question.kind() ) {
case "IN A" :
if ( typeof value == "string" && answer.length === 0 ) {
if ( questions.length > 1 ) {
return Promise.reject( new Error( "can't handle simple answer to multiple questions" ) );
}
that.answer.push( {
class: "IN",
type: "A",
name: question.name,
data: value
} );
}
break;
case "IN SOA" :
// convenience: implicitly provide authoritative SOA record to sole question
if ( soaRecord && questions.length === 1 && answer.length === 0 && soaRecord.name === question.name ) {
that.answer.push( soaRecord );
}
break;
}
// add SOA record if server is authoritative for sole question that didn't yield any answer
if ( soaRecord && questions.length === 1 && answer.length === 0 && authority.length === 0 )
that.authority.push( soaRecord );
const minTTL = Math.max( ( soaRecord ? soaRecord.data.ttl : this.connection.server.options.ttl ) || 1, 1 );
for ( const record of answer ) { wellFormedRecord( record, minTTL ); }
for ( const record of authority ) { wellFormedRecord( record, minTTL ); }
for ( const record of additional ) { wellFormedRecord( record, minTTL ); }
}
}
// ensure to have EDNS record in response if required
const ednsRecords = this.findEDNSRecords();
let ednsResponse;
if ( this.edns || this.responseCode > 0x0f ) {
if ( ednsRecords.length > 1 || ( ednsRecords === 1 && ednsRecords[0].section !== "additional" ) ) {
return Promise.reject( new Error( "invalid number or location of EDNS record(s) in response" ) );
}
if ( ednsRecords.length ) {
ednsResponse = ednsRecords[0].record;
} else {
ednsResponse = this.connection.server.addEDNSReply( this );
}
}
if ( this.responseCode > 0x0f ) {
ednsResponse.edns.extendedResult = ( this.responseCode & 0xff0 ) >> 4;
}
const reply = !this.ignoreEmpty || answer.length > 0 || authority.length > 0 || ( this.edns && this.responseCode > 0 ) ? that.toBinary() : null;
if ( !reply && this.connection.server.options.debug ) {
console.debug( "ignoring request" );
}
return that.connection.send( reply );
/**
* Fixes single DNS record.
*
* @param {DNSRecord} record record to be fixed
* @param {number} minTTL minimum TTL to use when missing TTL in record
* @returns {void}
*/
function wellFormedRecord( record, minTTL ) {
if ( !record.class ) {
record.class = "IN"; // eslint-disable-line no-param-reassign
}
if ( !record.ttl && !record.edns ) {
record.ttl = minTTL; // eslint-disable-line no-param-reassign
}
}
}
/**
* Looks for local definition of zone covering provided name.
*
* @param {string} name domain name
* @returns {?DNSRecord} found SOA record
*/
findZoneForName( name ) {
let soaRecord;
while ( name.length > 0 ) {
soaRecord = this.connection.server.zones[name];
if ( soaRecord )
return soaRecord;
const split = /^([^.\s]{1,63})(?:\.([^.\s].*))?$/.exec( name );
if ( !split ) {
throw new Error( "invalid name in query" );
}
name = split[2] == null ? "" : split[2]; // eslint-disable-line no-param-reassign
}
return null;
}
}
module.exports = function createServer( requestHandler, options = {} ) { // eslint-disable-line no-param-reassign
return new DNSServer( requestHandler, options );
};
module.exports.DNSServer = DNSServer;
module.exports.DNSRequest = DNSRequest;
module.exports.DNSResponse = DNSResponse;
/**
* @typedef {object} SocketAddress
* @property {string} address IP address
* @property {string} family address family, such as "inet"
* @property {number} port number of IP port
*/
/**
* @typedef {object} ServerSocket
* @property {string} type indicates type of socket
* @property {string} remoteAddress provides IP address of querying peer
* @property {number} remotePort provides port number of querying peer
* @property {DNSServer} server exposes server instance this socket is part of
* @property {function(Buffer):Promise} send sends provided DNS message to peer
*/