forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcore.js
3300 lines (2880 loc) · 96.7 KB
/
core.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
'use strict';
/* eslint-disable no-use-before-define */
const {
assertCrypto,
customInspectSymbol: kInspect,
} = require('internal/util');
assertCrypto();
const {
Array,
BigInt64Array,
Boolean,
Error,
Map,
Number,
Promise,
PromiseAll,
PromiseReject,
PromiseResolve,
Set,
Symbol,
} = primordials;
const { Buffer } = require('buffer');
const { isArrayBufferView } = require('internal/util/types');
const {
customInspect,
getAllowUnauthorized,
getSocketType,
setTransportParams,
toggleListeners,
validateNumber,
validateTransportParams,
validateQuicClientSessionOptions,
validateQuicSocketOptions,
validateQuicStreamOptions,
validateQuicSocketListenOptions,
validateQuicEndpointOptions,
validateCreateSecureContextOptions,
validateQuicSocketConnectOptions,
QuicStreamSharedState,
QuicSocketSharedState,
QuicSessionSharedState,
QLogStream,
} = require('internal/quic/util');
const assert = require('internal/assert');
const { EventEmitter, once } = require('events');
const fs = require('fs');
const fsPromisesInternal = require('internal/fs/promises');
const { Duplex } = require('stream');
const {
createSecureContext: _createSecureContext
} = require('tls');
const {
translatePeerCertificate
} = require('_tls_common');
const {
defaultTriggerAsyncIdScope,
symbols: {
async_id_symbol,
owner_symbol,
},
} = require('internal/async_hooks');
const dgram = require('dgram');
const internalDgram = require('internal/dgram');
const {
assertValidPseudoHeader,
assertValidPseudoHeaderResponse,
assertValidPseudoHeaderTrailer,
mapToHeaders,
} = require('internal/http2/util');
const {
constants: {
UV_UDP_IPV6ONLY,
UV_UDP_REUSEADDR,
}
} = internalBinding('udp_wrap');
const {
writeGeneric,
writevGeneric,
onStreamRead,
kAfterAsyncWrite,
kMaybeDestroy,
kUpdateTimer,
kHandle,
setStreamTimeout // eslint-disable-line no-unused-vars
} = require('internal/stream_base_commons');
const {
ShutdownWrap,
kReadBytesOrError,
streamBaseState
} = internalBinding('stream_wrap');
const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_STATE,
ERR_OPERATION_FAILED,
ERR_QUIC_FAILED_TO_CREATE_SESSION,
ERR_QUIC_INVALID_REMOTE_TRANSPORT_PARAMS,
ERR_QUIC_INVALID_TLS_SESSION_TICKET,
ERR_QUIC_VERSION_NEGOTIATION,
ERR_TLS_DH_PARAM_SIZE,
},
hideStackFrames,
errnoException,
exceptionWithHostPort
} = require('internal/errors');
const { FileHandle } = internalBinding('fs');
const { StreamPipe } = internalBinding('stream_pipe');
const { UV_EOF } = internalBinding('uv');
const {
QuicSocket: QuicSocketHandle,
QuicEndpoint: QuicEndpointHandle,
initSecureContext,
initSecureContextClient,
createClientSession: _createClientSession,
openBidirectionalStream: _openBidirectionalStream,
openUnidirectionalStream: _openUnidirectionalStream,
setCallbacks,
constants: {
AF_INET6,
NGTCP2_DEFAULT_MAX_PKTLEN,
IDX_QUIC_SESSION_STATS_CREATED_AT,
IDX_QUIC_SESSION_STATS_DESTROYED_AT,
IDX_QUIC_SESSION_STATS_HANDSHAKE_START_AT,
IDX_QUIC_SESSION_STATS_BYTES_RECEIVED,
IDX_QUIC_SESSION_STATS_BYTES_SENT,
IDX_QUIC_SESSION_STATS_BIDI_STREAM_COUNT,
IDX_QUIC_SESSION_STATS_UNI_STREAM_COUNT,
IDX_QUIC_SESSION_STATS_STREAMS_IN_COUNT,
IDX_QUIC_SESSION_STATS_STREAMS_OUT_COUNT,
IDX_QUIC_SESSION_STATS_KEYUPDATE_COUNT,
IDX_QUIC_SESSION_STATS_LOSS_RETRANSMIT_COUNT,
IDX_QUIC_SESSION_STATS_HANDSHAKE_COMPLETED_AT,
IDX_QUIC_SESSION_STATS_ACK_DELAY_RETRANSMIT_COUNT,
IDX_QUIC_SESSION_STATS_MAX_BYTES_IN_FLIGHT,
IDX_QUIC_SESSION_STATS_BLOCK_COUNT,
IDX_QUIC_SESSION_STATS_MIN_RTT,
IDX_QUIC_SESSION_STATS_SMOOTHED_RTT,
IDX_QUIC_SESSION_STATS_LATEST_RTT,
IDX_QUIC_STREAM_STATS_CREATED_AT,
IDX_QUIC_STREAM_STATS_DESTROYED_AT,
IDX_QUIC_STREAM_STATS_BYTES_RECEIVED,
IDX_QUIC_STREAM_STATS_BYTES_SENT,
IDX_QUIC_STREAM_STATS_MAX_OFFSET,
IDX_QUIC_STREAM_STATS_FINAL_SIZE,
IDX_QUIC_STREAM_STATS_MAX_OFFSET_ACK,
IDX_QUIC_STREAM_STATS_MAX_OFFSET_RECV,
IDX_QUIC_SOCKET_STATS_CREATED_AT,
IDX_QUIC_SOCKET_STATS_DESTROYED_AT,
IDX_QUIC_SOCKET_STATS_BOUND_AT,
IDX_QUIC_SOCKET_STATS_LISTEN_AT,
IDX_QUIC_SOCKET_STATS_BYTES_RECEIVED,
IDX_QUIC_SOCKET_STATS_BYTES_SENT,
IDX_QUIC_SOCKET_STATS_PACKETS_RECEIVED,
IDX_QUIC_SOCKET_STATS_PACKETS_IGNORED,
IDX_QUIC_SOCKET_STATS_PACKETS_SENT,
IDX_QUIC_SOCKET_STATS_SERVER_SESSIONS,
IDX_QUIC_SOCKET_STATS_CLIENT_SESSIONS,
IDX_QUIC_SOCKET_STATS_STATELESS_RESET_COUNT,
IDX_QUIC_SOCKET_STATS_SERVER_BUSY_COUNT,
ERR_FAILED_TO_CREATE_SESSION,
ERR_INVALID_REMOTE_TRANSPORT_PARAMS,
ERR_INVALID_TLS_SESSION_TICKET,
NGTCP2_PATH_VALIDATION_RESULT_FAILURE,
NGTCP2_NO_ERROR,
QUIC_ERROR_APPLICATION,
QUICSERVERSESSION_OPTION_REJECT_UNAUTHORIZED,
QUICSERVERSESSION_OPTION_REQUEST_CERT,
QUICCLIENTSESSION_OPTION_REQUEST_OCSP,
QUICCLIENTSESSION_OPTION_VERIFY_HOSTNAME_IDENTITY,
QUICSOCKET_OPTIONS_VALIDATE_ADDRESS,
QUICSOCKET_OPTIONS_VALIDATE_ADDRESS_LRU,
QUICSTREAM_HEADERS_KIND_NONE,
QUICSTREAM_HEADERS_KIND_INFORMATIONAL,
QUICSTREAM_HEADERS_KIND_INITIAL,
QUICSTREAM_HEADERS_KIND_TRAILING,
QUICSTREAM_HEADERS_KIND_PUSH,
QUICSTREAM_HEADER_FLAGS_NONE,
QUICSTREAM_HEADER_FLAGS_TERMINAL,
}
} = internalBinding('quic');
const {
Histogram,
kDestroy: kDestroyHistogram
} = require('internal/histogram');
const {
validateBoolean,
validateInteger,
validateObject,
} = require('internal/validators');
const emit = EventEmitter.prototype.emit;
const kAddSession = Symbol('kAddSession');
const kAddStream = Symbol('kAddStream');
const kBind = Symbol('kBind');
const kClose = Symbol('kClose');
const kClientHello = Symbol('kClientHello');
const kDestroy = Symbol('kDestroy');
const kEndpointBound = Symbol('kEndpointBound');
const kEndpointClose = Symbol('kEndpointClose');
const kHandleOcsp = Symbol('kHandleOcsp');
const kHandshake = Symbol('kHandshake');
const kHandshakeComplete = Symbol('kHandshakeComplete');
const kHandshakePost = Symbol('kHandshakePost');
const kHeaders = Symbol('kHeaders');
const kInternalState = Symbol('kInternalState');
const kInternalClientState = Symbol('kInternalClientState');
const kInternalServerState = Symbol('kInternalServerState');
const kListen = Symbol('kListen');
const kMaybeBind = Symbol('kMaybeBind');
const kOnFileOpened = Symbol('kOnFileOpened');
const kOnFileUnpipe = Symbol('kOnFileUnpipe');
const kOnPipedFileHandleRead = Symbol('kOnPipedFileHandleRead');
const kReady = Symbol('kReady');
const kRemoveSession = Symbol('kRemove');
const kRemoveStream = Symbol('kRemoveStream');
const kServerBusy = Symbol('kServerBusy');
const kSetHandle = Symbol('kSetHandle');
const kSetQLogStream = Symbol('kSetQLogStream');
const kSetSocket = Symbol('kSetSocket');
const kStartFilePipe = Symbol('kStartFilePipe');
const kStreamClose = Symbol('kStreamClose');
const kStreamOptions = Symbol('kStreamOptions');
const kStreamReset = Symbol('kStreamReset');
const kTrackWriteState = Symbol('kTrackWriteState');
const kUDPHandleForTesting = Symbol('kUDPHandleForTesting');
const kUsePreferredAddress = Symbol('kUsePreferredAddress');
const kVersionNegotiation = Symbol('kVersionNegotiation');
const kWriteGeneric = Symbol('kWriteGeneric');
const kRejections = Symbol.for('nodejs.rejection');
const kSocketUnbound = 0;
const kSocketPending = 1;
const kSocketBound = 2;
const kSocketDestroyed = 3;
let diagnosticPacketLossWarned = false;
let warnedVerifyHostnameIdentity = false;
let DOMException;
const lazyDOMException = hideStackFrames((message) => {
if (DOMException === undefined)
DOMException = internalBinding('messaging').DOMException;
return new DOMException(message);
});
assert(process.versions.ngtcp2 !== undefined);
// Called by the C++ internals when the QuicSocket is closed with
// or without an error. The only thing left to do is destroy the
// QuicSocket instance.
function onSocketClose(err) {
this[owner_symbol].destroy(err != null ? errnoException(err) : undefined);
}
// Called by the C++ internals when the server busy state of
// the QuicSocket has been changed.
function onSocketServerBusy() {
this[owner_symbol][kServerBusy]();
}
// Called by the C++ internals when a new server QuicSession has been created.
function onSessionReady(handle) {
const socket = this[owner_symbol];
const session =
new QuicServerSession(
socket,
handle,
socket[kStreamOptions]);
try {
socket.emit('session', session);
} catch (error) {
socket[kRejections](error, 'session', session);
}
}
// Called when the C++ QuicSession::Close() method has been called.
// Synchronously cleanup and destroy the JavaScript QuicSession.
function onSessionClose(code, family, silent, statelessReset) {
this[owner_symbol][kDestroy](code, family, silent, statelessReset);
}
// This callback is invoked at the start of the TLS handshake to provide
// some basic information about the ALPN, SNI, and Ciphers that are
// being requested. It is only called if the 'clientHelloHandler' option is
// specified on listen().
function onSessionClientHello(alpn, servername, ciphers) {
this[owner_symbol][kClientHello](alpn, servername, ciphers)
.then((context) => {
if (context !== undefined && !context?.context)
throw new ERR_INVALID_ARG_TYPE('context', 'SecureContext', context);
this.onClientHelloDone(context?.context);
})
.catch((error) => this[owner_symbol].destroy(error));
}
// This callback is only ever invoked for QuicServerSession instances,
// and is used to trigger OCSP request processing when needed. The
// user callback must invoke .onCertDone() in order for the
// TLS handshake to continue.
function onSessionCert(servername) {
this[owner_symbol][kHandleOcsp](servername)
.then((data) => {
if (data !== undefined) {
if (typeof data === 'string')
data = Buffer.from(data);
if (!isArrayBufferView(data)) {
throw new ERR_INVALID_ARG_TYPE(
'data',
['string', 'Buffer', 'TypedArray', 'DataView'],
data);
}
}
this.onCertDone(data);
})
.catch((error) => this[owner_symbol].destroy(error));
}
// This callback is only ever invoked for QuicClientSession instances,
// and is used to deliver the OCSP response as provided by the server.
// If the requestOCSP configuration option is false, this will never
// be called.
function onSessionStatus(data) {
this[owner_symbol][kHandleOcsp](data)
.catch((error) => this[owner_symbol].destroy(error));
}
// Called by the C++ internals when the TLS handshake is completed.
function onSessionHandshake(
servername,
alpn,
cipher,
cipherVersion,
maxPacketLength,
verifyErrorReason,
verifyErrorCode,
earlyData) {
this[owner_symbol][kHandshake](
servername,
alpn,
cipher,
cipherVersion,
maxPacketLength,
verifyErrorReason,
verifyErrorCode,
earlyData);
}
// Called by the C++ internals when TLS session ticket data is
// available. This is generally most useful on the client side
// where the session ticket needs to be persisted for session
// resumption and 0RTT.
function onSessionTicket(sessionTicket, transportParams) {
if (this[owner_symbol]) {
process.nextTick(
emit.bind(
this[owner_symbol],
'sessionTicket',
sessionTicket,
transportParams));
}
}
// Called by the C++ internals when path validation is completed.
// This is a purely informational event that is emitted only when
// there is a listener present for the pathValidation event.
function onSessionPathValidation(res, local, remote) {
const session = this[owner_symbol];
if (session) {
process.nextTick(
emit.bind(
session,
'pathValidation',
res === NGTCP2_PATH_VALIDATION_RESULT_FAILURE ? 'failure' : 'success',
local,
remote));
}
}
function onSessionUsePreferredAddress(address, port, family) {
const session = this[owner_symbol];
session[kUsePreferredAddress]({
address,
port,
type: family === AF_INET6 ? 'udp6' : 'udp4'
});
}
// Called by the C++ internals to emit a QLog record. This can
// be called before the QuicSession has been fully initialized,
// in which case we store a reference and defer emitting the
// qlog event until after we're initialized.
function onSessionQlog(handle) {
const session = this[owner_symbol];
const stream = new QLogStream(handle);
if (session)
session[kSetQLogStream](stream);
else
this.qlogStream = stream;
}
// Called by the C++ internals when a client QuicSession receives
// a version negotiation response from the server.
function onSessionVersionNegotiation(
version,
requestedVersions,
supportedVersions) {
if (this[owner_symbol]) {
this[owner_symbol][kVersionNegotiation](
version,
requestedVersions,
supportedVersions);
}
}
// Called by the C++ internals to emit keylogging details for a
// QuicSession.
function onSessionKeylog(line) {
if (this[owner_symbol]) {
this[owner_symbol].emit('keylog', line);
}
}
// Called by the C++ internals when a new QuicStream has been created.
function onStreamReady(streamHandle, id, push_id) {
const session = this[owner_symbol];
// onStreamReady should never be called if the stream is in a closing
// state because new streams should not have been accepted at the C++
// level.
assert(!session.closing);
const stream = new QuicStream({
...session[kStreamOptions],
writable: !(id & 0b10),
}, session, streamHandle, push_id);
process.nextTick(() => {
try {
session.emit('stream', stream);
} catch (error) {
stream.destroy(error);
}
});
}
// Called by the C++ internals when a stream is closed and
// needs to be destroyed on the JavaScript side.
function onStreamClose(id, appErrorCode) {
this[owner_symbol][kStreamClose](id, appErrorCode);
}
// Called by the C++ internals when a stream has been reset
function onStreamReset(id, appErrorCode) {
this[owner_symbol][kStreamReset](id, appErrorCode);
}
// Called when an error occurs in a QuicStream
function onStreamError(streamHandle, error) {
streamHandle[owner_symbol].destroy(error);
}
// Called when a block of headers has been fully
// received for the stream. Not all QuicStreams
// will support headers. The headers argument
// here is an Array of name-value pairs.
function onStreamHeaders(id, headers, kind, push_id) {
this[owner_symbol][kHeaders](id, headers, kind, push_id);
}
// When a stream is flow control blocked, causes a blocked event
// to be emitted. This is a purely informational event.
function onStreamBlocked() {
process.nextTick(emit.bind(this[owner_symbol], 'blocked'));
}
// Register the callbacks with the QUIC internal binding.
setCallbacks({
onSocketClose,
onSocketServerBusy,
onSessionReady,
onSessionCert,
onSessionStatus,
onSessionClientHello,
onSessionClose,
onSessionHandshake,
onSessionKeylog,
onSessionQlog,
onSessionTicket,
onSessionVersionNegotiation,
onStreamReady,
onStreamClose,
onStreamError,
onStreamReset,
onSessionPathValidation,
onSessionUsePreferredAddress,
onStreamHeaders,
onStreamBlocked,
});
// Creates the SecureContext used by QuicSocket instances that are listening
// for new connections.
function createSecureContext(options, init_cb) {
const sc_options = validateCreateSecureContextOptions(options);
const { groups, earlyData } = sc_options;
const sc = _createSecureContext(sc_options);
// TODO(@jasnell): Determine if it's really necessary to pass in groups here.
init_cb(sc.context, groups, earlyData);
return sc;
}
function onNewListener(event) {
toggleListeners(this[kInternalState].state, event, true);
}
function onRemoveListener(event) {
toggleListeners(this[kInternalState].state, event, false);
}
function getStats(obj, idx) {
const stats = obj[kHandle]?.stats || obj[kInternalState].stats;
// If stats is undefined at this point, it's just a bug
assert(stats);
return stats[idx];
}
function addressOrLocalhost(address, type) {
return address || (type === AF_INET6 ? '::' : '0.0.0.0');
}
function deferredClosePromise(state) {
return state.closePromise = new Promise((resolve, reject) => {
state.closePromiseResolve = resolve;
state.closePromiseReject = reject;
}).finally(() => {
state.closePromise = undefined;
state.closePromiseResolve = undefined;
state.closePromiseReject = undefined;
});
}
async function resolvePreferredAddress(lookup, preferredAddress) {
if (preferredAddress === undefined)
return {};
const {
address,
port,
type = 'udp4'
} = { ...preferredAddress };
const [typeVal] = getSocketType(type);
const {
address: ip
} = await lookup(address, typeVal === AF_INET6 ? 6 : 4);
return { ip, port, type };
}
// QuicEndpoint wraps a UDP socket and is owned
// by a QuicSocket. It does not exist independently
// of the QuicSocket.
class QuicEndpoint {
[kInternalState] = {
state: kSocketUnbound,
bindPromise: undefined,
closePromise: undefined,
closePromiseResolve: undefined,
closePromiseReject: undefined,
socket: undefined,
udpSocket: undefined,
address: undefined,
ipv6Only: undefined,
lookup: undefined,
port: undefined,
reuseAddr: undefined,
type: undefined,
fd: undefined
};
constructor(socket, options) {
const {
address,
ipv6Only,
lookup,
port = 0,
reuseAddr,
type,
preferred,
} = validateQuicEndpointOptions(options);
const state = this[kInternalState];
state.socket = socket;
state.address = addressOrLocalhost(address, type);
state.lookup = lookup;
state.ipv6Only = ipv6Only;
state.port = port;
state.reuseAddr = reuseAddr;
state.type = type;
state.udpSocket = dgram.createSocket(type === AF_INET6 ? 'udp6' : 'udp4');
// kUDPHandleForTesting is only used in the Node.js test suite to
// artificially test the endpoint. This code path should never be
// used in user code.
if (typeof options[kUDPHandleForTesting] === 'object') {
state.udpSocket.bind(options[kUDPHandleForTesting]);
state.state = kSocketBound;
state.socket[kEndpointBound](this);
}
const udpHandle = state.udpSocket[internalDgram.kStateSymbol].handle;
const handle = new QuicEndpointHandle(socket[kHandle], udpHandle);
handle[owner_symbol] = this;
this[kHandle] = handle;
socket[kHandle].addEndpoint(handle, preferred);
}
[kInspect](depth, options) {
return customInspect(this, {
address: this.address,
fd: this.fd,
type: this[kInternalState].type === AF_INET6 ? 'udp6' : 'udp4',
destroyed: this.destroyed,
bound: this.bound,
pending: this.pending,
}, depth, options);
}
bind(options) {
const state = this[kInternalState];
if (state.bindPromise !== undefined)
return state.bindPromise;
return state.bindPromise = this[kBind]().finally(() => {
state.bindPromise = undefined;
});
}
// Binds the QuicEndpoint to the local port. Returns a Promise
// that is resolved once the QuicEndpoint binds, or rejects if
// binding was not successful. Calling bind() multiple times
// before the Promise is resolved will return the same Promise.
// Calling bind() after the endpoint is already bound will
// immediately return a resolved promise. Calling bind() after
// the endpoint has been destroyed will cause the Promise to
// be rejected.
async [kBind](options) {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
if (state.state !== kSocketUnbound)
return this.address;
const { signal } = { ...options };
if (signal != null && !('aborted' in signal))
throw new ERR_INVALID_ARG_TYPE('options.signal', 'AbortSignal', signal);
// If an AbotSignal was passed in, check to make sure it is not already
// aborted before we continue on to do any work.
if (signal && signal.aborted)
throw new lazyDOMException('AbortError');
state.state = kSocketPending;
const {
address: ip
} = await state.lookup(state.address, state.type === AF_INET6 ? 6 : 4);
// It's possible for the QuicEndpoint to have been destroyed while
// we were waiting for the DNS lookup to complete. If so, reject
// the Promise.
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint was destroyed');
// If an AbortSignal was passed in, check to see if it was triggered
// while we were waiting.
if (signal && signal.aborted) {
state.state = kSocketUnbound;
throw new lazyDOMException('AbortError');
}
// From here on, any errors are fatal for the QuicEndpoint. Keep in
// mind that this means that the Bind Promise will be rejected *and*
// the QuicEndpoint will be destroyed with an error.
try {
const udpHandle = state.udpSocket[internalDgram.kStateSymbol].handle;
if (udpHandle == null) {
// It's not clear what cases trigger this but it is possible.
throw new ERR_OPERATION_FAILED('Acquiring UDP socket handle failed');
}
const flags =
(state.reuseAddr ? UV_UDP_REUSEADDR : 0) |
(state.ipv6Only ? UV_UDP_IPV6ONLY : 0);
const ret = udpHandle.bind(ip, state.port, flags);
if (ret)
throw exceptionWithHostPort(ret, 'bind', ip, state.port);
// On Windows, the fd will be meaningless, but we always record it.
state.fd = udpHandle.fd;
state.state = kSocketBound;
return this.address;
} catch (error) {
this.destroy(error);
throw error;
}
}
destroy(error) {
if (this.destroyed)
return;
const state = this[kInternalState];
state.state = kSocketDestroyed;
const handle = this[kHandle];
if (handle === undefined)
return;
this[kHandle] = undefined;
handle[owner_symbol] = undefined;
// Calling waitForPendingCallbacks starts the process of
// closing down the QuicEndpoint. Once all pending writes
// to the underlying libuv udp handle have completed, the
// ondone callback will be invoked, triggering the UDP
// socket to be closed. Once it is closed, we notify
// the QuicSocket that this QuicEndpoint has been closed,
// allowing it to be freed.
handle.ondone = () => {
state.udpSocket.close((err) => {
if (err) error = err;
if (error && typeof state.closePromiseReject === 'function')
state.closePromiseReject(error);
else if (typeof state.closePromiseResolve === 'function')
state.closePromiseResolve();
state.socket[kEndpointClose](this, error);
});
};
handle.waitForPendingCallbacks();
}
// Closes the QuicEndpoint. Returns a Promise that is resolved
// once the QuicEndpoint closes, or rejects if it closes with
// an error. Calling close() multiple times before the Promise
// is resolved will return the same Promise. Calling close()
// after will return a rejected Promise.
close() {
return this[kInternalState].closePromise || this[kClose]();
}
[kClose]() {
if (this.destroyed) {
return PromiseReject(
new ERR_INVALID_STATE('QuicEndpoint is already destroyed'));
}
const promise = deferredClosePromise(this[kInternalState]);
this.destroy();
return promise;
}
// If the QuicEndpoint is bound, returns an object detailing
// the local IP address, port, and address type to which it
// is bound. Otherwise, returns an empty object.
get address() {
const state = this[kInternalState];
if (state.state !== kSocketDestroyed) {
try {
return state.udpSocket.address();
} catch (err) {
if (err.code === 'EBADF') {
// If there is an EBADF error, the socket is not bound.
// Return empty object. Else, rethrow the error because
// something else bad happened.
return {};
}
throw err;
}
}
return {};
}
// On Windows, this always returns undefined.
get fd() {
return this[kInternalState].fd >= 0 ?
this[kInternalState].fd : undefined;
}
// True if the QuicEndpoint has been destroyed and is
// no longer usable.
get destroyed() {
return this[kInternalState].state === kSocketDestroyed;
}
// True if binding has been initiated and is in progress.
get pending() {
return this[kInternalState].state === kSocketPending;
}
// True if the QuicEndpoint has been bound to the localUDP port.
get bound() {
return this[kInternalState].state === kSocketBound;
}
setTTL(ttl) {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.setTTL(ttl);
return this;
}
setMulticastTTL(ttl) {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.setMulticastTTL(ttl);
return this;
}
setBroadcast(on = true) {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.setBroadcast(on);
return this;
}
setMulticastLoopback(on = true) {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.setMulticastLoopback(on);
return this;
}
setMulticastInterface(iface) {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.setMulticastInterface(iface);
return this;
}
addMembership(address, iface) {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.addMembership(address, iface);
return this;
}
dropMembership(address, iface) {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.dropMembership(address, iface);
return this;
}
ref() {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.ref();
return this;
}
unref() {
const state = this[kInternalState];
if (this.destroyed)
throw new ERR_INVALID_STATE('QuicEndpoint is already destroyed');
state.udpSocket.unref();
return this;
}
}
// QuicSocket wraps a UDP socket plus the associated TLS context and QUIC
// Protocol state. There may be *multiple* QUIC connections (QuicSession)
// associated with a single QuicSocket.
class QuicSocket extends EventEmitter {
[kInternalState] = {
alpn: undefined,
bindPromise: undefined,
client: undefined,
closePromise: undefined,
closePromiseResolve: undefined,
closePromiseReject: undefined,
defaultEncoding: undefined,
endpoints: new Set(),
highWaterMark: undefined,
listenPending: false,
listenPromise: undefined,
lookup: undefined,
ocspHandler: undefined,
clientHelloHandler: undefined,
server: undefined,
serverSecureContext: undefined,
sessions: new Set(),
state: kSocketUnbound,
sharedState: undefined,
stats: undefined,
};
constructor(options) {
const {
endpoint,
// Default configuration for QuicClientSessions
client,
// The maximum number of connections
maxConnections,
// The maximum number of connections per host
maxConnectionsPerHost,
// The maximum number of stateless resets per host
maxStatelessResetsPerHost,
// The maximum number of seconds for retry token
retryTokenTimeout,
// The DNS lookup function
lookup,
// Default configuration for QuicServerSessions
server,
// True if address verification should be used.
validateAddress,
// True if an LRU should be used for add validation
validateAddressLRU,
// Whether qlog should be enabled for sessions
qlog,
// Stateless reset token secret (16 byte buffer)
statelessResetSecret,
// When true, stateless resets will not be sent (default false)
disableStatelessReset,
} = validateQuicSocketOptions(options);
super({ captureRejections: true });
const state = this[kInternalState];
state.client = client;
state.server = server;
state.lookup = lookup;
let socketOptions = 0;
if (validateAddress)
socketOptions |= (1 << QUICSOCKET_OPTIONS_VALIDATE_ADDRESS);
if (validateAddressLRU)
socketOptions |= (1 << QUICSOCKET_OPTIONS_VALIDATE_ADDRESS_LRU);
this[kSetHandle](
new QuicSocketHandle(
socketOptions,
retryTokenTimeout,
maxConnections,
maxConnectionsPerHost,
maxStatelessResetsPerHost,
qlog,
statelessResetSecret,
disableStatelessReset));
this.addEndpoint({ ...endpoint, preferred: true });
}
[kRejections](err, eventname, ...args) {
switch (eventname) {
case 'session':
const session = args[0];
session.destroy(err);
process.nextTick(() => {
this.emit('sessionError', err, session);
});
return;
default:
// Fall through
}
this.destroy(err);
}
get [kStreamOptions]() {
const state = this[kInternalState];
return {