-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
server-node.js
1363 lines (1194 loc) · 38.9 KB
/
server-node.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
/*
* Copyright (c) 2021 RethinkDNS and its authors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// should always be the first import
// import whyIsNodeRunning from "why-is-node-running";
import "./core/node/config.js";
import { LfuCache } from "@serverless-dns/lfu-cache";
import * as h2c from "httpx-server";
import http2 from "node:http2";
import https from "node:https";
import net, { isIPv6 } from "node:net";
import os from "node:os";
import { finished } from "node:stream";
import tls from "node:tls";
import v8 from "node:v8";
import { V2ProxyProtocol } from "proxy-protocol-js";
import * as bufutil from "./commons/bufutil.js";
import * as nodecrypto from "./commons/crypto.js";
import * as dnsutil from "./commons/dnsutil.js";
import * as envutil from "./commons/envutil.js";
import * as util from "./commons/util.js";
import { handleRequest } from "./core/doh.js";
import * as nodeutil from "./core/node/util.js";
import { stopAfter, uptime } from "./core/svc.js";
import * as system from "./system.js";
/**
* @typedef {net.Socket} Socket
* @typedef {tls.TLSSocket} TLSSocket
* @typedef {http2.Http2ServerRequest} Http2ServerRequest
* @typedef {http2.Http2ServerResponse} Http2ServerResponse
*/
let OUR_RG_DN_RE = null; // regular dns name match
let OUR_WC_DN_RE = null; // wildcard dns name match
let log = null;
// todo: as metrics
class Stats {
constructor() {
this.noreqs = -1;
this.nofchecks = 0;
this.tlserr = 0;
this.fasttls = 0;
this.totfasttls = 0;
this.noftlsadjs = 0;
this.nofdrops = 0;
this.nofconns = 0;
this.openconns = 0;
this.noftimeouts = 0;
this.nofheapsnaps = 0;
// avg1, avg5, avg15, adj, maxconns
this.bp = [0, 0, 0, 0, 0];
}
str() {
return (
`reqs=${this.noreqs} c=${this.nofchecks} ` +
`drops=${this.nofdrops}/tot=${this.nofconns}/open=${this.openconns} ` +
`to=${this.noftimeouts}/tlserr=${this.tlserr} ` +
`tls0=${this.fasttls}/tls0miss=${this.totfasttls}/tlsadjs=${this.noftlsadjs} ` +
`n=${this.bp[4]}/adj=${this.bp[3]} ` +
`load=${this.bp[0]}/${this.bp[1]}/${this.bp[2]}`
);
}
}
class SoReport {
constructor() {
/** @type {int} total bytes transferred in preceding 1sec */
this.tx = 0;
/** @type {int} unix timestamp in millis */
this.lastsnd = 0;
}
}
class ConnW {
/**
* @param {Socket|TLSSocket} socket
*/
constructor(socket) {
this.socket = socket;
this.rep = new SoReport();
}
}
class Tracker {
constructor() {
this.zeroid = "";
/** @type {Array<Map<string, ConnW>>} */
this.connmap = [];
this.reports = [];
/** @type {Array<net.Server>} */
this.srvs = [];
}
valid(id) {
return id != null && this.zeroid !== id;
}
/**
* @param {net.Server|tls.Server} server
* @returns {string}
*/
sid(server) {
if (!server) return this.zeroid;
const saddr = server.address();
if (!saddr || !saddr.port) {
log.w("trackConn: no addr/port", saddr);
return this.zeroid;
}
return saddr.port + "";
}
/**
* @param {Socket?} sock
* @returns {string}
*/
cid(sock) {
if (!sock || util.emptyString(sock.remoteAddress)) return this.zeroid;
else return sock.remoteAddress + "|" + sock.remotePort;
}
/**
* @param {string} id
* @param {net.Server} s
* @returns {string} sid
*/
trackServer(id, s) {
if (!s) return this.zeroid;
const mapid = this.sid(s);
if (!this.valid(mapid)) {
log.w("trackServer: server not tracked", id, mapid);
return this.zeroid;
}
const cmap = this.connmap[mapid];
if (cmap) {
log.w("trackServer: server already tracked?", id, mapid);
return this.zeroid;
}
log.i("trackServer: new server", id, mapid);
this.connmap[mapid] = new Map();
this.srvs.push(s);
return mapid;
}
*servers() {
yield* this.srvs;
}
*conns() {
for (const cm of this.connmap) {
if (!cm) continue;
yield* cm.values();
}
}
/**
* @param {net.Server} server
* @param {Socket} sock
* @returns {string}
*/
trackConn(server, sock) {
// if no servers are being tracked, don't track connections either
// happens if the server did not start or this.end was called
if (util.emptyArray(this.srvs)) return this.zeroid;
if (!server || !server.listening || !sock) return this.zeroid;
const mapid = this.sid(server);
const connid = this.cid(sock);
const cmap = this.connmap[mapid];
if (!this.valid(mapid) || !this.valid(connid) || !cmap) {
log.d("trackConn: server/socket not tracked?", mapid, connid);
return this.zeroid;
}
cmap.set(connid, new ConnW(sock));
sock.on("close", (haderr) => cmap.delete(connid));
return connid;
}
/**
*
* @param {Socket|TLSSocket|null} sock
* @returns {SoReport?} rep
*/
sorep(sock) {
const connid = this.cid(sock);
if (!this.valid(connid)) return null; // unlikely
for (const cmap of this.connmap) {
if (!cmap) continue;
const connw = cmap.get(connid);
if (connw != null) return connw.rep;
}
return null; // sock not tracked!
}
/**
* @returns {[Array<net.Server>, Array<Map<string, ConnW>>]}
*/
end() {
const srvs = this.srvs;
const cmap = this.connmap;
this.srvs = [];
this.connmap = [];
return [srvs, cmap];
}
}
// nodejs.org/api/net.html#serverlisten
const zero6 = "::";
const tracker = new Tracker();
const stats = new Stats();
// blog.cloudflare.com/optimizing-tls-over-tcp-to-reduce-latency
// 1369 - (1500 - 1280) = 1149
const tlsStartFragmentSize = 1149; // bytes
const tlsMaxFragmentSize = 16 << 10; // 16kb
const tlsSessions = new LfuCache("tlsSessions", 10000);
const cpucount = os.cpus().length || 1;
const adjPeriodSec = 5;
const maxHeapSnaps = 20;
let adjTimer = null;
((main) => {
// listen for "go" and start the server
system.sub("go", systemUp);
// listen for "end" and stop the server
system.sub("stop", systemDown);
// ask prepare phase to commence
system.pub("prepare");
})();
function systemDown() {
// system-down even may arrive even before the process has had the chance
// to start, in which case globals like env and log may not be available
const upmins = (uptime() / 60000) | 0;
console.warn("W rcv stop; uptime", upmins, "mins", stats.str());
const shutdownTimeoutMs = envutil.shutdownTimeoutMs();
// servers will start rejecting conns when tracker is empty
const [srvs, cmap] = tracker.end();
util.timeout(shutdownTimeoutMs, bye);
if (adjTimer) clearInterval(adjTimer);
// 0 is ignored; github.com/nodejs/node/pull/48276
// accept only 1 conn (which keeps health-checks happy)
adjustMaxConns(1);
// drain all sockets stackoverflow.com/a/14636625
// TODO: handle proxy protocol sockets
for (const m of cmap) {
if (!m) continue;
console.warn("W closing...", m.size, "connections");
for (const v of m.values()) {
close(v.socket);
}
}
// stopping net.server only stops incoming reqs; it does not
// close open sockets: github.com/nodejs/node/issues/2642
for (const s of srvs) {
if (!s || !s.listening) continue;
const saddr = s.address();
console.warn("W stopping...", saddr);
s.close(() => down(saddr));
s.unref();
}
// test: util.next(whyIsNodeRunning, bye);
util.next(bye);
}
function systemUp() {
log = util.logger("NodeJs");
if (!log) throw new Error("logger unavailable on system up");
const downloadmode = envutil.blocklistDownloadOnly();
const profilermode = envutil.profileDnsResolves();
const tlsoffload = envutil.isCleartext();
// todo: tcp backlog for doh/dot servers not supported on bun 1.1
const tcpbacklog = envutil.tcpBacklog();
const maxconns = envutil.maxconns();
// see also: dns-transport.js:ioTimeout
const ioTimeoutMs = envutil.ioTimeoutMs();
const supportsHttp2 = envutil.isNode() || envutil.isDeno();
const isBun = envutil.isBun();
if (downloadmode) {
log.i("in download mode, not running the dns resolver");
return;
} else if (profilermode) {
const durationms = 60 * 1000; // 1 min
log.w("in profiler mode, run for", durationms, "and exit");
stopAfter(durationms);
} else {
adjTimer = util.repeat(adjPeriodSec * 1000, adjustMaxConns);
log.i(`cpu ${cpucount}, ip ${zero6}, tcpb ${tcpbacklog}, c ${maxconns}`);
}
// nodejs.org/api/net.html#netcreateserveroptions-connectionlistener
/** @type {net.ServerOpts} */
const serverOpts = {
keepAlive: true,
noDelay: true,
};
// default cipher suites
// nodejs.org/api/tls.html#modifying-the-default-tls-cipher-suite
let defaultTlsCiphers = "";
if (!util.emptyString(tls.DEFAULT_CIPHERS)) {
// nodejs.org/api/tls.html#tlsdefault_ciphers
defaultTlsCiphers = tls.DEFAULT_CIPHERS;
} else {
// nodejs.org/api/tls.html#tlsgetciphers
defaultTlsCiphers = tls
.getCiphers()
.map((c) => c.toUpperCase())
.join(":");
}
// aes128 is a 'cipher string' for tls1.2 and below
// docs.openssl.org/1.1.1/man1/ciphers/#cipher-strings
const preferAes128 =
"AES128:TLS_AES_128_CCM_SHA256:TLS_AES_128_CCM_8_SHA256:TLS_AES_128_GCM_SHA256";
// nodejs.org/api/tls.html#tlscreateserveroptions-secureconnectionlistener
/** @type {tls.SecureContextOptions} */
const tlsOpts = {
ciphers: preferAes128 + ":" + defaultTlsCiphers,
honorCipherOrder: true,
handshakeTimeout: Math.max((ioTimeoutMs / 2) | 0, 3 * 1000), // 3s in ms
// blog.cloudflare.com/tls-session-resumption-full-speed-and-secure
sessionTimeout: 60 * 60 * 24 * 7, // 7d in secs
};
// nodejs.org/api/http2.html#http2createsecureserveroptions-onrequesthandler
const h2Opts = {
allowHTTP1: true,
};
if (tlsoffload) {
// fly.io terminated tls?
const portdoh = envutil.dohCleartextBackendPort();
const portdot = envutil.dotCleartextBackendPort();
/** @type {net.ListenOptions} */
const dohOpts = { port: portdoh, host: zero6, backlog: tcpbacklog };
/** @type {net.ListenOptions} */
const dotOpts = { port: portdot, host: zero6, backlog: tcpbacklog };
// TODO: ProxyProtoV2 with TLS ClientHello (unsupported by Fly.io, rn)
// DNS over TLS Cleartext
const dotct = net.createServer(serverOpts, serveTCP).listen(dotOpts, () => {
up("DoT Cleartext", dotct.address());
trapServerEvents("dotct", dotct);
});
// DNS over HTTPS Cleartext
// Same port for http1.1/h2 does not work on node without tls, that is,
// http2.createServer with opts { ALPNProtocols: ["h2", "http/1.1"],
// allowHTTP1: true } doesn't handle http1.1 at all (but it does with
// http2.createSecureServer which involves tls).
// Ref (for servers): github.com/nodejs/node/issues/34296
// Ref (for clients): github.com/nodejs/node/issues/31759
// Impl: stackoverflow.com/a/42019773
const dohct = h2c
.createServer(serverOpts, serveHTTPS)
.listen(dohOpts, () => {
up("DoH Cleartext", dohct.address());
trapServerEvents("dohct", dohct);
});
} else {
// terminate tls ourselves
const secOpts = {
key: envutil.tlsKey(),
cert: envutil.tlsCrt(),
...tlsOpts,
...serverOpts,
};
const portdot1 = envutil.dotBackendPort();
const portdot2 = envutil.dotProxyProtoBackendPort();
const portdoh = envutil.dohBackendPort();
/** @type {net.ListenOptions} */
const dohOpts = { port: portdoh, host: zero6, backlog: tcpbacklog };
/** @type {net.ListenOptions} */
const dot1Opts = { port: portdot1, host: zero6, backlog: tcpbacklog };
/** @type {net.ListenOptions} */
const dot2Opts = { port: portdot2, host: zero6, backlog: tcpbacklog };
// DNS over TLS
const dot1 = tls.createServer(secOpts, serveTLS).listen(dot1Opts, () => {
up("DoT", dot1.address());
trapSecureServerEvents("dot1", dot1);
});
// DNS over TLS w ProxyProto
const dot2 =
envutil.isDotOverProxyProto() &&
net.createServer(serverOpts, serveDoTProxyProto).listen(dot2Opts, () => {
up("DoT ProxyProto", dot2.address());
trapServerEvents("dot2", dot2);
});
// DNS over HTTPS
if (supportsHttp2) {
const doh = http2
.createSecureServer({ ...secOpts, ...h2Opts }, serveHTTPS)
.listen(dohOpts, () => {
up("DoH2", doh.address());
trapSecureServerEvents("doh2", doh);
});
} else if (isBun) {
const doh = https
.createServer(secOpts, serveHTTPS)
.listen(dohOpts, () => {
up("DoH1", doh.address());
trapSecureServerEvents("doh1", doh);
});
} else {
console.log("unsupported runtime for doh");
}
}
const portcheck = envutil.httpCheckPort();
const hcheck = h2c.createServer(serve200).listen(portcheck, () => {
up("http-check", hcheck.address());
trapServerEvents("hcheck", hcheck);
});
heartbeat();
}
/**
* @param {string} id
* @param {... http2.Http2Server | net.Server} s
*/
function trapServerEvents(id, s) {
const ioTimeoutMs = envutil.ioTimeoutMs();
if (!s) return;
const sid = tracker.trackServer(id, s);
if (sid === tracker.zeroid) {
log.w("tcp: may be already tracking server", id);
return;
}
s.on("connection", (/** @type {Socket} */ socket) => {
stats.nofconns += 1;
stats.openconns += 1;
const id = tracker.trackConn(s, socket);
if (!tracker.valid(id)) {
log.i("tcp: not tracking; server shutting down?", id);
close(socket);
return;
}
socket.setTimeout(ioTimeoutMs, () => {
stats.noftimeouts += 1;
log.d("tcp: incoming conn timed out; " + id);
socket.end();
});
socket.on("error", (err) => {
log.d("tcp: incoming conn", id, "closed:", err.message);
close(socket);
});
socket.on("end", () => {
// TODO: is this needed? this is the default anyway
socket.end();
});
socket.on("close", () => {
stats.openconns -= 1;
});
});
// emitted when the req is discarded due to maxConnections
s.on("drop", (data) => {
stats.nofdrops += 1;
stats.nofconns += 1;
});
s.on("error", (err) => {
log.e("tcp: stop! server error; " + err.message, err);
stopAfter(0);
});
}
/**
* @param {string} id
* @param {http2.Http2SecureServer | tls.Server} s
*/
function trapSecureServerEvents(id, s) {
const ioTimeoutMs = envutil.ioTimeoutMs();
if (!s) return;
const sid = tracker.trackServer(id, s);
if (sid === tracker.zeroid) {
log.w("tls: may be already tracking server", id);
return;
}
// github.com/grpc/grpc-node/blob/e6ea6f517epackages/grpc-js/src/server.ts#L392
s.on("secureConnection", (/** @type {TLSSocket} */ socket) => {
stats.nofconns += 1;
stats.openconns += 1;
const id = tracker.trackConn(s, socket);
if (!tracker.valid(id)) {
log.i("tls: not tracking; server shutting down?", id);
close(socket);
return;
}
// github.com/nodejs/node-v0.x-archive/issues/6889
socket.setMaxSendFragment(tlsStartFragmentSize);
socket.setTimeout(ioTimeoutMs, () => {
stats.noftimeouts += 1;
log.d("tls: incoming conn timed out; " + id);
close(socket);
});
// error must be handled by Http2SecureServer
// github.com/nodejs/node/issues/35824
socket.on("error", (err) => {
log.e("tls: incoming conn", id, "closed;", err.message);
close(socket);
});
socket.on("end", () => {
// client gone, socket half-open at this point
// close this end of the socket, too
socket.end();
});
socket.on("close", () => {
stats.openconns -= 1;
});
});
const rottm = util.repeat(86400000 * 7, () => rotateTkt(s)); // 7d
s.on("close", () => clearInterval(rottm));
s.on("error", (err) => {
log.e("tls: stop! server error; " + err.message, err);
stopAfter(0);
});
// bajtos.net/posts/2013-08-07-improve-the-performance-of-the-node-js-https-server
// session tickets take precedence over session ids; -no_ticket is needed
// openssl s_client -connect :10000 -reconnect -tls1_2 -no_ticket
// on bun, since session tickets cannot be set by programs (though may be vended
// by the runtime itself), session ids may come in handy.
s.on("newSession", (id, data, next) => {
const hid = bufutil.hex(id);
tlsSessions.put(hid, data);
// log.d("tls: new session;", hid);
next();
});
s.on("resumeSession", (id, next) => {
const hid = bufutil.hex(id);
const data = tlsSessions.get(hid) || null;
// log.d("tls: resume;", hid, "ok?", data != null);
if (data) stats.fasttls += 1;
else stats.totfasttls += 1;
next(/* err*/ null, null);
});
// emitted when the req is discarded due to maxConnections
s.on("drop", (data) => {
stats.nofdrops += 1;
stats.nofconns += 1;
});
s.on("tlsClientError", (err, /** @type {TLSSocket} */ tlsSocket) => {
stats.tlserr += 1;
// fly tcp healthchecks also trigger tlsClientErrors
log.d("tls: client err;", err.message, addrstr(tlsSocket));
close(tlsSocket);
});
}
/**
* @param {TLSSocket|Socket} sock
*/
function addrstr(sock) {
if (!sock) return "";
if (sock.localAddress == null || sock.remoteAddress == null) return "";
return (
`[${sock.localAddress}]:${sock.localPort}` +
"->" +
`[${sock.remoteAddress}]:${sock.remotePort}`
);
}
/**
* @param {tls.Server} s
* @returns {void}
*/
function rotateTkt(s) {
if (envutil.isBun()) return;
if (!s || !s.listening) return;
let seed = bufutil.fromB64(envutil.secretb64());
if (bufutil.emptyBuf(seed)) {
seed = envutil.tlsKey();
}
let ctx = envutil.imageRef();
if (!util.emptyString(ctx)) {
const d = new Date();
const cur = d.getUTCFullYear() + " " + d.getUTCMonth(); // 2023 7
ctx = cur + ctx;
}
// tls session resumption with tickets (or ids) reduce the 3.5kb to 6.5kb
// overhead associated with tls handshake: netsekure.org/2010/03/tls-overhead
nodecrypto
.tkt48(seed, ctx)
.then((k) => s.setTicketKeys(k)) // not supported on bun
.catch((err) => log.e("tls: ticket rotation failed:", err));
}
function down(addr) {
console.warn(`W closed: [${addr.address}]:${addr.port}`);
}
function up(server, addr) {
log.i(server, `listening on: [${addr.address}]:${addr.port}`);
}
/**
* RST and/or closes tcp socket.
* @param {Socket | TLSSocket} sock
*/
function close(sock) {
if (!sock || sock.destroyed) return;
if (sock.connecting) sock.resetAndDestroy();
else sock.destroySoon();
sock.unref();
}
/**
* @param {Http2ServerResponse} res
*/
function resClose(res) {
if (res && !res.destroy) res.destroy();
}
/**
* @param {Http2ServerResponse} res
* @returns {Boolean}
*/
function resOkay(res) {
// determine if res is not destroyed, finished, and is writable
return res.writable;
}
/**
* @param {Socket} sock
* @returns {Boolean}
*/
function tcpOkay(sock) {
return sock.writable;
}
/**
* Creates a duplex pipe between `a` and `b` sockets.
* @param {Socket} a
* @param {Socket} b
* @return {Boolean} - true if pipe created, false if error
*/
function proxySockets(a, b) {
if (a.destroyed || b.destroyed) return false;
// handle errors? stackoverflow.com/a/61091744
a.pipe(b);
b.pipe(a);
return true;
}
/**
* Proxies connection to DOT server, retrieving proxy proto header.
* @param {Socket} clientSocket
*/
function serveDoTProxyProto(clientSocket) {
let ppHandled = false;
log.d("--> new client Connection");
const dotSock = net.connect(envutil.dotBackendPort(), () =>
log.d("pp: dot socket ready")
);
dotSock.on("error", (e) => {
log.w("pp: dot socket err", e);
close(clientSocket);
close(dotSock);
});
function handleProxyProto(buf) {
// Data from only first tcp segment is to be consumed to get proxy proto.
// After extracting proxy proto, a duplex pipe is created to DoT server.
// So, further tcp segments return here.
if (ppHandled) return;
const chunk = buf.toString("ascii");
const delim = chunk.indexOf("\r\n") + 2; // CRLF = \x0D \x0A
ppHandled = true;
if (delim < 0) {
log.e("pp: header invalid / not found =>", chunk);
close(clientSocket);
close(dotSock);
return;
}
try {
// TODO: admission control
const proto = V2ProxyProtocol.parse(chunk.slice(0, delim));
log.d(`pp: --> [${proto.source.ipAddress}]:${proto.source.port}`);
// remaining data from first tcp segment
if (!dotSock.destroyed) dotSock.write(buf.slice(delim));
const ok = proxySockets(clientSocket, dotSock);
if (!ok) throw new Error(proto + " err clientSock <> dotSock proxy");
} catch (e) {
log.w(e);
close(clientSocket);
close(dotSock);
return;
}
}
clientSocket.on("error", (e) => {
log.w("pp: client err, closing");
close(clientSocket);
close(dotSock);
});
clientSocket.on("data", handleProxyProto);
}
class ScratchBuffer {
constructor() {
/** @type {Buffer} */
this.qlenBuf = bufutil.createBuffer(dnsutil.dnsHeaderSize);
/** @type {Number} */
this.qlenBufOffset = bufutil.recycleBuffer(this.qlenBuf);
this.qBuf = null;
this.qBufOffset = 0;
}
allocOnce(sz) {
if (this.qBuf === null) {
this.qBuf = bufutil.createBuffer(sz);
this.qBufOffset = bufutil.recycleBuffer(this.qBuf);
}
}
reset() {
const b = this.qBuf;
this.qlenBufOffset = bufutil.recycleBuffer(this.qlenBuf);
this.qBuf = null;
this.qBufOffset = 0;
return b;
}
}
/**
* Get RegEx's to match dns names of a CA certificate.
* A non matching RegEx is returned if no DNS names are found.
* @param {TLSSocket} socket - TLS socket to get CA certificate from.
* @return {Array<[String]>} [regular RegExs, wildcard RegExs]
*/
function getDnRE(socket) {
const SAN_DNS_PREFIX = "DNS:";
const SAN = socket.getCertificate().subjectaltname;
// Compute DNS RegExs from TLS SAN (subject-alt-names)
// for max.rethinkdns.com SANs, see: https://crt.sh/?id=5708836299
const regExs = SAN.split(",").reduce(
(arr, entry) => {
entry = entry.trim();
// Ignore non-DNS entries
const u = entry.indexOf(SAN_DNS_PREFIX);
if (u !== 0) return arr;
// entry => DNS:*.max.rethinkdns.com
// sliced => *.max.rethinkdns.com
entry = entry.slice(SAN_DNS_PREFIX.length);
// d => *\.max\.rethinkdns\.com
// wc => true
// pos => 1
// match => [a-z0-9-_]*\.max\.rethinkdns\.com
// reStr => (^[a-z0-9-_]*\.max\.rethinkdns\.com$)
const d = entry.replaceAll(".", "\\.");
const wc = d.startsWith("*");
const pos = wc ? 1 : 0;
const match = wc ? "[a-z0-9-_]" + d : d;
const reStr = "(^" + match + "$)";
arr[pos].push(reStr);
return arr;
},
// [[Regular matches], [Wildcard matches]]
[[], []]
);
// Construct case-insensitive RegEx from the respective array of RE strings.
// RegExs strings are joined with OR operator, before constructing RegEx.
// If no RegEx strings are found, a non-matching RegEx `(?!)` is returned.
const rgDnRE = new RegExp(regExs[0].join("|") || "(?!)", "i");
const wcDnRE = new RegExp(regExs[1].join("|") || "(?!)", "i");
log.i("sni:", rgDnRE, wcDnRE);
return [rgDnRE, wcDnRE];
}
/**
* Gets flag and hostname from the wildcard domain name.
* @param {String} sni - Wildcard SNI
* @return {Array<String>} [flag, hostname]
*/
function getMetadata(sni) {
// 1-flag.max.rethinkdns.com => ["1-flag", "max", "rethinkdns", "com"]
// 1-flag.somedomain.tld => ["1-flag", "somedomain", "tld"]
const s = sni.split(".");
if (s.length > 2) {
// ["1-flag", "max", "rethinkdns", "com"] => "max.rethinkdns.com"
const host = s.splice(1).join(".");
// previously, "-" was replaced with "+" as doh handlers used "+" to
// differentiate between a b32 flag and a b64 flag ("-" is a valid b64url
// char; "+" is not); but not anymore. If ":" appears first, the flag
// is treated as b64 or if "-" appears first, then as a b32 flag.
const flag = s[0];
log.d(`flag: ${flag}, host: ${host}`);
return [flag, host];
} else {
// sni => max.rethinkdns.com
log.d(`flag: "", host: ${host}`);
return ["", sni];
}
}
/**
* Services a DNS over TLS connection
* @param {TLSSocket} socket
*/
function serveTLS(socket) {
const sni = socket.servername;
if (!sni) {
log.d("no sni, close conn");
close(socket);
return;
}
if (!OUR_RG_DN_RE || !OUR_WC_DN_RE) {
[OUR_RG_DN_RE, OUR_WC_DN_RE] = getDnRE(socket);
}
const isOurRgDn = OUR_RG_DN_RE.test(sni);
const isOurWcDn = OUR_WC_DN_RE.test(sni);
if (!isOurWcDn && !isOurRgDn) {
log.w("unexpected sni, close conn", sni);
close(socket);
return;
}
if (false) {
const tkt = bufutil.hex(socket.getTLSTicket());
const sess = bufutil.hex(socket.getSession());
const proto = socket.getProtocol();
const reused = socket.isSessionReused();
log.d(`(${proto}), reused? ${reused}; ticket: ${tkt}; sess: ${sess}`);
}
const [flag, host] = isOurWcDn ? getMetadata(sni) : ["", sni];
const sb = new ScratchBuffer();
log.d("----> dot request", host, flag);
socket.on("data", async (data) => {
const len = await handleTCPData(socket, data, sb, host, flag);
adjustTLSFragAfterWrites(socket, len);
});
}
/**
* Services a DNS over TCP connection
* @param {Socket} socket
*/
function serveTCP(socket) {
// TODO: TLS ClientHello is sent with proxy-proto v2
const [flag, host] = ["", "ignored.example.com"];
const sb = new ScratchBuffer();
log.d("----> dot cleartext request", host, flag);
socket.on("data", (data) => {
handleTCPData(socket, data, sb, host, flag);
});
}
/**
* Handle DNS over TCP/TLS data stream.
* @param {Socket} socket
* @param {Buffer} chunk - A TCP data segment
* @param {ScratchBuffer} sb - Scratch buffer
* @param {String} host - Hostname
* @param {String} flag - Blocklist Flag
* @returns {Promise<number>} n - bytes sent
*/
async function handleTCPData(socket, chunk, sb, host, flag) {
const cl = chunk.byteLength;
if (cl <= 0) return 0;
// read header first which contains length(dns-query)
const rem = dnsutil.dnsHeaderSize - sb.qlenBufOffset;
if (rem > 0) {
const seek = Math.min(rem, cl);
const read = chunk.slice(0, seek);
sb.qlenBuf.fill(read, sb.qlenBufOffset);
sb.qlenBufOffset += seek;
}
// header has not been read fully, yet; expect more data
// www.rfc-editor.org/rfc/rfc7766#section-8
if (sb.qlenBufOffset !== dnsutil.dnsHeaderSize) return 0;
const qlen = sb.qlenBuf.readUInt16BE();
if (!dnsutil.validateSize(qlen)) {
log.w(`tcp: query size err: ql:${qlen} cl:${cl} rem:${rem}`);
close(socket);
return 0;
}
// rem bytes already read, is any more left in chunk?
const size = cl - rem;
if (size <= 0) return 0;
// gobble up at most qlen bytes from chunk starting rem-th byte
const qlimit = rem + Math.min(qlen - sb.qBufOffset, size);
// hopefully fast github.com/nodejs/node/issues/20130#issuecomment-382417255
// chunk out dns-query starting rem-th byte
const data = chunk.slice(rem, qlimit);
// out of band data, if any
const oob = chunk.slice(qlimit);
sb.allocOnce(qlen);
sb.qBuf.fill(data, sb.qBufOffset);
sb.qBufOffset += data.byteLength;
log.d(`tcp: q: ${qlen}, sb.q: ${sb.qBufOffset}, cl: ${cl}, sz: ${size}`);
let n = 0;
// exactly qlen bytes read till now, handle the dns query
if (sb.qBufOffset === qlen) {
// extract out the query and reset the scratch-buffer
const b = sb.reset();
n += await handleTCPQuery(b, socket, host, flag);
// if there is any out of band data, handle it
if (!bufutil.emptyBuf(oob)) {
log.d(`tcp: pipelined, handle oob: ${oob.byteLength}`);
n += handleTCPData(socket, oob, sb, host, flag);
}
} // continue reading from socket
return n;
}
/**
* @param {Buffer} q
* @param {TLSSocket} socket
* @param {String} host
* @param {String} flag
* @returns {Promise<number>} n - bytes sent
*/
async function handleTCPQuery(q, socket, host, flag) {
heartbeat();
let n = 0;
let ok = true;
if (bufutil.emptyBuf(q) || !tcpOkay(socket)) return 0;