-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
2004 lines (1784 loc) · 61.2 KB
/
index.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
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 dns = require('node:dns');
const http = require('node:http');
const os = require('node:os');
const process = require('node:process');
const { Buffer } = require('node:buffer');
const { debuglog } = require('node:util');
const { getEventListeners, setMaxListeners } = require('node:events');
const { isIP, isIPv4, isIPv6 } = require('node:net');
const { toASCII } = require('punycode/');
const autoBind = require('auto-bind');
const getStream = require('get-stream');
const hostile = require('hostile');
const ipaddr = require('ipaddr.js');
const isStream = require('is-stream');
const mergeOptions = require('merge-options');
const pMap = require('p-map');
const pWaitFor = require('p-wait-for');
const packet = require('dns-packet');
const semver = require('semver');
const structuredClone = require('@ungap/structured-clone').default;
const { getService } = require('port-numbers');
const pkg = require('./package.json');
const debug = debuglog('tangerine');
// dynamically import dohdec
let dohdec;
// eslint-disable-next-line unicorn/prefer-top-level-await
import('dohdec').then((obj) => {
dohdec = obj;
});
// dynamically import private-ip
let isPrivateIP;
// eslint-disable-next-line unicorn/prefer-top-level-await
import('private-ip').then((obj) => {
isPrivateIP = obj.default;
});
const HOSTFILE = hostile
.get(true)
.map((s) => (Array.isArray(s) ? s.join(' ') : s))
.join('\n');
const HOSTS = [];
const hosts = hostile.get();
for (const line of hosts) {
const [ip, str] = line;
const hosts = str.split(' ');
HOSTS.push({ ip, hosts });
}
// <https://github.com/szmarczak/cacheable-lookup/pull/76>
class Tangerine extends dns.promises.Resolver {
static HOSTFILE = HOSTFILE;
static HOSTS = HOSTS;
static isValidPort(port) {
return Number.isSafeInteger(port) && port >= 0 && port <= 65535;
}
static CTYPE_BY_VALUE = {
1: 'PKIX',
2: 'SPKI',
3: 'PGP',
4: 'IPKIX',
5: 'ISPKI',
6: 'IPGP',
7: 'ACPKIX',
8: 'IACPKIX',
253: 'URI',
254: 'OID'
};
static getAddrConfigTypes() {
const networkInterfaces = os.networkInterfaces();
let hasIPv4 = false;
let hasIPv6 = false;
for (const key of Object.keys(networkInterfaces)) {
for (const obj of networkInterfaces[key]) {
if (!obj.internal) {
if (obj.family === 'IPv4') {
hasIPv4 = true;
} else if (obj.family === 'IPv6') {
hasIPv6 = true;
}
}
}
}
if (hasIPv4 && hasIPv6) return 0;
if (hasIPv4) return 4;
if (hasIPv6) return 6;
// NOTE: should this be an edge case where we return empty results (?)
return 0;
}
// <https://github.com/mafintosh/dns-packet/blob/master/examples/doh.js>
static getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//
// NOTE: we can most likely move to AggregateError instead
//
static combineErrors(errors) {
let err;
if (errors.length === 1) {
err = errors[0];
} else {
err = new Error(
[...new Set(errors.map((e) => e.message).filter(Boolean))].join('; ')
);
err.stack = [...new Set(errors.map((e) => e.stack).filter(Boolean))].join(
'\n\n'
);
// if all errors had `name` and they were all the same then preserve it
if (
errors[0].name !== undefined &&
errors.every((e) => e.name === errors[0].name)
)
err.name = errors[0].name;
// if all errors had `code` and they were all the same then preserve it
if (
errors[0].code !== undefined &&
errors.every((e) => e.code === errors[0].code)
)
err.code = errors[0].code;
// if all errors had `errno` and they were all the same then preserve it
if (
errors[0].errno !== undefined &&
errors.every((e) => e.errno === errors[0].errno)
)
err.errno = errors[0].errno;
// preserve original errors
err.errors = errors;
}
return err;
}
static CODES = new Set([
dns.ADDRGETNETWORKPARAMS,
dns.BADFAMILY,
dns.BADFLAGS,
dns.BADHINTS,
dns.BADNAME,
dns.BADQUERY,
dns.BADRESP,
dns.BADSTR,
dns.CANCELLED,
dns.CONNREFUSED,
dns.DESTRUCTION,
dns.EOF,
dns.FILE,
dns.FORMERR,
dns.LOADIPHLPAPI,
dns.NODATA,
dns.NOMEM,
dns.NONAME,
dns.NOTFOUND,
dns.NOTIMP,
dns.NOTINITIALIZED,
dns.REFUSED,
dns.SERVFAIL,
dns.TIMEOUT,
'EINVAL'
]);
static DNS_TYPES = new Set([
'A',
'AAAA',
'CAA',
'CNAME',
'MX',
'NAPTR',
'NS',
'PTR',
'SOA',
'SRV',
'TXT'
]);
// <https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
static TYPES = new Set([
'A',
'A6',
'AAAA',
'AFSDB',
'AMTRELAY',
'APL',
'ATMA',
'AVC',
'AXFR',
'CAA',
'CDNSKEY',
'CDS',
'CERT',
'CNAME',
'CSYNC',
'DHCID',
'DLV',
'DNAME',
'DNSKEY',
'DOA',
'DS',
'EID',
'EUI48',
'EUI64',
'GID',
'GPOS',
'HINFO',
'HIP',
'HTTPS',
'IPSECKEY',
'ISDN',
'IXFR',
'KEY',
'KX',
'L32',
'L64',
'LOC',
'LP',
'MAILA',
'MAILB',
'MB',
'MD',
'MF',
'MG',
'MINFO',
'MR',
'MX',
'NAPTR',
'NID',
'NIMLOC',
'NINFO',
'NS',
'NSAP',
'NSAP-PTR',
'NSEC',
'NSEC3',
'NSEC3PARAM',
'NULL',
'NXT',
'OPENPGPKEY',
'OPT',
'PTR',
'PX',
'RKEY',
'RP',
'RRSIG',
'RT',
'Reserved',
'SIG',
'SINK',
'SMIMEA',
'SOA',
'SPF',
'SRV',
'SSHFP',
'SVCB',
'TA',
'TALINK',
'TKEY',
'TLSA',
'TSIG',
'TXT',
'UID',
'UINFO',
'UNSPEC',
'URI',
'WKS',
'X25',
'ZONEMD'
]);
static ANY_TYPES = [
'A',
'AAAA',
'CNAME',
'MX',
'NAPTR',
'NS',
'PTR',
'SOA',
'SRV',
'TXT'
];
static NETWORK_ERROR_CODES = new Set([
'ENETDOWN',
'ENETRESET',
'ECONNRESET',
'EADDRINUSE',
'ECONNREFUSED',
'ENETUNREACH'
]);
static RETRY_STATUS_CODES = new Set([
408, 413, 429, 500, 502, 503, 504, 521, 522, 524
]);
static RETRY_ERROR_CODES = new Set([
'ETIMEOUT',
'ETIMEDOUT',
'ECONNRESET',
'EADDRINUSE',
'ECONNREFUSED',
'EPIPE',
// NOTE: dns behavior does not retry on ENOTFOUND
// <https://nodejs.org/api/dns.html#dnssetserversservers>
// 'ENOTFOUND',
'ENETUNREACH',
'EAI_AGAIN'
]);
// sourced from node, superagent, got, axios, and fetch
// <https://github.com/nodejs/node/issues/14554>
// <https://github.com/nodejs/node/issues/38361#issuecomment-1046151452>
// <https://github.com/axios/axios/blob/bdf493cf8b84eb3e3440e72d5725ba0f138e0451/lib/cancel/CanceledError.js#L17>
static ABORT_ERROR_CODES = new Set([
'ABORT_ERR',
'ECONNABORTED',
'ERR_CANCELED',
'ECANCELLED',
'ERR_ABORTED',
'UND_ERR_ABORTED'
]);
static getSysCall(rrtype) {
return `query${rrtype.slice(0, 1).toUpperCase()}${rrtype
.slice(1)
.toLowerCase()}`;
}
// <https://github.com/EduardoRuizM/native-dnssec-dns/blob/main/lib/client.js#L350>
static createError(name, rrtype, code = dns.BADRESP, errno) {
const syscall = this.getSysCall(rrtype);
if (this.ABORT_ERROR_CODES.has(code)) code = dns.CANCELLED;
else if (this.NETWORK_ERROR_CODES.has(code)) code = dns.CONNREFUSED;
else if (this.RETRY_ERROR_CODES.has(code)) code = dns.TIMEOUT;
else if (!this.CODES.has(code)) code = dns.BADRESP;
const err = new Error(`${syscall} ${code} ${name}`);
err.hostname = name;
err.syscall = syscall;
err.code = code;
err.errno = errno || undefined;
return err;
}
constructor(options = {}, request = require('undici').request) {
const timeout =
options.timeout && options.timeout !== -1 ? options.timeout : 5000;
const tries = options.tries || 4;
super({
timeout,
tries
});
if (typeof request !== 'function')
throw new Error(
'Request option must be a function (e.g. `undici.request` or `got`)'
);
this.request = request;
this.options = mergeOptions(
{
// <https://github.com/nodejs/node/issues/33353#issuecomment-627259827>
// > For posterity: there's a 75 second timeout.
// > Local testing with a blackholed DNS server shows that c-ares internally
// > retries four times (with 5, 10, 20 and 40 second timeouts)
// > before giving up with an ARES_ETIMEDOUT error.
timeout,
tries,
// dns servers will optionally retry in series
// and servers that error will get shifted to the end of list
servers: new Set(['1.1.1.1', '1.0.0.1']),
requestOptions: {
method: 'GET',
headers: {
'content-type': 'application/dns-message',
'user-agent': `${pkg.name}/${pkg.version}`,
accept: 'application/dns-message'
}
},
//
// NOTE: we set the default to "get" since it is faster from `benchmark` results
//
// http protocol to be used
protocol: 'https',
//
// NOTE: this value was changed from ipv4first to verbatim in v17.0.0
// and this feature was added in v14.8.0 and v16.4.0
// <https://nodejs.org/api/dns.html#dnspromisessetdefaultresultorderorder>
dnsOrder: semver.gte(process.version, 'v17.0.0')
? 'verbatim'
: 'ipv4first',
// https://github.com/cabinjs/cabin
// https://github.com/cabinjs/axe
logger: false,
// default id generator
// (e.g. set to a synchronous or async function such as `() => Tangerine.getRandomInt(1, 65534)`)
id: 0,
// concurrency for `resolveAny` (defaults to # of CPU's)
concurrency: os.cpus().length,
// ipv4 and ipv6 default addresses (from dns defaults)
ipv4: '0.0.0.0',
ipv6: '::0',
ipv4Port: undefined,
ipv6Port: undefined,
// cache mapping (e.g. txt -> Map/keyv/redis instance) - see below
cache: new Map(),
// <https://developers.cloudflare.com/dns/manage-dns-records/reference/ttl/>
defaultTTLSeconds: 300,
maxTTLSeconds: 86400,
// default is to support ioredis
// setCacheArgs(key, result) {
setCacheArgs() {
// also you have access to `result.expires` which is is ms since epoch
// (can be converted to Date via `new Date(result.expires)`)
// return ['PX', Math.round(result.ttl * 1000)];
return [];
},
// whether to do 1:1 HTTP -> DNS error mapping
returnHTTPErrors: false,
// whether to smart rotate and bump-to-end servers that have issues
smartRotate: true,
// fallback if status code was not found in http.STATUS_CODES
defaultHTTPErrorMessage: 'Unsuccessful HTTP response'
},
options
);
// timeout must be >= 0
if (!Number.isFinite(this.options.timeout) || this.options.timeout < 0)
throw new Error('Timeout must be >= 0');
// tries must be >= 1
if (!Number.isFinite(this.options.tries) || this.options.tries < 1)
throw new Error('Tries must be >= 1');
// request option method must be either GET or POST
if (
!['get', 'post'].includes(
this.options.requestOptions.method.toLowerCase()
)
)
throw new Error('Request options method must be either GET or POST');
// perform validation by re-using `setServers` method
this.setServers([...this.options.servers]);
if (
!(this.options.servers instanceof Set) ||
this.options.servers.size === 0
)
throw new Error(
'Servers must be an Array or Set with at least one server'
);
if (!['http', 'https'].includes(this.options.protocol))
throw new Error('Protocol must be http or https');
if (!['verbatim', 'ipv4first'].includes(this.options.dnsOrder))
throw new Error('DNS order must be either verbatim or ipv4first');
// if `cache: false` then caching is disabled
// but note that this doesn't disable `got` dnsCache which is separate
// so to turn that off, you need to supply `dnsCache: undefined` in `got` object (?)
if (this.options.cache === true) this.options.cache = new Map();
// convert `false` logger option into noop
// <https://github.com/breejs/bree/issues/147>
if (this.options.logger === false)
this.options.logger = {
/* istanbul ignore next */
info() {},
/* istanbul ignore next */
warn() {},
/* istanbul ignore next */
error() {}
};
// manage set of abort controllers
this.abortControllers = new Set();
//
// NOTE: bind methods so we don't have to programmatically call `.bind`
// (e.g. `getDmarcRecord(name, resolver.resolve.bind(resolver))`)
// (alternative to `autoBind(this)` is `this[method] = this[method].bind(this)`)
//
autoBind(this);
}
setLocalAddress(ipv4, ipv6) {
// ipv4 = default => '0.0.0.0'
// ipv6 = default => '::0'
if (ipv4) {
if (typeof ipv4 !== 'string') {
const err = new TypeError(
'The "ipv4" argument must be of type string.'
);
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
// if port specified then split it apart
let port;
if (ipv4.includes(':')) [ipv4, port] = ipv4.split(':');
if (!isIPv4(ipv4)) {
const err = new TypeError('Invalid IP address.');
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
// not sure if there's a built-in way with Node.js to do this (?)
if (port) {
port = Number(port);
// <https://github.com/leecjson/node-is-valid-port/blob/2da250b23e0d83bcfc042b44fa7cabdea1984a73/index.js#L3-L7>
if (!this.constructor.isValidPort(port)) {
const err = new TypeError('Invalid port.');
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
}
this.options.ipv4 = ipv4;
this.options.ipv4Port = port;
}
if (ipv6) {
if (typeof ipv6 !== 'string') {
const err = new TypeError(
'The "ipv6" argument must be of type string.'
);
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
// if port specified then split it apart
let port;
// if it starts with `[` then we can assume it's encoded as `[IPv6]` or `[IPv6]:PORT`
if (ipv6.startsWith('[')) {
const lastIndex = ipv6.lastIndexOf(']');
port = ipv6.slice(lastIndex + 2);
ipv6 = ipv6.slice(1, lastIndex);
}
// not sure if there's a built-in way with Node.js to do this (?)
if (port) {
port = Number(port);
// <https://github.com/leecjson/node-is-valid-port/blob/2da250b23e0d83bcfc042b44fa7cabdea1984a73/index.js#L3-L7>
if (!(Number.isSafeInteger(port) && port >= 0 && port <= 65535)) {
const err = new TypeError('Invalid port.');
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
}
if (!isIPv6(ipv6)) {
const err = new TypeError('Invalid IP address.');
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
this.options.ipv6 = ipv6;
this.options.ipv6Port = port;
}
}
// eslint-disable-next-line complexity
async lookup(name, options = {}) {
// validate name
if (typeof name !== 'string') {
const err = new TypeError('The "name" argument must be of type string.');
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
// if options is an integer, it must be 4 or 6
if (typeof options === 'number') {
if (options !== 0 && options !== 4 && options !== 6) {
const err = new TypeError(
`The argument 'family' must be one of: 0, 4, 6. Received ${options}`
);
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
options = { family: options };
} else if (
options?.family !== undefined &&
![0, 4, 6, 'IPv4', 'IPv6'].includes(options.family)
) {
// validate family
const err = new TypeError(
`The argument 'family' must be one of: 0, 4, 6. Received ${options.family}`
);
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
if (options?.family === 'IPv4') options.family = 4;
else if (options?.family === 'IPv6') options.family = 6;
if (typeof options.family !== 'number') options.family = 0;
// validate hints
// eslint-disable-next-line no-bitwise
if ((options?.hints & ~(dns.ADDRCONFIG | dns.ALL | dns.V4MAPPED)) !== 0) {
const err = new TypeError(
`The argument 'hints' is invalid. Received ${options.hints}`
);
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
if (name === '.') {
const err = this.constructor.createError(name, '', dns.NOTFOUND);
// remap and perform syscall
err.syscall = 'getaddrinfo';
err.message = err.message.replace('query', 'getaddrinfo');
err.errno = -3008; // <-- ?
// err.errno = -3007;
throw err;
}
// purge cache support
let purgeCache;
if (options?.purgeCache) {
purgeCache = true;
delete options.purgeCache;
}
if (options.hints) {
switch (options.hints) {
case dns.ADDRCONFIG: {
options.family = this.constructor.getAddrConfigTypes();
break;
}
// eslint-disable-next-line no-bitwise
case dns.ADDRCONFIG | dns.V4MAPPED: {
options.family = this.constructor.getAddrConfigTypes();
break;
}
// eslint-disable-next-line no-bitwise
case dns.ADDRCONFIG | dns.V4MAPPED | dns.ALL: {
options.family = this.constructor.getAddrConfigTypes();
break;
}
default: {
break;
}
}
}
// <https://github.com/c-ares/c-ares/blob/38b30bc922c21faa156939bde15ea35332c30e08/src/lib/ares_getaddrinfo.c#L407>
// <https://www.rfc-editor.org/rfc/rfc6761.html#section-6.3>
//
// > 'localhost and any domains falling within .localhost'
//
// if no system loopback match, then revert to the default
// <https://github.com/c-ares/c-ares/blob/38b30bc922c21faa156939bde15ea35332c30e08/src/lib/ares__addrinfo_localhost.c#L224-L229>
// - IPv4 = '127.0.0.1"
// - IPv6 = "::1"
//
let resolve4;
let resolve6;
const lower = name.toLowerCase();
for (const rule of this.constructor.HOSTS) {
if (rule.hosts.every((h) => h.toLowerCase() !== lower)) continue;
const type = isIP(rule.ip);
if (!resolve4 && type === 4) {
if (!Array.isArray(resolve4)) resolve4 = [rule.ip];
else if (!resolve4.includes(rule.ip)) resolve4.push([rule.ip]);
} else if (!resolve6 && type === 6) {
if (!Array.isArray(resolve6)) resolve6 = [rule.ip];
else if (!resolve6.includes(rule.ip)) resolve6.push(rule.ip);
}
}
// safeguard (matches c-ares)
if (lower === 'localhost' || lower === 'localhost.') {
resolve4 ||= ['127.0.0.1'];
resolve6 ||= ['::1'];
}
if (isIPv4(name)) {
resolve4 = [name];
resolve6 = [];
} else if (isIPv6(name)) {
resolve6 = [name];
resolve4 = [];
}
// resolve the first A or AAAA record (conditionally)
const results = await Promise.all(
[
Array.isArray(resolve4)
? Promise.resolve(resolve4)
: this.resolve4(name, { purgeCache, noThrowOnNODATA: true }),
Array.isArray(resolve6)
? Promise.resolve(resolve6)
: this.resolve6(name, { purgeCache, noThrowOnNODATA: true })
].map((p) => p.catch((err) => err))
);
const errors = [];
let answers = [];
for (const result of results) {
if (result instanceof Error) {
errors.push(result);
} else {
answers.push(result);
}
}
if (
answers.length === 0 &&
errors.length > 0 &&
errors.every((e) => e.code === errors[0].code)
) {
const err = this.constructor.createError(
name,
'',
errors[0].code === dns.BADNAME ? dns.NOTFOUND : errors[0].code
);
// remap and perform syscall
err.syscall = 'getaddrinfo';
err.message = err.message.replace('query', 'getaddrinfo');
err.errno = -3008;
throw err;
}
// default node behavior seems to return IPv4 by default always regardless
if (answers.length > 0)
answers =
answers[0].length > 0 &&
(options.family === undefined || options.family === 0)
? answers[0]
: answers.flat();
// if no results then throw ENODATA
if (answers.length === 0) {
const err = this.constructor.createError(name, '', dns.NODATA);
// remap and perform syscall
err.syscall = 'getaddrinfo';
err.message = err.message.replace('query', 'getaddrinfo');
err.errno = -3008;
throw err;
}
// respect options from dns module
// <https://nodejs.org/api/dns.html#dnspromiseslookuphostname-options>
// - [x] `family` (4, 6, or 0, default is 0)
// - [x] `hints` multiple flags may be passed by bitwise OR'ing values
// - [x] `all` (iff true, then return all results, otherwise single result)
// - [x] `verbatim` - if `true` then return as-is, otherwise use dns order
//
// <https://nodejs.org/api/dns.html#supported-getaddrinfo-flags>
//
// dns.ADDRCONFIG:
// Limits returned address types to the types of non-loopback addresses configured on the system.
// For example, IPv4 addresses are only returned if the current system has at least one IPv4 address configured.
// dns.V4MAPPED:
// If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses.
// It is not supported on some operating systems (e.g. FreeBSD 10.1).
// dns.ALL:
// If dns.V4MAPPED is specified, return resolved IPv6 addresses as well as IPv4 mapped IPv6 addresses.
//
if (options.hints) {
switch (options.hints) {
case dns.V4MAPPED: {
if (options.family === 6 && !answers.some((answer) => isIPv6(answer)))
answers = answers.map((answer) =>
ipaddr.parse(answer).toIPv4MappedAddress().toString()
);
break;
}
case dns.ALL: {
options.all = true;
break;
}
// eslint-disable-next-line no-bitwise
case dns.ADDRCONFIG | dns.V4MAPPED: {
if (options.family === 6 && !answers.some((answer) => isIPv6(answer)))
answers = answers.map((answer) =>
ipaddr.parse(answer).toIPv4MappedAddress().toString()
);
break;
}
// eslint-disable-next-line no-bitwise
case dns.V4MAPPED | dns.ALL: {
if (options.family === 6 && !answers.some((answer) => isIPv6(answer)))
answers = answers.map((answer) =>
ipaddr.parse(answer).toIPv4MappedAddress().toString()
);
options.all = true;
break;
}
// eslint-disable-next-line no-bitwise
case dns.ADDRCONFIG | dns.V4MAPPED | dns.ALL: {
if (options.family === 6 && !answers.some((answer) => isIPv6(answer)))
answers = answers.map((answer) =>
ipaddr.parse(answer).toIPv4MappedAddress().toString()
);
options.all = true;
break;
}
default: {
break;
}
}
}
if (options.family === 4)
answers = answers.filter((answer) => isIPv4(answer));
else if (options.family === 6)
answers = answers.filter((answer) => isIPv6(answer));
//
// respect sort order from `setDefaultResultOrder` method
//
// NOTE: we need to optimize this sort logic at some point
//
if (options.verbatim !== true && this.options.dnsOrder === 'ipv4first') {
answers = answers.sort((a, b) => {
const aFamily = isIP(a);
const bFamily = isIP(b);
if (aFamily < bFamily) return -1;
if (aFamily > bFamily) return 1;
return 0;
});
}
return options.all === true
? answers.map((answer) => ({
address: answer,
family: isIP(answer)
}))
: { address: answers[0], family: isIP(answers[0]) };
}
// <https://man7.org/linux/man-pages/man3/getnameinfo.3.html>
async lookupService(address, port, abortController, purgeCache = false) {
if (!address || !port) {
const err = new TypeError(
'The "address" and "port" arguments must be specified.'
);
err.code = 'ERR_MISSING_ARGS';
throw err;
}
if (!isIP(address)) {
const err = new TypeError(
`The argument 'address' is invalid. Received '${address}'`
);
err.code = 'ERR_INVALID_ARG_VALUE';
throw err;
}
if (!this.constructor.isValidPort(port)) {
const err = new TypeError(
`Port should be >= 0 and < 65536. Received ${port}.`
);
err.code = 'ERR_SOCKET_BAD_PORT';
throw err;
}
const { name } = getService(port);
// reverse lookup
try {
const [hostname] = await this.reverse(
address,
abortController,
purgeCache
);
return { hostname, service: name };
} catch (err) {
err.syscall = 'getnameinfo';
throw err;
}
}
async reverse(ip, abortController, purgeCache = false) {
// basically reverse the IP and then perform PTR lookup
if (typeof ip !== 'string') {
const err = new TypeError('The "ip" argument must be of type string.');
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
if (!isIP(ip)) {
const err = this.constructor.createError(ip, '', 'EINVAL');
err.message = `getHostByAddr EINVAL ${err.hostname}`;
err.syscall = 'getHostByAddr';
err.errno = -22;
if (!ip) delete err.hostname;
throw err;
}
// edge case where localhost IP returns matches
if (!isPrivateIP) await pWaitFor(() => Boolean(isPrivateIP));
const answers = new Set();
let match = false;
for (const rule of this.constructor.HOSTS) {
if (rule.ip === ip) {
match = true;
for (const host of rule.hosts.slice(1)) {
answers.add(host);
}
}
}
if (answers.size > 0 || match) return [...answers];
// NOTE: we can prob remove this (?)
// if (ip === '::1' || ip === '127.0.0.1') return [];
// reverse the IP address
if (!dohdec) await pWaitFor(() => Boolean(dohdec));
const name = dohdec.DNSoverHTTPS.reverse(ip);
// perform resolvePTR
try {
const answers = await this.resolve(
name,
'PTR',
{ purgeCache },
abortController
);
return answers;
} catch (err) {
// remap syscall
err.syscall = 'getHostByAddr';
err.message = `${err.syscall} ${err.code} ${ip}`;
err.hostname = ip;
throw err;
}
}
//
// NOTE: we support an `options.ecsSubnet` property (e.g. in addition to `ttl`)
//
resolve4(name, options, abortController) {
return this.resolve(name, 'A', options, abortController);
}
resolve6(name, options, abortController) {
return this.resolve(name, 'AAAA', options, abortController);
}
resolveCaa(name, options, abortController) {
return this.resolve(name, 'CAA', options, abortController);
}
resolveCname(name, options, abortController) {
return this.resolve(name, 'CNAME', options, abortController);
}
resolveMx(name, options, abortController) {
return this.resolve(name, 'MX', options, abortController);
}
resolveNaptr(name, options, abortController) {
return this.resolve(name, 'NAPTR', options, abortController);
}
resolveNs(name, options, abortController) {