forked from iriscouch/dnsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.js
393 lines (329 loc) · 12.1 KB
/
message.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
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
// Copyright 2012 Iris Couch, all rights reserved.
"use strict";
const Util = require( "util" );
const Decode = require( "./decode" );
const { Encoder } = require( "./encode" );
const { SECTIONS, typeToLabel, classToLabel } = require( "./constants" );
/**
* Implements representation of a single DNS message.
*
* @property {number} id a number representing the unique query ID
* @property {string} type "request" or "response"
* @property {number} responseCode response code
* @property {?RawEDNSResourceRecord} edns data of first encountered OPT RR in additional section
* @property {string} opcode one out of "query", "iquery", "status", "unassigned", "notify", "update"
* @property {boolean} authoritative indicates if message is an authoritative answer
* @property {boolean} truncated indicates if message has been truncated due to oversize
* @property {boolean} recursionDesired indicates query is asking for recursive processing
* @property {boolean} recursionAvailable indicates whether service is supporting recursive processing of queries
* @property {boolean} authenticated marks response message to be authenticated by server
* @property {boolean} checkingDisabled indicates in a request message that client is accepting non-authenticated data in response
* @property {DNSRecord[]} question records in question section
* @property {DNSRecord[]} answer records in answer section
* @property {DNSRecord[]} authority records in authority section
* @property {DNSRecord[]} additional records in additional section
*/
class DNSMessage {
/**
* @param {Buffer|object} body sequence of octets describing DNS message in wire format or some object similar to DNSMessage to load properties from
*/
constructor( body ) {
this.id = null;
this.type = null;
this.responseCode = null;
this.opcode = null;
this.authoritative = null;
this.truncated = null;
this.recursionDesired = null;
this.recursionAvailable = null;
this.authenticated = null;
this.checkingDisabled = null;
if ( Buffer.isBuffer( body ) ) {
this.parse( body );
} else if ( body && typeof body === "object" ) {
Object.assign( this, body );
for ( const section of SECTIONS ) {
const records = this[section] = [];
if ( Array.isArray( records ) )
records.forEach( ( record, i ) => {
records[i] = new DNSRecord( record );
} );
}
} else {
throw new Error( "DNSMessage must be created with raw buffer or object describing message content" );
}
}
/**
* Decodes whole DNS message from sequence of octets.
*
* @param {Buffer} body sequence of octets describing DNS message in wire format
* @returns {void}
*/
parse( body ) {
this.id = Decode.id( body );
this.type = Decode.qr( body ) === 0 ? "request" : "response";
this.responseCode = Decode.rcode( body );
this.edns = null;
const opcodeNames = [ "query", "iquery", "status", null, "notify", "update" ];
const opcode = Decode.opcode( body );
this.opcode = opcodeNames[opcode] || null;
this.authoritative = Boolean( Decode.aa( body ) );
this.truncated = Boolean( Decode.tc( body ) );
this.recursionDesired = Boolean( Decode.rd( body ) );
this.recursionAvailable = Boolean( Decode.ra( body ) );
this.authenticated = Boolean( Decode.ad( body ) );
this.checkingDisabled = Boolean( Decode.cd( body ) );
const sectionsCache = Decode.sections( body );
for ( const section of SECTIONS ) {
const count = Decode.recordCount( body, section );
const records = this[section] = new Array( count );
for ( let i = 0; i < count; i++ ) {
const record = records[i] = new DNSRecord( body, section, i, sectionsCache );
if ( record.edns && !this.edns && section === "additional" ) {
this.responseCode += record.edns.extendedResult << 4;
this.edns = record.edns;
}
}
}
}
/**
* Searches provided message for EDNS-specific OPT RR.
*
* @returns {EDNSRecordLocation[]} list of found EDNS records
*/
findEDNSRecords() {
const ednsRecords = [];
for ( const section of SECTIONS ) {
/** @type {DNSRecord[]} */
const records = this[section];
const numRecords = records.length;
for ( let i = 0; i < numRecords; i++ ) {
const record = records[i];
if ( record.edns ) {
ednsRecords.push( { section, index: i, record } );
}
}
}
return ednsRecords;
}
/**
* Serializes DNS message into sequence of octets describing it in wire format.
*
* @returns {Buffer} sequence of octets describing DNS message in wire format
*/
toBinary() {
const limit = this.connection && this.connection.type === "tcp" ? 65535 : this.edns ? this.edns.udpSize : 512;
return new Encoder().message( this ).toBinary( limit );
}
/**
* Renders string containing some essential information on DNS message.
*
* @returns {string} description of current DNS message
*/
toString() {
const info = [
Util.format( "ID : %d", this.id ),
Util.format( "Type : %s", this.type ),
Util.format( "Opcode : %s", this.opcode ),
Util.format( "Authoritative : %s", this.authoritative ),
Util.format( "Truncated : %s", this.truncated ),
Util.format( "Recursion Desired : %s", this.recursionDesired ),
Util.format( "Recursion Available: %s", this.recursionAvailable ),
Util.format( "Response Code : %d", this.responseCode ),
];
for ( const section of SECTIONS ) {
if ( this[section].length > 0 ) {
info.push( Util.format( ";; %s SECTION:", section.toUpperCase() ) );
for ( const record of this[section] ) {
info.push( record.toString() );
}
}
}
return info.join( "\n" );
}
}
/**
* Represents an individual record in a DNS message.
*
* @property {string} name domain name this record is applying to
* @property {string} type type of resource record ('A', 'NS', 'CNAME', etc. or 'Unknown')
* @property {string} class network class of resource record ('IN', 'None' 'Unknown')
* @property {number} ttl time to live, number of seconds for caching this record
* @property {?(object|string|Array)} data record data in type-specific format, null if not applicable
* @property {?RawEDNSResourceRecord} edns EDNS-related information in case of record being OPT RR in compliance with RFC 6891
*/
class DNSRecord {
/**
* @param {Buffer|object} body sequence of octets describing DNS record in wire format or data of DNS record extracted before
* @param {string} sectionName name of DNS message section this record is associated with
* @param {number} recordNum record's index into selected section's set of records
* @param {ParsedSectionsData} sectionsCache previously parsed information on records per section
*/
constructor( body, sectionName = undefined, recordNum = NaN, sectionsCache = null ) {
this.name = null;
this.type = null;
this.class = null;
if ( Buffer.isBuffer( body ) ) {
if ( sectionName != null && recordNum > -1 ) {
this.parse( body, sectionName, recordNum, sectionsCache || body );
} else {
throw new Error( "missing section name and record index for decoding record from wire format" );
}
} else if ( typeof body === "object" ) {
Object.keys( body ).forEach( key => { this[key] = body[key]; } );
} else
throw new Error( "Must provide a buffer or object argument with message contents" );
}
/**
* Extracts information on single DNS record from provided buffer.
*
* @param {Buffer} body sequence of octets describing DNS record in wire format
* @param {string} sectionName name of message section this record belongs to
* @param {number} recordNum index of record to decode
* @param {Buffer|ParsedSectionsData} sections sequence of octets describing full DNS message or previously extracted sections data
* @returns {void}
*/
parse( body, sectionName, recordNum, sections ) {
const record = Decode.getRecord( sections, sectionName, recordNum );
if ( sectionName === "additional" && record.edns ) {
this.edns = record;
this.name = "";
this.class = "IN";
this.type = "OPT";
return;
}
this.edns = null;
this.name = record.name;
this.class = classToLabel( record.class );
this.type = typeToLabel( record.type );
if ( !this.class )
throw new Error( `Record #${recordNum} in section "${sectionName} has unknown class #${record.class}` );
if ( !this.type )
throw new Error( `Record #${recordNum} in section "${sectionName}" has unknown type #${record.type}` );
if ( sectionName === "question" )
return;
this.ttl = record.ttl;
const rdata = record.data;
switch ( this.kind() ) {
case "IN A" :
if ( rdata.length !== 4 )
throw new Error( "Bad IN A data: " + JSON.stringify( this ) );
this.data = renderIPv4( rdata );
break;
case "IN AAAA" :
if ( rdata.length !== 16 )
throw new Error( "Bad IN AAAA data: " + JSON.stringify( this ) );
this.data = renderIPv6( rdata );
break;
case "IN NS" :
case "IN CNAME" :
case "IN PTR" :
this.data = Decode.uncompress( body, rdata );
break;
case "IN TXT" :
this.data = Decode.txt( body, rdata );
if ( this.data.length === 0 )
this.data = "";
else if ( this.data.length === 1 )
this.data = this.data[0];
break;
case "IN MX" :
this.data = Decode.mx( body, rdata );
break;
case "IN SRV" :
this.data = Decode.srv( body, rdata );
break;
case "IN SOA" :
this.data = Decode.soa( body, rdata );
this.data.rname = this.data.rname.replace( /\./, "@" );
break;
case "IN DS" :
this.data = {
keyTag: ( rdata[0] << 8 ) + rdata[1],
algorithm: rdata[2],
digestType: rdata[3],
digest: rdata.slice( 4 ).toJSON(), // Convert to a list of numbers.
};
break;
case "NONE A" :
this.data = [];
break;
default :
throw new Error( "Unknown record " + this.kind() + ": " + JSON.stringify( this ) );
}
}
/**
* Renders identifier on current kind of resource record.
*
* @returns {string} string combining class and type of resource record
*/
kind() {
return this.class + " " + this.type;
}
/**
* Renders current record as string e.g. for dumping/logging.
*
* @returns {string} rendered string describing current record
*/
toString() {
const { data } = this;
let rendered;
if ( this.type === "MX" && data ) {
rendered = leftPad( 3, data[0] ) + " " + data[1];
} else if ( Buffer.isBuffer( data ) ) {
rendered = data.toString( "hex" );
} else if ( Array.isArray( data ) ) {
rendered = data.join( " " );
} else if ( typeof data === "object" && data ) {
rendered = JSON.stringify( data );
} else {
rendered = data == null ? "" : String( data ) || "";
}
return [
leftPad( 23, this.name ),
leftPad( 7, this.ttl || "" ),
leftPad( 7, this.class ),
leftPad( 7, this.type ),
rendered,
].join( " " );
}
}
/**
* Prepends provided string with additional whitespace to ensure given minimum
* length.
*
* @param {number} minimumLength minimum length of resulting string
* @param {*} string value to be represented as string
* @returns {string} provided value represented as string extended to desired minimum length with SPC
*/
function leftPad( minimumLength, string ) {
const asString = String( string );
const missing = minimumLength - asString.length;
return missing > 0 ? new Array( missing ).fill( " " ).join( "" ) + asString : asString;
}
/**
* Renders binary encoded IPv4 address in CIDR notation.
*
* @param {Buffer} octets binary encoded IPv4 address as sequence of four octets
* @returns {string} encoded IPv4 address in CIDR notation
*/
function renderIPv4( octets ) {
return Array.prototype.slice.call( octets, 0, 4 ).join( "." );
}
/**
* Renders binary encoded IPv6 address in related CIDR notation.
*
* @param {Buffer} buf binary encoded IPv6 address as sequence of four octets
* @returns {string} encoded IPv6 address in CIDR notation
*/
function renderIPv6( buf ) {
return buf.toString( "hex" ).replace( /(....)/g, "$1:" ).replace( /:$/, "" );
}
exports.DNSMessage = DNSMessage;
exports.DNSRecord = DNSRecord;
/**
* @typedef {object} EDNSRecordLocation
* @property {string} section name of section record was found in
* @property {number} index found record's index into list of named section's records
* @property {DNSRecord} record found EDNS record
*/