-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathquic.js
More file actions
5149 lines (4709 loc) Β· 166 KB
/
quic.js
File metadata and controls
5149 lines (4709 loc) Β· 166 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
'use strict';
// TODO(@jasnell) Temporarily ignoring c8 covrerage for this file while tests
// are still being developed.
/* c8 ignore start */
const {
ArrayIsArray,
ArrayPrototypePush,
BigInt,
DataViewPrototypeGetByteLength,
FunctionPrototypeBind,
Number,
ObjectDefineProperties,
ObjectKeys,
PromisePrototypeThen,
PromiseResolve,
PromiseWithResolvers,
SafeSet,
Symbol,
SymbolAsyncDispose,
SymbolAsyncIterator,
SymbolDispose,
SymbolIterator,
TypedArrayPrototypeGetByteLength,
Uint8Array,
} = primordials;
const {
getOptionValue,
} = require('internal/options');
// QUIC requires that Node.js be compiled with crypto support.
if (!process.features.quic || !getOptionValue('--experimental-quic')) {
return;
}
const { inspect } = require('internal/util/inspect');
let debug = require('internal/util/debuglog').debuglog('quic', (fn) => {
debug = fn;
});
const {
Endpoint: Endpoint_,
setCallbacks,
// The constants to be exposed to end users for various options.
CC_ALGO_RENO_STR: CC_ALGO_RENO,
CC_ALGO_CUBIC_STR: CC_ALGO_CUBIC,
CC_ALGO_BBR_STR: CC_ALGO_BBR,
DEFAULT_CIPHERS,
DEFAULT_GROUPS,
// Internal constants for use by the implementation.
// These are not exposed to end users.
PREFERRED_ADDRESS_IGNORE: kPreferredAddressIgnore,
PREFERRED_ADDRESS_USE: kPreferredAddressUse,
DEFAULT_PREFERRED_ADDRESS_POLICY: kPreferredAddressDefault,
STREAM_DIRECTION_BIDIRECTIONAL: kStreamDirectionBidirectional,
STREAM_DIRECTION_UNIDIRECTIONAL: kStreamDirectionUnidirectional,
CLOSECONTEXT_CLOSE: kCloseContextClose,
CLOSECONTEXT_BIND_FAILURE: kCloseContextBindFailure,
CLOSECONTEXT_LISTEN_FAILURE: kCloseContextListenFailure,
CLOSECONTEXT_RECEIVE_FAILURE: kCloseContextReceiveFailure,
CLOSECONTEXT_SEND_FAILURE: kCloseContextSendFailure,
CLOSECONTEXT_START_FAILURE: kCloseContextStartFailure,
QUIC_STREAM_HEADERS_KIND_INITIAL: kHeadersKindInitial,
QUIC_STREAM_HEADERS_KIND_HINTS: kHeadersKindHints,
QUIC_STREAM_HEADERS_KIND_TRAILING: kHeadersKindTrailing,
QUIC_STREAM_HEADERS_FLAGS_NONE: kHeadersFlagsNone,
QUIC_STREAM_HEADERS_FLAGS_TERMINAL: kHeadersFlagsTerminal,
} = internalBinding('quic');
// Maps the numeric HeadersKind constants from C++ to user-facing strings.
// Indexed by the enum value (HINTS=0, INITIAL=1, TRAILING=2).
const kHeadersKindName = [];
kHeadersKindName[kHeadersKindHints] = 'hints';
kHeadersKindName[kHeadersKindInitial] = 'initial';
kHeadersKindName[kHeadersKindTrailing] = 'trailing';
const {
markPromiseAsHandled,
} = internalBinding('util');
const {
isArrayBuffer,
isArrayBufferView,
isDataView,
isPromise,
isSharedArrayBuffer,
} = require('util/types');
const {
Buffer,
} = require('buffer');
const {
codes: {
ERR_ILLEGAL_CONSTRUCTOR,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_INVALID_STATE,
ERR_INVALID_THIS,
ERR_MISSING_ARGS,
ERR_OUT_OF_RANGE,
ERR_QUIC_CONNECTION_FAILED,
ERR_QUIC_ENDPOINT_CLOSED,
ERR_QUIC_OPEN_STREAM_FAILED,
ERR_QUIC_STREAM_ABORTED,
ERR_QUIC_STREAM_RESET,
ERR_QUIC_VERSION_NEGOTIATION_ERROR,
},
} = require('internal/errors');
const {
InternalSocketAddress,
SocketAddress,
kHandle: kSocketAddressHandle,
} = require('internal/socketaddress');
const {
createBlobReaderIterable,
isBlob,
kHandle: kBlobHandle,
} = require('internal/blob');
const {
drainableProtocol,
kValidatedSource,
} = require('internal/streams/iter/types');
const {
toUint8Array,
convertChunks,
} = require('internal/streams/iter/utils');
const {
from: streamFrom,
fromSync: streamFromSync,
} = require('internal/streams/iter/from');
const {
getKeyObjectHandle,
getKeyObjectType,
isKeyObject,
} = require('internal/crypto/keys');
const {
FileHandle,
kHandle: kFileHandle,
kLocked: kFileLocked,
} = require('internal/fs/promises');
const {
validateAbortSignal,
validateBoolean,
validateFunction,
validateInteger,
validateObject,
validateOneOf,
validateString,
} = require('internal/validators');
const {
buildNgHeaderString,
assertValidPseudoHeader,
} = require('internal/http2/util');
const kEmptyObject = { __proto__: null };
const {
kAttachFileHandle,
kBlocked,
kConnect,
kDatagram,
kDatagramStatus,
kDrain,
kEarlyDataRejected,
kFinishClose,
kGoaway,
kHandshake,
kHandshakeCompleted,
kHeaders,
kOwner,
kRemoveSession,
kKeylog,
kListen,
kNewSession,
kQlog,
kRemoveStream,
kNewStream,
kNewToken,
kOrigin,
kStreamCallbacks,
kPathValidation,
kPrivateConstructor,
kReset,
kSendHeaders,
kSessionTicket,
kTrailers,
kVersionNegotiation,
kInspect,
kWantsHeaders,
kWantsTrailers,
} = require('internal/quic/symbols');
const {
QuicEndpointStats,
QuicStreamStats,
QuicSessionStats,
} = require('internal/quic/stats');
const {
QuicEndpointState,
QuicSessionState,
QuicStreamState,
} = require('internal/quic/state');
const assert = require('internal/assert');
const {
hasObserver,
startPerf,
stopPerf,
} = require('internal/perf/observe');
const kPerfEntry = Symbol('kPerfEntry');
const {
onEndpointCreatedChannel,
onEndpointListeningChannel,
onEndpointClosingChannel,
onEndpointClosedChannel,
onEndpointErrorChannel,
onEndpointBusyChangeChannel,
onEndpointClientSessionChannel,
onEndpointServerSessionChannel,
onSessionOpenStreamChannel,
onSessionReceivedStreamChannel,
onSessionSendDatagramChannel,
onSessionUpdateKeyChannel,
onSessionClosingChannel,
onSessionClosedChannel,
onSessionReceiveDatagramChannel,
onSessionReceiveDatagramStatusChannel,
onSessionPathValidationChannel,
onSessionNewTokenChannel,
onSessionTicketChannel,
onSessionVersionNegotiationChannel,
onSessionOriginChannel,
onSessionHandshakeChannel,
onSessionGoawayChannel,
onSessionEarlyRejectedChannel,
onStreamClosedChannel,
onStreamHeadersChannel,
onStreamTrailersChannel,
onStreamInfoChannel,
onStreamResetChannel,
onStreamBlockedChannel,
onSessionErrorChannel,
onEndpointConnectChannel,
} = require('internal/quic/diagnostics');
const kNilDatagramId = 0n;
// Module-level registry of all live QuicEndpoint instances. Used by
// connect() and listen() to find existing endpoints for reuse instead
// of creating a new one per session.
const endpointRegistry = new SafeSet();
/**
* @typedef {import('../socketaddress.js').SocketAddress} SocketAddress
* @typedef {import('../crypto/keys.js').KeyObject} KeyObject
*/
/**
* @typedef {object} OpenStreamOptions
* @property {string|ArrayBuffer|SharedArrayBuffer|ArrayBufferView|Blob|
* FileHandle|AsyncIterable|Iterable|Promise|null} [body] The outbound
* body source. See the public docs for `stream.setBody()` for details
* on supported types. When omitted, the stream is closed immediately.
* @property {object} [headers] Initial request or response headers to
* send. Only used when the negotiated application supports headers
* (e.g. HTTP/3).
* @property {'high'|'default'|'low'} [priority] The priority level of the stream.
* @property {boolean} [incremental] Whether to interleave data with same-priority streams.
* @property {number} [highWaterMark] The high water mark for write
* backpressure, in bytes. **Default:** `65536`.
* @property {OnHeadersCallback} [onheaders] Callback for incoming initial headers
* @property {OnTrailersCallback} [ontrailers] Callback for incoming trailing headers
* @property {OnInfoCallback} [oninfo] Callback for informational (1xx) headers
* @property {OnWantTrailersCallback} [onwanttrailers] Callback fired when the
* transport is ready to send trailers for this stream.
*/
/**
* Provides the configuration options for a QuicEndpoint.
* @typedef {object} EndpointOptions
* @property {SocketAddress|string} [address] The local address to bind to
* @property {bigint|number} [addressLRUSize] The size of the address LRU cache
* @property {'reno'|'cubic'|'bbr'} [cc] The congestion control algorithm
* @property {boolean} [disableStatelessReset] When true, the endpoint will not send stateless resets
* @property {bigint|number} [idleTimeout] The default idle timeout for sessions on this endpoint
* @property {boolean} [ipv6Only] Use IPv6 only
* @property {bigint|number} [maxConnectionsPerHost] The maximum number of connections per host
* @property {bigint|number} [maxConnectionsTotal] The maximum number of total connections
* @property {bigint|number} [maxRetries] The maximum number of retries
* @property {bigint|number} [maxStatelessResetsPerHost] The maximum number of stateless resets per host
* @property {ArrayBufferView} [resetTokenSecret] The reset token secret
* @property {bigint|number} [retryTokenExpiration] The retry token expiration
* @property {number} [rxDiagnosticLoss] The receive diagnostic loss probability (range 0.0-1.0)
* @property {bigint|number} [tokenExpiration] The token expiration
* @property {ArrayBufferView} [tokenSecret] The token secret
* @property {number} [txDiagnosticLoss] The transmit diagnostic loss probability (range 0.0-1.0)
* @property {number} [udpReceiveBufferSize] The UDP receive buffer size
* @property {number} [udpSendBufferSize] The UDP send buffer size
* @property {number} [udpTTL] The UDP TTL
* @property {boolean} [validateAddress] Validate the address using retry packets
*/
/**
* @typedef {object} TransportParams
* @property {SocketAddress} [preferredAddressIpv4] The preferred IPv4 address
* @property {SocketAddress} [preferredAddressIpv6] The preferred IPv6 address
* @property {bigint|number} [initialMaxStreamDataBidiLocal] The initial maximum stream data bidirectional local
* @property {bigint|number} [initialMaxStreamDataBidiRemote] The initial maximum stream data bidirectional remote
* @property {bigint|number} [initialMaxStreamDataUni] The initial maximum stream data unidirectional
* @property {bigint|number} [initialMaxData] The initial maximum data
* @property {bigint|number} [initialMaxStreamsBidi] The initial maximum streams bidirectional
* @property {bigint|number} [initialMaxStreamsUni] The initial maximum streams unidirectional
* @property {bigint|number} [maxIdleTimeout] The maximum idle timeout
* @property {bigint|number} [activeConnectionIDLimit] The active connection ID limit
* @property {bigint|number} [ackDelayExponent] The acknowledgment delay exponent
* @property {bigint|number} [maxAckDelay] The maximum acknowledgment delay
* @property {bigint|number} [maxDatagramFrameSize] The maximum datagram frame size
*/
/**
* @typedef {object} ApplicationOptions
* @property {bigint|number} [maxHeaderPairs] The maximum header pairs
* @property {bigint|number} [maxHeaderLength] The maximum header length
* @property {bigint|number} [maxFieldSectionSize] The maximum field section size
* @property {bigint|number} [qpackMaxDTableCapacity] The qpack maximum dynamic table capacity
* @property {bigint|number} [qpackEncoderMaxDTableCapacity] The qpack encoder maximum dynamic table capacity
* @property {bigint|number} [qpackBlockedStreams] The qpack blocked streams
* @property {boolean} [enableConnectProtocol] Enable the connect protocol
* @property {boolean} [enableDatagrams] Enable datagrams
*/
/**
* Per-identity TLS options. Used as the values in the `sni` map of
* `SessionOptions` for server endpoints.
* @typedef {object} IdentityOptions
* @property {KeyObject|KeyObject[]} keys The TLS private keys.
* @property {ArrayBuffer|ArrayBufferView|Array<ArrayBuffer|ArrayBufferView>} certs The TLS certificates.
* @property {boolean} [verifyPrivateKey] Verify the private key.
* **Default:** `false`.
* @property {number} [port] The port to advertise in HTTP/3 ORIGIN frames
* for this host name. **Default:** `443`.
* @property {boolean} [authoritative] Whether to include this host name
* in HTTP/3 ORIGIN frames. **Default:** `true`. Wildcard (`'*'`)
* entries are always excluded regardless of this setting.
*/
/**
* @typedef {object} SessionOptions
* @property {EndpointOptions|QuicEndpoint} [endpoint] An endpoint to use.
* @property {boolean} [reuseEndpoint] When `true` (default), `connect()`
* will attempt to reuse an existing endpoint rather than create a new
* one. Has no effect for server sessions.
* @property {number} [version] The QUIC version
* @property {number} [minVersion] The minimum acceptable QUIC version
* @property {'use'|'ignore'|'default'} [preferredAddressPolicy] The preferred address policy
* @property {ApplicationOptions} [application] The application options
* @property {TransportParams} [transportParams] The transport parameters
* @property {string} [servername] The server name identifier (client only)
* @property {string|string[]} [alpn] The ALPN protocol identifier(s).
* For client sessions, a single string. For server sessions, an array
* of protocol names in preference order.
* @property {string} [ciphers] The TLS ciphers
* @property {string} [groups] The TLS key-exchange groups
* @property {boolean} [keylog] Enable TLS key logging
* @property {boolean} [verifyClient] Verify the client certificate (server only)
* @property {boolean} [tlsTrace] Enable TLS tracing
* @property {boolean} [enableEarlyData] Enable 0-RTT early data.
* **Default:** `true`.
* @property {boolean} [rejectUnauthorized] Verify the peer certificate
* against the supplied CAs. **Default:** `true`.
* @property {boolean} [verifyPrivateKey] Verify the private key (client only)
* @property {KeyObject|KeyObject[]} [keys] The TLS private keys (client only)
* @property {ArrayBuffer|ArrayBufferView|Array<ArrayBuffer|ArrayBufferView>} [certs] The TLS certificates (client only)
* @property {ArrayBuffer|ArrayBufferView|Array<ArrayBuffer|ArrayBufferView>} [ca] The certificate authority
* @property {ArrayBuffer|ArrayBufferView|Array<ArrayBuffer|ArrayBufferView>} [crl] The certificate revocation list
* @property {{[key: string]: IdentityOptions}} [sni] Map of host names to
* per-identity TLS options for Server Name Indication. Required for
* server sessions. The special key `'*'` specifies the optional
* default/fallback identity.
* @property {boolean} [qlog] Enable qlog
* @property {ArrayBufferView} [sessionTicket] A session ticket from a
* prior session, used to resume that session (client only).
* @property {ArrayBufferView} [token] An opaque address validation token
* previously received from the server via `onnewtoken` (client only).
* @property {bigint|number} [handshakeTimeout] The handshake timeout
* @property {bigint|number} [keepAlive] The keep-alive timeout in milliseconds. When set,
* PING frames will be sent automatically to prevent idle timeout.
* @property {bigint|number} [maxStreamWindow] The maximum stream window
* @property {bigint|number} [maxWindow] The maximum connection window
* @property {bigint|number} [maxPayloadSize] The maximum payload size
* @property {bigint|number} [unacknowledgedPacketThreshold] The unacknowledged packet threshold
* @property {'reno'|'cubic'|'bbr'} [cc] The congestion control algorithm
* @property {'drop-oldest'|'drop-newest'} [datagramDropPolicy] The
* policy used when the pending datagram queue is full.
* **Default:** `'drop-oldest'`.
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
* **Default:** `3`.
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
* datagram is retried before being abandoned. Range `1..255`.
* **Default:** `5`.
* @property {OnSessionErrorCallback} [onerror] Session error callback.
* @property {OnStreamCallback} [onstream] Incoming stream callback.
* @property {OnDatagramCallback} [ondatagram] Incoming datagram callback.
* @property {OnDatagramStatusCallback} [ondatagramstatus] Outgoing datagram status callback.
* @property {OnPathValidationCallback} [onpathvalidation] Path validation callback.
* @property {OnSessionTicketCallback} [onsessionticket] New session-ticket callback.
* @property {OnVersionNegotiationCallback} [onversionnegotiation] Version negotiation callback.
* @property {OnHandshakeCallback} [onhandshake] Handshake-completed callback.
* @property {OnNewTokenCallback} [onnewtoken] NEW_TOKEN frame callback (client only).
* @property {OnOriginCallback} [onorigin] ORIGIN frame callback (client only).
* @property {OnGoawayCallback} [ongoaway] GOAWAY frame callback.
* @property {OnKeylogCallback} [onkeylog] TLS key-log callback.
* @property {OnQlogCallback} [onqlog] qlog data callback.
* @property {OnHeadersCallback} [onheaders] Default per-stream initial-headers callback.
* @property {OnTrailersCallback} [ontrailers] Default per-stream trailing-headers callback.
* @property {OnInfoCallback} [oninfo] Default per-stream informational-headers callback.
* @property {OnWantTrailersCallback} [onwanttrailers] Default per-stream
* want-trailers callback.
*/
/**
* @typedef {object} Datagrams
* @property {ReadableStream} readable The readable stream
* @property {WritableStream} writable The writable stream
*/
/**
* @typedef {object} Path
* @property {SocketAddress} local The local address
* @property {SocketAddress} remote The remote address
*/
/**
* @typedef {object} QuicSessionInfo
* @property {SocketAddress} local The local address
* @property {SocketAddress} remote The remote address
* @property {string} protocol The alpn protocol identifier negotiated for this session
* @property {string} servername The servername identifier for this session
* @property {string} cipher The cipher suite negotiated for this session
* @property {string} cipherVersion The version of the cipher suite negotiated for this session
* @property {string} [validationErrorReason] The reason the session failed validation (if any)
* @property {string} [validationErrorCode] The error code for the validation failure (if any)
*/
/**
* Called when the Endpoint receives a new server-side Session.
* @callback OnSessionCallback
* @this {QuicEndpoint}
* @param {QuicSession} session
* @returns {void}
*/
/**
* Called when a session is destroyed with an error.
* @callback OnSessionErrorCallback
* @this {QuicSession}
* @param {any} error
* @returns {void}
*/
/**
* @callback OnStreamCallback
* @this {QuicSession}
* @param {QuicStream} stream
* @returns {void}
*/
/**
* @callback OnDatagramCallback
* @this {QuicSession}
* @param {Uint8Array} datagram
* @param {boolean} early A datagram is early if it was received before the TLS handshake completed
* @returns {void}
*/
/**
* Called when the status of a previously sent datagram is reported.
* @callback OnDatagramStatusCallback
* @this {QuicSession}
* @param {bigint} id The datagram id
* @param {'acknowledged'|'lost'|'abandoned'} status
* @returns {void}
*/
/**
* Called when QUIC path validation completes (or fails).
* @callback OnPathValidationCallback
* @this {QuicSession}
* @param {'success'|'failure'|'aborted'} result
* @param {SocketAddress} newLocalAddress
* @param {SocketAddress} newRemoteAddress
* @param {SocketAddress|null} oldLocalAddress
* @param {SocketAddress|null} oldRemoteAddress
* @param {boolean} [preferredAddress] `true` if the validation was triggered
* by a preferred-address migration on the client side.
* @returns {void}
*/
/**
* @callback OnSessionTicketCallback
* @this {QuicSession}
* @param {object} ticket
* @returns {void}
*/
/**
* Called when the server responds with a Version Negotiation packet.
* The session is destroyed immediately after this returns.
* @callback OnVersionNegotiationCallback
* @this {QuicSession}
* @param {number} version The QUIC version configured for this session
* @param {number[]} requestedVersions The versions advertised by the server
* @param {number[]} supportedVersions A `[minVersion, maxVersion]` pair
* @returns {void}
*/
/**
* Called when the TLS handshake completes successfully.
* @callback OnHandshakeCallback
* @this {QuicSession}
* @param {string} sni
* @param {string} alpn
* @param {string} cipher
* @param {string} cipherVersion
* @param {string} [validationErrorReason]
* @param {number} [validationErrorCode]
* @param {boolean} earlyDataAttempted
* @param {boolean} earlyDataAccepted
* @returns {void}
*/
/**
* Called when the server issues a NEW_TOKEN frame to the client.
* @callback OnNewTokenCallback
* @this {QuicSession}
* @param {Buffer} token The opaque token data
* @param {SocketAddress} address The remote server address
* @returns {void}
*/
/**
* Called when the server sends an ORIGIN frame.
* @callback OnOriginCallback
* @this {QuicSession}
* @param {string[]} origins The list of origins the server claims authority for
* @returns {void}
*/
/**
* Called when the peer sends a GOAWAY frame (HTTP/3 only).
* @callback OnGoawayCallback
* @this {QuicSession}
* @param {bigint} lastStreamId The highest stream ID the peer may have processed
* @returns {void}
*/
/**
* Called when TLS key-log material is available. Only fires when
* `sessionOptions.keylog` is `true`.
* @callback OnKeylogCallback
* @this {QuicSession}
* @param {string} line A single NSS Key Log Format line, including trailing newline.
* @returns {void}
*/
/**
* Called when qlog diagnostic data is available. Only fires when
* `sessionOptions.qlog` is `true`.
* @callback OnQlogCallback
* @this {QuicSession}
* @param {string} data A chunk of JSON-SEQ formatted qlog data
* @param {boolean} fin `true` if this is the final qlog chunk for the session.
* @returns {void}
*/
/**
* @callback OnBlockedCallback
* @this {QuicStream}
* @returns {void}
*/
/**
* @callback OnStreamErrorCallback
* @this {QuicStream}
* @param {any} error
* @returns {void}
*/
/**
* Called when initial request or response headers are received.
* @callback OnHeadersCallback
* @this {QuicStream}
* @param {object} headers Header object with lowercase string keys and
* string or string-array values.
* @returns {void}
*/
/**
* Called when trailing headers are received from the peer.
* @callback OnTrailersCallback
* @this {QuicStream}
* @param {object} trailers Trailing header object.
* @returns {void}
*/
/**
* Called when informational (1xx) headers are received from the server
* (e.g. 103 Early Hints).
* @callback OnInfoCallback
* @this {QuicStream}
* @param {object} headers Informational header object.
* @returns {void}
*/
/**
* Called when the transport is ready to send trailers for this stream.
* The handler should call `stream.sendTrailers(...)` (or
* `stream.sendTrailers()` with previously-set trailers) to provide them.
* @callback OnWantTrailersCallback
* @this {QuicStream}
* @returns {void}
*/
setCallbacks({
// QuicEndpoint callbacks
/**
* Called when the QuicEndpoint C++ handle has closed and we need to finish
* cleaning up the JS side.
* @param {number} context Identifies the reason the endpoint was closed.
* @param {number} status If context indicates an error, provides the error code.
*/
onEndpointClose(context, status) {
debug('endpoint close callback', status);
this[kOwner][kFinishClose](context, status);
},
/**
* Called when the QuicEndpoint C++ handle receives a new server-side session
* @param {*} session The QuicSession C++ handle
*/
onSessionNew(session) {
debug('new server session callback', this[kOwner], session);
this[kOwner][kNewSession](session);
},
// QuicSession callbacks
/**
* Called when the underlying session C++ handle is closed either normally
* or with an error.
* @param {number} errorType
* @param {number} code
* @param {string} [reason]
* @param {string} [errorName] Decoded TLS alert name when `code` is a
* CRYPTO_ERROR; otherwise undefined.
*/
onSessionClose(errorType, code, reason, errorName) {
debug('session close callback', errorType, code, reason, errorName);
this[kOwner][kFinishClose](errorType, code, reason, errorName);
},
/**
* Called when the peer sends a GOAWAY frame (HTTP/3 only).
* @param {bigint} lastStreamId The highest stream ID the peer may have
* processed. Streams above this ID were not processed and can be retried.
*/
onSessionGoaway(lastStreamId) {
debug('session goaway callback', lastStreamId);
this[kOwner][kGoaway](lastStreamId);
},
/**
* Called when a datagram is received on this session.
* @param {Uint8Array} uint8Array
* @param {boolean} early
*/
onSessionDatagram(uint8Array, early) {
debug('session datagram callback', TypedArrayPrototypeGetByteLength(uint8Array), early);
this[kOwner][kDatagram](uint8Array, early);
},
/**
* Called when the status of a datagram is received.
* @param {bigint} id
* @param {'lost' | 'acknowledged'} status
*/
onSessionDatagramStatus(id, status) {
debug('session datagram status callback', id, status);
this[kOwner][kDatagramStatus](id, status);
},
/**
* Called when the session handshake completes.
* @param {string} servername
* @param {string} protocol
* @param {string} cipher
* @param {string} cipherVersion
* @param {string} validationErrorReason
* @param {number} validationErrorCode
* @param {boolean} earlyDataAttempted
* @param {boolean} earlyDataAccepted
*/
onSessionHandshake(servername, protocol, cipher, cipherVersion,
validationErrorReason,
validationErrorCode,
earlyDataAttempted,
earlyDataAccepted) {
debug('session handshake callback', servername, protocol, cipher, cipherVersion,
validationErrorReason, validationErrorCode,
earlyDataAttempted, earlyDataAccepted);
this[kOwner][kHandshake](servername, protocol, cipher, cipherVersion,
validationErrorReason, validationErrorCode,
earlyDataAttempted, earlyDataAccepted);
},
/**
* Called when the session path validation completes.
* @param {'aborted'|'failure'|'success'} result
* @param {SocketAddress} newLocalAddress
* @param {SocketAddress} newRemoteAddress
* @param {SocketAddress} oldLocalAddress
* @param {SocketAddress} oldRemoteAddress
* @param {boolean} preferredAddress
*/
onSessionPathValidation(result, newLocalAddress, newRemoteAddress,
oldLocalAddress, oldRemoteAddress, preferredAddress) {
debug('session path validation callback', this[kOwner]);
this[kOwner][kPathValidation](result, newLocalAddress, newRemoteAddress,
oldLocalAddress, oldRemoteAddress,
preferredAddress);
},
/**
* Called when the session generates a new TLS session ticket
* @param {object} ticket An opaque session ticket
*/
onSessionTicket(ticket) {
debug('session ticket callback', this[kOwner]);
this[kOwner][kSessionTicket](ticket);
},
/**
* Called when the client receives a NEW_TOKEN frame from the server.
* The token can be used for future connections to the same server
* address to skip address validation.
* @param {Buffer} token The opaque token data
* @param {SocketAddress} address The remote server address
*/
onSessionNewToken(token, address) {
debug('session new token callback', this[kOwner]);
this[kOwner][kNewToken](token, address);
},
/**
* Called when the server rejects 0-RTT early data. All streams
* opened during the 0-RTT phase have been destroyed. The
* application should re-open streams if needed.
*/
onSessionEarlyDataRejected() {
debug('session early data rejected callback', this[kOwner]);
this[kOwner][kEarlyDataRejected]();
},
/**
* Called when the session receives an ORIGIN frame from the peer (RFC 9412).
* @param {string[]} origins The list of origins the peer claims authority for
*/
onSessionOrigin(origins) {
debug('session origin callback', this[kOwner]);
this[kOwner][kOrigin](origins);
},
/**
* Called when the session receives a session version negotiation request
* @param {*} version
* @param {*} requestedVersions
* @param {*} supportedVersions
*/
onSessionVersionNegotiation(version,
requestedVersions,
supportedVersions) {
debug('session version negotiation callback', version, requestedVersions, supportedVersions,
this[kOwner]);
this[kOwner][kVersionNegotiation](version, requestedVersions, supportedVersions);
// Note that immediately following a version negotiation event, the
// session will be destroyed.
},
onSessionKeyLog(line) {
debug('session key log callback', line, this[kOwner]);
this[kOwner][kKeylog](line);
},
onSessionQlog(data, fin) {
if (this[kOwner] === undefined) {
// Qlog data can arrive during ngtcp2_conn creation, before the
// QuicSession JS wrapper exists. Cache until the wrapper is ready.
this._pendingQlog ??= [];
this._pendingQlog.push(data, fin);
return;
}
debug('session qlog callback', this[kOwner]);
this[kOwner][kQlog](data, fin);
},
/**
* Called when a new stream has been received for the session
* @param {object} stream The QuicStream C++ handle
* @param {number} direction The stream direction (0 == bidi, 1 == uni)
*/
onStreamCreated(stream, direction) {
const session = this[kOwner];
// The event is ignored and the stream destroyed if the session has been destroyed.
debug('stream created callback', session, direction);
if (session.destroyed) {
stream.destroy();
return;
};
session[kNewStream](stream, direction);
},
// QuicStream callbacks
onStreamBlocked() {
debug('stream blocked callback', this[kOwner]);
// Called when the stream C++ handle has been blocked by flow control.
this[kOwner][kBlocked]();
},
onStreamDrain() {
// Called when the stream's outbound buffer has capacity for more data.
debug('stream drain callback', this[kOwner]);
this[kOwner][kDrain]();
},
onStreamClose(error) {
// Called when the stream C++ handle has been closed. The error is
// either undefined (clean close) or a raw array [type, code, reason]
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
if (error !== undefined) {
error = convertQuicError(error);
}
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
this[kOwner][kFinishClose](error);
},
onStreamReset(error) {
// Called when the stream C++ handle has received a stream reset.
if (error !== undefined) {
error = convertQuicError(error);
}
debug('stream reset callback', this[kOwner], error);
this[kOwner][kReset](error);
},
onStreamHeaders(headers, kind) {
// Called when the stream C++ handle has received a full block of headers.
debug(`stream ${this[kOwner].id} headers callback`, headers, kind);
this[kOwner][kHeaders](headers, kind);
},
onStreamTrailers() {
// Called when the stream C++ handle is ready to receive trailing headers.
debug('stream want trailers callback', this[kOwner]);
this[kOwner][kTrailers]();
},
});
// QUIC error codes are 62-bit varints (RFC 9000 section 16). The
// maximum representable code is 2**62 - 1.
const kMaxQuicErrorCode = (1n << 62n) - 1n;
/**
* An Error subclass that carries an explicit numeric QUIC error code.
* Use this when destroying a stream or aborting an outbound writer to
* communicate a specific application-protocol-defined error code to
* the peer. When a `QuicError` is supplied, the QUIC stack uses
* `errorCode` as the wire code for the resulting RESET_STREAM /
* STOP_SENDING / CONNECTION_CLOSE frame; otherwise the negotiated
* application's "internal error" code is used (see
* `QuicSessionState.internalErrorCode`).
*
* The Node.js error code (`error.code`) defaults to
* `'ERR_QUIC_STREAM_ABORTED'` but can be overridden via
* `options.code`. The numeric QUIC code lives on the separate
* `errorCode` property to avoid colliding with Node.js's convention
* that `error.code` is a string.
*/
class QuicError extends Error {
/** @type {bigint} */
#errorCode;
/** @type {'transport' | 'application'} */
#type;
/**
* @param {string} message
* @param {object} options
* @param {bigint|number} options.errorCode The numeric QUIC error
* code. Numbers are coerced to BigInt. Must be a non-negative
* 62-bit unsigned varint
* (`0n <= errorCode <= 2n ** 62n - 1n`).
* @param {string} [options.code] The Node.js-style error code
* string assigned to `error.code`. Defaults to
* `'ERR_QUIC_STREAM_ABORTED'`.
* @param {'transport'|'application'} [options.type] Whether the
* code is a transport-layer code (defined by RFC 9000) or an
* application-layer code (defined by the negotiated ALPN, e.g.
* RFC 9114 for HTTP/3). Defaults to `'application'`. Stream
* resets always carry application codes; this option is exposed
* for use sites that may target either layer.
*/
constructor(message, options = kEmptyObject) {
validateString(message, 'message');
validateObject(options, 'options');
const {
errorCode,
code = 'ERR_QUIC_STREAM_ABORTED',
type = 'application',
} = options;
if (errorCode === undefined) {
throw new ERR_MISSING_ARGS('options.errorCode');
}
if (typeof errorCode !== 'bigint' && typeof errorCode !== 'number') {
throw new ERR_INVALID_ARG_TYPE('options.errorCode',
['bigint', 'number'], errorCode);
}
validateString(code, 'options.code');
validateOneOf(type, 'options.type', ['transport', 'application']);
const numericCode = BigInt(errorCode);
if (numericCode < 0n || numericCode > kMaxQuicErrorCode) {
throw new ERR_OUT_OF_RANGE('options.errorCode',
`>= 0 and <= ${kMaxQuicErrorCode}`,
errorCode);
}
super(message);
this.code = code;
this.#errorCode = numericCode;
this.#type = type;
}
/** @type {bigint} */
get errorCode() {
return this.#errorCode;
}
/** @type {'transport' | 'application'} */
get type() {
return this.#type;
}
}
// Build the human-readable message for an ERR_QUIC_TRANSPORT_ERROR or
// ERR_QUIC_APPLICATION_ERROR. `errorName` is the symbolic name for
// the wire code when known: either the OpenSSL-decoded TLS alert
// (CRYPTO_ERROR; 0x100..0x1ff) or one of the named transport codes
// from RFC 9000 (e.g. PROTOCOL_VIOLATION). Otherwise undefined.
// `reason` is the peer-supplied UTF-8 reason string from the
// CONNECTION_CLOSE / RESET_STREAM frame, often empty.
function quicErrorMessage(prefix, errorCode, reason, errorName) {
let msg = `${prefix} `;
msg += errorName ? `${errorName} (${errorCode})` : `${errorCode}`;
if (reason) msg += `: ${reason}`;
return msg;
}
function makeQuicError(code, prefix, type, errorCode, reason, errorName) {
const err = new QuicError(
quicErrorMessage(prefix, errorCode, reason, errorName),
{ errorCode, code, type });
if (reason) err.reason = reason;
if (errorName) err.errorName = errorName;
return err;
}
function convertQuicError(error) {
const type = error[0];
const code = error[1];
const reason = error[2];
const errorName = error[3];
switch (type) {
case 'transport':