-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathpacket.js
More file actions
1687 lines (1623 loc) · 53.1 KB
/
Copy pathpacket.js
File metadata and controls
1687 lines (1623 loc) · 53.1 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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const net = require('node:net');
const { debuglog, inspect } = require('node:util');
const { randomInt } = require('node:crypto');
const BufferReader = require('./lib/reader');
const BufferWriter = require('./lib/writer');
const debug = debuglog('dns2');
// Canonical IPv6 text form per RFC 5952:
// - lower case hex, no leading zeros per group (handled by toString(16))
// - the longest run of >= 2 zero groups is replaced with "::"
// - on ties, the first such run is chosen
// - a single zero group is NOT compressed
const toIPv6 = buffer => {
const segments = buffer.map(part => (part > 0 ? part.toString(16) : '0'));
let bestStart = -1;
let bestLen = 0;
let curStart = -1;
let curLen = 0;
for (let i = 0; i < segments.length; i++) {
if (segments[i] === '0') {
if (curLen === 0) curStart = i;
curLen++;
if (curLen > bestLen) {
bestLen = curLen;
bestStart = curStart;
}
} else {
curLen = 0;
}
}
if (bestLen < 2) return segments.join(':');
const before = segments.slice(0, bestStart).join(':');
const after = segments.slice(bestStart + bestLen).join(':');
return `${before}::${after}`;
};
const fromIPv6 = address => {
const digits = address.split(':');
// Leading/trailing "::" produces an empty leading/trailing element that is
// not a zero group of its own; drop it so only the interior "" marks the run.
if (digits[0] === '') {
digits.shift();
}
if (digits[digits.length - 1] === '') {
digits.pop();
}
// The interior empty string occupies a slot of its own, so it stands in for
// one more group than the shortfall in `digits`.
const missingFields = 8 - digits.length + 1;
return digits.flatMap(digit =>
digit === '' ? Array(missingFields).fill('0') : digit.padStart(4, '0'),
);
};
/**
* [Packet description]
* @param {[type]} data [description]
* @docs https://tools.ietf.org/html/rfc1034
* @docs https://tools.ietf.org/html/rfc1035
*
* <Buffer 29 64 01 00 00 01 00 00 00 00 00 00
* |-ID----------- HEADER ----------->|
*
* 03 77 77 77 01 7a 02 63 6e 00 00 01 00 01>
* <-W--W--W-----Z-----C--N>|<----------->|
*/
function Packet(data) {
this.header = {};
this.questions = [];
this.answers = [];
this.authorities = [];
this.additionals = [];
// Populated by Packet.parse with one Packet.DecodeError per record it could
// not decode; empty for messages built in memory or parsed cleanly.
this.errors = [];
if (data instanceof Packet) {
return data;
} else if (data instanceof Packet.Header) {
this.header = data;
} else if (data instanceof Packet.Question) {
this.questions.push(data);
} else if (data instanceof Packet.Resource) {
this.answers.push(data);
} else if (typeof data === 'string') {
this.questions.push(data);
} else if (typeof data === 'object') {
const type = {}.toString.call(data).match(/\[object (\w+)\]/)[1];
if (type === 'Array') {
this.questions = data;
}
if (type === 'Object') {
this.header = data;
}
}
return this;
}
// Octets in a DNS message header (RFC 1035 §4.1.1).
Packet.HEADER_SIZE = 12;
/**
* [QUERY_TYPE description]
* @type {Object}
* @docs https://tools.ietf.org/html/rfc1035#section-3.2.2
*/
Packet.TYPE = {
A: 0x01,
NS: 0x02,
MD: 0x03,
MF: 0x04,
CNAME: 0x05,
SOA: 0x06,
MB: 0x07,
MG: 0x08,
MR: 0x09,
NULL: 0x0a,
WKS: 0x0b,
PTR: 0x0c,
HINFO: 0x0d,
MINFO: 0x0e,
MX: 0x0f,
TXT: 0x10,
AAAA: 0x1c,
SRV: 0x21,
EDNS: 0x29,
RRSIG: 0x2e,
SPF: 0x63,
AXFR: 0xfc,
MAILB: 0xfd,
MAILA: 0xfe,
ANY: 0xff,
CAA: 0x101,
DNSKEY: 0x30,
};
/**
* Reverse of Packet.TYPE, used to dispatch rdata codecs and to name types in
* diagnostics.
* @type {Object}
*/
Packet.TYPE_NAME = Object.fromEntries(
Object.entries(Packet.TYPE).map(([name, code]) => [code, name]),
);
/**
* Name of a type code, falling back to the RFC 3597 §5 "TYPE<n>" presentation
* for types this library has no codec for.
* @param {number} code
* @return {string}
*/
Packet.typeName = code => Packet.TYPE_NAME[code] || `TYPE${code}`;
/**
* [QUERY_CLASS description]
* @type {Object}
* @docs https://tools.ietf.org/html/rfc1035#section-3.2.4
*/
Packet.CLASS = {
IN: 0x01,
CS: 0x02,
CH: 0x03,
HS: 0x04,
ANY: 0xff,
};
/**
* DNS response codes
* @type {Object}
* @docs https://tools.ietf.org/html/rfc1035#section-4.1.1
*/
Packet.RCODE = {
NOERROR: 0,
FORMERR: 1,
SERVFAIL: 2,
NXDOMAIN: 3,
NOTIMP: 4,
REFUSED: 5,
YXDOMAIN: 6,
YXRRSET: 7,
NXRRSET: 8,
NOTAUTH: 9,
NOTZONE: 10,
DSOTYPENI: 11,
// Codes above 15 do not fit the header's 4-bit RCODE field: the high byte
// travels in an OPT record's TTL (RFC 6891 §6.1.3), so a response using one
// MUST carry an OPT. Packet.toBuffer performs that split.
//
// 16 has two assignments in the IANA registry — BADVERS for an unsupported
// EDNS version (RFC 6891) and BADSIG for a TSIG failure (RFC 8945). They
// share the code point on the wire; only context tells them apart.
BADVERS: 16,
BADSIG: 16,
BADKEY: 17,
BADTIME: 18,
BADMODE: 19,
BADNAME: 20,
BADALG: 21,
BADTRUNC: 22,
BADCOOKIE: 23,
};
/**
* [EDNS_OPTION_CODE description]
* @type {Object}
* @docs https://tools.ietf.org/html/rfc6891#section-6.1.2
*/
Packet.EDNS_OPTION_CODE = {
ECS: 0x08,
EDE: 0x0f,
};
/**
* Extended DNS Error INFO-CODEs. These explain a response; they do not replace
* its RCODE. Codes past 24 are later registry additions, some originating from
* drafts or vendor implementations rather than a published RFC.
* @type {Object}
* @docs https://tools.ietf.org/html/rfc8914#section-4
* @docs https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#extended-dns-error-codes
*/
Packet.EDE = {
OTHER: 0,
UNSUPPORTED_DNSKEY_ALGORITHM: 1,
UNSUPPORTED_DS_DIGEST_TYPE: 2,
STALE_ANSWER: 3,
FORGED_ANSWER: 4,
DNSSEC_INDETERMINATE: 5,
DNSSEC_BOGUS: 6,
SIGNATURE_EXPIRED: 7,
SIGNATURE_NOT_YET_VALID: 8,
DNSKEY_MISSING: 9,
RRSIGS_MISSING: 10,
NO_ZONE_KEY_BIT_SET: 11,
NSEC_MISSING: 12,
CACHED_ERROR: 13,
NOT_READY: 14,
BLOCKED: 15,
CENSORED: 16,
FILTERED: 17,
PROHIBITED: 18,
STALE_NXDOMAIN_ANSWER: 19,
NOT_AUTHORITATIVE: 20,
NOT_SUPPORTED: 21,
NO_REACHABLE_AUTHORITY: 22,
NETWORK_ERROR: 23,
INVALID_DATA: 24,
SIGNATURE_EXPIRED_BEFORE_VALID: 25,
TOO_EARLY: 26,
UNSUPPORTED_NSEC3_ITERATIONS: 27,
UNABLE_TO_CONFORM_TO_POLICY: 28,
SYNTHESIZED: 29,
INVALID_QUERY_TYPE: 30,
RATE_LIMITED: 31,
OVER_QUOTA: 32,
NEGATIVE_TRUST_ANCHOR: 33,
NEW_DELEGATION_ONLY: 34,
};
/**
* Reverse of Packet.EDE, for naming a received INFO-CODE in diagnostics.
* @type {Object}
*/
Packet.EDE_NAME = Object.fromEntries(
Object.entries(Packet.EDE).map(([name, code]) => [code, name]),
);
/**
* Reverse of Packet.EDNS_OPTION_CODE.
* @type {Object}
*/
Packet.EDNS_OPTION_NAME = Object.fromEntries(
Object.entries(Packet.EDNS_OPTION_CODE).map(([name, code]) => [code, name]),
);
/**
* Generate a cryptographically random 16-bit DNS transaction ID.
* RFC 5452 §3 — the full 16-bit space must be used from a CSPRNG to make
* response forgery / cache poisoning impractical.
* @return {number} integer in [0, 0xFFFF]
*/
Packet.uuid = function () {
return randomInt(0x10000);
};
/**
* A record, question, or message that could not be decoded.
*
* Records that fail to decode are dropped rather than half-populated, so the
* reason has to travel separately: Packet.parse collects one of these per
* failure on `packet.errors`, and throws one when the message itself is
* unusable.
*
* @property {string} [section] questions / answers / authorities / additionals
* @property {number} [index] position of the record within that section
* @property {number} [offset] octet offset in the message where it started
* @property {boolean} recovered whether decoding resumed after this failure
*/
class DecodeError extends Error {
constructor(message, context = {}) {
const { section, index, offset, cause } = context;
const where =
section === undefined
? ''
: `${section}[${index}]${offset === undefined ? '' : ` at offset ${offset}`}: `;
super(`${where}${message}`, cause ? { cause } : undefined);
this.name = 'DecodeError';
Object.assign(this, context);
this.recovered = !!context.recovered;
}
}
Packet.DecodeError = DecodeError;
/**
* [parse description]
* @param {[type]} buffer [description]
* @return {[type]} [description]
* @throws {Packet.DecodeError} when the message has no usable header; per-record
* failures are reported on the returned packet's `errors` array
*/
Packet.parse = function (buffer) {
if (!Buffer.isBuffer(buffer)) {
throw new DecodeError(
`expected a Buffer, got ${buffer === null ? 'null' : typeof buffer}`,
);
}
if (buffer.length < Packet.HEADER_SIZE) {
throw new DecodeError(
`message is ${buffer.length} octets, too short for the ` +
`${Packet.HEADER_SIZE}-octet header (RFC 1035 §4.1.1)`,
);
}
const packet = new Packet();
const reader = new Packet.Reader(buffer);
packet.header = Packet.Header.parse(reader);
// A failure that left the reader misaligned makes every later record in the
// message garbage, so parsing stops there rather than manufacturing junk
// records. Failures confined to one record's RDATA are recoverable: the
// reader is repositioned by RDLENGTH and the next record still decodes.
sections: for (const [section, decoder, count] of [
['questions', Packet.Question, packet.header.qdcount],
['answers', Packet.Resource, packet.header.ancount],
['authorities', Packet.Resource, packet.header.nscount],
['additionals', Packet.Resource, packet.header.arcount],
]) {
for (let index = 0; index < count; index++) {
const offset = reader.offset / 8;
try {
packet[section].push(decoder.parse(reader));
} catch (cause) {
const error = new DecodeError(cause.message, {
section,
index,
offset,
recovered: !!cause.recovered,
cause,
});
packet.errors.push(error);
debug('node-dns > %s', error.message);
if (!error.recovered) break sections;
}
}
}
// RFC 6891 §6.1.3: when an OPT record is present the wire RCODE is 12 bits:
// the 4 low bits come from the header, the 8 high bits come from the OPT
// record's TTL high byte. Merge them so callers see the full 12-bit value.
const opt = packet.additionals.find(r => r && r.type === Packet.TYPE.EDNS);
if (opt && opt.extendedRcode) {
packet.header.rcode =
(opt.extendedRcode << 4) | (packet.header.rcode & 0xf);
}
return packet;
};
/**
* recursive
*/
Object.defineProperty(Packet.prototype, 'recursive', {
enumerable: true,
configurable: true,
get() {
return !!this.header.rd;
},
set(yn) {
this.header.rd = +yn;
},
});
/**
* [toBuffer description]
* @return {[type]} [description]
*/
Packet.prototype.toBuffer = function (writer) {
writer = writer || new Packet.Writer();
// RFC 1035 §4.1.4 — record the byte offset of each name we encode so later
// occurrences can be replaced by a compression pointer. The map is owned by
// the top-level message writer; rdata encoders that recursively encode
// names participate automatically.
if (!writer.names) writer.names = new Map();
this.header.qdcount = this.questions.length;
this.header.ancount = this.answers.length;
this.header.nscount = this.authorities.length;
this.header.arcount = this.additionals.length;
if (!(this instanceof Packet.Header)) {
this.header = new Packet.Header(this.header);
}
// RFC 6891 §6.1.3: if the caller set a header.rcode >= 16 the high byte must
// be carried in the OPT record's TTL. Propagate it before the header is
// serialized so the low nibble alone goes into the header.
if (this.header.rcode > 0xf) {
const opt = this.additionals.find(r => r && r.type === Packet.TYPE.EDNS);
if (opt) {
opt.extendedRcode = (this.header.rcode >>> 4) & 0xff;
opt.ttl = ednsTtl(opt.extendedRcode, opt.version || 0, opt.doFlag);
} else {
debug(
'node-dns > rcode %d > 15 but no OPT record; truncating to low nibble',
this.header.rcode,
);
}
}
this.header.toBuffer(writer);
[
// section encoder
['questions', Packet.Question],
['answers', Packet.Resource],
['authorities', Packet.Resource],
['additionals', Packet.Resource],
].forEach(
function (def) {
const section = def[0];
const Encoder = def[1];
(this[section] || []).forEach(function (resource) {
Encoder.encode(resource, writer);
});
}.bind(this),
);
return writer.toBuffer();
};
/**
* [Header description]
* @param {[type]} options [description]
* @docs https://tools.ietf.org/html/rfc1035#section-4.1.1
*/
Packet.Header = function (header) {
this.id = 0;
this.qr = 0;
this.opcode = 0;
this.aa = 0;
this.tc = 0;
this.rd = 0;
this.ra = 0;
this.z = 0;
this.ad = 0;
this.cd = 0;
this.rcode = 0;
this.qdcount = 0;
this.ancount = 0;
this.nscount = 0;
this.arcount = 0;
for (const k in header) {
this[k] = header[k];
}
return this;
};
/**
* [parse description]
* @param {[type]} buffer [description]
* @return {[type]} [description]
* @docs https://tools.ietf.org/html/rfc1035#section-4.1.1
*/
Packet.Header.parse = function (reader) {
const header = new Packet.Header();
if (reader instanceof Buffer) {
reader = new Packet.Reader(reader);
}
header.id = reader.read(16);
header.qr = reader.read(1);
header.opcode = reader.read(4);
header.aa = reader.read(1);
header.tc = reader.read(1);
header.rd = reader.read(1);
header.ra = reader.read(1);
// RFC 4035 §3.2.3 repurposed the second and third Z bits as AD and CD.
header.z = reader.read(1);
header.ad = reader.read(1);
header.cd = reader.read(1);
header.rcode = reader.read(4);
header.qdcount = reader.read(16);
header.ancount = reader.read(16);
header.nscount = reader.read(16);
header.arcount = reader.read(16);
return header;
};
/**
* [toBuffer description]
* @return {[type]} [description]
*/
Packet.Header.prototype.toBuffer = function (writer) {
writer = writer || new Packet.Writer();
writer.write(this.id, 16);
writer.write(this.qr, 1);
writer.write(this.opcode, 4);
writer.write(this.aa, 1);
writer.write(this.tc, 1);
writer.write(this.rd, 1);
writer.write(this.ra, 1);
// RFC 1035 §4.1.1: the Z bit is reserved and must be zero in outgoing
// messages, regardless of what was preserved from any inbound packet.
writer.write(0, 1);
writer.write(this.ad, 1);
writer.write(this.cd, 1);
writer.write(this.rcode & 0xf, 4);
writer.write(this.qdcount, 16);
writer.write(this.ancount, 16);
writer.write(this.nscount, 16);
writer.write(this.arcount, 16);
return writer.toBuffer();
};
/**
* Question section format
* @docs https://tools.ietf.org/html/rfc1035#section-4.1.2
*/
Packet.Question = function (name, type, cls) {
const defaults = {
type: Packet.TYPE.ANY,
class: Packet.CLASS.ANY,
};
if (typeof name === 'object') {
for (const k in name) {
this[k] = name[k] || defaults[k];
}
} else {
this.name = name;
this.type = type || defaults.type;
this.class = cls || defaults.class;
}
return this;
};
/**
* [toBuffer description]
* @param {[type]} writer [description]
* @return {[type]} [description]
*/
Packet.Question.prototype.toBuffer = function (writer) {
return Packet.Question.encode(this, writer);
};
/**
* [parse description]
* @param {[type]} reader [description]
* @return {[type]} [description]
*/
Packet.Question.parse = Packet.Question.decode = function (reader) {
const question = new Packet.Question();
if (reader instanceof Buffer) {
reader = new Packet.Reader(reader);
}
question.name = Packet.Name.decode(reader);
question.type = reader.read(16);
question.class = reader.read(16);
return question;
};
// A non-numeric TYPE or CLASS would be written as 16 zero bits, turning a typo
// such as Packet.TYPE.AAA (undefined) into a valid-looking type 0 on the wire.
const assertCode = (value, field, context) => {
if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
// inspect, not JSON.stringify: the latter renders NaN and Infinity as
// "null". Nor String(), which renders the string '1' as 1 — the very
// confusion this message exists to resolve.
throw new Error(
`${context}: ${field} must be a 16-bit integer, got ${inspect(value)}`,
);
}
};
Packet.Question.encode = function (question, writer) {
const ownsWriter = !writer;
writer = writer || new Packet.Writer();
assertCode(question.type, 'type', `Question encode "${question.name}"`);
assertCode(question.class, 'class', `Question encode "${question.name}"`);
Packet.Name.encode(question.name, writer);
writer.write(question.type, 16);
writer.write(question.class, 16);
return ownsWriter ? writer.toBuffer() : undefined;
};
/**
* Resource record format
* @docs https://tools.ietf.org/html/rfc1035#section-4.1.3
*/
Packet.Resource = function (name, type, cls, ttl) {
const defaults = {
name: '',
ttl: 300,
type: Packet.TYPE.ANY,
class: Packet.CLASS.ANY,
};
let input;
if (typeof name === 'object') {
input = name;
} else {
input = {
name,
type,
class: cls,
ttl,
};
}
Object.assign(this, defaults, input);
return this;
};
/**
* [toBuffer description]
* @param {[type]} writer [description]
* @return {[type]} [description]
*/
Packet.Resource.prototype.toBuffer = function (writer) {
return Packet.Resource.encode(this, writer);
};
/**
* [encode description]
* @param {[type]} resource [description]
* @param {[type]} writer [description]
* @return {[type]} [description]
*/
Packet.Resource.encode = function (resource, writer) {
writer = writer || new Packet.Writer();
assertCode(resource.type, 'type', `Resource encode "${resource.name}"`);
assertCode(resource.class, 'class', `Resource encode "${resource.name}"`);
Packet.Name.encode(resource.name, writer);
writer.write(resource.type, 16);
writer.write(resource.class, 16);
// RFC 2181 §8: TTL is an unsigned 32-bit value but high-bit values are
// historically unsafe; clamp to 2^31 - 1 on the wire.
writer.write(Math.min(resource.ttl >>> 0, 0x7fffffff), 32);
const encoder = Packet.TYPE_NAME[resource.type];
// RDLENGTH is owned here, not by each rdata encoder. We write a 16-bit
// placeholder, dispatch to the rdata encoder, then back-fill the length.
// This is what lets rdata encoders use compression pointers without having
// to predict their compressed length up front.
const rdlenBitPos = writer.bitLength();
writer.write(0, 16);
const rdataBitStart = writer.bitLength();
const codec = encoder && Packet.Resource[encoder];
if (codec && codec.encode) {
codec.encode(resource, writer);
} else {
debug('node-dns > unknown encoder %s(%j)', encoder, resource.type);
// Fallback for unknown / decoder-only types: round-trip the raw RDATA the
// decoder preserved as `resource.data`. Without this, RDATA would be
// omitted entirely, truncating the wire format and corrupting any
// records that follow.
const data = Buffer.isBuffer(resource.data)
? resource.data
: Buffer.alloc(0);
for (const byte of data) {
writer.write(byte, 8);
}
}
const rdlen = (writer.bitLength() - rdataBitStart) / 8;
writer.patch(rdlenBitPos, rdlen, 16);
return writer.toBuffer();
};
/**
* [parse description]
* @param {[type]} reader [description]
* @return {[type]} [description]
*/
Packet.Resource.parse = Packet.Resource.decode = function (reader) {
if (reader instanceof Buffer) {
reader = new Packet.Reader(reader);
}
let resource = new Packet.Resource();
resource.name = Packet.Name.decode(reader);
resource.type = reader.read(16);
resource.class = reader.read(16);
resource.ttl = reader.read(32);
// RFC 2181 §8: TTLs are an unsigned 32-bit field but legacy implementations
// treated them as signed. Anything with the high bit set is clamped to
// 2^31 - 1 so it cannot be misinterpreted as a negative value.
if (resource.ttl > 0x7fffffff) resource.ttl = 0x7fffffff;
const length = reader.read(16);
const label = `${Packet.typeName(resource.type)} record "${resource.name}"`;
if (length * 8 > reader.remaining()) {
throw new Error(
`${label} declares RDLENGTH ${length} but only ` +
`${reader.remaining() / 8} octet(s) remain in the message`,
);
}
// RDLENGTH delimits the record on the wire, so it — not the rdata decoder —
// decides where the next record begins. Restoring the cursor to that boundary
// keeps a malformed record from cascading into the ones that follow, and lets
// Packet.parse report the failure as recoverable.
const rdataStart = reader.offset;
const rdataEnd = rdataStart + length * 8;
const parser = Packet.TYPE_NAME[resource.type];
const codec = parser && Packet.Resource[parser];
try {
if (codec && codec.decode) {
resource = codec.decode.call(resource, reader, length);
if (reader.offset !== rdataEnd) {
throw new Error(
`${label} rdata consumed ${(reader.offset - rdataStart) / 8} ` +
`octet(s), RDLENGTH declares ${length}`,
);
}
} else {
debug('node-dns > unknown parser type: %s(%j)', parser, resource.type);
// RFC 3597 §5: retain unknown rdata verbatim so it can be re-emitted.
resource.data = Buffer.from(
reader.buffer.subarray(rdataStart / 8, rdataEnd / 8),
);
}
} catch (cause) {
cause.recovered = true;
throw cause;
} finally {
reader.offset = rdataEnd;
}
return resource;
};
/**
* [encode_name description]
* @param {[type]} domain [description]
* @return {[type]} [description]
*/
// RFC 1035 §2.3.4 — wire-format limits.
Packet.Name = {
COPY: 0xc0,
MAX_LABEL: 63,
MAX_NAME: 255,
decode: function (reader) {
if (reader instanceof Buffer) {
reader = new Packet.Reader(reader);
}
const name = [];
let o;
let len = reader.read(8);
// Track each pointer target we follow. A crafted packet can chain
// pointers in a cycle; without this guard, decode would loop forever.
const visited = new Set();
// Cumulative wire-format octets consumed for this name. RFC 1035 §2.3.4
// caps the total — including the trailing zero-length root label — at
// 255, so the running tally starts at 1 (the terminator) and adds the
// length byte + label bytes for each non-root label.
let totalOctets = 1;
while (len) {
if ((len & Packet.Name.COPY) === Packet.Name.COPY) {
len -= Packet.Name.COPY;
len = len << 8;
const pos = len + reader.read(8);
if (visited.has(pos)) {
throw new Error('Name decode: pointer cycle detected');
}
visited.add(pos);
if (!o) o = reader.offset;
reader.offset = pos * 8;
len = reader.read(8);
continue;
}
// RFC 1035: a label length byte has its top two bits clear (00).
// The 01/10 combinations are reserved and indicate a malformed name.
if (len & 0xc0) {
throw new Error(
`Name decode: invalid label length byte 0x${len.toString(16)}`,
);
}
if (len > Packet.Name.MAX_LABEL) {
throw new Error(
`Name decode: label exceeds ${Packet.Name.MAX_LABEL} octets`,
);
}
totalOctets += len + 1;
if (totalOctets > Packet.Name.MAX_NAME) {
throw new Error(
`Name decode: name exceeds ${Packet.Name.MAX_NAME} octets`,
);
}
let part = '';
while (len--) part += String.fromCharCode(reader.read(8));
name.push(part);
len = reader.read(8);
}
if (o) reader.offset = o;
return name.join('.');
},
encode: function (domain, writer) {
// Only materialize a Buffer when we created the writer; if the caller
// passed one, they own the final toBuffer() and we avoid an O(buffer)
// materialization per name (a big deal once many records share a suffix).
const ownsWriter = !writer;
writer = writer || new Packet.Writer();
const parts = (domain || '').split('.').filter(part => !!part);
let totalOctets = 1; // root terminator
for (const part of parts) {
if (part.length > Packet.Name.MAX_LABEL) {
throw new Error(
`Name encode: label "${part}" is ${part.length} octets ` +
`(max ${Packet.Name.MAX_LABEL})`,
);
}
totalOctets += part.length + 1;
}
if (totalOctets > Packet.Name.MAX_NAME) {
throw new Error(
`Name encode: name "${domain}" encodes to ${totalOctets} octets ` +
`(max ${Packet.Name.MAX_NAME})`,
);
}
// RFC 1035 §4.1.4 — if the writer carries a name-offset table, emit a
// compression pointer for any suffix we've already serialized; otherwise
// record this suffix at its current byte offset so later names can point
// here. Compression pointers can address only the first 16 KiB of a
// message (14-bit offset); past that we fall back to literal labels.
const compress = writer.names instanceof Map;
for (let i = 0; i < parts.length; i++) {
const suffix = parts.slice(i).join('.').toLowerCase();
if (compress && writer.names.has(suffix)) {
writer.write(0xc000 | writer.names.get(suffix), 16);
return ownsWriter ? writer.toBuffer() : undefined;
}
if (compress) {
const byteOffset = writer.byteLength();
if (byteOffset < 0x4000) writer.names.set(suffix, byteOffset);
}
writer.write(parts[i].length, 8);
for (let j = 0; j < parts[i].length; j++) {
writer.write(parts[i].charCodeAt(j), 8);
}
}
writer.write(0, 8);
return ownsWriter ? writer.toBuffer() : undefined;
},
};
/**
* [A description]
* @type {Object}
* @docs https://tools.ietf.org/html/rfc1035#section-3.4.1
*/
Packet.Resource.A = function (address) {
this.type = Packet.TYPE.A;
this.class = Packet.CLASS.IN;
this.address = address;
return this;
};
Packet.Resource.A.encode = function (record, writer) {
writer = writer || new Packet.Writer();
// Without this check a malformed address writes NaN octets, silently
// encoding as 0.0.0.0 on the wire.
if (!net.isIPv4(record.address)) {
throw new Error(
`A encode: invalid IPv4 address ${JSON.stringify(record.address)}`,
);
}
// RDLENGTH is written by Packet.Resource.encode; only emit the rdata here.
// No toBuffer() — the caller owns materialization (avoids O(N) re-walks of
// the message bit-array per record).
record.address.split('.').forEach(function (part) {
writer.write(parseInt(part, 10), 8);
});
};
Packet.Resource.A.decode = function (reader, length) {
// RFC 1035 §3.4.1 — ADDRESS is exactly one 32-bit value.
if (length !== 4) {
throw new Error(`A decode: RDLENGTH is ${length}, expected 4`);
}
const parts = [];
while (length--) parts.push(reader.read(8));
this.address = parts.join('.');
return this;
};
/**
* [MX description]
* @param {[type]} exchange [description]
* @param {[type]} priority [description]
* @docs https://tools.ietf.org/html/rfc1035#section-3.3.9
*/
Packet.Resource.MX = function (exchange, priority) {
this.type = Packet.TYPE.MX;
this.class = Packet.CLASS.IN;
this.exchange = exchange;
this.priority = priority;
return this;
};
/**
* [encode description]
* @param {[type]} record [description]
* @param {[type]} writer [description]
* @return {[type]} [description]
*/
Packet.Resource.MX.encode = function (record, writer) {
writer = writer || new Packet.Writer();
writer.write(record.priority, 16);
Packet.Name.encode(record.exchange, writer);
};
/**
* [decode description]
* @param {[type]} reader [description]
* @param {[type]} length [description]
* @return {[type]} [description]
*/
Packet.Resource.MX.decode = function (reader, length) {
this.priority = reader.read(16);
this.exchange = Packet.Name.decode(reader);
return this;
};
/**
* [AAAA description]
* @type {Object}
* @docs https://en.wikipedia.org/wiki/IPv6
*/
Packet.Resource.AAAA = {
decode: function (reader, length) {
// RFC 3596 §2.2 — a 128-bit address. An odd or short length would step the
// `length -= 2` countdown past zero and read into the following records.
if (length !== 16) {
throw new Error(`AAAA decode: RDLENGTH is ${length}, expected 16`);
}
const parts = [];
while (length) {
length -= 2;
parts.push(reader.read(16));
}
this.address = toIPv6(parts);
return this;
},
encode: function (record, writer) {
writer = writer || new Packet.Writer();
if (!net.isIPv6(record.address)) {
throw new Error(
`AAAA encode: invalid IPv6 address ${JSON.stringify(record.address)}`,
);
}
fromIPv6(record.address).forEach(function (part) {
writer.write(parseInt(part, 16), 16);
});
},
};
/**
* [NS description]
* @type {Object}
* @docs https://tools.ietf.org/html/rfc1035#section-3.3.11
*/
Packet.Resource.NS = {
decode: function (reader, length) {
this.ns = Packet.Name.decode(reader);
return this;
},
encode: function (record, writer) {
writer = writer || new Packet.Writer();
Packet.Name.encode(record.ns, writer);
},
};
/**
* [CNAME description]
* @type {Object}
* @docs https://tools.ietf.org/html/rfc1035#section-3.3.1
*/
Packet.Resource.PTR = Packet.Resource.CNAME = {
decode: function (reader, length) {
this.domain = Packet.Name.decode(reader);
return this;
},
encode: function (record, writer) {
writer = writer || new Packet.Writer();
Packet.Name.encode(record.domain, writer);
},
};
/**
* [SPF description]
* @type {[type]}
* @docs https://tools.ietf.org/html/rfc1035#section-3.3.14
*/
Packet.Resource.SPF = Packet.Resource.TXT = {
// RFC 1035 §3.3.14: TXT RDATA is one or more length-prefixed
// <character-string> items. Preserve those boundaries by returning an
// array — joining them silently corrupts SPF/DKIM and other multi-string
// records whose semantics depend on segmentation.
decode: function (reader, length) {
const strings = [];
let bytesRead = 0;
while (bytesRead < length) {
const chunkLength = reader.read(8);
bytesRead++;
// A character-string whose length runs past the end of RDATA would make
// us read into the next record; Packet.Resource.parse restores the cursor
// to the RDLENGTH boundary so the following records still decode.
if (chunkLength > length - bytesRead) {
throw new Error(
`TXT decode: character-string of ${chunkLength} octets overruns ` +
`RDATA (${length - bytesRead} octets remaining)`,
);
}
const bytes = Buffer.alloc(chunkLength);