mirror of
https://github.com/nodejs/node.git
synced 2026-12-03 18:03:02 -05:00
quic: initial QUIC implementation
Co-authored-by: Anna Henningsen <anna@addaleax.net> Co-authored-by: Daniel Bevenius <daniel.bevenius@gmail.com> Co-authored-by: gengjiawen <technicalcute@gmail.com> Co-authored-by: James M Snell <jasnell@gmail.com> Co-authored-by: Lucas Pardue <lucaspardue.24.7@gmail.com> Co-authored-by: Ouyang Yadong <oyydoibh@gmail.com> Co-authored-by: Juan Jos<C3><A9> Arboleda <soyjuanarbol@gmail.com> Co-authored-by: Trivikram Kamat <trivikr.dev@gmail.com> Co-authored-by: Denys Otrishko <shishugi@gmail.com> PR-URL: https://github.com/nodejs/node/pull/32379 Reviewed-By: Anna Henningsen <anna@addaleax.net>
This commit is contained in:
102 files changed
+25305
-15
No files matched your search
@@ -1316,6 +1316,58 @@ The externally maintained libraries used by Node.js are:
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
"""
|
||||
|
||||
- ngtcp2, located at deps/ngtcp2, is licensed as follows:
|
||||
"""
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2016 ngtcp2 contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
"""
|
||||
|
||||
- nghttp3, located at deps/nghttp3, is licensed as follows:
|
||||
"""
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2019 nghttp3 contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
"""
|
||||
|
||||
- node-inspect, located at deps/node-inspect, is licensed as follows:
|
||||
"""
|
||||
Copyright Node.js contributors. All rights reserved.
|
||||
|
||||
@@ -122,6 +122,11 @@ parser.add_option('--error-on-warn',
|
||||
dest='error_on_warn',
|
||||
help='Turn compiler warnings into errors for node core sources.')
|
||||
|
||||
parser.add_option('--experimental-quic',
|
||||
action='store_true',
|
||||
dest='experimental_quic',
|
||||
help='enable experimental quic support')
|
||||
|
||||
parser.add_option('--gdb',
|
||||
action='store_true',
|
||||
dest='gdb',
|
||||
@@ -269,6 +274,48 @@ shared_optgroup.add_option('--shared-nghttp2-libpath',
|
||||
dest='shared_nghttp2_libpath',
|
||||
help='a directory to search for the shared nghttp2 DLLs')
|
||||
|
||||
shared_optgroup.add_option('--shared-ngtcp2',
|
||||
action='store_true',
|
||||
dest='shared_ngtcp2',
|
||||
help='link to a shared ngtcp2 DLL instead of static linking')
|
||||
|
||||
shared_optgroup.add_option('--shared-ngtcp2-includes',
|
||||
action='store',
|
||||
dest='shared_ngtcp2_includes',
|
||||
help='directory containing ngtcp2 header files')
|
||||
|
||||
shared_optgroup.add_option('--shared-ngtcp2-libname',
|
||||
action='store',
|
||||
dest='shared_ngtcp2_libname',
|
||||
default='ngtcp2',
|
||||
help='alternative lib name to link to [default: %default]')
|
||||
|
||||
shared_optgroup.add_option('--shared-ngtcp2-libpath',
|
||||
action='store',
|
||||
dest='shared_ngtcp2_libpath',
|
||||
help='a directory to search for the shared ngtcp2 DLLs')
|
||||
|
||||
shared_optgroup.add_option('--shared-nghttp3',
|
||||
action='store_true',
|
||||
dest='shared_nghttp3',
|
||||
help='link to a shared nghttp3 DLL instead of static linking')
|
||||
|
||||
shared_optgroup.add_option('--shared-nghttp3-includes',
|
||||
action='store',
|
||||
dest='shared_nghttp3_includes',
|
||||
help='directory containing nghttp3 header files')
|
||||
|
||||
shared_optgroup.add_option('--shared-nghttp3-libname',
|
||||
action='store',
|
||||
dest='shared_nghttp3_libname',
|
||||
default='nghttp3',
|
||||
help='alternative lib name to link to [default: %default]')
|
||||
|
||||
shared_optgroup.add_option('--shared-nghttp3-libpath',
|
||||
action='store',
|
||||
dest='shared_nghttp3_libpath',
|
||||
help='a directory to search for the shared nghttp3 DLLs')
|
||||
|
||||
shared_optgroup.add_option('--shared-openssl',
|
||||
action='store_true',
|
||||
dest='shared_openssl',
|
||||
@@ -1178,6 +1225,14 @@ def configure_node(o):
|
||||
else:
|
||||
o['variables']['debug_nghttp2'] = 'false'
|
||||
|
||||
if options.experimental_quic:
|
||||
if options.shared_openssl:
|
||||
raise Exception('QUIC requires a modified version of OpenSSL and '
|
||||
'cannot be enabled when using --shared-openssl.')
|
||||
o['variables']['experimental_quic'] = 1
|
||||
else:
|
||||
o['variables']['experimental_quic'] = 'false'
|
||||
|
||||
o['variables']['node_no_browser_globals'] = b(options.no_browser_globals)
|
||||
|
||||
o['variables']['node_shared'] = b(options.shared)
|
||||
@@ -1309,6 +1364,8 @@ def configure_openssl(o):
|
||||
without_ssl_error('--openssl-fips')
|
||||
if options.openssl_default_cipher_list:
|
||||
without_ssl_error('--openssl-default-cipher-list')
|
||||
if options.experimental_quic:
|
||||
without_ssl_error('--experimental-quic')
|
||||
return
|
||||
|
||||
if options.use_openssl_ca_store:
|
||||
|
||||
Vendored
+7
@@ -16,6 +16,13 @@
|
||||
'OPENSSL_NO_HW',
|
||||
],
|
||||
'conditions': [
|
||||
[
|
||||
# Disable building QUIC support in openssl if experimental_quic
|
||||
# is not enabled.
|
||||
'experimental_quic!=1', {
|
||||
'defines': ['OPENSSL_NO_QUIC=1'],
|
||||
}
|
||||
],
|
||||
[ 'openssl_no_asm==1', {
|
||||
'includes': ['./openssl_no_asm.gypi'],
|
||||
}, 'target_arch=="arm64" and OS=="win"', {
|
||||
|
||||
@@ -1717,6 +1717,125 @@ Accessing `Object.prototype.__proto__` has been forbidden using
|
||||
[`Object.setPrototypeOf`][] should be used to get and set the prototype of an
|
||||
object.
|
||||
|
||||
<a id="ERR_QUIC_CANNOT_SET_GROUPS"></a>
|
||||
### `ERR_QUIC_CANNOT_SET_GROUPS`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUIC_ERROR"></a>
|
||||
### `ERR_QUIC_ERROR`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUIC_TLS13_REQUIRED"></a>
|
||||
### `ERR_QUIC_TLS13_REQUIRED`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICCLIENTSESSION_FAILED"></a>
|
||||
### `ERR_QUICCLIENTSESSION_FAILED`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICCLIENTSESSION_FAILED_SETSOCKET"></a>
|
||||
### `ERR_QUICCLIENTSESSION_FAILED_SETSOCKET`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSESSION_DESTROYED"></a>
|
||||
### `ERR_QUICSESSION_DESTROYED`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSESSION_INVALID_DCID"></a>
|
||||
### `ERR_QUICSESSION_INVALID_DCID`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSESSION_UPDATEKEY"></a>
|
||||
### `ERR_QUICSESSION_UPDATEKEY`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSESSION_VERSION_NEGOTIATION"></a>
|
||||
### `ERR_QUICSESSION_VERSION_NEGOTIATION`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSOCKET_DESTROYED"></a>
|
||||
### `ERR_QUICSOCKET_DESTROYED`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSOCKET_INVALID_STATELESS_RESET_SECRET_LENGTH"></a>
|
||||
### `ERR_QUICSOCKET_INVALID_STATELESS_RESET_SECRET_LENGTH`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSOCKET_LISTENING"></a>
|
||||
### `ERR_QUICSOCKET_LISTENING`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSOCKET_UNBOUND"></a>
|
||||
### `ERR_QUICSOCKET_UNBOUND`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSTREAM_DESTROYED"></a>
|
||||
### `ERR_QUICSTREAM_DESTROYED`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSTREAM_INVALID_PUSH"></a>
|
||||
### `ERR_QUICSTREAM_INVALID_PUSH`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSTREAM_OPEN_FAILED"></a>
|
||||
### `ERR_QUICSTREAM_OPEN_FAILED`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_QUICSTREAM_UNSUPPORTED_PUSH"></a>
|
||||
### `ERR_QUICSTREAM_UNSUPPORTED_PUSH`
|
||||
|
||||
> Stability: 1 - Experimental
|
||||
|
||||
TBD
|
||||
|
||||
<a id="ERR_REQUIRE_ESM"></a>
|
||||
### `ERR_REQUIRE_ESM`
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
* [Process](process.html)
|
||||
* [Punycode](punycode.html)
|
||||
* [Query Strings](querystring.html)
|
||||
* [QUIC](quic.html)
|
||||
* [Readline](readline.html)
|
||||
* [REPL](repl.html)
|
||||
* [Report](report.html)
|
||||
|
||||
@@ -1105,6 +1105,14 @@ immediately initiates connection with
|
||||
[`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`],
|
||||
then returns the `net.Socket` that starts the connection.
|
||||
|
||||
## `net.createQuicSocket([options])`
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
Creates and returns a new `QuicSocket`. Please refer to the [QUIC documentation][]
|
||||
for details.
|
||||
|
||||
## `net.createServer([options][, connectionListener])`
|
||||
<!-- YAML
|
||||
added: v0.5.0
|
||||
@@ -1213,6 +1221,7 @@ Returns `true` if input is a version 6 IP address, otherwise returns `false`.
|
||||
[IPC]: #net_ipc_support
|
||||
[Identifying paths for IPC connections]: #net_identifying_paths_for_ipc_connections
|
||||
[Readable Stream]: stream.html#stream_class_stream_readable
|
||||
[QUIC documentation]: quic.html
|
||||
[`'close'`]: #net_event_close
|
||||
[`'connect'`]: #net_event_connect
|
||||
[`'connection'`]: #net_event_connection
|
||||
|
||||
+2277
File diff suppressed because it is too large.
Load diff
@@ -1312,6 +1312,61 @@ E('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => {
|
||||
return `Package subpath '${subpath}' is not defined by "exports" in ${
|
||||
pkgPath} imported from ${base}`;
|
||||
}, Error);
|
||||
E('ERR_QUICCLIENTSESSION_FAILED',
|
||||
'Failed to create a new QuicClientSession: %s', Error);
|
||||
E('ERR_QUICCLIENTSESSION_FAILED_SETSOCKET',
|
||||
'Failed to set the QuicSocket', Error);
|
||||
E('ERR_QUICSESSION_DESTROYED',
|
||||
'Cannot call %s after a QuicSession has been destroyed', Error);
|
||||
E('ERR_QUICSESSION_INVALID_DCID', 'Invalid DCID value: %s', Error);
|
||||
E('ERR_QUICSESSION_UPDATEKEY', 'Unable to update QuicSession keys', Error);
|
||||
E('ERR_QUICSESSION_VERSION_NEGOTIATION',
|
||||
(version, requestedVersions, supportedVersions) => {
|
||||
return 'QUIC session received version negotiation from server. ' +
|
||||
`Version: ${version}. Requested: ${requestedVersions.join(', ')} ` +
|
||||
`Supported: ${supportedVersions.join(', ')}`;
|
||||
},
|
||||
Error);
|
||||
E('ERR_QUICSOCKET_DESTROYED',
|
||||
'Cannot call %s after a QuicSocket has been destroyed', Error);
|
||||
E('ERR_QUICSOCKET_INVALID_STATELESS_RESET_SECRET_LENGTH',
|
||||
'The stateResetToken must be exactly 16-bytes in length',
|
||||
Error);
|
||||
E('ERR_QUICSOCKET_LISTENING',
|
||||
'This QuicSocket is already listening', Error);
|
||||
E('ERR_QUICSOCKET_UNBOUND',
|
||||
'Cannot call %s before a QuicSocket has been bound', Error);
|
||||
E('ERR_QUICSTREAM_DESTROYED',
|
||||
'Cannot call %s after a QuicStream has been destroyed', Error);
|
||||
E('ERR_QUICSTREAM_INVALID_PUSH',
|
||||
'Push streams are only supported on client-initiated, bidirectional streams',
|
||||
Error);
|
||||
E('ERR_QUICSTREAM_OPEN_FAILED', 'Opening a new QuicStream failed', Error);
|
||||
E('ERR_QUICSTREAM_UNSUPPORTED_PUSH',
|
||||
'Push streams are not supported on this QuicSession', Error);
|
||||
E('ERR_QUIC_ERROR', function(code, family) {
|
||||
const {
|
||||
constants: {
|
||||
QUIC_ERROR_APPLICATION,
|
||||
QUIC_ERROR_CRYPTO,
|
||||
QUIC_ERROR_SESSION,
|
||||
}
|
||||
} = internalBinding('quic');
|
||||
let familyType = 'unknown';
|
||||
switch (family) {
|
||||
case QUIC_ERROR_APPLICATION:
|
||||
familyType = 'application';
|
||||
break;
|
||||
case QUIC_ERROR_CRYPTO:
|
||||
familyType = 'crypto';
|
||||
break;
|
||||
case QUIC_ERROR_SESSION:
|
||||
familyType = 'session';
|
||||
break;
|
||||
}
|
||||
return `QUIC session closed with ${familyType} error code ${code}`;
|
||||
}, Error);
|
||||
E('ERR_QUIC_TLS13_REQUIRED', 'QUIC requires TLS version 1.3', Error);
|
||||
E('ERR_REQUIRE_ESM',
|
||||
(filename, parentPath = null, packageJsonPath = null) => {
|
||||
let msg = `Must use import to load ES Module: ${filename}`;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,773 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
NumberINFINITY,
|
||||
NumberNEGATIVE_INFINITY,
|
||||
} = primordials;
|
||||
|
||||
const {
|
||||
codes: {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_INVALID_ARG_VALUE,
|
||||
ERR_OUT_OF_RANGE,
|
||||
ERR_QUICSESSION_INVALID_DCID,
|
||||
ERR_QUICSOCKET_INVALID_STATELESS_RESET_SECRET_LENGTH,
|
||||
},
|
||||
} = require('internal/errors');
|
||||
|
||||
const assert = require('internal/assert');
|
||||
assert(process.versions.ngtcp2 !== undefined);
|
||||
|
||||
const {
|
||||
isIP,
|
||||
} = require('internal/net');
|
||||
|
||||
const {
|
||||
getOptionValue,
|
||||
getAllowUnauthorized,
|
||||
} = require('internal/options');
|
||||
|
||||
const { Buffer } = require('buffer');
|
||||
|
||||
const {
|
||||
sessionConfig,
|
||||
http3Config,
|
||||
constants: {
|
||||
AF_INET,
|
||||
AF_INET6,
|
||||
NGTCP2_ALPN_H3,
|
||||
DEFAULT_RETRYTOKEN_EXPIRATION,
|
||||
DEFAULT_MAX_CONNECTIONS,
|
||||
DEFAULT_MAX_CONNECTIONS_PER_HOST,
|
||||
DEFAULT_MAX_STATELESS_RESETS_PER_HOST,
|
||||
IDX_QUIC_SESSION_ACTIVE_CONNECTION_ID_LIMIT,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_LOCAL,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_REMOTE,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_UNI,
|
||||
IDX_QUIC_SESSION_MAX_DATA,
|
||||
IDX_QUIC_SESSION_MAX_STREAMS_BIDI,
|
||||
IDX_QUIC_SESSION_MAX_STREAMS_UNI,
|
||||
IDX_QUIC_SESSION_MAX_IDLE_TIMEOUT,
|
||||
IDX_QUIC_SESSION_MAX_ACK_DELAY,
|
||||
IDX_QUIC_SESSION_MAX_PACKET_SIZE,
|
||||
IDX_QUIC_SESSION_CONFIG_COUNT,
|
||||
IDX_QUIC_SESSION_STATE_CERT_ENABLED,
|
||||
IDX_QUIC_SESSION_STATE_CLIENT_HELLO_ENABLED,
|
||||
IDX_QUIC_SESSION_STATE_KEYLOG_ENABLED,
|
||||
IDX_QUIC_SESSION_STATE_PATH_VALIDATED_ENABLED,
|
||||
IDX_QUIC_SESSION_STATE_USE_PREFERRED_ADDRESS_ENABLED,
|
||||
IDX_HTTP3_QPACK_MAX_TABLE_CAPACITY,
|
||||
IDX_HTTP3_QPACK_BLOCKED_STREAMS,
|
||||
IDX_HTTP3_MAX_HEADER_LIST_SIZE,
|
||||
IDX_HTTP3_MAX_PUSHES,
|
||||
IDX_HTTP3_MAX_HEADER_PAIRS,
|
||||
IDX_HTTP3_MAX_HEADER_LENGTH,
|
||||
IDX_HTTP3_CONFIG_COUNT,
|
||||
MAX_RETRYTOKEN_EXPIRATION,
|
||||
MIN_RETRYTOKEN_EXPIRATION,
|
||||
NGTCP2_NO_ERROR,
|
||||
NGTCP2_MAX_CIDLEN,
|
||||
NGTCP2_MIN_CIDLEN,
|
||||
QUIC_PREFERRED_ADDRESS_IGNORE,
|
||||
QUIC_PREFERRED_ADDRESS_USE,
|
||||
QUIC_ERROR_APPLICATION,
|
||||
}
|
||||
} = internalBinding('quic');
|
||||
|
||||
const {
|
||||
validateBoolean,
|
||||
validateBuffer,
|
||||
validateInteger,
|
||||
validateObject,
|
||||
validatePort,
|
||||
validateString,
|
||||
} = require('internal/validators');
|
||||
|
||||
const kDefaultQuicCiphers = 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:' +
|
||||
'TLS_CHACHA20_POLY1305_SHA256';
|
||||
const kDefaultGroups = 'P-256:X25519:P-384:P-521';
|
||||
|
||||
let dns;
|
||||
|
||||
function lazyDNS() {
|
||||
if (!dns)
|
||||
dns = require('dns');
|
||||
return dns;
|
||||
}
|
||||
|
||||
// This is here rather than in internal/validators to
|
||||
// prevent performance degredation in default cases.
|
||||
function validateNumber(value, name,
|
||||
min = NumberNEGATIVE_INFINITY,
|
||||
max = NumberINFINITY) {
|
||||
if (typeof value !== 'number')
|
||||
throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
|
||||
if (value < min || value > max)
|
||||
throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
|
||||
}
|
||||
|
||||
function getSocketType(type = 'udp4') {
|
||||
switch (type) {
|
||||
case 'udp4': return AF_INET;
|
||||
case 'udp6': return AF_INET6;
|
||||
}
|
||||
throw new ERR_INVALID_ARG_VALUE('options.type', type);
|
||||
}
|
||||
|
||||
function lookup4(address, callback) {
|
||||
const { lookup } = lazyDNS();
|
||||
lookup(address || '127.0.0.1', 4, callback);
|
||||
}
|
||||
|
||||
function lookup6(address, callback) {
|
||||
const { lookup } = lazyDNS();
|
||||
lookup(address || '::1', 6, callback);
|
||||
}
|
||||
|
||||
function validateCloseCode(code) {
|
||||
if (code != null && typeof code === 'object') {
|
||||
return {
|
||||
closeCode: code.code || NGTCP2_NO_ERROR,
|
||||
closeFamily: code.family || QUIC_ERROR_APPLICATION,
|
||||
};
|
||||
} else if (typeof code === 'number') {
|
||||
return {
|
||||
closeCode: code,
|
||||
closeFamily: QUIC_ERROR_APPLICATION,
|
||||
};
|
||||
}
|
||||
throw new ERR_INVALID_ARG_TYPE('code', ['number', 'Object'], code);
|
||||
}
|
||||
|
||||
function validateLookup(lookup) {
|
||||
if (lookup && typeof lookup !== 'function')
|
||||
throw new ERR_INVALID_ARG_TYPE('options.lookup', 'Function', lookup);
|
||||
}
|
||||
|
||||
function validatePreferredAddress(address) {
|
||||
if (address !== undefined) {
|
||||
validateObject(address, 'options.preferredAddress');
|
||||
validateString(address.address, 'options.preferredAddress.address');
|
||||
if (address.port !== undefined)
|
||||
validatePort(address.port, 'options.preferredAddress.port');
|
||||
getSocketType(address.type);
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
// Validate known transport parameters, ignoring any that are not
|
||||
// supported. Ensures that only supported parameters are passed on.
|
||||
function validateTransportParams(params) {
|
||||
const {
|
||||
activeConnectionIdLimit,
|
||||
maxStreamDataBidiLocal,
|
||||
maxStreamDataBidiRemote,
|
||||
maxStreamDataUni,
|
||||
maxData,
|
||||
maxStreamsBidi,
|
||||
maxStreamsUni,
|
||||
idleTimeout,
|
||||
maxPacketSize,
|
||||
maxAckDelay,
|
||||
preferredAddress,
|
||||
rejectUnauthorized,
|
||||
requestCert,
|
||||
h3: {
|
||||
qpackMaxTableCapacity,
|
||||
qpackBlockedStreams,
|
||||
maxHeaderListSize,
|
||||
maxPushes,
|
||||
maxHeaderPairs,
|
||||
maxHeaderLength = getOptionValue('--max-http-header-size'),
|
||||
},
|
||||
} = { h3: {}, ...params };
|
||||
|
||||
if (activeConnectionIdLimit !== undefined) {
|
||||
validateInteger(
|
||||
activeConnectionIdLimit,
|
||||
'options.activeConnectionIdLimit',
|
||||
/* min */ 2,
|
||||
/* max */ 8);
|
||||
}
|
||||
if (maxStreamDataBidiLocal !== undefined) {
|
||||
validateInteger(
|
||||
maxStreamDataBidiLocal,
|
||||
'options.maxStreamDataBidiLocal',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxStreamDataBidiRemote !== undefined) {
|
||||
validateInteger(
|
||||
maxStreamDataBidiRemote,
|
||||
'options.maxStreamDataBidiRemote',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxStreamDataUni !== undefined) {
|
||||
validateInteger(
|
||||
maxStreamDataUni,
|
||||
'options.maxStreamDataUni',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxData !== undefined) {
|
||||
validateInteger(
|
||||
maxData,
|
||||
'options.maxData',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxStreamsBidi !== undefined) {
|
||||
validateInteger(
|
||||
maxStreamsBidi,
|
||||
'options.maxStreamsBidi',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxStreamsUni !== undefined) {
|
||||
validateInteger(
|
||||
maxStreamsUni,
|
||||
'options.maxStreamsUni',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (idleTimeout !== undefined) {
|
||||
validateInteger(
|
||||
idleTimeout,
|
||||
'options.idleTimeout',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxPacketSize !== undefined) {
|
||||
validateInteger(
|
||||
maxPacketSize,
|
||||
'options.maxPacketSize',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxAckDelay !== undefined) {
|
||||
validateInteger(
|
||||
maxAckDelay,
|
||||
'options.maxAckDelay',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (qpackMaxTableCapacity !== undefined) {
|
||||
validateInteger(
|
||||
qpackMaxTableCapacity,
|
||||
'options.h3.qpackMaxTableCapacity',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (qpackBlockedStreams !== undefined) {
|
||||
validateInteger(
|
||||
qpackBlockedStreams,
|
||||
'options.h3.qpackBlockedStreams',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxHeaderListSize !== undefined) {
|
||||
validateInteger(
|
||||
maxHeaderListSize,
|
||||
'options.h3.maxHeaderListSize',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxPushes !== undefined) {
|
||||
validateInteger(
|
||||
maxPushes,
|
||||
'options.h3.maxPushes',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxHeaderPairs !== undefined) {
|
||||
validateInteger(
|
||||
maxHeaderPairs,
|
||||
'options.h3.maxHeaderPairs',
|
||||
/* min */ 0);
|
||||
}
|
||||
if (maxHeaderLength !== undefined) {
|
||||
validateInteger(
|
||||
maxHeaderLength,
|
||||
'options.h3.maxHeaderLength',
|
||||
/* min */ 0);
|
||||
}
|
||||
|
||||
validatePreferredAddress(preferredAddress);
|
||||
|
||||
return {
|
||||
activeConnectionIdLimit,
|
||||
maxStreamDataBidiLocal,
|
||||
maxStreamDataBidiRemote,
|
||||
maxStreamDataUni,
|
||||
maxData,
|
||||
maxStreamsBidi,
|
||||
maxStreamsUni,
|
||||
idleTimeout,
|
||||
maxPacketSize,
|
||||
maxAckDelay,
|
||||
preferredAddress,
|
||||
rejectUnauthorized,
|
||||
requestCert,
|
||||
h3: {
|
||||
qpackMaxTableCapacity,
|
||||
qpackBlockedStreams,
|
||||
maxHeaderListSize,
|
||||
maxPushes,
|
||||
maxHeaderPairs,
|
||||
maxHeaderLength,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function validateQuicClientSessionOptions(options = {}) {
|
||||
if (options !== null && typeof options !== 'object')
|
||||
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
|
||||
const {
|
||||
autoStart = true,
|
||||
address = 'localhost',
|
||||
alpn = '',
|
||||
dcid: dcid_value,
|
||||
ipv6Only = false,
|
||||
minDHSize = 1024,
|
||||
port = 0,
|
||||
preferredAddressPolicy = 'ignore',
|
||||
remoteTransportParams,
|
||||
requestOCSP = false,
|
||||
servername = (isIP(address) ? '' : address),
|
||||
sessionTicket,
|
||||
verifyHostnameIdentity = true,
|
||||
qlog = false,
|
||||
highWaterMark,
|
||||
defaultEncoding,
|
||||
} = options;
|
||||
|
||||
validateBoolean(autoStart, 'options.autoStart');
|
||||
validateNumber(minDHSize, 'options.minDHSize');
|
||||
validatePort(port, 'options.port');
|
||||
validateString(address, 'options.address');
|
||||
validateString(alpn, 'options.alpn');
|
||||
validateString(servername, 'options.servername');
|
||||
|
||||
if (isIP(servername)) {
|
||||
throw new ERR_INVALID_ARG_VALUE(
|
||||
'options.servername',
|
||||
servername,
|
||||
'cannot be an IP address');
|
||||
}
|
||||
|
||||
if (remoteTransportParams !== undefined)
|
||||
validateBuffer(remoteTransportParams, 'options.remoteTransportParams');
|
||||
|
||||
if (sessionTicket !== undefined)
|
||||
validateBuffer(sessionTicket, 'options.sessionTicket');
|
||||
|
||||
let dcid;
|
||||
if (dcid_value !== undefined) {
|
||||
if (typeof dcid_value === 'string') {
|
||||
// If it's a string, it must be a hex encoded string
|
||||
try {
|
||||
dcid = Buffer.from(dcid_value, 'hex');
|
||||
} catch {
|
||||
throw new ERR_QUICSESSION_INVALID_DCID(dcid);
|
||||
}
|
||||
}
|
||||
|
||||
validateBuffer(
|
||||
dcid_value,
|
||||
'options.dcid',
|
||||
['string', 'Buffer', 'TypedArray', 'DataView']);
|
||||
|
||||
if (dcid_value.length > NGTCP2_MAX_CIDLEN ||
|
||||
dcid_value.length < NGTCP2_MIN_CIDLEN) {
|
||||
throw new ERR_QUICSESSION_INVALID_DCID(dcid_value.toString('hex'));
|
||||
}
|
||||
|
||||
dcid = dcid_value;
|
||||
}
|
||||
|
||||
if (preferredAddressPolicy !== undefined)
|
||||
validateString(preferredAddressPolicy, 'options.preferredAddressPolicy');
|
||||
|
||||
validateBoolean(ipv6Only, 'options.ipv6Only');
|
||||
validateBoolean(requestOCSP, 'options.requestOCSP');
|
||||
validateBoolean(verifyHostnameIdentity, 'options.verifyHostnameIdentity');
|
||||
validateBoolean(qlog, 'options.qlog');
|
||||
|
||||
return {
|
||||
autoStart,
|
||||
address,
|
||||
alpn,
|
||||
dcid,
|
||||
ipv6Only,
|
||||
minDHSize,
|
||||
port,
|
||||
preferredAddressPolicy:
|
||||
preferredAddressPolicy === 'accept' ?
|
||||
QUIC_PREFERRED_ADDRESS_USE :
|
||||
QUIC_PREFERRED_ADDRESS_IGNORE,
|
||||
remoteTransportParams,
|
||||
requestOCSP,
|
||||
servername,
|
||||
sessionTicket,
|
||||
verifyHostnameIdentity,
|
||||
qlog,
|
||||
...validateQuicStreamOptions({ highWaterMark, defaultEncoding })
|
||||
};
|
||||
}
|
||||
|
||||
function validateQuicStreamOptions(options = {}) {
|
||||
validateObject(options);
|
||||
const {
|
||||
defaultEncoding = 'utf8',
|
||||
halfOpen,
|
||||
highWaterMark,
|
||||
} = options;
|
||||
if (!Buffer.isEncoding(defaultEncoding)) {
|
||||
throw new ERR_INVALID_ARG_VALUE(
|
||||
'options.defaultEncoding',
|
||||
defaultEncoding,
|
||||
'is not a valid encoding');
|
||||
}
|
||||
if (halfOpen !== undefined)
|
||||
validateBoolean(halfOpen, 'options.halfOpen');
|
||||
if (highWaterMark !== undefined) {
|
||||
validateInteger(
|
||||
highWaterMark,
|
||||
'options.highWaterMark',
|
||||
/* min */ 0);
|
||||
}
|
||||
return {
|
||||
defaultEncoding,
|
||||
halfOpen,
|
||||
highWaterMark,
|
||||
};
|
||||
}
|
||||
|
||||
function validateQuicEndpointOptions(options = {}, name = 'options') {
|
||||
validateObject(options, name);
|
||||
if (options === null || typeof options !== 'object')
|
||||
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
|
||||
const {
|
||||
address,
|
||||
ipv6Only = false,
|
||||
lookup,
|
||||
port = 0,
|
||||
reuseAddr = false,
|
||||
type = 'udp4',
|
||||
preferred = false,
|
||||
} = options;
|
||||
if (address !== undefined)
|
||||
validateString(address, 'options.address');
|
||||
validatePort(port, 'options.port');
|
||||
validateString(type, 'options.type');
|
||||
validateLookup(lookup);
|
||||
validateBoolean(ipv6Only, 'options.ipv6Only');
|
||||
validateBoolean(reuseAddr, 'options.reuseAddr');
|
||||
validateBoolean(preferred, 'options.preferred');
|
||||
return {
|
||||
address,
|
||||
ipv6Only,
|
||||
lookup,
|
||||
port,
|
||||
preferred,
|
||||
reuseAddr,
|
||||
type: getSocketType(type),
|
||||
};
|
||||
}
|
||||
|
||||
function validateQuicSocketOptions(options = {}) {
|
||||
validateObject(options, 'options');
|
||||
|
||||
const {
|
||||
autoClose = false,
|
||||
client = {},
|
||||
disableStatelessReset = false,
|
||||
endpoint = { port: 0, type: 'udp4' },
|
||||
lookup,
|
||||
maxConnections = DEFAULT_MAX_CONNECTIONS,
|
||||
maxConnectionsPerHost = DEFAULT_MAX_CONNECTIONS_PER_HOST,
|
||||
maxStatelessResetsPerHost = DEFAULT_MAX_STATELESS_RESETS_PER_HOST,
|
||||
qlog = false,
|
||||
retryTokenTimeout = DEFAULT_RETRYTOKEN_EXPIRATION,
|
||||
server = {},
|
||||
statelessResetSecret,
|
||||
type = endpoint.type || 'udp4',
|
||||
validateAddressLRU = false,
|
||||
validateAddress = false,
|
||||
} = options;
|
||||
|
||||
validateQuicEndpointOptions(endpoint, 'options.endpoint');
|
||||
validateObject(client, 'options.client');
|
||||
validateObject(server, 'options.server');
|
||||
validateString(type, 'options.type');
|
||||
validateLookup(lookup);
|
||||
validateBoolean(validateAddress, 'options.validateAddress');
|
||||
validateBoolean(validateAddressLRU, 'options.validateAddressLRU');
|
||||
validateBoolean(autoClose, 'options.autoClose');
|
||||
validateBoolean(qlog, 'options.qlog');
|
||||
validateBoolean(disableStatelessReset, 'options.disableStatelessReset');
|
||||
|
||||
if (retryTokenTimeout !== undefined) {
|
||||
validateInteger(
|
||||
retryTokenTimeout,
|
||||
'options.retryTokenTimeout',
|
||||
/* min */ MIN_RETRYTOKEN_EXPIRATION,
|
||||
/* max */ MAX_RETRYTOKEN_EXPIRATION);
|
||||
}
|
||||
if (maxConnections !== undefined) {
|
||||
validateInteger(
|
||||
maxConnections,
|
||||
'options.maxConnections',
|
||||
/* min */ 1);
|
||||
}
|
||||
if (maxConnectionsPerHost !== undefined) {
|
||||
validateInteger(
|
||||
maxConnectionsPerHost,
|
||||
'options.maxConnectionsPerHost',
|
||||
/* min */ 1);
|
||||
}
|
||||
if (maxStatelessResetsPerHost !== undefined) {
|
||||
validateInteger(
|
||||
maxStatelessResetsPerHost,
|
||||
'options.maxStatelessResetsPerHost',
|
||||
/* min */ 1);
|
||||
}
|
||||
|
||||
if (statelessResetSecret !== undefined) {
|
||||
validateBuffer(statelessResetSecret, 'options.statelessResetSecret');
|
||||
if (statelessResetSecret.length !== 16)
|
||||
throw new ERR_QUICSOCKET_INVALID_STATELESS_RESET_SECRET_LENGTH();
|
||||
}
|
||||
|
||||
return {
|
||||
endpoint,
|
||||
autoClose,
|
||||
client,
|
||||
lookup,
|
||||
maxConnections,
|
||||
maxConnectionsPerHost,
|
||||
maxStatelessResetsPerHost,
|
||||
retryTokenTimeout,
|
||||
server,
|
||||
type: getSocketType(type),
|
||||
validateAddress: validateAddress || validateAddressLRU,
|
||||
validateAddressLRU,
|
||||
qlog,
|
||||
statelessResetSecret,
|
||||
disableStatelessReset,
|
||||
};
|
||||
}
|
||||
|
||||
function validateQuicSocketListenOptions(options = {}) {
|
||||
validateObject(options);
|
||||
const {
|
||||
alpn = NGTCP2_ALPN_H3,
|
||||
defaultEncoding,
|
||||
highWaterMark,
|
||||
requestCert,
|
||||
rejectUnauthorized,
|
||||
} = options;
|
||||
validateString(alpn, 'options.alpn');
|
||||
if (rejectUnauthorized !== undefined)
|
||||
validateBoolean(rejectUnauthorized, 'options.rejectUnauthorized');
|
||||
if (requestCert !== undefined)
|
||||
validateBoolean(requestCert, 'options.requestCert');
|
||||
|
||||
const transportParams =
|
||||
validateTransportParams(
|
||||
options,
|
||||
NGTCP2_MAX_CIDLEN,
|
||||
NGTCP2_MIN_CIDLEN);
|
||||
|
||||
return {
|
||||
alpn,
|
||||
rejectUnauthorized,
|
||||
requestCert,
|
||||
transportParams,
|
||||
...validateQuicStreamOptions({ highWaterMark, defaultEncoding })
|
||||
};
|
||||
}
|
||||
|
||||
function validateQuicSocketConnectOptions(options = {}) {
|
||||
validateObject(options);
|
||||
const {
|
||||
type = 'udp4',
|
||||
address,
|
||||
} = options;
|
||||
if (address !== undefined)
|
||||
validateString(address, 'options.address');
|
||||
return {
|
||||
type: getSocketType(type),
|
||||
address,
|
||||
};
|
||||
}
|
||||
|
||||
function validateCreateSecureContextOptions(options = {}) {
|
||||
validateObject(options);
|
||||
const {
|
||||
ca,
|
||||
cert,
|
||||
ciphers = kDefaultQuicCiphers,
|
||||
clientCertEngine,
|
||||
crl,
|
||||
dhparam,
|
||||
ecdhCurve,
|
||||
groups = kDefaultGroups,
|
||||
honorCipherOrder,
|
||||
key,
|
||||
earlyData = true, // Early data is enabled by default
|
||||
passphrase,
|
||||
pfx,
|
||||
sessionIdContext,
|
||||
secureProtocol
|
||||
} = options;
|
||||
validateString(ciphers, 'option.ciphers');
|
||||
validateString(groups, 'option.groups');
|
||||
if (earlyData !== undefined)
|
||||
validateBoolean(earlyData, 'option.earlyData');
|
||||
|
||||
// Additional validation occurs within the tls
|
||||
// createSecureContext function.
|
||||
return {
|
||||
ca,
|
||||
cert,
|
||||
ciphers,
|
||||
clientCertEngine,
|
||||
crl,
|
||||
dhparam,
|
||||
ecdhCurve,
|
||||
groups,
|
||||
honorCipherOrder,
|
||||
key,
|
||||
earlyData,
|
||||
passphrase,
|
||||
pfx,
|
||||
sessionIdContext,
|
||||
secureProtocol
|
||||
};
|
||||
}
|
||||
|
||||
function setConfigField(buffer, val, index) {
|
||||
if (typeof val === 'number') {
|
||||
buffer[index] = val;
|
||||
return 1 << index;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Extracts configuration options and updates the aliased buffer
|
||||
// arrays that are used to communicate config choices to the c++
|
||||
// internals.
|
||||
function setTransportParams(config) {
|
||||
const {
|
||||
activeConnectionIdLimit,
|
||||
maxStreamDataBidiLocal,
|
||||
maxStreamDataBidiRemote,
|
||||
maxStreamDataUni,
|
||||
maxData,
|
||||
maxStreamsBidi,
|
||||
maxStreamsUni,
|
||||
idleTimeout,
|
||||
maxPacketSize,
|
||||
maxAckDelay,
|
||||
h3: {
|
||||
qpackMaxTableCapacity,
|
||||
qpackBlockedStreams,
|
||||
maxHeaderListSize,
|
||||
maxPushes,
|
||||
maxHeaderPairs,
|
||||
maxHeaderLength,
|
||||
},
|
||||
} = { h3: {}, ...config };
|
||||
|
||||
// The const flags is a bitmap that is used to communicate whether or not a
|
||||
// given configuration value has been explicitly provided.
|
||||
const flags = setConfigField(sessionConfig,
|
||||
activeConnectionIdLimit,
|
||||
IDX_QUIC_SESSION_ACTIVE_CONNECTION_ID_LIMIT) |
|
||||
setConfigField(sessionConfig,
|
||||
maxStreamDataBidiLocal,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_LOCAL) |
|
||||
setConfigField(sessionConfig,
|
||||
maxStreamDataBidiRemote,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_REMOTE) |
|
||||
setConfigField(sessionConfig,
|
||||
maxStreamDataUni,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_UNI) |
|
||||
setConfigField(sessionConfig,
|
||||
maxData,
|
||||
IDX_QUIC_SESSION_MAX_DATA) |
|
||||
setConfigField(sessionConfig,
|
||||
maxStreamsBidi,
|
||||
IDX_QUIC_SESSION_MAX_STREAMS_BIDI) |
|
||||
setConfigField(sessionConfig,
|
||||
maxStreamsUni,
|
||||
IDX_QUIC_SESSION_MAX_STREAMS_UNI) |
|
||||
setConfigField(sessionConfig,
|
||||
idleTimeout,
|
||||
IDX_QUIC_SESSION_MAX_IDLE_TIMEOUT) |
|
||||
setConfigField(sessionConfig,
|
||||
maxAckDelay,
|
||||
IDX_QUIC_SESSION_MAX_ACK_DELAY) |
|
||||
setConfigField(sessionConfig,
|
||||
maxPacketSize,
|
||||
IDX_QUIC_SESSION_MAX_PACKET_SIZE);
|
||||
|
||||
sessionConfig[IDX_QUIC_SESSION_CONFIG_COUNT] = flags;
|
||||
|
||||
const h3flags = setConfigField(http3Config,
|
||||
qpackMaxTableCapacity,
|
||||
IDX_HTTP3_QPACK_MAX_TABLE_CAPACITY) |
|
||||
setConfigField(http3Config,
|
||||
qpackBlockedStreams,
|
||||
IDX_HTTP3_QPACK_BLOCKED_STREAMS) |
|
||||
setConfigField(http3Config,
|
||||
maxHeaderListSize,
|
||||
IDX_HTTP3_MAX_HEADER_LIST_SIZE) |
|
||||
setConfigField(http3Config,
|
||||
maxPushes,
|
||||
IDX_HTTP3_MAX_PUSHES) |
|
||||
setConfigField(http3Config,
|
||||
maxHeaderPairs,
|
||||
IDX_HTTP3_MAX_HEADER_PAIRS) |
|
||||
setConfigField(http3Config,
|
||||
maxHeaderLength,
|
||||
IDX_HTTP3_MAX_HEADER_LENGTH);
|
||||
|
||||
http3Config[IDX_HTTP3_CONFIG_COUNT] = h3flags;
|
||||
}
|
||||
|
||||
// Some events that are emitted originate from the C++ internals and are
|
||||
// fairly expensive and optional. An aliased array buffer is used to
|
||||
// communicate that a handler has been added for the optional events
|
||||
// so that the C++ internals know there is an actual listener. The event
|
||||
// will not be emitted if there is no handler.
|
||||
function toggleListeners(handle, event, on) {
|
||||
if (handle === undefined)
|
||||
return;
|
||||
const val = on ? 1 : 0;
|
||||
switch (event) {
|
||||
case 'keylog':
|
||||
handle.state[IDX_QUIC_SESSION_STATE_KEYLOG_ENABLED] = val;
|
||||
break;
|
||||
case 'clientHello':
|
||||
handle.state[IDX_QUIC_SESSION_STATE_CLIENT_HELLO_ENABLED] = val;
|
||||
break;
|
||||
case 'pathValidation':
|
||||
handle.state[IDX_QUIC_SESSION_STATE_PATH_VALIDATED_ENABLED] = val;
|
||||
break;
|
||||
case 'OCSPRequest':
|
||||
handle.state[IDX_QUIC_SESSION_STATE_CERT_ENABLED] = val;
|
||||
break;
|
||||
case 'usePreferredAddress':
|
||||
handle.state[IDX_QUIC_SESSION_STATE_USE_PREFERRED_ADDRESS_ENABLED] = on;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getAllowUnauthorized,
|
||||
getSocketType,
|
||||
lookup4,
|
||||
lookup6,
|
||||
setTransportParams,
|
||||
toggleListeners,
|
||||
validateNumber,
|
||||
validateCloseCode,
|
||||
validateTransportParams,
|
||||
validateQuicClientSessionOptions,
|
||||
validateQuicSocketOptions,
|
||||
validateQuicStreamOptions,
|
||||
validateQuicSocketListenOptions,
|
||||
validateQuicEndpointOptions,
|
||||
validateCreateSecureContextOptions,
|
||||
validateQuicSocketConnectOptions,
|
||||
};
|
||||
@@ -108,7 +108,7 @@ function onWriteComplete(status) {
|
||||
this.callback(null);
|
||||
}
|
||||
|
||||
function createWriteWrap(handle) {
|
||||
function createWriteWrap(handle, callback) {
|
||||
const req = new WriteWrap();
|
||||
|
||||
req.handle = handle;
|
||||
@@ -116,12 +116,13 @@ function createWriteWrap(handle) {
|
||||
req.async = false;
|
||||
req.bytes = 0;
|
||||
req.buffer = null;
|
||||
req.callback = callback;
|
||||
|
||||
return req;
|
||||
}
|
||||
|
||||
function writevGeneric(self, data, cb) {
|
||||
const req = createWriteWrap(self[kHandle]);
|
||||
const req = createWriteWrap(self[kHandle], cb);
|
||||
const allBuffers = data.allBuffers;
|
||||
let chunks;
|
||||
if (allBuffers) {
|
||||
@@ -146,7 +147,7 @@ function writevGeneric(self, data, cb) {
|
||||
}
|
||||
|
||||
function writeGeneric(self, data, encoding, cb) {
|
||||
const req = createWriteWrap(self[kHandle]);
|
||||
const req = createWriteWrap(self[kHandle], cb);
|
||||
const err = handleWriteReq(req, data, encoding);
|
||||
|
||||
afterWriteDispatched(req, err, cb);
|
||||
@@ -160,10 +161,8 @@ function afterWriteDispatched(req, err, cb) {
|
||||
if (err !== 0)
|
||||
return cb(errnoException(err, 'write', req.error));
|
||||
|
||||
if (!req.async) {
|
||||
cb();
|
||||
} else {
|
||||
req.callback = cb;
|
||||
if (!req.async && typeof req.callback === 'function') {
|
||||
req.callback();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
@@ -38,6 +38,9 @@ const { inspect } = require('internal/util/inspect');
|
||||
let debug = require('internal/util/debuglog').debuglog('net', (fn) => {
|
||||
debug = fn;
|
||||
});
|
||||
const {
|
||||
assertCrypto,
|
||||
} = require('internal/util');
|
||||
const {
|
||||
isIP,
|
||||
isIPv4,
|
||||
@@ -1726,3 +1729,25 @@ module.exports = {
|
||||
Socket,
|
||||
Stream: Socket, // Legacy naming
|
||||
};
|
||||
|
||||
if (process.versions.ngtcp2 !== undefined) {
|
||||
let quic;
|
||||
|
||||
function lazyQuic() {
|
||||
if (quic === undefined) {
|
||||
assertCrypto();
|
||||
quic = require('internal/quic/core');
|
||||
process.emitWarning(
|
||||
'The QUIC protocol is experimental and not yet ' +
|
||||
'supported for production use',
|
||||
'ExperimentalWarning');
|
||||
}
|
||||
return quic;
|
||||
}
|
||||
|
||||
function createQuicSocket(...args) {
|
||||
return lazyQuic().createSocket(...args);
|
||||
}
|
||||
|
||||
module.exports.createQuicSocket = createQuicSocket;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
'variables': {
|
||||
'experimental_quic': 'false',
|
||||
'v8_use_siphash%': 0,
|
||||
'v8_trace_maps%': 0,
|
||||
'v8_enable_pointer_compression%': 0,
|
||||
@@ -19,6 +20,8 @@
|
||||
'node_shared_cares%': 'false',
|
||||
'node_shared_libuv%': 'false',
|
||||
'node_shared_nghttp2%': 'false',
|
||||
'node_shared_ngtcp2%': 'false',
|
||||
'node_shared_nghttp3%': 'false',
|
||||
'node_use_openssl%': 'true',
|
||||
'node_shared_openssl%': 'false',
|
||||
'node_v8_options%': '',
|
||||
@@ -190,6 +193,8 @@
|
||||
'lib/internal/process/task_queues.js',
|
||||
'lib/internal/querystring.js',
|
||||
'lib/internal/readline/utils.js',
|
||||
'lib/internal/quic/core.js',
|
||||
'lib/internal/quic/util.js',
|
||||
'lib/internal/repl.js',
|
||||
'lib/internal/repl/await.js',
|
||||
'lib/internal/repl/history.js',
|
||||
@@ -903,6 +908,38 @@
|
||||
'node_target_type=="executable"', {
|
||||
'defines': [ 'NODE_ENABLE_LARGE_CODE_PAGES=1' ],
|
||||
}],
|
||||
[
|
||||
# We can only use QUIC if using our modified, static linked
|
||||
# OpenSSL because we have patched in the QUIC support.
|
||||
'node_use_openssl=="true" and node_shared_openssl=="false" and experimental_quic==1', {
|
||||
'defines': ['NODE_EXPERIMENTAL_QUIC=1'],
|
||||
'sources': [
|
||||
'src/node_bob.h',
|
||||
'src/node_bob-inl.h',
|
||||
'src/quic/node_quic_buffer.h',
|
||||
'src/quic/node_quic_buffer-inl.h',
|
||||
'src/quic/node_quic_crypto.h',
|
||||
'src/quic/node_quic_session.h',
|
||||
'src/quic/node_quic_session-inl.h',
|
||||
'src/quic/node_quic_socket.h',
|
||||
'src/quic/node_quic_socket-inl.h',
|
||||
'src/quic/node_quic_stream.h',
|
||||
'src/quic/node_quic_stream-inl.h',
|
||||
'src/quic/node_quic_util.h',
|
||||
'src/quic/node_quic_util-inl.h',
|
||||
'src/quic/node_quic_state.h',
|
||||
'src/quic/node_quic_default_application.h',
|
||||
'src/quic/node_quic_http3_application.h',
|
||||
'src/quic/node_quic_buffer.cc',
|
||||
'src/quic/node_quic_crypto.cc',
|
||||
'src/quic/node_quic_session.cc',
|
||||
'src/quic/node_quic_socket.cc',
|
||||
'src/quic/node_quic_stream.cc',
|
||||
'src/quic/node_quic.cc',
|
||||
'src/quic/node_quic_default_application.cc',
|
||||
'src/quic/node_quic_http3_application.cc'
|
||||
]
|
||||
}],
|
||||
[ 'use_openssl_def==1', {
|
||||
# TODO(bnoordhuis) Make all platforms export the same list of symbols.
|
||||
# Teach mkssldef.py to generate linker maps that UNIX linkers understand.
|
||||
@@ -1188,6 +1225,16 @@
|
||||
'HAVE_OPENSSL=1',
|
||||
],
|
||||
}],
|
||||
[ 'node_use_openssl=="true" and experimental_quic==1', {
|
||||
'defines': [
|
||||
'NODE_EXPERIMENTAL_QUIC=1',
|
||||
],
|
||||
'sources': [
|
||||
'test/cctest/test_quic_buffer.cc',
|
||||
'test/cctest/test_quic_cid.cc',
|
||||
'test/cctest/test_quic_verifyhostnameidentity.cc'
|
||||
]
|
||||
}],
|
||||
['v8_enable_inspector==1', {
|
||||
'sources': [
|
||||
'test/cctest/test_inspector_socket.cc',
|
||||
|
||||
@@ -187,6 +187,24 @@
|
||||
'dependencies': [ 'deps/nghttp2/nghttp2.gyp:nghttp2' ],
|
||||
}],
|
||||
|
||||
[
|
||||
'experimental_quic==1', {
|
||||
'conditions': [
|
||||
[
|
||||
'node_shared_ngtcp2=="false"', {
|
||||
'dependencies': [
|
||||
'deps/ngtcp2/ngtcp2.gyp:ngtcp2',
|
||||
]}
|
||||
],
|
||||
[
|
||||
'node_shared_nghttp3=="false"', {
|
||||
'dependencies': [
|
||||
'deps/nghttp3/nghttp3.gyp:nghttp3'
|
||||
]}
|
||||
]
|
||||
]}
|
||||
],
|
||||
|
||||
[ 'node_shared_brotli=="false"', {
|
||||
'dependencies': [ 'deps/brotli/brotli.gyp:brotli' ],
|
||||
}],
|
||||
|
||||
@@ -59,6 +59,11 @@ namespace node {
|
||||
V(PROCESSWRAP) \
|
||||
V(PROMISE) \
|
||||
V(QUERYWRAP) \
|
||||
V(QUICCLIENTSESSION) \
|
||||
V(QUICSERVERSESSION) \
|
||||
V(QUICSENDWRAP) \
|
||||
V(QUICSOCKET) \
|
||||
V(QUICSTREAM) \
|
||||
V(SHUTDOWNWRAP) \
|
||||
V(SIGNALWRAP) \
|
||||
V(STATWATCHER) \
|
||||
|
||||
@@ -45,6 +45,7 @@ void FWrite(FILE* file, const std::string& str);
|
||||
V(INSPECTOR_SERVER) \
|
||||
V(INSPECTOR_PROFILER) \
|
||||
V(CODE_CACHE) \
|
||||
V(NGTCP2_DEBUG) \
|
||||
V(WASI)
|
||||
|
||||
enum class DebugCategory {
|
||||
|
||||
@@ -172,6 +172,7 @@ constexpr size_t kFsStatsBufferLength =
|
||||
// Strings are per-isolate primitives but Environment proxies them
|
||||
// for the sake of convenience. Strings should be ASCII-only.
|
||||
#define PER_ISOLATE_STRING_PROPERTIES(V) \
|
||||
V(ack_string, "ack") \
|
||||
V(address_string, "address") \
|
||||
V(aliases_string, "aliases") \
|
||||
V(args_string, "args") \
|
||||
@@ -334,6 +335,8 @@ constexpr size_t kFsStatsBufferLength =
|
||||
V(psk_string, "psk") \
|
||||
V(pubkey_string, "pubkey") \
|
||||
V(query_string, "query") \
|
||||
V(quic_alpn_string, "h3-27") \
|
||||
V(rate_string, "rate") \
|
||||
V(raw_string, "raw") \
|
||||
V(read_host_object_string, "_readHostObject") \
|
||||
V(readable_string, "readable") \
|
||||
@@ -361,6 +364,8 @@ constexpr size_t kFsStatsBufferLength =
|
||||
V(stack_string, "stack") \
|
||||
V(standard_name_string, "standardName") \
|
||||
V(start_time_string, "startTime") \
|
||||
V(state_string, "state") \
|
||||
V(stats_string, "stats") \
|
||||
V(status_string, "status") \
|
||||
V(stdio_string, "stdio") \
|
||||
V(subject_string, "subject") \
|
||||
@@ -399,6 +404,16 @@ constexpr size_t kFsStatsBufferLength =
|
||||
V(x_forwarded_string, "x-forwarded-for") \
|
||||
V(zero_return_string, "ZERO_RETURN")
|
||||
|
||||
#if defined(NODE_EXPERIMENTAL_QUIC) && NODE_EXPERIMENTAL_QUIC
|
||||
# define QUIC_ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V) \
|
||||
V(quicclientsession_instance_template, v8::ObjectTemplate) \
|
||||
V(quicserversession_instance_template, v8::ObjectTemplate) \
|
||||
V(quicserverstream_instance_template, v8::ObjectTemplate) \
|
||||
V(quicsocketsendwrap_instance_template, v8::ObjectTemplate)
|
||||
#else
|
||||
# define QUIC_ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
|
||||
#endif
|
||||
|
||||
#define ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V) \
|
||||
V(async_wrap_ctor_template, v8::FunctionTemplate) \
|
||||
V(async_wrap_object_ctor_template, v8::FunctionTemplate) \
|
||||
@@ -428,7 +443,38 @@ constexpr size_t kFsStatsBufferLength =
|
||||
V(tcp_constructor_template, v8::FunctionTemplate) \
|
||||
V(tty_constructor_template, v8::FunctionTemplate) \
|
||||
V(write_wrap_template, v8::ObjectTemplate) \
|
||||
V(worker_heap_snapshot_taker_template, v8::ObjectTemplate)
|
||||
V(worker_heap_snapshot_taker_template, v8::ObjectTemplate) \
|
||||
QUIC_ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
|
||||
|
||||
#if defined(NODE_EXPERIMENTAL_QUIC) && NODE_EXPERIMENTAL_QUIC
|
||||
# define QUIC_ENVIRONMENT_STRONG_PERSISTENT_VALUES(V) \
|
||||
V(quic_on_socket_close_function, v8::Function) \
|
||||
V(quic_on_socket_error_function, v8::Function) \
|
||||
V(quic_on_socket_server_busy_function, v8::Function) \
|
||||
V(quic_on_session_cert_function, v8::Function) \
|
||||
V(quic_on_session_client_hello_function, v8::Function) \
|
||||
V(quic_on_session_close_function, v8::Function) \
|
||||
V(quic_on_session_destroyed_function, v8::Function) \
|
||||
V(quic_on_session_error_function, v8::Function) \
|
||||
V(quic_on_session_handshake_function, v8::Function) \
|
||||
V(quic_on_session_keylog_function, v8::Function) \
|
||||
V(quic_on_session_path_validation_function, v8::Function) \
|
||||
V(quic_on_session_use_preferred_address_function, v8::Function) \
|
||||
V(quic_on_session_qlog_function, v8::Function) \
|
||||
V(quic_on_session_ready_function, v8::Function) \
|
||||
V(quic_on_session_silent_close_function, v8::Function) \
|
||||
V(quic_on_session_status_function, v8::Function) \
|
||||
V(quic_on_session_ticket_function, v8::Function) \
|
||||
V(quic_on_session_version_negotiation_function, v8::Function) \
|
||||
V(quic_on_stream_close_function, v8::Function) \
|
||||
V(quic_on_stream_error_function, v8::Function) \
|
||||
V(quic_on_stream_ready_function, v8::Function) \
|
||||
V(quic_on_stream_reset_function, v8::Function) \
|
||||
V(quic_on_stream_headers_function, v8::Function) \
|
||||
V(quic_on_stream_blocked_function, v8::Function)
|
||||
#else
|
||||
# define QUIC_ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
|
||||
#endif
|
||||
|
||||
#define ENVIRONMENT_STRONG_PERSISTENT_VALUES(V) \
|
||||
V(async_hooks_after_function, v8::Function) \
|
||||
@@ -477,7 +523,8 @@ constexpr size_t kFsStatsBufferLength =
|
||||
V(tls_wrap_constructor_function, v8::Function) \
|
||||
V(trace_category_state_function, v8::Function) \
|
||||
V(udp_constructor_function, v8::Function) \
|
||||
V(url_constructor_function, v8::Function)
|
||||
V(url_constructor_function, v8::Function) \
|
||||
QUIC_ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
|
||||
|
||||
class Environment;
|
||||
struct AllocatedBuffer;
|
||||
|
||||
+2
-1
@@ -93,10 +93,11 @@ class HandleWrap : public AsyncWrap {
|
||||
return state_ == kClosing || state_ == kClosed;
|
||||
}
|
||||
|
||||
static void OnClose(uv_handle_t* handle);
|
||||
|
||||
private:
|
||||
friend class Environment;
|
||||
friend void GetActiveHandles(const v8::FunctionCallbackInfo<v8::Value>&);
|
||||
static void OnClose(uv_handle_t* handle);
|
||||
|
||||
// handle_wrap_queue_ needs to be at a fixed offset from the start of the
|
||||
// class because it is used by src/node_postmortem_metadata.cc to calculate
|
||||
|
||||
@@ -11,6 +11,12 @@
|
||||
#define NODE_BUILTIN_OPENSSL_MODULES(V)
|
||||
#endif
|
||||
|
||||
#if defined(NODE_EXPERIMENTAL_QUIC) && NODE_EXPERIMENTAL_QUIC
|
||||
#define NODE_BUILTIN_QUIC_MODULES(V) V(quic)
|
||||
#else
|
||||
#define NODE_BUILTIN_QUIC_MODULES(V)
|
||||
#endif
|
||||
|
||||
#if NODE_HAVE_I18N_SUPPORT
|
||||
#define NODE_BUILTIN_ICU_MODULES(V) V(icu)
|
||||
#else
|
||||
@@ -89,6 +95,7 @@
|
||||
#define NODE_BUILTIN_MODULES(V) \
|
||||
NODE_BUILTIN_STANDARD_MODULES(V) \
|
||||
NODE_BUILTIN_OPENSSL_MODULES(V) \
|
||||
NODE_BUILTIN_QUIC_MODULES(V) \
|
||||
NODE_BUILTIN_ICU_MODULES(V) \
|
||||
NODE_BUILTIN_PROFILER_MODULES(V) \
|
||||
NODE_BUILTIN_DTRACE_MODULES(V)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#ifndef SRC_NODE_BOB_INL_H_
|
||||
#define SRC_NODE_BOB_INL_H_
|
||||
|
||||
#include "node_bob.h"
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace node {
|
||||
namespace bob {
|
||||
|
||||
template <typename T>
|
||||
int SourceImpl<T>::Pull(
|
||||
Next<T> next,
|
||||
int options,
|
||||
T* data,
|
||||
size_t count,
|
||||
size_t max_count_hint) {
|
||||
|
||||
int status;
|
||||
if (eos_) {
|
||||
status = bob::Status::STATUS_EOS;
|
||||
std::move(next)(status, nullptr, 0, [](size_t len) {});
|
||||
return status;
|
||||
}
|
||||
|
||||
status = DoPull(std::move(next), options, data, count, max_count_hint);
|
||||
|
||||
if (status == bob::Status::STATUS_END)
|
||||
eos_ = true;
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
} // namespace bob
|
||||
} // namespace node
|
||||
|
||||
#endif // SRC_NODE_BOB_INL_H_
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
#ifndef SRC_NODE_BOB_H_
|
||||
#define SRC_NODE_BOB_H_
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace node {
|
||||
namespace bob {
|
||||
|
||||
constexpr size_t kMaxCountHint = 16;
|
||||
|
||||
// Negative status codes indicate error conditions.
|
||||
enum Status : int {
|
||||
// Indicates that an attempt was made to pull after end.
|
||||
STATUS_EOS = -1,
|
||||
|
||||
// Indicates the end of the stream. No additional
|
||||
// data will be available and the consumer should stop
|
||||
// pulling.
|
||||
STATUS_END = 0,
|
||||
|
||||
// Indicates that there is additional data available
|
||||
// and the consumer may continue to pull.
|
||||
STATUS_CONTINUE = 1,
|
||||
|
||||
// Indicates that there is no additional data available
|
||||
// but the stream has not ended. The consumer should not
|
||||
// continue to pull but may resume pulling later when
|
||||
// data is available.
|
||||
STATUS_BLOCK = 2,
|
||||
|
||||
// Indicates that there is no additional data available
|
||||
// but the stream has not ended and the source will call
|
||||
// next again later when data is available. STATUS_WAIT
|
||||
// must not be used with the OPTIONS_SYNC option.
|
||||
STATUS_WAIT = 3,
|
||||
};
|
||||
|
||||
enum Options : int {
|
||||
OPTIONS_NONE = 0,
|
||||
|
||||
// Indicates that the consumer is requesting the end
|
||||
// of the stream.
|
||||
OPTIONS_END = 1,
|
||||
|
||||
// Indicates that the consumer requires the source to
|
||||
// invoke Next synchronously. If the source is
|
||||
// unable to provide data immediately but the
|
||||
// stream has not yet ended, it should call Next
|
||||
// using STATUS_BLOCK. When not set, the source
|
||||
// may call Next asynchronously.
|
||||
OPTIONS_SYNC = 2
|
||||
};
|
||||
|
||||
// There are Sources and there are Consumers.
|
||||
//
|
||||
// Consumers get data by calling Source::Pull,
|
||||
// optionally passing along a status and allocated
|
||||
// buffer space for the source to fill, and a Next
|
||||
// function the Source will call when data is
|
||||
// available.
|
||||
//
|
||||
// The source calls Next to deliver the data. It can
|
||||
// choose to either use the allocated buffer space
|
||||
// provided by the consumer or it can allocate its own
|
||||
// buffers and push those instead. If it allocates
|
||||
// its own, it can send a Done function that the
|
||||
// Sink will call when it is done consuming the data.
|
||||
using Done = std::function<void(size_t)>;
|
||||
template <typename T>
|
||||
using Next = std::function<void(int, const T*, size_t count, Done done)>;
|
||||
|
||||
template <typename T>
|
||||
class Source {
|
||||
public:
|
||||
virtual int Pull(
|
||||
Next<T> next,
|
||||
int options,
|
||||
T* data,
|
||||
size_t count,
|
||||
size_t max_count_hint = kMaxCountHint) = 0;
|
||||
};
|
||||
|
||||
|
||||
template <typename T>
|
||||
class SourceImpl : public Source<T> {
|
||||
public:
|
||||
int Pull(
|
||||
Next<T> next,
|
||||
int options,
|
||||
T* data,
|
||||
size_t count,
|
||||
size_t max_count_hint = kMaxCountHint) override;
|
||||
|
||||
bool is_eos() const { return eos_; }
|
||||
|
||||
protected:
|
||||
virtual int DoPull(
|
||||
Next<T> next,
|
||||
int options,
|
||||
T* data,
|
||||
size_t count,
|
||||
size_t max_count_hint) = 0;
|
||||
|
||||
private:
|
||||
bool eos_ = false;
|
||||
};
|
||||
|
||||
} // namespace bob
|
||||
} // namespace node
|
||||
|
||||
#endif // SRC_NODE_BOB_H_
|
||||
+6
-2
@@ -56,7 +56,9 @@ void OnFatalError(const char* location, const char* message);
|
||||
V(ERR_VM_MODULE_CACHED_DATA_REJECTED, Error) \
|
||||
V(ERR_WASI_NOT_STARTED, Error) \
|
||||
V(ERR_WORKER_INIT_FAILED, Error) \
|
||||
V(ERR_PROTO_ACCESS, Error)
|
||||
V(ERR_PROTO_ACCESS, Error) \
|
||||
V(ERR_QUIC_CANNOT_SET_GROUPS, Error) \
|
||||
V(ERR_QUIC_FAILURE_SETTING_SNI_CONTEXT, Error)
|
||||
|
||||
#define V(code, type) \
|
||||
inline v8::Local<v8::Value> code(v8::Isolate* isolate, \
|
||||
@@ -111,7 +113,9 @@ void OnFatalError(const char* location, const char* message);
|
||||
V(ERR_WORKER_INIT_FAILED, "Worker initialization failure") \
|
||||
V(ERR_PROTO_ACCESS, \
|
||||
"Accessing Object.prototype.__proto__ has been " \
|
||||
"disallowed with --disable-proto=throw")
|
||||
"disallowed with --disable-proto=throw") \
|
||||
V(ERR_QUIC_CANNOT_SET_GROUPS, "Cannot set groups") \
|
||||
V(ERR_QUIC_FAILURE_SETTING_SNI_CONTEXT, "Failure setting SNI context")
|
||||
|
||||
#define V(code, message) \
|
||||
inline v8::Local<v8::Value> code(v8::Isolate* isolate) { \
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
#include <openssl/opensslv.h>
|
||||
#endif // HAVE_OPENSSL
|
||||
|
||||
#if defined(NODE_EXPERIMENTAL_QUIC) && NODE_EXPERIMENTAL_QUIC
|
||||
#include <ngtcp2/version.h>
|
||||
#include <nghttp3/version.h>
|
||||
#endif
|
||||
|
||||
#ifdef NODE_HAVE_I18N_SUPPORT
|
||||
#include <unicode/timezone.h>
|
||||
#include <unicode/ulocdata.h>
|
||||
@@ -91,6 +96,11 @@ Metadata::Versions::Versions() {
|
||||
openssl = GetOpenSSLVersion();
|
||||
#endif
|
||||
|
||||
#if defined(NODE_EXPERIMENTAL_QUIC) && NODE_EXPERIMENTAL_QUIC
|
||||
ngtcp2 = NGTCP2_VERSION;
|
||||
nghttp3 = NGHTTP3_VERSION;
|
||||
#endif
|
||||
|
||||
#ifdef NODE_HAVE_I18N_SUPPORT
|
||||
icu = U_ICU_VERSION;
|
||||
unicode = U_UNICODE_VERSION;
|
||||
|
||||
@@ -38,6 +38,12 @@ namespace node {
|
||||
#define NODE_VERSIONS_KEY_CRYPTO(V)
|
||||
#endif
|
||||
|
||||
#if defined(NODE_EXPERIMENTAL_QUIC) && NODE_EXPERIMENTAL_QUIC
|
||||
#define NODE_VERSIONS_KEY_QUIC(V) V(ngtcp2) V(nghttp3)
|
||||
#else
|
||||
#define NODE_VERSIONS_KEY_QUIC(V)
|
||||
#endif
|
||||
|
||||
#ifdef NODE_HAVE_I18N_SUPPORT
|
||||
#define NODE_VERSIONS_KEY_INTL(V) \
|
||||
V(cldr) \
|
||||
@@ -51,6 +57,7 @@ namespace node {
|
||||
#define NODE_VERSIONS_KEYS(V) \
|
||||
NODE_VERSIONS_KEYS_BASE(V) \
|
||||
NODE_VERSIONS_KEY_CRYPTO(V) \
|
||||
NODE_VERSIONS_KEY_QUIC(V) \
|
||||
NODE_VERSIONS_KEY_INTL(V)
|
||||
|
||||
class Metadata {
|
||||
|
||||
@@ -101,7 +101,10 @@ void NativeModuleLoader::InitializeModuleCategories() {
|
||||
"internal/process/policy",
|
||||
"internal/streams/lazy_transform",
|
||||
#endif // !HAVE_OPENSSL
|
||||
|
||||
#if !NODE_EXPERIMENTAL_QUIC
|
||||
"internal/quic/core",
|
||||
"internal/quic/util",
|
||||
#endif
|
||||
"sys", // Deprecated.
|
||||
"wasi", // Experimental.
|
||||
"internal/test/binding",
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
#include "debug_utils-inl.h"
|
||||
#include "node.h"
|
||||
#include "env-inl.h"
|
||||
#include "node_crypto.h" // SecureContext
|
||||
#include "node_crypto_common.h"
|
||||
#include "node_errors.h"
|
||||
#include "node_process.h"
|
||||
#include "node_quic_crypto.h"
|
||||
#include "node_quic_session-inl.h"
|
||||
#include "node_quic_socket-inl.h"
|
||||
#include "node_quic_stream-inl.h"
|
||||
#include "node_quic_state.h"
|
||||
#include "node_quic_util-inl.h"
|
||||
#include "node_sockaddr-inl.h"
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
namespace node {
|
||||
|
||||
using crypto::SecureContext;
|
||||
using v8::Context;
|
||||
using v8::Function;
|
||||
using v8::FunctionCallbackInfo;
|
||||
using v8::HandleScope;
|
||||
using v8::Isolate;
|
||||
using v8::Local;
|
||||
using v8::Object;
|
||||
using v8::Value;
|
||||
|
||||
namespace quic {
|
||||
|
||||
constexpr FastStringKey QuicState::binding_data_name;
|
||||
|
||||
void QuicState::MemoryInfo(MemoryTracker* tracker) const {
|
||||
tracker->TrackField("root_buffer", root_buffer);
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Register the JavaScript callbacks the internal binding will use to report
|
||||
// status and updates. This is called only once when the quic module is loaded.
|
||||
void QuicSetCallbacks(const FunctionCallbackInfo<Value>& args) {
|
||||
Environment* env = Environment::GetCurrent(args);
|
||||
CHECK(args[0]->IsObject());
|
||||
Local<Object> obj = args[0].As<Object>();
|
||||
|
||||
#define SETFUNCTION(name, callback) \
|
||||
do { \
|
||||
Local<Value> fn; \
|
||||
CHECK(obj->Get(env->context(), \
|
||||
FIXED_ONE_BYTE_STRING(env->isolate(), name)).ToLocal(&fn));\
|
||||
CHECK(fn->IsFunction()); \
|
||||
env->set_quic_on_##callback##_function(fn.As<Function>()); \
|
||||
} while (0)
|
||||
|
||||
SETFUNCTION("onSocketClose", socket_close);
|
||||
SETFUNCTION("onSocketError", socket_error);
|
||||
SETFUNCTION("onSessionReady", session_ready);
|
||||
SETFUNCTION("onSessionCert", session_cert);
|
||||
SETFUNCTION("onSessionClientHello", session_client_hello);
|
||||
SETFUNCTION("onSessionClose", session_close);
|
||||
SETFUNCTION("onSessionDestroyed", session_destroyed);
|
||||
SETFUNCTION("onSessionError", session_error);
|
||||
SETFUNCTION("onSessionHandshake", session_handshake);
|
||||
SETFUNCTION("onSessionKeylog", session_keylog);
|
||||
SETFUNCTION("onSessionUsePreferredAddress", session_use_preferred_address);
|
||||
SETFUNCTION("onSessionPathValidation", session_path_validation);
|
||||
SETFUNCTION("onSessionQlog", session_qlog);
|
||||
SETFUNCTION("onSessionSilentClose", session_silent_close);
|
||||
SETFUNCTION("onSessionStatus", session_status);
|
||||
SETFUNCTION("onSessionTicket", session_ticket);
|
||||
SETFUNCTION("onSessionVersionNegotiation", session_version_negotiation);
|
||||
SETFUNCTION("onStreamReady", stream_ready);
|
||||
SETFUNCTION("onStreamClose", stream_close);
|
||||
SETFUNCTION("onStreamError", stream_error);
|
||||
SETFUNCTION("onStreamReset", stream_reset);
|
||||
SETFUNCTION("onSocketServerBusy", socket_server_busy);
|
||||
SETFUNCTION("onStreamHeaders", stream_headers);
|
||||
SETFUNCTION("onStreamBlocked", stream_blocked);
|
||||
|
||||
#undef SETFUNCTION
|
||||
}
|
||||
|
||||
// Sets QUIC specific configuration options for the SecureContext.
|
||||
// It's entirely likely that there's a better way to do this, but
|
||||
// for now this works.
|
||||
template <ngtcp2_crypto_side side>
|
||||
void QuicInitSecureContext(const FunctionCallbackInfo<Value>& args) {
|
||||
Environment* env = Environment::GetCurrent(args);
|
||||
CHECK(args[0]->IsObject()); // Secure Context
|
||||
CHECK(args[1]->IsString()); // groups
|
||||
CHECK(args[2]->IsBoolean()); // early data
|
||||
|
||||
SecureContext* sc;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&sc, args[0].As<Object>(),
|
||||
args.GetReturnValue().Set(UV_EBADF));
|
||||
const node::Utf8Value groups(env->isolate(), args[1]);
|
||||
|
||||
bool early_data = args[2]->BooleanValue(env->isolate());
|
||||
|
||||
InitializeSecureContext(
|
||||
BaseObjectPtr<SecureContext>(sc),
|
||||
early_data,
|
||||
side);
|
||||
|
||||
if (!crypto::SetGroups(sc, *groups))
|
||||
THROW_ERR_QUIC_CANNOT_SET_GROUPS(env);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void Initialize(Local<Object> target,
|
||||
Local<Value> unused,
|
||||
Local<Context> context,
|
||||
void* priv) {
|
||||
Environment* env = Environment::GetCurrent(context);
|
||||
Isolate* isolate = env->isolate();
|
||||
HandleScope handle_scope(isolate);
|
||||
|
||||
HistogramBase::Initialize(env);
|
||||
|
||||
QuicState* const state =
|
||||
env->AddBindingData<QuicState>(context, target);
|
||||
if (state == nullptr) return;
|
||||
|
||||
#define SET_STATE_TYPEDARRAY(name, field) \
|
||||
target->Set(context, \
|
||||
FIXED_ONE_BYTE_STRING(isolate, (name)), \
|
||||
(field.GetJSArray())).FromJust()
|
||||
SET_STATE_TYPEDARRAY("sessionConfig", state->quicsessionconfig_buffer);
|
||||
SET_STATE_TYPEDARRAY("http3Config", state->http3config_buffer);
|
||||
#undef SET_STATE_TYPEDARRAY
|
||||
|
||||
QuicSocket::Initialize(env, target, context);
|
||||
QuicEndpoint::Initialize(env, target, context);
|
||||
QuicSession::Initialize(env, target, context);
|
||||
QuicStream::Initialize(env, target, context);
|
||||
|
||||
env->SetMethod(target,
|
||||
"setCallbacks",
|
||||
QuicSetCallbacks);
|
||||
env->SetMethod(target,
|
||||
"initSecureContext",
|
||||
QuicInitSecureContext<NGTCP2_CRYPTO_SIDE_SERVER>);
|
||||
env->SetMethod(target,
|
||||
"initSecureContextClient",
|
||||
QuicInitSecureContext<NGTCP2_CRYPTO_SIDE_CLIENT>);
|
||||
|
||||
Local<Object> constants = Object::New(env->isolate());
|
||||
|
||||
// TODO(@jasnell): Audit which constants are actually being used in JS
|
||||
#define QUIC_CONSTANTS(V) \
|
||||
V(DEFAULT_MAX_STREAM_DATA_BIDI_LOCAL) \
|
||||
V(DEFAULT_RETRYTOKEN_EXPIRATION) \
|
||||
V(DEFAULT_MAX_CONNECTIONS) \
|
||||
V(DEFAULT_MAX_CONNECTIONS_PER_HOST) \
|
||||
V(DEFAULT_MAX_STATELESS_RESETS_PER_HOST) \
|
||||
V(IDX_HTTP3_QPACK_MAX_TABLE_CAPACITY) \
|
||||
V(IDX_HTTP3_QPACK_BLOCKED_STREAMS) \
|
||||
V(IDX_HTTP3_MAX_HEADER_LIST_SIZE) \
|
||||
V(IDX_HTTP3_MAX_PUSHES) \
|
||||
V(IDX_HTTP3_MAX_HEADER_PAIRS) \
|
||||
V(IDX_HTTP3_MAX_HEADER_LENGTH) \
|
||||
V(IDX_HTTP3_CONFIG_COUNT) \
|
||||
V(IDX_QUIC_SESSION_ACTIVE_CONNECTION_ID_LIMIT) \
|
||||
V(IDX_QUIC_SESSION_MAX_IDLE_TIMEOUT) \
|
||||
V(IDX_QUIC_SESSION_MAX_DATA) \
|
||||
V(IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_LOCAL) \
|
||||
V(IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_REMOTE) \
|
||||
V(IDX_QUIC_SESSION_MAX_STREAM_DATA_UNI) \
|
||||
V(IDX_QUIC_SESSION_MAX_STREAMS_BIDI) \
|
||||
V(IDX_QUIC_SESSION_MAX_STREAMS_UNI) \
|
||||
V(IDX_QUIC_SESSION_MAX_PACKET_SIZE) \
|
||||
V(IDX_QUIC_SESSION_ACK_DELAY_EXPONENT) \
|
||||
V(IDX_QUIC_SESSION_DISABLE_MIGRATION) \
|
||||
V(IDX_QUIC_SESSION_MAX_ACK_DELAY) \
|
||||
V(IDX_QUIC_SESSION_CONFIG_COUNT) \
|
||||
V(IDX_QUIC_SESSION_STATE_CERT_ENABLED) \
|
||||
V(IDX_QUIC_SESSION_STATE_CLIENT_HELLO_ENABLED) \
|
||||
V(IDX_QUIC_SESSION_STATE_USE_PREFERRED_ADDRESS_ENABLED) \
|
||||
V(IDX_QUIC_SESSION_STATE_PATH_VALIDATED_ENABLED) \
|
||||
V(IDX_QUIC_SESSION_STATE_KEYLOG_ENABLED) \
|
||||
V(IDX_QUIC_SESSION_STATE_MAX_STREAMS_BIDI) \
|
||||
V(IDX_QUIC_SESSION_STATE_MAX_STREAMS_UNI) \
|
||||
V(IDX_QUIC_SESSION_STATE_MAX_DATA_LEFT) \
|
||||
V(IDX_QUIC_SESSION_STATE_BYTES_IN_FLIGHT) \
|
||||
V(IDX_QUIC_SESSION_STATE_HANDSHAKE_CONFIRMED) \
|
||||
V(IDX_QUIC_SESSION_STATE_IDLE_TIMEOUT) \
|
||||
V(MAX_RETRYTOKEN_EXPIRATION) \
|
||||
V(MIN_RETRYTOKEN_EXPIRATION) \
|
||||
V(NGTCP2_APP_NOERROR) \
|
||||
V(NGTCP2_PATH_VALIDATION_RESULT_FAILURE) \
|
||||
V(NGTCP2_PATH_VALIDATION_RESULT_SUCCESS) \
|
||||
V(QUIC_ERROR_APPLICATION) \
|
||||
V(QUIC_ERROR_CRYPTO) \
|
||||
V(QUIC_ERROR_SESSION) \
|
||||
V(QUIC_PREFERRED_ADDRESS_USE) \
|
||||
V(QUIC_PREFERRED_ADDRESS_IGNORE) \
|
||||
V(QUICCLIENTSESSION_OPTION_REQUEST_OCSP) \
|
||||
V(QUICCLIENTSESSION_OPTION_VERIFY_HOSTNAME_IDENTITY) \
|
||||
V(QUICSERVERSESSION_OPTION_REJECT_UNAUTHORIZED) \
|
||||
V(QUICSERVERSESSION_OPTION_REQUEST_CERT) \
|
||||
V(QUICSOCKET_OPTIONS_VALIDATE_ADDRESS) \
|
||||
V(QUICSOCKET_OPTIONS_VALIDATE_ADDRESS_LRU) \
|
||||
V(QUICSTREAM_HEADER_FLAGS_NONE) \
|
||||
V(QUICSTREAM_HEADER_FLAGS_TERMINAL) \
|
||||
V(QUICSTREAM_HEADERS_KIND_NONE) \
|
||||
V(QUICSTREAM_HEADERS_KIND_INFORMATIONAL) \
|
||||
V(QUICSTREAM_HEADERS_KIND_PUSH) \
|
||||
V(QUICSTREAM_HEADERS_KIND_INITIAL) \
|
||||
V(QUICSTREAM_HEADERS_KIND_TRAILING) \
|
||||
V(ERR_FAILED_TO_CREATE_SESSION) \
|
||||
V(UV_EBADF)
|
||||
|
||||
#define V(name, _, __) \
|
||||
NODE_DEFINE_CONSTANT(constants, IDX_QUIC_SESSION_STATS_##name);
|
||||
SESSION_STATS(V)
|
||||
#undef V
|
||||
|
||||
#define V(name, _, __) \
|
||||
NODE_DEFINE_CONSTANT(constants, IDX_QUIC_SOCKET_STATS_##name);
|
||||
SOCKET_STATS(V)
|
||||
#undef V
|
||||
|
||||
#define V(name, _, __) \
|
||||
NODE_DEFINE_CONSTANT(constants, IDX_QUIC_STREAM_STATS_##name);
|
||||
STREAM_STATS(V)
|
||||
#undef V
|
||||
|
||||
#define V(name) NODE_DEFINE_CONSTANT(constants, name);
|
||||
QUIC_CONSTANTS(V)
|
||||
#undef V
|
||||
|
||||
NODE_DEFINE_CONSTANT(constants, NGTCP2_PROTO_VER);
|
||||
NODE_DEFINE_CONSTANT(constants, NGTCP2_DEFAULT_MAX_ACK_DELAY);
|
||||
NODE_DEFINE_CONSTANT(constants, NGTCP2_MAX_CIDLEN);
|
||||
NODE_DEFINE_CONSTANT(constants, NGTCP2_MIN_CIDLEN);
|
||||
NODE_DEFINE_CONSTANT(constants, NGTCP2_NO_ERROR);
|
||||
NODE_DEFINE_CONSTANT(constants, AF_INET);
|
||||
NODE_DEFINE_CONSTANT(constants, AF_INET6);
|
||||
NODE_DEFINE_STRING_CONSTANT(constants,
|
||||
NODE_STRINGIFY_HELPER(NGTCP2_ALPN_H3),
|
||||
NGTCP2_ALPN_H3);
|
||||
|
||||
target->Set(context, env->constants_string(), constants).FromJust();
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
NODE_MODULE_CONTEXT_AWARE_INTERNAL(quic, node::quic::Initialize)
|
||||
@@ -0,0 +1,99 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_BUFFER_INL_H_
|
||||
#define SRC_QUIC_NODE_QUIC_BUFFER_INL_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "node_quic_buffer.h"
|
||||
#include "node_bob-inl.h"
|
||||
#include "util-inl.h"
|
||||
#include "uv.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace node {
|
||||
|
||||
namespace quic {
|
||||
|
||||
QuicBufferChunk::QuicBufferChunk(size_t len)
|
||||
: data_buf_(len, 0),
|
||||
buf_(uv_buf_init(reinterpret_cast<char*>(data_buf_.data()), len)),
|
||||
length_(len),
|
||||
done_called_(true) {}
|
||||
|
||||
QuicBufferChunk::QuicBufferChunk(uv_buf_t buf, DoneCB done)
|
||||
: buf_(buf),
|
||||
length_(buf.len) {
|
||||
if (done != nullptr)
|
||||
done_ = std::move(done);
|
||||
}
|
||||
|
||||
QuicBufferChunk::~QuicBufferChunk() {
|
||||
CHECK(done_called_);
|
||||
}
|
||||
|
||||
size_t QuicBufferChunk::Seek(size_t amount) {
|
||||
amount = std::min(amount, remaining());
|
||||
buf_.base += amount;
|
||||
buf_.len -= amount;
|
||||
return amount;
|
||||
}
|
||||
|
||||
size_t QuicBufferChunk::Consume(size_t amount) {
|
||||
amount = std::min(amount, length_);
|
||||
length_ -= amount;
|
||||
return amount;
|
||||
}
|
||||
|
||||
void QuicBufferChunk::Done(int status) {
|
||||
if (done_called_) return;
|
||||
done_called_ = true;
|
||||
if (done_ != nullptr)
|
||||
std::move(done_)(status);
|
||||
}
|
||||
|
||||
QuicBuffer::QuicBuffer(QuicBuffer&& src) noexcept
|
||||
: head_(src.head_),
|
||||
tail_(src.tail_),
|
||||
ended_(src.ended_),
|
||||
length_(src.length_) {
|
||||
root_ = std::move(src.root_);
|
||||
src.head_ = nullptr;
|
||||
src.tail_ = nullptr;
|
||||
src.length_ = 0;
|
||||
src.remaining_ = 0;
|
||||
src.ended_ = false;
|
||||
}
|
||||
|
||||
|
||||
QuicBuffer& QuicBuffer::operator=(QuicBuffer&& src) noexcept {
|
||||
if (this == &src) return *this;
|
||||
this->~QuicBuffer();
|
||||
return *new(this) QuicBuffer(std::move(src));
|
||||
}
|
||||
|
||||
bool QuicBuffer::is_empty(uv_buf_t buf) {
|
||||
DCHECK_IMPLIES(buf.base == nullptr, buf.len == 0);
|
||||
return buf.len == 0;
|
||||
}
|
||||
|
||||
size_t QuicBuffer::Consume(size_t amount) {
|
||||
return Consume(0, amount);
|
||||
}
|
||||
|
||||
size_t QuicBuffer::Cancel(int status) {
|
||||
if (canceled_) return 0;
|
||||
canceled_ = true;
|
||||
size_t t = Consume(status, length());
|
||||
return t;
|
||||
}
|
||||
|
||||
void QuicBuffer::Push(uv_buf_t buf, DoneCB done) {
|
||||
std::unique_ptr<QuicBufferChunk> chunk =
|
||||
std::make_unique<QuicBufferChunk>(buf, done);
|
||||
Push(std::move(chunk));
|
||||
}
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // NODE_WANT_INTERNALS
|
||||
#endif // SRC_QUIC_NODE_QUIC_BUFFER_INL_H_
|
||||
@@ -0,0 +1,159 @@
|
||||
#include "node_quic_buffer-inl.h" // NOLINT(build/include)
|
||||
#include "node_bob-inl.h"
|
||||
#include "util.h"
|
||||
#include "uv.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
namespace node {
|
||||
namespace quic {
|
||||
|
||||
void QuicBufferChunk::MemoryInfo(MemoryTracker* tracker) const {
|
||||
tracker->TrackField("buf", data_buf_);
|
||||
tracker->TrackField("next", next_);
|
||||
}
|
||||
|
||||
size_t QuicBuffer::Push(uv_buf_t* bufs, size_t nbufs, DoneCB done) {
|
||||
size_t len = 0;
|
||||
if (nbufs == 0 || bufs == nullptr || is_empty(bufs[0])) {
|
||||
done(0);
|
||||
return 0;
|
||||
}
|
||||
size_t n = 0;
|
||||
while (nbufs > 1) {
|
||||
if (!is_empty(bufs[n])) {
|
||||
Push(bufs[n]);
|
||||
len += bufs[n].len;
|
||||
}
|
||||
n++;
|
||||
nbufs--;
|
||||
}
|
||||
len += bufs[n].len;
|
||||
Push(bufs[n], done);
|
||||
return len;
|
||||
}
|
||||
|
||||
void QuicBuffer::Push(std::unique_ptr<QuicBufferChunk> chunk) {
|
||||
CHECK(!ended_);
|
||||
length_ += chunk->remaining();
|
||||
remaining_ += chunk->remaining();
|
||||
if (!tail_) {
|
||||
root_ = std::move(chunk);
|
||||
head_ = tail_ = root_.get();
|
||||
} else {
|
||||
tail_->next_ = std::move(chunk);
|
||||
tail_ = tail_->next_.get();
|
||||
if (!head_)
|
||||
head_ = tail_;
|
||||
}
|
||||
}
|
||||
|
||||
size_t QuicBuffer::Seek(size_t amount) {
|
||||
size_t len = 0;
|
||||
while (head_ && amount > 0) {
|
||||
size_t amt = head_->Seek(amount);
|
||||
amount -= amt;
|
||||
len += amt;
|
||||
remaining_ -= amt;
|
||||
if (head_->remaining())
|
||||
break;
|
||||
head_ = head_->next_.get();
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
bool QuicBuffer::Pop(int status) {
|
||||
if (!root_)
|
||||
return false;
|
||||
std::unique_ptr<QuicBufferChunk> root(std::move(root_));
|
||||
root_ = std::move(root.get()->next_);
|
||||
|
||||
if (head_ == root.get())
|
||||
head_ = root_.get();
|
||||
if (tail_ == root.get())
|
||||
tail_ = root_.get();
|
||||
|
||||
root->Done(status);
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t QuicBuffer::Consume(int status, size_t amount) {
|
||||
size_t amt = std::min(amount, length_);
|
||||
size_t len = 0;
|
||||
while (root_ && amt > 0) {
|
||||
auto root = root_.get();
|
||||
size_t consumed = root->Consume(amt);
|
||||
len += consumed;
|
||||
length_ -= consumed;
|
||||
amt -= consumed;
|
||||
if (root->length() > 0)
|
||||
break;
|
||||
Pop(status);
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
void QuicBuffer::MemoryInfo(MemoryTracker* tracker) const {
|
||||
tracker->TrackField("root", root_);
|
||||
}
|
||||
|
||||
int QuicBuffer::DoPull(
|
||||
bob::Next<ngtcp2_vec> next,
|
||||
int options,
|
||||
ngtcp2_vec* data,
|
||||
size_t count,
|
||||
size_t max_count_hint) {
|
||||
size_t len = 0;
|
||||
size_t numbytes = 0;
|
||||
int status = bob::Status::STATUS_CONTINUE;
|
||||
|
||||
// There's no data to read.
|
||||
if (!remaining() || head_ == nullptr) {
|
||||
status = is_ended() ?
|
||||
bob::Status::STATUS_END :
|
||||
bob::Status::STATUS_BLOCK;
|
||||
std::move(next)(status, nullptr, 0, [](size_t len) {});
|
||||
return status;
|
||||
}
|
||||
|
||||
// Ensure that there's storage space.
|
||||
MaybeStackBuffer<ngtcp2_vec, kMaxVectorCount> vec;
|
||||
if (data == nullptr || count == 0) {
|
||||
vec.AllocateSufficientStorage(max_count_hint);
|
||||
data = vec.out();
|
||||
} else {
|
||||
max_count_hint = std::min(count, max_count_hint);
|
||||
}
|
||||
|
||||
// Build the list of buffers.
|
||||
QuicBufferChunk* pos = head_;
|
||||
while (pos != nullptr && len < max_count_hint) {
|
||||
data[len].base = reinterpret_cast<uint8_t*>(pos->buf().base);
|
||||
data[len].len = pos->buf().len;
|
||||
numbytes += data[len].len;
|
||||
len++;
|
||||
pos = pos->next_.get();
|
||||
}
|
||||
|
||||
// If the buffer is ended, and the number of bytes
|
||||
// matches the total remaining and OPTIONS_END is
|
||||
// used, set the status to STATUS_END.
|
||||
if (is_ended() &&
|
||||
numbytes == remaining() &&
|
||||
options & bob::OPTIONS_END)
|
||||
status = bob::Status::STATUS_END;
|
||||
|
||||
// Pass the data back out to the caller.
|
||||
std::move(next)(
|
||||
status,
|
||||
data,
|
||||
len,
|
||||
std::move([this](size_t len) { Seek(len); }));
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
@@ -0,0 +1,239 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_BUFFER_H_
|
||||
#define SRC_QUIC_NODE_QUIC_BUFFER_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "memory_tracker-inl.h"
|
||||
#include "ngtcp2/ngtcp2.h"
|
||||
#include "node.h"
|
||||
#include "node_bob.h"
|
||||
#include "node_internals.h"
|
||||
#include "util.h"
|
||||
#include "uv.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace node {
|
||||
namespace quic {
|
||||
|
||||
class QuicBuffer;
|
||||
|
||||
constexpr size_t kMaxVectorCount = 16;
|
||||
|
||||
using DoneCB = std::function<void(int)>;
|
||||
|
||||
// When data is sent over QUIC, we are required to retain it in memory
|
||||
// until we receive an acknowledgement that it has been successfully
|
||||
// acknowledged. The QuicBuffer object is what we use to handle that
|
||||
// and track until it is acknowledged. To understand the QuicBuffer
|
||||
// object itself, it is important to understand how ngtcp2 and nghttp3
|
||||
// handle data that is given to it to serialize into QUIC packets.
|
||||
//
|
||||
// An individual QUIC packet may contain multiple QUIC frames. Whenever
|
||||
// we create a QUIC packet, we really have no idea what frames are going
|
||||
// to be encoded or how much buffered handshake or stream data is going
|
||||
// to be included within that QuicPacket. If there is buffered data
|
||||
// available for a stream, we provide an array of pointers to that data
|
||||
// and an indication about how much data is available, then we leave it
|
||||
// entirely up to ngtcp2 and nghttp3 to determine how much of the data
|
||||
// to encode into the QUIC packet. It is only *after* the QUIC packet
|
||||
// is encoded that we can know how much was actually written.
|
||||
//
|
||||
// Once written to a QUIC Packet, we have to keep the data in memory
|
||||
// until an acknowledgement is received. In QUIC, acknowledgements are
|
||||
// received per range of packets.
|
||||
//
|
||||
// QuicBuffer is complicated because it needs to be able to accomplish
|
||||
// three things: (a) buffering uv_buf_t instances passed down from
|
||||
// JavaScript without memcpy and keeping track of the Write callback
|
||||
// associated with each, (b) tracking what data has already been
|
||||
// encoded in a QUIC packet and what data is remaining to be read, and
|
||||
// (c) tracking which data has been acknowledged and which hasn't.
|
||||
// QuicBuffer is further complicated by design quirks and limitations
|
||||
// of the StreamBase API and how it interacts with the JavaScript side.
|
||||
//
|
||||
// QuicBuffer is essentially a linked list of QuicBufferChunk instances.
|
||||
// A single QuicBufferChunk wraps a single non-zero-length uv_buf_t.
|
||||
// When the QuicBufferChunk is created, we capture the total length
|
||||
// of the buffer and the total number of bytes remaining to be sent.
|
||||
// Initially, these numbers are identical.
|
||||
//
|
||||
// When data is encoded into a QuicPacket, we advance the QuicBufferChunk's
|
||||
// remaining-to-be-read by the number of bytes actually encoded. If there
|
||||
// are no more bytes remaining to be encoded, we move to the next chunk
|
||||
// in the linked list.
|
||||
//
|
||||
// When an acknowledgement is received, we decrement the QuicBufferChunk's
|
||||
// length by the number of acknowledged bytes. Once the unacknowledged
|
||||
// length reaches 0, we invoke the callback function associated with the
|
||||
// QuicBufferChunk (if any).
|
||||
//
|
||||
// QuicStream is a StreamBase implementation. For every DoWrite call,
|
||||
// it receives one or more uv_buf_t instances in a single batch associated
|
||||
// with a single write callback. For each uv_buf_t DoWrite gets, a
|
||||
// corresponding QuicBufferChunk is added to the QuicBuffer, with the
|
||||
// callback associated with the final chunk added to the list.
|
||||
|
||||
|
||||
// A QuicBufferChunk contains the actual buffered data
|
||||
// along with a callback to be called when the data has
|
||||
// been consumed.
|
||||
//
|
||||
// Any given chunk as a remaining-to-be-acknowledged length (length()) and a
|
||||
// remaining-to-be-read-length (remaining()). The former tracks the number
|
||||
// of bytes that have yet to be acknowledged by the QUIC peer. Once the
|
||||
// remaining-to-be-acknowledged length reaches zero, the done callback
|
||||
// associated with the QuicBufferChunk can be called and the QuicBufferChunk
|
||||
// can be discarded. The remaining-to-be-read length is adjusted as data is
|
||||
// serialized into QUIC packets and sent.
|
||||
// The remaining-to-be-acknowledged length is adjusted using consume(),
|
||||
// while the remaining-to-be-ead length is adjusted using seek().
|
||||
class QuicBufferChunk : public MemoryRetainer {
|
||||
public:
|
||||
// Default non-op done handler.
|
||||
static void default_done(int status) {}
|
||||
|
||||
// In this variant, the QuicBufferChunk owns the underlying
|
||||
// data storage within a vector. The data will be
|
||||
// freed when the QuicBufferChunk is destroyed.
|
||||
inline explicit QuicBufferChunk(size_t len);
|
||||
|
||||
// In this variant, the QuicBufferChunk only maintains a
|
||||
// pointer to the underlying data buffer. The QuicBufferChunk
|
||||
// does not take ownership of the buffer. The done callback
|
||||
// is invoked to let the caller know when the chunk is no
|
||||
// longer being used.
|
||||
inline QuicBufferChunk(uv_buf_t buf_, DoneCB done_);
|
||||
|
||||
inline ~QuicBufferChunk() override;
|
||||
|
||||
// Invokes the done callback associated with the QuicBufferChunk.
|
||||
inline void Done(int status);
|
||||
|
||||
// length() provides the remaining-to-be-acknowledged length.
|
||||
// The QuicBufferChunk must be retained in memory while this
|
||||
// count is greater than zero. The length is adjusted by
|
||||
// calling Consume();
|
||||
inline size_t length() const { return length_; }
|
||||
|
||||
// remaining() provides the remaining-to-be-read length number of bytes.
|
||||
// The length is adjusted by calling Seek()
|
||||
inline size_t remaining() const { return buf_.len; }
|
||||
|
||||
// Consumes (acknowledges) the given number of bytes. If amount
|
||||
// is greater than length(), only length() bytes are consumed.
|
||||
// Returns the actual number of bytes consumed.
|
||||
inline size_t Consume(size_t amount);
|
||||
|
||||
// Seeks (reads) the given number of bytes. If amount is greater
|
||||
// than remaining(), only remaining() bytes are read. Returns
|
||||
// the actual number of bytes read.
|
||||
inline size_t Seek(size_t amount);
|
||||
|
||||
uint8_t* out() { return reinterpret_cast<uint8_t*>(buf_.base); }
|
||||
uv_buf_t buf() { return buf_; }
|
||||
const uv_buf_t buf() const { return buf_; }
|
||||
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
SET_MEMORY_INFO_NAME(QuicBufferChunk)
|
||||
SET_SELF_SIZE(QuicBufferChunk)
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> data_buf_;
|
||||
uv_buf_t buf_;
|
||||
DoneCB done_ = default_done;
|
||||
size_t length_ = 0;
|
||||
bool done_called_ = false;
|
||||
std::unique_ptr<QuicBufferChunk> next_;
|
||||
|
||||
friend class QuicBuffer;
|
||||
};
|
||||
|
||||
class QuicBuffer : public bob::SourceImpl<ngtcp2_vec>,
|
||||
public MemoryRetainer {
|
||||
public:
|
||||
QuicBuffer() = default;
|
||||
|
||||
inline QuicBuffer(QuicBuffer&& src) noexcept;
|
||||
inline QuicBuffer& operator=(QuicBuffer&& src) noexcept;
|
||||
|
||||
~QuicBuffer() override {
|
||||
Cancel(); // Cancel the remaining data
|
||||
CHECK_EQ(length_, 0);
|
||||
}
|
||||
|
||||
// Marks the QuicBuffer as having ended, preventing new QuicBufferChunk
|
||||
// instances from being appended to the linked list and allowing the
|
||||
// Pull operation to know when to signal that the flow of data is
|
||||
// completed.
|
||||
void End() { ended_ = true; }
|
||||
bool is_ended() const { return ended_; }
|
||||
|
||||
// Push one or more uv_buf_t instances into the buffer.
|
||||
// the DoneCB callback will be invoked when the last
|
||||
// uv_buf_t in the bufs array is consumed and popped out
|
||||
// of the internal linked list. Ownership of the uv_buf_t
|
||||
// remains with the caller.
|
||||
size_t Push(
|
||||
uv_buf_t* bufs,
|
||||
size_t nbufs,
|
||||
DoneCB done = QuicBufferChunk::default_done);
|
||||
|
||||
// Pushes a single QuicBufferChunk into the linked list
|
||||
void Push(std::unique_ptr<QuicBufferChunk> chunk);
|
||||
|
||||
// Consume the given number of bytes within the buffer. If amount
|
||||
// is greater than length(), length() bytes are consumed. Returns
|
||||
// the actual number of bytes consumed.
|
||||
inline size_t Consume(size_t amount);
|
||||
|
||||
// Cancels the remaining bytes within the buffer.
|
||||
inline size_t Cancel(int status = UV_ECANCELED);
|
||||
|
||||
// Seeks (reads) the given number of bytes. If amount is greater
|
||||
// than remaining(), seeks remaining() bytes. Returns the actual
|
||||
// number of bytes read.
|
||||
size_t Seek(size_t amount);
|
||||
|
||||
// The total number of unacknowledged bytes remaining.
|
||||
size_t length() const { return length_; }
|
||||
|
||||
// The total number of unread bytes remaining.
|
||||
size_t remaining() const { return remaining_; }
|
||||
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
SET_MEMORY_INFO_NAME(QuicBuffer);
|
||||
SET_SELF_SIZE(QuicBuffer);
|
||||
|
||||
protected:
|
||||
int DoPull(
|
||||
bob::Next<ngtcp2_vec> next,
|
||||
int options,
|
||||
ngtcp2_vec* data,
|
||||
size_t count,
|
||||
size_t max_count_hint) override;
|
||||
|
||||
private:
|
||||
inline static bool is_empty(uv_buf_t buf);
|
||||
size_t Consume(int status, size_t amount);
|
||||
bool Pop(int status = 0);
|
||||
inline void Push(uv_buf_t buf, DoneCB done = nullptr);
|
||||
|
||||
std::unique_ptr<QuicBufferChunk> root_;
|
||||
QuicBufferChunk* head_ = nullptr; // Current Read Position
|
||||
QuicBufferChunk* tail_ = nullptr; // Current Write Position
|
||||
|
||||
bool canceled_ = false;
|
||||
bool ended_ = false;
|
||||
size_t length_ = 0;
|
||||
size_t remaining_ = 0;
|
||||
|
||||
friend class QuicBufferChunk;
|
||||
};
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_BUFFER_H_
|
||||
@@ -0,0 +1,961 @@
|
||||
#include "node_quic_crypto.h"
|
||||
#include "env-inl.h"
|
||||
#include "node_crypto.h"
|
||||
#include "node_crypto_common.h"
|
||||
#include "node_process.h"
|
||||
#include "node_quic_session-inl.h"
|
||||
#include "node_quic_util-inl.h"
|
||||
#include "node_sockaddr-inl.h"
|
||||
#include "node_url.h"
|
||||
#include "string_bytes.h"
|
||||
#include "v8.h"
|
||||
#include "util-inl.h"
|
||||
|
||||
#include <ngtcp2/ngtcp2.h>
|
||||
#include <ngtcp2/ngtcp2_crypto.h>
|
||||
#include <openssl/bio.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/kdf.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/x509v3.h>
|
||||
|
||||
#include <iterator>
|
||||
#include <numeric>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace node {
|
||||
|
||||
using crypto::EntropySource;
|
||||
using v8::Local;
|
||||
using v8::String;
|
||||
using v8::Value;
|
||||
|
||||
namespace quic {
|
||||
|
||||
bool SessionTicketAppData::Set(const uint8_t* data, size_t len) {
|
||||
if (set_)
|
||||
return false;
|
||||
set_ = true;
|
||||
SSL_SESSION_set1_ticket_appdata(session_, data, len);
|
||||
return set_;
|
||||
}
|
||||
|
||||
bool SessionTicketAppData::Get(uint8_t** data, size_t* len) const {
|
||||
return SSL_SESSION_get0_ticket_appdata(
|
||||
session_,
|
||||
reinterpret_cast<void**>(data),
|
||||
len) == 1;
|
||||
}
|
||||
|
||||
namespace {
|
||||
constexpr int kCryptoTokenKeylen = 32;
|
||||
constexpr int kCryptoTokenIvlen = 32;
|
||||
|
||||
// Used solely to derive the keys used to generate and
|
||||
// validate retry tokens. The implementation of this is
|
||||
// Node.js specific. We use the current implementation
|
||||
// because it is simple.
|
||||
bool DeriveTokenKey(
|
||||
uint8_t* token_key,
|
||||
uint8_t* token_iv,
|
||||
const uint8_t* rand_data,
|
||||
size_t rand_datalen,
|
||||
const ngtcp2_crypto_ctx& ctx,
|
||||
const uint8_t* token_secret) {
|
||||
static constexpr int kCryptoTokenSecretlen = 32;
|
||||
uint8_t secret[kCryptoTokenSecretlen];
|
||||
|
||||
return
|
||||
NGTCP2_OK(ngtcp2_crypto_hkdf_extract(
|
||||
secret,
|
||||
&ctx.md,
|
||||
token_secret,
|
||||
kTokenSecretLen,
|
||||
rand_data,
|
||||
rand_datalen)) &&
|
||||
NGTCP2_OK(ngtcp2_crypto_derive_packet_protection_key(
|
||||
token_key,
|
||||
token_iv,
|
||||
nullptr,
|
||||
&ctx.aead,
|
||||
&ctx.md,
|
||||
secret,
|
||||
kCryptoTokenSecretlen));
|
||||
}
|
||||
|
||||
// Retry tokens are generated only by QUIC servers. They
|
||||
// are opaque to QUIC clients and must not be guessable by
|
||||
// on- or off-path attackers. A QUIC server sends a RETRY
|
||||
// token as a way of initiating explicit path validation
|
||||
// with a client in response to an initial QUIC packet.
|
||||
// The client, upon receiving a RETRY, must abandon the
|
||||
// initial connection attempt and try again, including the
|
||||
// received retry token in the new initial packet sent to
|
||||
// the server. If the server is performing explicit
|
||||
// valiation, it will look for the presence of the retry
|
||||
// token and validate it if found. The internal structure
|
||||
// of the retry token must be meaningful to the server,
|
||||
// and the server must be able to validate the token without
|
||||
// relying on any state left over from the previous connection
|
||||
// attempt. The implementation here is entirely Node.js
|
||||
// specific.
|
||||
//
|
||||
// The token is generated by:
|
||||
// 1. Appending the raw bytes of given socket address, the current
|
||||
// timestamp, and the original CID together into a single byte
|
||||
// array.
|
||||
// 2. Generating a block of random data that is used together with
|
||||
// the token secret to cryptographically derive an encryption key.
|
||||
// 3. Encrypting the byte array from step 1 using the encryption key
|
||||
// from step 2.
|
||||
// 4. Appending random data generated in step 2 to the token.
|
||||
//
|
||||
// The token secret must be kept secret on the QUIC server that
|
||||
// generated the retry. When multiple QUIC servers are used in a
|
||||
// cluster, it cannot be guaranteed that the same QUIC server
|
||||
// instance will receive the subsequent new Initial packet. Therefore,
|
||||
// all QUIC servers in the cluster should either share or be aware
|
||||
// of the same token secret or a mechanism needs to be implemented
|
||||
// to ensure that subsequent packets are routed to the same QUIC
|
||||
// server instance.
|
||||
//
|
||||
// A malicious peer could attempt to guess the token secret by
|
||||
// sending a large number specially crafted RETRY-eliciting packets
|
||||
// to a server then analyzing the resulting retry tokens. To reduce
|
||||
// the possibility of such attacks, the current implementation of
|
||||
// QuicSocket generates the token secret randomly for each instance,
|
||||
// and the number of RETRY responses sent to a given remote address
|
||||
// should be limited. Such attacks should be of little actual value
|
||||
// in most cases.
|
||||
bool GenerateRetryToken(
|
||||
uint8_t* token,
|
||||
size_t* tokenlen,
|
||||
const SocketAddress& addr,
|
||||
const QuicCID& ocid,
|
||||
const uint8_t* token_secret) {
|
||||
std::array<uint8_t, 4096> plaintext;
|
||||
uint8_t rand_data[kTokenRandLen];
|
||||
uint8_t token_key[kCryptoTokenKeylen];
|
||||
uint8_t token_iv[kCryptoTokenIvlen];
|
||||
|
||||
ngtcp2_crypto_ctx ctx;
|
||||
ngtcp2_crypto_ctx_initial(&ctx);
|
||||
size_t ivlen = ngtcp2_crypto_packet_protection_ivlen(&ctx.aead);
|
||||
uint64_t now = uv_hrtime();
|
||||
|
||||
auto p = std::begin(plaintext);
|
||||
p = std::copy_n(addr.raw(), addr.length(), p);
|
||||
p = std::copy_n(reinterpret_cast<uint8_t*>(&now), sizeof(uint64_t), p);
|
||||
p = std::copy_n(ocid->data, ocid->datalen, p);
|
||||
|
||||
EntropySource(rand_data, kTokenRandLen);
|
||||
|
||||
if (!DeriveTokenKey(
|
||||
token_key,
|
||||
token_iv,
|
||||
rand_data,
|
||||
kTokenRandLen,
|
||||
ctx,
|
||||
token_secret)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t plaintextlen = std::distance(std::begin(plaintext), p);
|
||||
if (NGTCP2_ERR(ngtcp2_crypto_encrypt(
|
||||
token,
|
||||
&ctx.aead,
|
||||
plaintext.data(),
|
||||
plaintextlen,
|
||||
token_key,
|
||||
token_iv,
|
||||
ivlen,
|
||||
addr.raw(),
|
||||
addr.length()))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*tokenlen = plaintextlen + ngtcp2_crypto_aead_taglen(&ctx.aead);
|
||||
memcpy(token + (*tokenlen), rand_data, kTokenRandLen);
|
||||
*tokenlen += kTokenRandLen;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// A stateless reset token is used when a QUIC endpoint receives a
|
||||
// QUIC packet with a short header but the associated connection ID
|
||||
// cannot be matched to any known QuicSession. In such cases, the
|
||||
// receiver may choose to send a subtle opaque indication to the
|
||||
// sending peer that state for the QuicSession has apparently been
|
||||
// lost. For any on- or off- path attacker, a stateless reset packet
|
||||
// resembles any other QUIC packet with a short header. In order to
|
||||
// be successfully handled as a stateless reset, the peer must have
|
||||
// already seen a reset token issued to it associated with the given
|
||||
// CID. The token itself is opaque to the peer that receives is but
|
||||
// must be possible to statelessly recreate by the peer that
|
||||
// originally created it. The actual implementation is Node.js
|
||||
// specific but we currently defer to a utility function provided
|
||||
// by ngtcp2.
|
||||
bool GenerateResetToken(
|
||||
uint8_t* token,
|
||||
const uint8_t* secret,
|
||||
const QuicCID& cid) {
|
||||
ngtcp2_crypto_ctx ctx;
|
||||
ngtcp2_crypto_ctx_initial(&ctx);
|
||||
return NGTCP2_OK(ngtcp2_crypto_generate_stateless_reset_token(
|
||||
token,
|
||||
&ctx.md,
|
||||
secret,
|
||||
NGTCP2_STATELESS_RESET_TOKENLEN,
|
||||
cid.cid()));
|
||||
}
|
||||
|
||||
// Generates a RETRY packet. See the notes for GenerateRetryToken for details.
|
||||
std::unique_ptr<QuicPacket> GenerateRetryPacket(
|
||||
const uint8_t* token_secret,
|
||||
const QuicCID& dcid,
|
||||
const QuicCID& scid,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr) {
|
||||
|
||||
uint8_t token[256];
|
||||
size_t tokenlen = sizeof(token);
|
||||
|
||||
if (!GenerateRetryToken(token, &tokenlen, remote_addr, dcid, token_secret))
|
||||
return {};
|
||||
|
||||
QuicCID cid;
|
||||
EntropySource(cid.data(), kScidLen);
|
||||
cid.set_length(kScidLen);
|
||||
|
||||
size_t pktlen = tokenlen + (2 * NGTCP2_MAX_CIDLEN) + scid.length() + 8;
|
||||
CHECK_LE(pktlen, NGTCP2_MAX_PKT_SIZE);
|
||||
|
||||
auto packet = QuicPacket::Create("retry", pktlen);
|
||||
ssize_t nwrite =
|
||||
ngtcp2_crypto_write_retry(
|
||||
packet->data(),
|
||||
NGTCP2_MAX_PKTLEN_IPV4,
|
||||
scid.cid(),
|
||||
cid.cid(),
|
||||
dcid.cid(),
|
||||
token,
|
||||
tokenlen);
|
||||
if (nwrite <= 0)
|
||||
return {};
|
||||
packet->set_length(nwrite);
|
||||
return packet;
|
||||
}
|
||||
|
||||
// Validates a retry token included in the given header. This will return
|
||||
// true if the token cannot be validated, false otherwise. A token is
|
||||
// valid if it can be successfully decrypted using the key derived from
|
||||
// random data embedded in the token, the structure of the token matches
|
||||
// that generated by the GenerateRetryToken function, and the token was
|
||||
// not generated earlier than now - verification_expiration. If validation
|
||||
// is successful, ocid will be updated to the original connection ID encoded
|
||||
// in the encrypted token.
|
||||
bool InvalidRetryToken(
|
||||
const ngtcp2_pkt_hd& hd,
|
||||
const SocketAddress& addr,
|
||||
QuicCID* ocid,
|
||||
const uint8_t* token_secret,
|
||||
uint64_t verification_expiration) {
|
||||
|
||||
if (hd.tokenlen < kTokenRandLen)
|
||||
return true;
|
||||
|
||||
ngtcp2_crypto_ctx ctx;
|
||||
ngtcp2_crypto_ctx_initial(&ctx);
|
||||
|
||||
size_t ivlen = ngtcp2_crypto_packet_protection_ivlen(&ctx.aead);
|
||||
|
||||
size_t ciphertextlen = hd.tokenlen - kTokenRandLen;
|
||||
const uint8_t* ciphertext = hd.token;
|
||||
const uint8_t* rand_data = hd.token + ciphertextlen;
|
||||
|
||||
uint8_t token_key[kCryptoTokenKeylen];
|
||||
uint8_t token_iv[kCryptoTokenIvlen];
|
||||
|
||||
if (!DeriveTokenKey(
|
||||
token_key,
|
||||
token_iv,
|
||||
rand_data,
|
||||
kTokenRandLen,
|
||||
ctx,
|
||||
token_secret)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
uint8_t plaintext[4096];
|
||||
|
||||
if (NGTCP2_ERR(ngtcp2_crypto_decrypt(
|
||||
plaintext,
|
||||
&ctx.aead,
|
||||
ciphertext,
|
||||
ciphertextlen,
|
||||
token_key,
|
||||
token_iv,
|
||||
ivlen,
|
||||
addr.raw(),
|
||||
addr.length()))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t plaintextlen = ciphertextlen - ngtcp2_crypto_aead_taglen(&ctx.aead);
|
||||
if (plaintextlen < addr.length() + sizeof(uint64_t))
|
||||
return true;
|
||||
|
||||
ssize_t cil = plaintextlen - addr.length() - sizeof(uint64_t);
|
||||
if ((cil != 0 && (cil < NGTCP2_MIN_CIDLEN || cil > NGTCP2_MAX_CIDLEN)) ||
|
||||
memcmp(plaintext, addr.raw(), addr.length()) != 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
uint64_t t;
|
||||
memcpy(&t, plaintext + addr.length(), sizeof(uint64_t));
|
||||
|
||||
// 10-second window by default, but configurable for each
|
||||
// QuicSocket instance with a MIN_RETRYTOKEN_EXPIRATION second
|
||||
// minimum and a MAX_RETRYTOKEN_EXPIRATION second maximum.
|
||||
if (t + verification_expiration * NGTCP2_SECONDS < uv_hrtime())
|
||||
return true;
|
||||
|
||||
ngtcp2_cid_init(
|
||||
ocid->cid(),
|
||||
plaintext + addr.length() + sizeof(uint64_t),
|
||||
cil);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
bool SplitHostname(
|
||||
const char* hostname,
|
||||
std::vector<std::string>* parts,
|
||||
const char delim = '.') {
|
||||
static std::string check_str =
|
||||
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30"
|
||||
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40"
|
||||
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50"
|
||||
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60"
|
||||
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70"
|
||||
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F";
|
||||
|
||||
std::stringstream str(hostname);
|
||||
std::string part;
|
||||
while (getline(str, part, delim)) {
|
||||
// if (part.length() == 0 ||
|
||||
// part.find_first_not_of(check_str) != std::string::npos) {
|
||||
// return false;
|
||||
// }
|
||||
for (size_t n = 0; n < part.length(); n++) {
|
||||
if (part[n] >= 'A' && part[n] <= 'Z')
|
||||
part[n] = (part[n] | 0x20); // Lower case the letter
|
||||
if (check_str.find(part[n]) == std::string::npos)
|
||||
return false;
|
||||
}
|
||||
parts->push_back(part);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CheckCertNames(
|
||||
const std::vector<std::string>& host_parts,
|
||||
const std::string& name,
|
||||
bool use_wildcard = true) {
|
||||
|
||||
if (name.length() == 0)
|
||||
return false;
|
||||
|
||||
std::vector<std::string> name_parts;
|
||||
if (!SplitHostname(name.c_str(), &name_parts))
|
||||
return false;
|
||||
|
||||
if (name_parts.size() != host_parts.size())
|
||||
return false;
|
||||
|
||||
for (size_t n = host_parts.size() - 1; n > 0; --n) {
|
||||
if (host_parts[n] != name_parts[n])
|
||||
return false;
|
||||
}
|
||||
|
||||
if (name_parts[0].find("*") == std::string::npos ||
|
||||
name_parts[0].find("xn--") != std::string::npos) {
|
||||
return host_parts[0] == name_parts[0];
|
||||
}
|
||||
|
||||
if (!use_wildcard)
|
||||
return false;
|
||||
|
||||
std::vector<std::string> sub_parts;
|
||||
SplitHostname(name_parts[0].c_str(), &sub_parts, '*');
|
||||
|
||||
if (sub_parts.size() > 2)
|
||||
return false;
|
||||
|
||||
if (name_parts.size() <= 2)
|
||||
return false;
|
||||
|
||||
std::string prefix;
|
||||
std::string suffix;
|
||||
if (sub_parts.size() == 2) {
|
||||
prefix = sub_parts[0];
|
||||
suffix = sub_parts[1];
|
||||
} else {
|
||||
prefix = "";
|
||||
suffix = sub_parts[0];
|
||||
}
|
||||
|
||||
if (prefix.length() + suffix.length() > host_parts[0].length())
|
||||
return false;
|
||||
|
||||
if (host_parts[0].compare(0, prefix.length(), prefix))
|
||||
return false;
|
||||
|
||||
if (host_parts[0].compare(
|
||||
host_parts[0].length() - suffix.length(),
|
||||
suffix.length(), suffix)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int VerifyHostnameIdentity(
|
||||
const crypto::SSLPointer& ssl,
|
||||
const char* hostname) {
|
||||
int err = X509_V_ERR_HOSTNAME_MISMATCH;
|
||||
crypto::X509Pointer cert(SSL_get_peer_certificate(ssl.get()));
|
||||
if (!cert)
|
||||
return err;
|
||||
|
||||
// There are several pieces of information we need from the cert at this point
|
||||
// 1. The Subject (if it exists)
|
||||
// 2. The collection of Alt Names (if it exists)
|
||||
//
|
||||
// The certificate may have many Alt Names. We only care about the ones that
|
||||
// are prefixed with 'DNS:', 'URI:', or 'IP Address:'. We might check
|
||||
// additional ones later but we'll start with these.
|
||||
//
|
||||
// Ideally, we'd be able to *just* use OpenSSL's built in name checking for
|
||||
// this (SSL_set1_host and X509_check_host) but it does not appear to do
|
||||
// checking on URI or IP Address Alt names, which is unfortunate. We need
|
||||
// both of those to retain compatibility with the peer identity verification
|
||||
// Node.js already does elsewhere. At the very least, we'll use
|
||||
// X509_check_host here first as a first step. If it is successful, awesome,
|
||||
// there's nothing else for us to do. Return and be happy!
|
||||
if (X509_check_host(
|
||||
cert.get(),
|
||||
hostname,
|
||||
strlen(hostname),
|
||||
X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT |
|
||||
X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS |
|
||||
X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS,
|
||||
nullptr) > 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (X509_check_ip_asc(
|
||||
cert.get(),
|
||||
hostname,
|
||||
X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT) > 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// If we've made it this far, then we have to perform a more check
|
||||
return VerifyHostnameIdentity(
|
||||
hostname,
|
||||
crypto::GetCertificateCN(cert.get()),
|
||||
crypto::GetCertificateAltNames(cert.get()));
|
||||
}
|
||||
|
||||
int VerifyHostnameIdentity(
|
||||
const char* hostname,
|
||||
const std::string& cert_cn,
|
||||
const std::unordered_multimap<std::string, std::string>& altnames) {
|
||||
|
||||
int err = X509_V_ERR_HOSTNAME_MISMATCH;
|
||||
|
||||
// 1. If the hostname is an IP address (v4 or v6), the certificate is valid
|
||||
// if and only if there is an 'IP Address:' alt name specifying the same
|
||||
// IP address. The IP address must be canonicalized to ensure a proper
|
||||
// check. It's possible that the X509_check_ip_asc covers this. If so,
|
||||
// we can remove this check.
|
||||
|
||||
if (SocketAddress::is_numeric_host(hostname)) {
|
||||
auto ips = altnames.equal_range("ip");
|
||||
for (auto ip = ips.first; ip != ips.second; ++ip) {
|
||||
if (ip->second.compare(hostname) == 0) {
|
||||
// Success!
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
// No match, and since the hostname is an IP address, skip any
|
||||
// further checks
|
||||
return err;
|
||||
}
|
||||
|
||||
auto dns_names = altnames.equal_range("dns");
|
||||
auto uri_names = altnames.equal_range("uri");
|
||||
|
||||
size_t dns_count = std::distance(dns_names.first, dns_names.second);
|
||||
size_t uri_count = std::distance(uri_names.first, uri_names.second);
|
||||
|
||||
std::vector<std::string> host_parts;
|
||||
SplitHostname(hostname, &host_parts);
|
||||
|
||||
// 2. If there no 'DNS:' or 'URI:' Alt names, if the certificate has a
|
||||
// Subject, then we need to extract the CN field from the Subject. and
|
||||
// check that the hostname matches the CN, taking into consideration
|
||||
// the possibility of a wildcard in the CN. If there is a match, congrats,
|
||||
// we have a valid certificate. Return and be happy.
|
||||
|
||||
if (dns_count == 0 && uri_count == 0) {
|
||||
if (cert_cn.length() > 0 && CheckCertNames(host_parts, cert_cn))
|
||||
return 0;
|
||||
// No match, and since there are no dns or uri entries, return
|
||||
return err;
|
||||
}
|
||||
|
||||
// 3. If, however, there are 'DNS:' and 'URI:' Alt names, things become more
|
||||
// complicated. Essentially, we need to iterate through each 'DNS:' and
|
||||
// 'URI:' Alt name to find one that matches. The 'DNS:' Alt names are
|
||||
// relatively simple but may include wildcards. The 'URI:' Alt names
|
||||
// require the name to be parsed as a URL, then extract the hostname from
|
||||
// the URL, which is then checked against the hostname. If you find a
|
||||
// match, yay! Return and be happy. (Note, it's possible that the 'DNS:'
|
||||
// check in this step is redundant to the X509_check_host check. If so,
|
||||
// we can simplify by removing those checks here.)
|
||||
|
||||
// First, let's check dns names
|
||||
for (auto name = dns_names.first; name != dns_names.second; ++name) {
|
||||
if (name->first.length() > 0 &&
|
||||
CheckCertNames(host_parts, name->second)) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Then, check uri names
|
||||
for (auto name = uri_names.first; name != uri_names.second; ++name) {
|
||||
if (name->first.length() > 0 &&
|
||||
CheckCertNames(host_parts, name->second, false)) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Failing all of the previous checks, we assume the certificate is
|
||||
// invalid for an unspecified reason.
|
||||
return err;
|
||||
}
|
||||
|
||||
// Get the ALPN protocol identifier that was negotiated for the session
|
||||
Local<Value> GetALPNProtocol(const QuicSession& session) {
|
||||
QuicCryptoContext* ctx = session.crypto_context();
|
||||
Environment* env = session.env();
|
||||
std::string alpn = ctx->selected_alpn();
|
||||
if (alpn == NGTCP2_ALPN_H3 + 1) {
|
||||
return env->quic_alpn_string();
|
||||
} else {
|
||||
return ToV8Value(
|
||||
env->context(),
|
||||
alpn,
|
||||
env->isolate()).FromMaybe(Local<Value>());
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
int CertCB(SSL* ssl, void* arg) {
|
||||
QuicSession* session = static_cast<QuicSession*>(arg);
|
||||
return SSL_get_tlsext_status_type(ssl) == TLSEXT_STATUSTYPE_ocsp ?
|
||||
session->crypto_context()->OnOCSP() : 1;
|
||||
}
|
||||
|
||||
void Keylog_CB(const SSL* ssl, const char* line) {
|
||||
QuicSession* session = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
session->crypto_context()->Keylog(line);
|
||||
}
|
||||
|
||||
int Client_Hello_CB(
|
||||
SSL* ssl,
|
||||
int* tls_alert,
|
||||
void* arg) {
|
||||
QuicSession* session = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
int ret = session->crypto_context()->OnClientHello();
|
||||
switch (ret) {
|
||||
case 0:
|
||||
return 1;
|
||||
case -1:
|
||||
return -1;
|
||||
default:
|
||||
*tls_alert = ret;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int AlpnSelection(
|
||||
SSL* ssl,
|
||||
const unsigned char** out,
|
||||
unsigned char* outlen,
|
||||
const unsigned char* in,
|
||||
unsigned int inlen,
|
||||
void* arg) {
|
||||
QuicSession* session = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
|
||||
unsigned char* tmp;
|
||||
|
||||
// The QuicServerSession supports exactly one ALPN identifier. If that does
|
||||
// not match any of the ALPN identifiers provided in the client request,
|
||||
// then we fail here. Note that this will not fail the TLS handshake, so
|
||||
// we have to check later if the ALPN matches the expected identifier or not.
|
||||
if (SSL_select_next_proto(
|
||||
&tmp,
|
||||
outlen,
|
||||
reinterpret_cast<const unsigned char*>(session->alpn().c_str()),
|
||||
session->alpn().length(),
|
||||
in,
|
||||
inlen) == OPENSSL_NPN_NO_OVERLAP) {
|
||||
return SSL_TLSEXT_ERR_NOACK;
|
||||
}
|
||||
*out = tmp;
|
||||
return SSL_TLSEXT_ERR_OK;
|
||||
}
|
||||
|
||||
int AllowEarlyDataCB(SSL* ssl, void* arg) {
|
||||
QuicSession* session = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
return session->allow_early_data() ? 1 : 0;
|
||||
}
|
||||
|
||||
int TLS_Status_Callback(SSL* ssl, void* arg) {
|
||||
QuicSession* session = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
return session->crypto_context()->OnTLSStatus();
|
||||
}
|
||||
|
||||
int New_Session_Callback(SSL* ssl, SSL_SESSION* session) {
|
||||
QuicSession* s = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
return s->set_session(session);
|
||||
}
|
||||
|
||||
int GenerateSessionTicket(SSL* ssl, void* arg) {
|
||||
QuicSession* s = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
SessionTicketAppData app_data(SSL_get_session(ssl));
|
||||
s->SetSessionTicketAppData(app_data);
|
||||
return 1;
|
||||
}
|
||||
|
||||
SSL_TICKET_RETURN DecryptSessionTicket(
|
||||
SSL* ssl,
|
||||
SSL_SESSION* session,
|
||||
const unsigned char* keyname,
|
||||
size_t keyname_len,
|
||||
SSL_TICKET_STATUS status,
|
||||
void* arg) {
|
||||
QuicSession* s = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
SessionTicketAppData::Flag flag = SessionTicketAppData::Flag::STATUS_NONE;
|
||||
switch (status) {
|
||||
default:
|
||||
return SSL_TICKET_RETURN_IGNORE;
|
||||
case SSL_TICKET_EMPTY:
|
||||
// Fall through
|
||||
case SSL_TICKET_NO_DECRYPT:
|
||||
return SSL_TICKET_RETURN_IGNORE_RENEW;
|
||||
case SSL_TICKET_SUCCESS_RENEW:
|
||||
flag = SessionTicketAppData::Flag::STATUS_RENEW;
|
||||
// Fall through
|
||||
case SSL_TICKET_SUCCESS:
|
||||
SessionTicketAppData app_data(session);
|
||||
switch (s->GetSessionTicketAppData(app_data, flag)) {
|
||||
default:
|
||||
return SSL_TICKET_RETURN_IGNORE;
|
||||
case SessionTicketAppData::Status::TICKET_IGNORE:
|
||||
return SSL_TICKET_RETURN_IGNORE;
|
||||
case SessionTicketAppData::Status::TICKET_IGNORE_RENEW:
|
||||
return SSL_TICKET_RETURN_IGNORE_RENEW;
|
||||
case SessionTicketAppData::Status::TICKET_USE:
|
||||
return SSL_TICKET_RETURN_USE;
|
||||
case SessionTicketAppData::Status::TICKET_USE_RENEW:
|
||||
return SSL_TICKET_RETURN_USE_RENEW;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int SetEncryptionSecrets(
|
||||
SSL* ssl,
|
||||
OSSL_ENCRYPTION_LEVEL ossl_level,
|
||||
const uint8_t* read_secret,
|
||||
const uint8_t* write_secret,
|
||||
size_t secret_len) {
|
||||
QuicSession* session = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
return session->crypto_context()->OnSecrets(
|
||||
from_ossl_level(ossl_level),
|
||||
read_secret,
|
||||
write_secret,
|
||||
secret_len) ? 1 : 0;
|
||||
}
|
||||
|
||||
int AddHandshakeData(
|
||||
SSL* ssl,
|
||||
OSSL_ENCRYPTION_LEVEL ossl_level,
|
||||
const uint8_t* data,
|
||||
size_t len) {
|
||||
QuicSession* session = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
session->crypto_context()->WriteHandshake(
|
||||
from_ossl_level(ossl_level),
|
||||
data,
|
||||
len);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int FlushFlight(SSL* ssl) { return 1; }
|
||||
|
||||
int SendAlert(
|
||||
SSL* ssl,
|
||||
enum ssl_encryption_level_t level,
|
||||
uint8_t alert) {
|
||||
QuicSession* session = static_cast<QuicSession*>(SSL_get_app_data(ssl));
|
||||
session->crypto_context()->set_tls_alert(alert);
|
||||
return 1;
|
||||
}
|
||||
|
||||
bool SetTransportParams(QuicSession* session, const crypto::SSLPointer& ssl) {
|
||||
ngtcp2_transport_params params;
|
||||
ngtcp2_conn_get_local_transport_params(session->connection(), ¶ms);
|
||||
uint8_t buf[512];
|
||||
ssize_t nwrite = ngtcp2_encode_transport_params(
|
||||
buf,
|
||||
arraysize(buf),
|
||||
NGTCP2_TRANSPORT_PARAMS_TYPE_ENCRYPTED_EXTENSIONS,
|
||||
¶ms);
|
||||
return nwrite >= 0 &&
|
||||
SSL_set_quic_transport_params(ssl.get(), buf, nwrite) == 1;
|
||||
}
|
||||
|
||||
SSL_QUIC_METHOD quic_method = SSL_QUIC_METHOD{
|
||||
SetEncryptionSecrets,
|
||||
AddHandshakeData,
|
||||
FlushFlight,
|
||||
SendAlert
|
||||
};
|
||||
|
||||
void SetHostname(const crypto::SSLPointer& ssl, const std::string& hostname) {
|
||||
// If the hostname is an IP address, use an empty string
|
||||
// as the hostname instead.
|
||||
if (SocketAddress::is_numeric_host(hostname.c_str())) {
|
||||
SSL_set_tlsext_host_name(ssl.get(), "");
|
||||
} else {
|
||||
SSL_set_tlsext_host_name(ssl.get(), hostname.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void InitializeTLS(QuicSession* session, const crypto::SSLPointer& ssl) {
|
||||
QuicCryptoContext* ctx = session->crypto_context();
|
||||
Environment* env = session->env();
|
||||
QuicState* quic_state = session->quic_state();
|
||||
|
||||
SSL_set_app_data(ssl.get(), session);
|
||||
SSL_set_cert_cb(ssl.get(), CertCB,
|
||||
const_cast<void*>(reinterpret_cast<const void*>(session)));
|
||||
SSL_set_verify(ssl.get(), SSL_VERIFY_NONE, crypto::VerifyCallback);
|
||||
|
||||
// Enable tracing if the `--trace-tls` command line flag is used.
|
||||
if (env->options()->trace_tls) {
|
||||
ctx->EnableTrace();
|
||||
if (quic_state->warn_trace_tls) {
|
||||
quic_state->warn_trace_tls = false;
|
||||
ProcessEmitWarning(env,
|
||||
"Enabling --trace-tls can expose sensitive data "
|
||||
"in the resulting log");
|
||||
}
|
||||
}
|
||||
|
||||
switch (ctx->side()) {
|
||||
case NGTCP2_CRYPTO_SIDE_CLIENT: {
|
||||
SSL_set_connect_state(ssl.get());
|
||||
crypto::SetALPN(ssl, session->alpn());
|
||||
SetHostname(ssl, session->hostname());
|
||||
if (ctx->is_option_set(QUICCLIENTSESSION_OPTION_REQUEST_OCSP))
|
||||
SSL_set_tlsext_status_type(ssl.get(), TLSEXT_STATUSTYPE_ocsp);
|
||||
break;
|
||||
}
|
||||
case NGTCP2_CRYPTO_SIDE_SERVER: {
|
||||
SSL_set_accept_state(ssl.get());
|
||||
if (ctx->is_option_set(QUICSERVERSESSION_OPTION_REQUEST_CERT)) {
|
||||
int verify_mode = SSL_VERIFY_PEER;
|
||||
if (ctx->is_option_set(QUICSERVERSESSION_OPTION_REJECT_UNAUTHORIZED))
|
||||
verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
|
||||
SSL_set_verify(ssl.get(), verify_mode, crypto::VerifyCallback);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
|
||||
SetTransportParams(session, ssl);
|
||||
}
|
||||
|
||||
void InitializeSecureContext(
|
||||
BaseObjectPtr<crypto::SecureContext> sc,
|
||||
bool early_data,
|
||||
ngtcp2_crypto_side side) {
|
||||
// TODO(@jasnell): Using a static value for this at the moment but
|
||||
// we need to determine if a non-static or per-session value is better.
|
||||
constexpr static unsigned char session_id_ctx[] = "node.js quic server";
|
||||
switch (side) {
|
||||
case NGTCP2_CRYPTO_SIDE_SERVER:
|
||||
SSL_CTX_set_options(
|
||||
**sc,
|
||||
(SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
|
||||
SSL_OP_SINGLE_ECDH_USE |
|
||||
SSL_OP_CIPHER_SERVER_PREFERENCE |
|
||||
SSL_OP_NO_ANTI_REPLAY);
|
||||
|
||||
SSL_CTX_set_mode(**sc, SSL_MODE_RELEASE_BUFFERS);
|
||||
|
||||
SSL_CTX_set_alpn_select_cb(**sc, AlpnSelection, nullptr);
|
||||
SSL_CTX_set_client_hello_cb(**sc, Client_Hello_CB, nullptr);
|
||||
|
||||
SSL_CTX_set_session_ticket_cb(
|
||||
**sc,
|
||||
GenerateSessionTicket,
|
||||
DecryptSessionTicket,
|
||||
nullptr);
|
||||
|
||||
if (early_data) {
|
||||
SSL_CTX_set_max_early_data(**sc, 0xffffffff);
|
||||
SSL_CTX_set_allow_early_data_cb(**sc, AllowEarlyDataCB, nullptr);
|
||||
}
|
||||
|
||||
SSL_CTX_set_session_id_context(
|
||||
**sc,
|
||||
session_id_ctx,
|
||||
sizeof(session_id_ctx) - 1);
|
||||
break;
|
||||
case NGTCP2_CRYPTO_SIDE_CLIENT:
|
||||
SSL_CTX_set_session_cache_mode(
|
||||
**sc,
|
||||
SSL_SESS_CACHE_CLIENT |
|
||||
SSL_SESS_CACHE_NO_INTERNAL_STORE);
|
||||
SSL_CTX_sess_set_new_cb(**sc, New_Session_Callback);
|
||||
break;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
SSL_CTX_set_min_proto_version(**sc, TLS1_3_VERSION);
|
||||
SSL_CTX_set_max_proto_version(**sc, TLS1_3_VERSION);
|
||||
SSL_CTX_set_default_verify_paths(**sc);
|
||||
SSL_CTX_set_tlsext_status_cb(**sc, TLS_Status_Callback);
|
||||
SSL_CTX_set_keylog_callback(**sc, Keylog_CB);
|
||||
SSL_CTX_set_tlsext_status_arg(**sc, nullptr);
|
||||
SSL_CTX_set_quic_method(**sc, &quic_method);
|
||||
}
|
||||
|
||||
bool DeriveAndInstallInitialKey(
|
||||
const QuicSession& session,
|
||||
const QuicCID& dcid) {
|
||||
uint8_t initial_secret[NGTCP2_CRYPTO_INITIAL_SECRETLEN];
|
||||
uint8_t rx_secret[NGTCP2_CRYPTO_INITIAL_SECRETLEN];
|
||||
uint8_t tx_secret[NGTCP2_CRYPTO_INITIAL_SECRETLEN];
|
||||
uint8_t rx_key[NGTCP2_CRYPTO_INITIAL_KEYLEN];
|
||||
uint8_t tx_key[NGTCP2_CRYPTO_INITIAL_KEYLEN];
|
||||
uint8_t rx_hp[NGTCP2_CRYPTO_INITIAL_KEYLEN];
|
||||
uint8_t tx_hp[NGTCP2_CRYPTO_INITIAL_KEYLEN];
|
||||
uint8_t rx_iv[NGTCP2_CRYPTO_INITIAL_IVLEN];
|
||||
uint8_t tx_iv[NGTCP2_CRYPTO_INITIAL_IVLEN];
|
||||
return NGTCP2_OK(ngtcp2_crypto_derive_and_install_initial_key(
|
||||
session.connection(),
|
||||
rx_secret,
|
||||
tx_secret,
|
||||
initial_secret,
|
||||
rx_key,
|
||||
rx_iv,
|
||||
rx_hp,
|
||||
tx_key,
|
||||
tx_iv,
|
||||
tx_hp,
|
||||
dcid.cid(),
|
||||
session.crypto_context()->side()));
|
||||
}
|
||||
|
||||
ngtcp2_crypto_level from_ossl_level(OSSL_ENCRYPTION_LEVEL ossl_level) {
|
||||
switch (ossl_level) {
|
||||
case ssl_encryption_initial:
|
||||
return NGTCP2_CRYPTO_LEVEL_INITIAL;
|
||||
case ssl_encryption_early_data:
|
||||
return NGTCP2_CRYPTO_LEVEL_EARLY;
|
||||
case ssl_encryption_handshake:
|
||||
return NGTCP2_CRYPTO_LEVEL_HANDSHAKE;
|
||||
case ssl_encryption_application:
|
||||
return NGTCP2_CRYPTO_LEVEL_APP;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
|
||||
const char* crypto_level_name(ngtcp2_crypto_level level) {
|
||||
switch (level) {
|
||||
case NGTCP2_CRYPTO_LEVEL_INITIAL:
|
||||
return "initial";
|
||||
case NGTCP2_CRYPTO_LEVEL_EARLY:
|
||||
return "early";
|
||||
case NGTCP2_CRYPTO_LEVEL_HANDSHAKE:
|
||||
return "handshake";
|
||||
case NGTCP2_CRYPTO_LEVEL_APP:
|
||||
return "app";
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
|
||||
// When using IPv6, QUIC recommends the use of IPv6 Flow Labels
|
||||
// as specified in https://tools.ietf.org/html/rfc6437. These
|
||||
// are used as a means of reliably associating packets exchanged
|
||||
// as part of a single flow and protecting against certain kinds
|
||||
// of attacks.
|
||||
uint32_t GenerateFlowLabel(
|
||||
const SocketAddress& local,
|
||||
const SocketAddress& remote,
|
||||
const QuicCID& cid,
|
||||
const uint8_t* secret,
|
||||
size_t secretlen) {
|
||||
static constexpr size_t kInfoLen =
|
||||
(sizeof(sockaddr_in6) * 2) + NGTCP2_MAX_CIDLEN;
|
||||
|
||||
uint32_t label = 0;
|
||||
|
||||
std::array<uint8_t, kInfoLen> plaintext;
|
||||
size_t infolen = local.length() + remote.length() + cid.length();
|
||||
CHECK_LE(infolen, kInfoLen);
|
||||
|
||||
ngtcp2_crypto_ctx ctx;
|
||||
ngtcp2_crypto_ctx_initial(&ctx);
|
||||
|
||||
auto p = std::begin(plaintext);
|
||||
p = std::copy_n(local.raw(), local.length(), p);
|
||||
p = std::copy_n(remote.raw(), remote.length(), p);
|
||||
p = std::copy_n(cid->data, cid->datalen, p);
|
||||
|
||||
ngtcp2_crypto_hkdf_expand(
|
||||
reinterpret_cast<uint8_t*>(&label),
|
||||
sizeof(label),
|
||||
&ctx.md,
|
||||
secret,
|
||||
secretlen,
|
||||
plaintext.data(),
|
||||
infolen);
|
||||
|
||||
label &= kLabelMask;
|
||||
DCHECK_LE(label, kLabelMask);
|
||||
return label;
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
@@ -0,0 +1,157 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_CRYPTO_H_
|
||||
#define SRC_QUIC_NODE_QUIC_CRYPTO_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "node_crypto.h"
|
||||
#include "node_quic_util.h"
|
||||
#include "v8.h"
|
||||
|
||||
#include <ngtcp2/ngtcp2.h>
|
||||
#include <ngtcp2/ngtcp2_crypto.h>
|
||||
#include <openssl/ssl.h>
|
||||
|
||||
namespace node {
|
||||
|
||||
namespace quic {
|
||||
|
||||
// Crypto and OpenSSL related utility functions used in
|
||||
// various places throughout the QUIC implementation.
|
||||
|
||||
// Forward declaration
|
||||
class QuicSession;
|
||||
class QuicPacket;
|
||||
|
||||
// many ngtcp2 functions return 0 to indicate success
|
||||
// and non-zero to indicate failure. Most of the time,
|
||||
// for such functions we don't care about the specific
|
||||
// return value so we simplify using a macro.
|
||||
|
||||
#define NGTCP2_ERR(V) (V != 0)
|
||||
#define NGTCP2_OK(V) (V == 0)
|
||||
|
||||
// Called by QuicInitSecureContext to initialize the
|
||||
// given SecureContext with the defaults for the given
|
||||
// QUIC side (client or server).
|
||||
void InitializeSecureContext(
|
||||
BaseObjectPtr<crypto::SecureContext> sc,
|
||||
bool early_data,
|
||||
ngtcp2_crypto_side side);
|
||||
|
||||
// Called in the QuicSession::InitServer and
|
||||
// QuicSession::InitClient to configure the
|
||||
// appropriate settings for the SSL* associated
|
||||
// with the session.
|
||||
void InitializeTLS(QuicSession* session, const crypto::SSLPointer& ssl);
|
||||
|
||||
// Called when the client QuicSession is created and
|
||||
// when the server QuicSession first receives the
|
||||
// client hello.
|
||||
bool DeriveAndInstallInitialKey(
|
||||
const QuicSession& session,
|
||||
const QuicCID& dcid);
|
||||
|
||||
// Generates a stateless reset token using HKDF with the
|
||||
// cid and token secret as input. The token secret is
|
||||
// either provided by user code when a QuicSocket is
|
||||
// created or is generated randomly.
|
||||
//
|
||||
// QUIC leaves the generation of stateless session tokens
|
||||
// up to the implementation to figure out. The idea, however,
|
||||
// is that it ought to be possible to generate a stateless
|
||||
// reset token reliably even when all state for a connection
|
||||
// has been lost. We use the cid as it's the only reliably
|
||||
// consistent bit of data we have when a session is destroyed.
|
||||
bool GenerateResetToken(
|
||||
uint8_t* token,
|
||||
const uint8_t* secret,
|
||||
const QuicCID& cid);
|
||||
|
||||
// The Retry Token is an encrypted token that is sent to the client
|
||||
// by the server as part of the path validation flow. The plaintext
|
||||
// format within the token is opaque and only meaningful the server.
|
||||
// We can structure it any way we want. It needs to:
|
||||
// * be hard to guess
|
||||
// * be time limited
|
||||
// * be specific to the client address
|
||||
// * be specific to the original cid
|
||||
// * contain random data.
|
||||
std::unique_ptr<QuicPacket> GenerateRetryPacket(
|
||||
const uint8_t* token_secret,
|
||||
const QuicCID& dcid,
|
||||
const QuicCID& scid,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr);
|
||||
|
||||
// The IPv6 Flow Label is generated and set whenever IPv6 is used.
|
||||
// The label is derived as a cryptographic function of the CID,
|
||||
// local and remote addresses, and the given secret, that is then
|
||||
// truncated to a 20-bit value (per IPv6 requirements). In QUIC,
|
||||
// the flow label *may* be used as a way of disambiguating IP
|
||||
// packets that belong to the same flow from a remote peer.
|
||||
uint32_t GenerateFlowLabel(
|
||||
const SocketAddress& local,
|
||||
const SocketAddress& remote,
|
||||
const QuicCID& cid,
|
||||
const uint8_t* secret,
|
||||
size_t secretlen);
|
||||
|
||||
// Verifies the validity of a retry token. Returns true if the
|
||||
// token is *not valid*, false otherwise. If the token is valid,
|
||||
// the ocid will be updated to the original CID value encoded
|
||||
// within the successfully validated, encrypted token.
|
||||
bool InvalidRetryToken(
|
||||
const ngtcp2_pkt_hd& hd,
|
||||
const SocketAddress& addr,
|
||||
QuicCID* ocid,
|
||||
const uint8_t* token_secret,
|
||||
uint64_t verification_expiration);
|
||||
|
||||
int VerifyHostnameIdentity(const crypto::SSLPointer& ssl, const char* hostname);
|
||||
int VerifyHostnameIdentity(
|
||||
const char* hostname,
|
||||
const std::string& cert_cn,
|
||||
const std::unordered_multimap<std::string, std::string>& altnames);
|
||||
|
||||
// Get the ALPN protocol identifier that was negotiated for the session
|
||||
v8::Local<v8::Value> GetALPNProtocol(const QuicSession& session);
|
||||
|
||||
ngtcp2_crypto_level from_ossl_level(OSSL_ENCRYPTION_LEVEL ossl_level);
|
||||
const char* crypto_level_name(ngtcp2_crypto_level level);
|
||||
|
||||
// SessionTicketAppData is a utility class that is used only during
|
||||
// the generation or access of TLS stateless sesson tickets. It
|
||||
// exists solely to provide a easier way for QuicApplication instances
|
||||
// to set relevant metadata in the session ticket when it is created,
|
||||
// and the exract and subsequently verify that data when a ticket is
|
||||
// received and is being validated. The app data is completely opaque
|
||||
// to anything other than the server-side of the QuicApplication that
|
||||
// sets it.
|
||||
class SessionTicketAppData {
|
||||
public:
|
||||
enum class Status {
|
||||
TICKET_USE,
|
||||
TICKET_USE_RENEW,
|
||||
TICKET_IGNORE,
|
||||
TICKET_IGNORE_RENEW
|
||||
};
|
||||
|
||||
enum class Flag {
|
||||
STATUS_NONE,
|
||||
STATUS_RENEW
|
||||
};
|
||||
|
||||
explicit SessionTicketAppData(SSL_SESSION* session) : session_(session) {}
|
||||
bool Set(const uint8_t* data, size_t len);
|
||||
bool Get(uint8_t** data, size_t* len) const;
|
||||
|
||||
private:
|
||||
bool set_ = false;
|
||||
SSL_SESSION* session_;
|
||||
};
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // NODE_WANT_INTERNALS
|
||||
#endif // SRC_QUIC_NODE_QUIC_CRYPTO_H_
|
||||
@@ -0,0 +1,181 @@
|
||||
#include "debug_utils-inl.h"
|
||||
#include "node_quic_buffer-inl.h"
|
||||
#include "node_quic_default_application.h"
|
||||
#include "node_quic_session-inl.h"
|
||||
#include "node_quic_socket-inl.h"
|
||||
#include "node_quic_stream-inl.h"
|
||||
#include "node_quic_util-inl.h"
|
||||
#include "node_sockaddr-inl.h"
|
||||
#include <ngtcp2/ngtcp2.h>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace node {
|
||||
namespace quic {
|
||||
|
||||
namespace {
|
||||
void Consume(ngtcp2_vec** pvec, size_t* pcnt, size_t len) {
|
||||
ngtcp2_vec* v = *pvec;
|
||||
size_t cnt = *pcnt;
|
||||
|
||||
for (; cnt > 0; --cnt, ++v) {
|
||||
if (v->len > len) {
|
||||
v->len -= len;
|
||||
v->base += len;
|
||||
break;
|
||||
}
|
||||
len -= v->len;
|
||||
}
|
||||
|
||||
*pvec = v;
|
||||
*pcnt = cnt;
|
||||
}
|
||||
|
||||
int IsEmpty(const ngtcp2_vec* vec, size_t cnt) {
|
||||
size_t i;
|
||||
for (i = 0; i < cnt && vec[i].len == 0; ++i) {}
|
||||
return i == cnt;
|
||||
}
|
||||
} // anonymous namespace
|
||||
|
||||
DefaultApplication::DefaultApplication(
|
||||
QuicSession* session) :
|
||||
QuicApplication(session) {}
|
||||
|
||||
bool DefaultApplication::Initialize() {
|
||||
if (needs_init()) {
|
||||
Debug(session(), "Default QUIC Application Initialized");
|
||||
set_init_done();
|
||||
}
|
||||
return needs_init();
|
||||
}
|
||||
|
||||
void DefaultApplication::ScheduleStream(int64_t stream_id) {
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
Debug(session(), "Scheduling stream %" PRIu64, stream_id);
|
||||
if (LIKELY(stream))
|
||||
stream->Schedule(&stream_queue_);
|
||||
}
|
||||
|
||||
void DefaultApplication::UnscheduleStream(int64_t stream_id) {
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
Debug(session(), "Unscheduling stream %" PRIu64, stream_id);
|
||||
if (LIKELY(stream))
|
||||
stream->Unschedule();
|
||||
}
|
||||
|
||||
void DefaultApplication::StreamClose(
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code) {
|
||||
if (!session()->HasStream(stream_id))
|
||||
return;
|
||||
if (app_error_code == 0)
|
||||
app_error_code = NGTCP2_APP_NOERROR;
|
||||
UnscheduleStream(stream_id);
|
||||
QuicApplication::StreamClose(stream_id, app_error_code);
|
||||
}
|
||||
|
||||
void DefaultApplication::ResumeStream(int64_t stream_id) {
|
||||
Debug(session(), "Stream %" PRId64 " has data to send", stream_id);
|
||||
ScheduleStream(stream_id);
|
||||
}
|
||||
|
||||
bool DefaultApplication::ReceiveStreamData(
|
||||
int64_t stream_id,
|
||||
int fin,
|
||||
const uint8_t* data,
|
||||
size_t datalen,
|
||||
uint64_t offset) {
|
||||
// Ensure that the QuicStream exists before deferring to
|
||||
// QuicApplication specific processing logic.
|
||||
Debug(session(), "Default QUIC Application receiving stream data");
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
if (!stream) {
|
||||
// Shutdown the stream explicitly if the session is being closed.
|
||||
if (session()->is_gracefully_closing()) {
|
||||
session()->ResetStream(stream_id, NGTCP2_ERR_CLOSING);
|
||||
return true;
|
||||
}
|
||||
|
||||
// One potential DOS attack vector is to send a bunch of
|
||||
// empty stream frames to commit resources. Check that
|
||||
// here. Essentially, we only want to create a new stream
|
||||
// if the datalen is greater than 0, otherwise, we ignore
|
||||
// the packet. ngtcp2 should be handling this for us,
|
||||
// but we handle it just to be safe.
|
||||
if (UNLIKELY(datalen == 0))
|
||||
return true;
|
||||
|
||||
stream = session()->CreateStream(stream_id);
|
||||
}
|
||||
CHECK(stream);
|
||||
|
||||
stream->ReceiveData(fin, data, datalen, offset);
|
||||
return true;
|
||||
}
|
||||
|
||||
int DefaultApplication::GetStreamData(StreamData* stream_data) {
|
||||
QuicStream* stream = stream_queue_.PopFront();
|
||||
// If stream is nullptr, there are no streams with data pending.
|
||||
if (stream == nullptr)
|
||||
return 0;
|
||||
|
||||
stream_data->stream.reset(stream);
|
||||
stream_data->id = stream->id();
|
||||
|
||||
auto next = [&](
|
||||
int status,
|
||||
const ngtcp2_vec* data,
|
||||
size_t count,
|
||||
bob::Done done) {
|
||||
switch (status) {
|
||||
case bob::Status::STATUS_BLOCK:
|
||||
// Fall through
|
||||
case bob::Status::STATUS_WAIT:
|
||||
// Fall through
|
||||
case bob::Status::STATUS_EOS:
|
||||
return;
|
||||
case bob::Status::STATUS_END:
|
||||
stream_data->fin = 1;
|
||||
}
|
||||
stream_data->count = count;
|
||||
|
||||
if (count > 0) {
|
||||
stream->Schedule(&stream_queue_);
|
||||
stream_data->remaining = get_length(data, count);
|
||||
} else {
|
||||
stream_data->remaining = 0;
|
||||
}
|
||||
};
|
||||
|
||||
if (LIKELY(!stream->is_eos())) {
|
||||
CHECK_GE(stream->Pull(
|
||||
std::move(next),
|
||||
bob::Options::OPTIONS_SYNC,
|
||||
stream_data->data,
|
||||
arraysize(stream_data->data),
|
||||
kMaxVectorCount), 0);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool DefaultApplication::StreamCommit(
|
||||
StreamData* stream_data,
|
||||
size_t datalen) {
|
||||
CHECK(stream_data->stream);
|
||||
stream_data->remaining -= datalen;
|
||||
Consume(&stream_data->buf, &stream_data->count, datalen);
|
||||
stream_data->stream->Commit(datalen);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DefaultApplication::ShouldSetFin(const StreamData& stream_data) {
|
||||
if (!stream_data.stream ||
|
||||
!IsEmpty(stream_data.buf, stream_data.count))
|
||||
return false;
|
||||
return !stream_data.stream->is_writable();
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
@@ -0,0 +1,61 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_DEFAULT_APPLICATION_H_
|
||||
#define SRC_QUIC_NODE_QUIC_DEFAULT_APPLICATION_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "node_quic_stream.h"
|
||||
#include "node_quic_session.h"
|
||||
#include "node_quic_util.h"
|
||||
#include "util.h"
|
||||
#include "v8.h"
|
||||
|
||||
namespace node {
|
||||
|
||||
namespace quic {
|
||||
|
||||
// The DefaultApplication is used whenever an unknown/unrecognized
|
||||
// alpn identifier is used. It switches the QUIC implementation into
|
||||
// a minimal/generic mode that defers all application level processing
|
||||
// to the user-code level. Headers are not supported by QuicStream
|
||||
// instances created under the default application.
|
||||
class DefaultApplication final : public QuicApplication {
|
||||
public:
|
||||
explicit DefaultApplication(QuicSession* session);
|
||||
|
||||
bool Initialize() override;
|
||||
|
||||
void StopTrackingMemory(void* ptr) override {
|
||||
// Do nothing. Not used.
|
||||
}
|
||||
|
||||
bool ReceiveStreamData(
|
||||
int64_t stream_id,
|
||||
int fin,
|
||||
const uint8_t* data,
|
||||
size_t datalen,
|
||||
uint64_t offset) override;
|
||||
|
||||
int GetStreamData(StreamData* stream_data) override;
|
||||
|
||||
void ResumeStream(int64_t stream_id) override;
|
||||
void StreamClose(int64_t stream_id, uint64_t app_error_code) override;
|
||||
bool ShouldSetFin(const StreamData& stream_data) override;
|
||||
bool StreamCommit(StreamData* stream_data, size_t datalen) override;
|
||||
|
||||
SET_SELF_SIZE(DefaultApplication)
|
||||
SET_MEMORY_INFO_NAME(DefaultApplication)
|
||||
SET_NO_MEMORY_INFO()
|
||||
|
||||
private:
|
||||
void ScheduleStream(int64_t stream_id);
|
||||
void UnscheduleStream(int64_t stream_id);
|
||||
|
||||
QuicStream::Queue stream_queue_;
|
||||
};
|
||||
|
||||
} // namespace quic
|
||||
|
||||
} // namespace node
|
||||
|
||||
#endif // NODE_WANT_INTERNALS
|
||||
#endif // SRC_QUIC_NODE_QUIC_DEFAULT_APPLICATION_H_
|
||||
@@ -0,0 +1,935 @@
|
||||
#include "node.h"
|
||||
#include "debug_utils-inl.h"
|
||||
#include "node_mem-inl.h"
|
||||
#include "node_quic_buffer-inl.h"
|
||||
#include "node_quic_http3_application.h"
|
||||
#include "node_quic_session-inl.h"
|
||||
#include "node_quic_socket-inl.h"
|
||||
#include "node_quic_stream-inl.h"
|
||||
#include "node_quic_util-inl.h"
|
||||
#include "node_sockaddr-inl.h"
|
||||
#include "node_http_common-inl.h"
|
||||
|
||||
#include <ngtcp2/ngtcp2.h>
|
||||
#include <nghttp3/nghttp3.h>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
namespace node {
|
||||
|
||||
using v8::Array;
|
||||
using v8::Local;
|
||||
|
||||
namespace quic {
|
||||
|
||||
// nghttp3 uses a numeric identifier for a large number
|
||||
// of known HTTP header names. These allow us to use
|
||||
// static strings for those rather than allocating new
|
||||
// strings all of the time. The list of strings supported
|
||||
// is included in node_http_common.h
|
||||
#define V1(name, value) case NGHTTP3_QPACK_TOKEN__##name: return value;
|
||||
#define V2(name, value) case NGHTTP3_QPACK_TOKEN_##name: return value;
|
||||
const char* Http3HeaderTraits::ToHttpHeaderName(int32_t token) {
|
||||
switch (token) {
|
||||
default:
|
||||
// Fall through
|
||||
case -1: return nullptr;
|
||||
HTTP_SPECIAL_HEADERS(V1)
|
||||
HTTP_REGULAR_HEADERS(V2)
|
||||
}
|
||||
}
|
||||
#undef V1
|
||||
#undef V2
|
||||
|
||||
template <typename M, typename T>
|
||||
void Http3Application::SetConfig(
|
||||
int idx,
|
||||
M T::*member) {
|
||||
AliasedFloat64Array& buffer = session()->quic_state()->http3config_buffer;
|
||||
uint64_t flags = static_cast<uint64_t>(buffer[IDX_HTTP3_CONFIG_COUNT]);
|
||||
if (flags & (1ULL << idx))
|
||||
config_.*member = static_cast<uint64_t>(buffer[idx]);
|
||||
}
|
||||
|
||||
Http3Application::Http3Application(
|
||||
QuicSession* session)
|
||||
: QuicApplication(session),
|
||||
alloc_info_(MakeAllocator()) {
|
||||
// Collect Configuration Details.
|
||||
SetConfig<size_t>(IDX_HTTP3_QPACK_MAX_TABLE_CAPACITY,
|
||||
&Http3ApplicationConfig::qpack_max_table_capacity);
|
||||
SetConfig<size_t>(IDX_HTTP3_QPACK_BLOCKED_STREAMS,
|
||||
&Http3ApplicationConfig::qpack_blocked_streams);
|
||||
SetConfig(IDX_HTTP3_MAX_HEADER_LIST_SIZE,
|
||||
&Http3ApplicationConfig::max_header_list_size);
|
||||
SetConfig(IDX_HTTP3_MAX_PUSHES,
|
||||
&Http3ApplicationConfig::max_pushes);
|
||||
SetConfig(IDX_HTTP3_MAX_HEADER_PAIRS,
|
||||
&Http3ApplicationConfig::max_header_pairs);
|
||||
SetConfig(IDX_HTTP3_MAX_HEADER_LENGTH,
|
||||
&Http3ApplicationConfig::max_header_length);
|
||||
set_max_header_pairs(
|
||||
session->is_server()
|
||||
? GetServerMaxHeaderPairs(config_.max_header_pairs)
|
||||
: GetClientMaxHeaderPairs(config_.max_header_pairs));
|
||||
set_max_header_length(config_.max_header_length);
|
||||
|
||||
session->quic_state()->http3config_buffer[IDX_HTTP3_CONFIG_COUNT] = 0;
|
||||
}
|
||||
|
||||
// Push streams in HTTP/3 are a bit complicated.
|
||||
// First, it's important to know that only an HTTP/3 server can
|
||||
// create a push stream.
|
||||
// Second, it's important to recognize that a push stream is
|
||||
// essentially an *assumed* request. For instance, if a client
|
||||
// requests a webpage that has links to css and js files, and
|
||||
// the server expects the client to send subsequent requests
|
||||
// for those css and js files, the server can shortcut the
|
||||
// process by opening a push stream for each additional resource
|
||||
// it assumes the client to make.
|
||||
// Third, a push stream can only be opened within the context
|
||||
// of an HTTP/3 request/response. Essentially, a server receives
|
||||
// a request and while processing the response, the server can
|
||||
// open one or more push streams.
|
||||
//
|
||||
// Now... a push stream consists of two components: a push promise
|
||||
// and a push fulfillment. The push promise is sent *as part of
|
||||
// the response on the original stream* and is assigned a push id
|
||||
// and a block of headers containing the *assumed request headers*.
|
||||
// The push promise is sent on the request/response bidirectional
|
||||
// stream.
|
||||
// The push fulfillment is a unidirectional stream opened by the
|
||||
// server that contains the push id, the response header block, and
|
||||
// the response payload.
|
||||
// Here's where it can get a bit complicated: the server sends the
|
||||
// push promise and the push fulfillment on two different, and
|
||||
// independent QUIC streams. The push id is used to correlate
|
||||
// those on the client side, but, it's entirely possible for the
|
||||
// client to receive the push fulfillment before it actually receives
|
||||
// the push promise. It's *unlikely*, but it's possible. Fortunately,
|
||||
// nghttp3 handles the complexity of that for us internally but
|
||||
// makes for some weird timing and could lead to some amount of
|
||||
// buffering to occur.
|
||||
//
|
||||
// The *logical* order of events from the client side *should*
|
||||
// be: (a) receive the push promise containing assumed request
|
||||
// headers, (b) receive the push fulfillment containing the
|
||||
// response headers followed immediately by the response payload.
|
||||
//
|
||||
// On the server side, the steps are: (a) first create the push
|
||||
// promise creating the push_id then (b) open the unidirectional
|
||||
// stream that will be used to fullfil the push promise. Once that
|
||||
// unidirectional stream is created, the push id and unidirectional
|
||||
// stream ID must be bound. The CreateAndBindPushStream handles (b)
|
||||
int64_t Http3Application::CreateAndBindPushStream(int64_t push_id) {
|
||||
CHECK(session()->is_server());
|
||||
int64_t stream_id;
|
||||
if (!session()->OpenUnidirectionalStream(&stream_id))
|
||||
return 0;
|
||||
return nghttp3_conn_bind_push_stream(
|
||||
connection(),
|
||||
push_id,
|
||||
stream_id) == 0 ? stream_id : 0;
|
||||
}
|
||||
|
||||
bool Http3Application::SubmitPushPromise(
|
||||
int64_t id,
|
||||
int64_t* push_id,
|
||||
int64_t* stream_id,
|
||||
const Http3Headers& headers) {
|
||||
// Successfully creating the push promise and opening the
|
||||
// fulfillment stream will queue nghttp3 up to send data.
|
||||
// Creating the SendSessionScope here ensures that when
|
||||
// SubmitPush exits, SendPendingData will be called if
|
||||
// we are not within the context of an ngtcp2 callback.
|
||||
QuicSession::SendSessionScope send_scope(session());
|
||||
|
||||
Debug(
|
||||
session(),
|
||||
"Submitting %d push promise headers",
|
||||
headers.length());
|
||||
if (nghttp3_conn_submit_push_promise(
|
||||
connection(),
|
||||
push_id,
|
||||
id,
|
||||
headers.data(),
|
||||
headers.length()) != 0) {
|
||||
return false;
|
||||
}
|
||||
// Once we've successfully submitting the push promise and have
|
||||
// a push id assigned, we create the push fulfillment stream.
|
||||
*stream_id = CreateAndBindPushStream(*push_id);
|
||||
return *stream_id != 0; // push stream can never use stream id 0
|
||||
}
|
||||
|
||||
bool Http3Application::SubmitInformation(
|
||||
int64_t id,
|
||||
const Http3Headers& headers) {
|
||||
QuicSession::SendSessionScope send_scope(session());
|
||||
Debug(
|
||||
session(),
|
||||
"Submitting %d informational headers for stream %" PRId64,
|
||||
headers.length(),
|
||||
id);
|
||||
return nghttp3_conn_submit_info(
|
||||
connection(),
|
||||
id,
|
||||
headers.data(),
|
||||
headers.length()) == 0;
|
||||
}
|
||||
|
||||
bool Http3Application::SubmitTrailers(
|
||||
int64_t id,
|
||||
const Http3Headers& headers) {
|
||||
QuicSession::SendSessionScope send_scope(session());
|
||||
Debug(
|
||||
session(),
|
||||
"Submitting %d trailing headers for stream %" PRId64,
|
||||
headers.length(),
|
||||
id);
|
||||
return nghttp3_conn_submit_trailers(
|
||||
connection(),
|
||||
id,
|
||||
headers.data(),
|
||||
headers.length()) == 0;
|
||||
}
|
||||
|
||||
bool Http3Application::SubmitHeaders(
|
||||
int64_t id,
|
||||
const Http3Headers& headers,
|
||||
int32_t flags) {
|
||||
QuicSession::SendSessionScope send_scope(session());
|
||||
static constexpr nghttp3_data_reader reader = {
|
||||
Http3Application::OnReadData };
|
||||
const nghttp3_data_reader* reader_ptr = nullptr;
|
||||
if (!(flags & QUICSTREAM_HEADER_FLAGS_TERMINAL))
|
||||
reader_ptr = &reader;
|
||||
|
||||
switch (session()->crypto_context()->side()) {
|
||||
case NGTCP2_CRYPTO_SIDE_CLIENT:
|
||||
return nghttp3_conn_submit_request(
|
||||
connection(),
|
||||
id,
|
||||
headers.data(),
|
||||
headers.length(),
|
||||
reader_ptr,
|
||||
nullptr) == 0;
|
||||
case NGTCP2_CRYPTO_SIDE_SERVER:
|
||||
return nghttp3_conn_submit_response(
|
||||
connection(),
|
||||
id,
|
||||
headers.data(),
|
||||
headers.length(),
|
||||
reader_ptr) == 0;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
|
||||
// SubmitPush initiates a push stream by first creating a push promise
|
||||
// with an associated push id, then opening the unidirectional stream
|
||||
// that is used to fullfill it. Assuming both operations are successful,
|
||||
// the QuicStream instance is created and added to the server QuicSession.
|
||||
//
|
||||
// The headers block passed to the submit push contains the assumed
|
||||
// *request* headers. The response headers are provided using the
|
||||
// SubmitHeaders() function on the created QuicStream.
|
||||
BaseObjectPtr<QuicStream> Http3Application::SubmitPush(
|
||||
int64_t id,
|
||||
Local<Array> headers) {
|
||||
// If the QuicSession is not a server session, return false
|
||||
// immediately. Push streams cannot be sent by an HTTP/3 client.
|
||||
if (!session()->is_server())
|
||||
return {};
|
||||
|
||||
Http3Headers nva(env(), headers);
|
||||
int64_t push_id;
|
||||
int64_t stream_id;
|
||||
|
||||
// There are several reasons why push may fail. We currently handle
|
||||
// them all the same. Later we might want to differentiate when the
|
||||
// return value is NGHTTP3_ERR_PUSH_ID_BLOCKED.
|
||||
return SubmitPushPromise(id, &push_id, &stream_id, nva) ?
|
||||
QuicStream::New(session(), stream_id, push_id) :
|
||||
BaseObjectPtr<QuicStream>();
|
||||
}
|
||||
|
||||
// Submit informational headers (response headers that use a 1xx
|
||||
// status code). If the QuicSession is not a server session, return
|
||||
// false immediately because info headers cannot be sent by a
|
||||
// client
|
||||
bool Http3Application::SubmitInformation(
|
||||
int64_t stream_id,
|
||||
Local<Array> headers) {
|
||||
if (!session()->is_server())
|
||||
return false;
|
||||
Http3Headers nva(session()->env(), headers);
|
||||
return SubmitInformation(stream_id, nva);
|
||||
}
|
||||
|
||||
// For client sessions, submits request headers. For server sessions,
|
||||
// submits response headers.
|
||||
bool Http3Application::SubmitHeaders(
|
||||
int64_t stream_id,
|
||||
Local<Array> headers,
|
||||
uint32_t flags) {
|
||||
Http3Headers nva(session()->env(), headers);
|
||||
return SubmitHeaders(stream_id, nva, flags);
|
||||
}
|
||||
|
||||
// Submits trailing headers for the HTTP/3 request or response.
|
||||
bool Http3Application::SubmitTrailers(
|
||||
int64_t stream_id,
|
||||
Local<Array> headers) {
|
||||
Http3Headers nva(session()->env(), headers);
|
||||
return SubmitTrailers(stream_id, nva);
|
||||
}
|
||||
|
||||
void Http3Application::CheckAllocatedSize(size_t previous_size) const {
|
||||
CHECK_GE(current_nghttp3_memory_, previous_size);
|
||||
}
|
||||
|
||||
void Http3Application::IncreaseAllocatedSize(size_t size) {
|
||||
current_nghttp3_memory_ += size;
|
||||
}
|
||||
|
||||
void Http3Application::DecreaseAllocatedSize(size_t size) {
|
||||
current_nghttp3_memory_ -= size;
|
||||
}
|
||||
|
||||
void Http3Application::MemoryInfo(MemoryTracker* tracker) const {
|
||||
tracker->TrackFieldWithSize("current_nghttp3_memory",
|
||||
current_nghttp3_memory_);
|
||||
}
|
||||
|
||||
// Creates the underlying nghttp3 connection state for the session.
|
||||
void Http3Application::CreateConnection() {
|
||||
// nghttp3_conn_server_new and nghttp3_conn_client_new share
|
||||
// identical definitions, so new_fn will work for both.
|
||||
using new_fn = decltype(&nghttp3_conn_server_new);
|
||||
static new_fn fns[] = {
|
||||
nghttp3_conn_client_new, // NGTCP2_CRYPTO_SIDE_CLIENT
|
||||
nghttp3_conn_server_new, // NGTCP2_CRYPTO_SIDE_SERVER
|
||||
};
|
||||
|
||||
ngtcp2_crypto_side side = session()->crypto_context()->side();
|
||||
nghttp3_conn* conn;
|
||||
|
||||
CHECK_EQ(fns[side](
|
||||
&conn,
|
||||
&callbacks_[side],
|
||||
&config_,
|
||||
&alloc_info_,
|
||||
this), 0);
|
||||
CHECK_NOT_NULL(conn);
|
||||
connection_.reset(conn);
|
||||
}
|
||||
|
||||
// The HTTP/3 QUIC binding uses a single unidirectional control
|
||||
// stream in each direction to exchange frames impacting the entire
|
||||
// connection.
|
||||
bool Http3Application::CreateAndBindControlStream() {
|
||||
if (!session()->OpenUnidirectionalStream(&control_stream_id_))
|
||||
return false;
|
||||
Debug(
|
||||
session(),
|
||||
"Open stream %" PRId64 " and bind as control stream",
|
||||
control_stream_id_);
|
||||
return nghttp3_conn_bind_control_stream(
|
||||
connection(),
|
||||
control_stream_id_) == 0;
|
||||
}
|
||||
|
||||
// The HTTP/3 QUIC binding creates two unidirectional streams in
|
||||
// each direction to exchange header compression details.
|
||||
bool Http3Application::CreateAndBindQPackStreams() {
|
||||
if (!session()->OpenUnidirectionalStream(&qpack_enc_stream_id_) ||
|
||||
!session()->OpenUnidirectionalStream(&qpack_dec_stream_id_)) {
|
||||
return false;
|
||||
}
|
||||
Debug(
|
||||
session(),
|
||||
"Open streams %" PRId64 " and %" PRId64 " and bind as qpack streams",
|
||||
qpack_enc_stream_id_,
|
||||
qpack_dec_stream_id_);
|
||||
return nghttp3_conn_bind_qpack_streams(
|
||||
connection(),
|
||||
qpack_enc_stream_id_,
|
||||
qpack_dec_stream_id_) == 0;
|
||||
}
|
||||
|
||||
bool Http3Application::Initialize() {
|
||||
if (!needs_init())
|
||||
return false;
|
||||
|
||||
// The QuicSession must allow for at least three local unidirectional streams.
|
||||
// This number is fixed by the http3 specification and represent the
|
||||
// control stream and two qpack management streams.
|
||||
if (session()->max_local_streams_uni() < 3)
|
||||
return false;
|
||||
|
||||
Debug(session(), "QPack Max Table Capacity: %" PRIu64,
|
||||
config_.qpack_max_table_capacity);
|
||||
Debug(session(), "QPack Blocked Streams: %" PRIu64,
|
||||
config_.qpack_blocked_streams);
|
||||
Debug(session(), "Max Header List Size: %" PRIu64,
|
||||
config_.max_header_list_size);
|
||||
Debug(session(), "Max Pushes: %" PRIu64,
|
||||
config_.max_pushes);
|
||||
|
||||
CreateConnection();
|
||||
Debug(session(), "HTTP/3 connection created");
|
||||
|
||||
ngtcp2_transport_params params;
|
||||
session()->GetLocalTransportParams(¶ms);
|
||||
|
||||
if (session()->is_server()) {
|
||||
nghttp3_conn_set_max_client_streams_bidi(
|
||||
connection(),
|
||||
params.initial_max_streams_bidi);
|
||||
}
|
||||
|
||||
if (!CreateAndBindControlStream() ||
|
||||
!CreateAndBindQPackStreams()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
set_init_done();
|
||||
return true;
|
||||
}
|
||||
|
||||
// All HTTP/3 control, header, and stream data arrives as QUIC stream data.
|
||||
// Here we pass the received data off to nghttp3 for processing. This will
|
||||
// trigger the invocation of the various nghttp3 callbacks.
|
||||
bool Http3Application::ReceiveStreamData(
|
||||
int64_t stream_id,
|
||||
int fin,
|
||||
const uint8_t* data,
|
||||
size_t datalen,
|
||||
uint64_t offset) {
|
||||
Debug(session(), "Receiving %" PRIu64 " bytes for stream %" PRIu64 "%s",
|
||||
datalen, stream_id, fin == 1 ? " (fin)" : "");
|
||||
ssize_t nread =
|
||||
nghttp3_conn_read_stream(
|
||||
connection(), stream_id, data, datalen, fin);
|
||||
if (nread < 0) {
|
||||
Debug(session(), "Failure to read HTTP/3 Stream Data [%" PRId64 "]", nread);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// This is the QUIC-level stream data acknowledgement. It is called for
|
||||
// all streams, including unidirectional streams. This has to forward on
|
||||
// to nghttp3 for processing. The Http3Application::AckedStreamData might
|
||||
// be called as a result to acknowledge (and free) QuicStream data.
|
||||
void Http3Application::AcknowledgeStreamData(
|
||||
int64_t stream_id,
|
||||
uint64_t offset,
|
||||
size_t datalen) {
|
||||
if (nghttp3_conn_add_ack_offset(connection(), stream_id, datalen) != 0)
|
||||
Debug(session(), "Failure to acknowledge HTTP/3 Stream Data");
|
||||
}
|
||||
|
||||
void Http3Application::StreamClose(
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code) {
|
||||
if (app_error_code == 0)
|
||||
app_error_code = NGTCP2_APP_NOERROR;
|
||||
nghttp3_conn_close_stream(connection(), stream_id, app_error_code);
|
||||
QuicApplication::StreamClose(stream_id, app_error_code);
|
||||
}
|
||||
|
||||
void Http3Application::StreamReset(
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code) {
|
||||
nghttp3_conn_reset_stream(connection(), stream_id);
|
||||
QuicApplication::StreamReset(stream_id, app_error_code);
|
||||
}
|
||||
|
||||
// When SendPendingData tries to send data for a given stream and there
|
||||
// is no data to send but the QuicStream is still writable, it will
|
||||
// be paused. When there's data available, the stream is resumed.
|
||||
void Http3Application::ResumeStream(int64_t stream_id) {
|
||||
nghttp3_conn_resume_stream(connection(), stream_id);
|
||||
}
|
||||
|
||||
// When stream data cannot be sent because of flow control, it is marked
|
||||
// as being blocked. When the flow control windows expands, nghttp3 has
|
||||
// to be told to unblock the stream so it knows to try sending data again.
|
||||
void Http3Application::ExtendMaxStreamData(
|
||||
int64_t stream_id,
|
||||
uint64_t max_data) {
|
||||
nghttp3_conn_unblock_stream(connection(), stream_id);
|
||||
}
|
||||
|
||||
// When stream data cannot be sent because of flow control, it is marked
|
||||
// as being blocked.
|
||||
bool Http3Application::BlockStream(int64_t stream_id) {
|
||||
int err = nghttp3_conn_block_stream(connection(), stream_id);
|
||||
if (err != 0) {
|
||||
session()->set_last_error(QUIC_ERROR_APPLICATION, err);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// nghttp3 keeps track of how much QuicStream data it has available and
|
||||
// has sent. StreamCommit is called when a QuicPacket is serialized
|
||||
// and updates nghttp3's internal state.
|
||||
bool Http3Application::StreamCommit(StreamData* stream_data, size_t datalen) {
|
||||
int err = nghttp3_conn_add_write_offset(
|
||||
connection(),
|
||||
stream_data->id,
|
||||
datalen);
|
||||
if (err != 0) {
|
||||
session()->set_last_error(QUIC_ERROR_APPLICATION, err);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// GetStreamData is called by SendPendingData to collect the QuicStream data
|
||||
// that is to be packaged into a serialized QuicPacket. There may or may not
|
||||
// be any stream data to send. The call to nghttp3_conn_writev_stream will
|
||||
// provide any available stream data (if any). If nghttp3 is not sure if
|
||||
// there is data to send, it will subsequently call Http3Application::ReadData
|
||||
// to collect available data from the QuicStream.
|
||||
int Http3Application::GetStreamData(StreamData* stream_data) {
|
||||
ssize_t ret = 0;
|
||||
if (connection() && session()->max_data_left()) {
|
||||
ret = nghttp3_conn_writev_stream(
|
||||
connection(),
|
||||
&stream_data->id,
|
||||
&stream_data->fin,
|
||||
reinterpret_cast<nghttp3_vec*>(stream_data->data),
|
||||
sizeof(stream_data->data));
|
||||
if (ret < 0)
|
||||
return static_cast<int>(ret);
|
||||
else
|
||||
stream_data->remaining = stream_data->count = static_cast<size_t>(ret);
|
||||
}
|
||||
if (stream_data->id > -1) {
|
||||
Debug(session(), "Selected %" PRId64 " buffers for stream %" PRId64 "%s",
|
||||
stream_data->count,
|
||||
stream_data->id,
|
||||
stream_data->fin == 1 ? " (fin)" : "");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Determines whether SendPendingData should set fin on the QuicStream
|
||||
bool Http3Application::ShouldSetFin(const StreamData& stream_data) {
|
||||
return stream_data.id > -1 &&
|
||||
!is_control_stream(stream_data.id) &&
|
||||
stream_data.fin == 1;
|
||||
}
|
||||
|
||||
// This is where nghttp3 pulls the data from the outgoing
|
||||
// buffer to prepare it to be sent on the QUIC stream.
|
||||
ssize_t Http3Application::ReadData(
|
||||
int64_t stream_id,
|
||||
nghttp3_vec* vec,
|
||||
size_t veccnt,
|
||||
uint32_t* pflags) {
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
CHECK(stream);
|
||||
|
||||
ssize_t ret = NGHTTP3_ERR_WOULDBLOCK;
|
||||
|
||||
auto next = [&](
|
||||
int status,
|
||||
const ngtcp2_vec* data,
|
||||
size_t count,
|
||||
bob::Done done) {
|
||||
CHECK_LE(count, veccnt);
|
||||
|
||||
switch (status) {
|
||||
case bob::Status::STATUS_BLOCK:
|
||||
// Fall through
|
||||
case bob::Status::STATUS_WAIT:
|
||||
// Fall through
|
||||
case bob::Status::STATUS_EOS:
|
||||
return;
|
||||
case bob::Status::STATUS_END:
|
||||
*pflags |= NGHTTP3_DATA_FLAG_EOF;
|
||||
break;
|
||||
}
|
||||
|
||||
ret = count;
|
||||
size_t numbytes =
|
||||
nghttp3_vec_len(
|
||||
reinterpret_cast<const nghttp3_vec*>(data),
|
||||
count);
|
||||
std::move(done)(numbytes);
|
||||
|
||||
Debug(session(), "Sending %" PRIu64 " bytes for stream %" PRId64,
|
||||
numbytes, stream_id);
|
||||
};
|
||||
|
||||
CHECK_GE(stream->Pull(
|
||||
std::move(next),
|
||||
// Set OPTIONS_END here because nghttp3 takes over responsibility
|
||||
// for ensuring the data all gets written out.
|
||||
bob::Options::OPTIONS_END | bob::Options::OPTIONS_SYNC,
|
||||
reinterpret_cast<ngtcp2_vec*>(vec),
|
||||
veccnt,
|
||||
kMaxVectorCount), 0);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Outgoing data is retained in memory until it is acknowledged.
|
||||
void Http3Application::AckedStreamData(int64_t stream_id, size_t datalen) {
|
||||
Acknowledge(stream_id, 0, datalen);
|
||||
}
|
||||
|
||||
void Http3Application::StreamClosed(
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code) {
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
CHECK(stream);
|
||||
stream->ReceiveData(1, nullptr, 0, 0);
|
||||
session()->listener()->OnStreamClose(stream_id, app_error_code);
|
||||
}
|
||||
|
||||
BaseObjectPtr<QuicStream> Http3Application::FindOrCreateStream(
|
||||
int64_t stream_id) {
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
if (!stream) {
|
||||
if (session()->is_gracefully_closing()) {
|
||||
nghttp3_conn_close_stream(connection(), stream_id, NGTCP2_ERR_CLOSING);
|
||||
return {};
|
||||
}
|
||||
stream = session()->CreateStream(stream_id);
|
||||
nghttp3_conn_set_stream_user_data(connection(), stream_id, stream.get());
|
||||
}
|
||||
CHECK(stream);
|
||||
return stream;
|
||||
}
|
||||
|
||||
void Http3Application::ReceiveData(
|
||||
int64_t stream_id,
|
||||
const uint8_t* data,
|
||||
size_t datalen) {
|
||||
FindOrCreateStream(stream_id)->ReceiveData(0, data, datalen, 0);
|
||||
}
|
||||
|
||||
void Http3Application::DeferredConsume(
|
||||
int64_t stream_id,
|
||||
size_t consumed) {
|
||||
// Do nothing here for now. nghttp3 uses the on_deferred_consume
|
||||
// callback to notify when stream data that had previously been
|
||||
// deferred has been delivered to the application so that the
|
||||
// stream data offset can be extended. However, we extend the
|
||||
// data offset from within QuicStream when the data is delivered
|
||||
// so we don't have to do it here.
|
||||
}
|
||||
|
||||
// Called when a nghttp3 detects that a new block of headers
|
||||
// has been received. Http3Application::ReceiveHeader will
|
||||
// be called for each name+value pair received, then
|
||||
// Http3Application::EndHeaders will be called to finalize
|
||||
// the header block.
|
||||
void Http3Application::BeginHeaders(
|
||||
int64_t stream_id,
|
||||
QuicStreamHeadersKind kind) {
|
||||
Debug(session(), "Starting header block for stream %" PRId64, stream_id);
|
||||
FindOrCreateStream(stream_id)->BeginHeaders(kind);
|
||||
}
|
||||
|
||||
// As each header name+value pair is received, it is stored internally
|
||||
// by the QuicStream until stream->EndHeaders() is called, during which
|
||||
// the collected headers are converted to an array and passed off to
|
||||
// the javascript side.
|
||||
bool Http3Application::ReceiveHeader(
|
||||
int64_t stream_id,
|
||||
int32_t token,
|
||||
nghttp3_rcbuf* name,
|
||||
nghttp3_rcbuf* value,
|
||||
uint8_t flags) {
|
||||
// Protect against zero-length headers (zero-length if either the
|
||||
// name or value are zero-length). Such headers are simply ignored.
|
||||
if (!Http3Header::IsZeroLength(name, value)) {
|
||||
Debug(session(), "Receiving header for stream %" PRId64, stream_id);
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
CHECK(stream);
|
||||
if (token == NGHTTP3_QPACK_TOKEN__STATUS) {
|
||||
nghttp3_vec vec = nghttp3_rcbuf_get_buf(value);
|
||||
if (vec.base[0] == '1')
|
||||
stream->set_headers_kind(QUICSTREAM_HEADERS_KIND_INFORMATIONAL);
|
||||
else
|
||||
stream->set_headers_kind(QUICSTREAM_HEADERS_KIND_INITIAL);
|
||||
}
|
||||
auto header = std::make_unique<Http3Header>(
|
||||
session()->env(),
|
||||
token,
|
||||
name,
|
||||
value,
|
||||
flags);
|
||||
return stream->AddHeader(std::move(header));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Marks the completion of a headers block.
|
||||
void Http3Application::EndHeaders(int64_t stream_id, int64_t push_id) {
|
||||
Debug(session(), "Ending header block for stream %" PRId64, stream_id);
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
CHECK(stream);
|
||||
stream->EndHeaders();
|
||||
}
|
||||
|
||||
void Http3Application::CancelPush(
|
||||
int64_t push_id,
|
||||
int64_t stream_id) {
|
||||
Debug(session(), "push stream canceled");
|
||||
}
|
||||
|
||||
void Http3Application::PushStream(
|
||||
int64_t push_id,
|
||||
int64_t stream_id) {
|
||||
Debug(session(), "Received push stream %" PRIu64 " (%" PRIu64 ")",
|
||||
stream_id, push_id);
|
||||
}
|
||||
|
||||
void Http3Application::SendStopSending(
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code) {
|
||||
session()->ResetStream(stream_id, app_error_code);
|
||||
}
|
||||
|
||||
void Http3Application::EndStream(int64_t stream_id) {
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
CHECK(stream);
|
||||
stream->ReceiveData(1, nullptr, 0, 0);
|
||||
}
|
||||
|
||||
const nghttp3_conn_callbacks Http3Application::callbacks_[2] = {
|
||||
// NGTCP2_CRYPTO_SIDE_CLIENT
|
||||
{
|
||||
OnAckedStreamData,
|
||||
OnStreamClose,
|
||||
OnReceiveData,
|
||||
OnDeferredConsume,
|
||||
OnBeginHeaders,
|
||||
OnReceiveHeader,
|
||||
OnEndHeaders,
|
||||
OnBeginTrailers, // Begin Trailers
|
||||
OnReceiveHeader, // Receive Trailer
|
||||
OnEndHeaders, // End Trailers
|
||||
OnBeginPushPromise,
|
||||
OnReceivePushPromise,
|
||||
OnEndPushPromise,
|
||||
OnCancelPush,
|
||||
OnSendStopSending,
|
||||
OnPushStream,
|
||||
OnEndStream
|
||||
},
|
||||
// NGTCP2_CRYPTO_SIDE_SERVER
|
||||
{
|
||||
OnAckedStreamData,
|
||||
OnStreamClose,
|
||||
OnReceiveData,
|
||||
OnDeferredConsume,
|
||||
OnBeginHeaders,
|
||||
OnReceiveHeader,
|
||||
OnEndHeaders,
|
||||
OnBeginTrailers, // Begin Trailers
|
||||
OnReceiveHeader, // Receive Trailer
|
||||
OnEndHeaders, // End Trailers
|
||||
OnBeginPushPromise,
|
||||
OnReceivePushPromise,
|
||||
OnEndPushPromise,
|
||||
OnCancelPush,
|
||||
OnSendStopSending,
|
||||
OnPushStream,
|
||||
OnEndStream
|
||||
}
|
||||
};
|
||||
|
||||
int Http3Application::OnAckedStreamData(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
size_t datalen,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->AckedStreamData(stream_id, datalen);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnStreamClose(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->StreamClosed(stream_id, app_error_code);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnReceiveData(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
const uint8_t* data,
|
||||
size_t datalen,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->ReceiveData(stream_id, data, datalen);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnDeferredConsume(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
size_t consumed,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->DeferredConsume(stream_id, consumed);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnBeginHeaders(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->BeginHeaders(stream_id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnBeginTrailers(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->BeginHeaders(stream_id, QUICSTREAM_HEADERS_KIND_TRAILING);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnReceiveHeader(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
int32_t token,
|
||||
nghttp3_rcbuf* name,
|
||||
nghttp3_rcbuf* value,
|
||||
uint8_t flags,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
// TODO(@jasnell): Need to determine the appropriate response code here
|
||||
// for when the header is not going to be accepted.
|
||||
return app->ReceiveHeader(stream_id, token, name, value, flags) ?
|
||||
0 : NGHTTP3_ERR_CALLBACK_FAILURE;
|
||||
}
|
||||
|
||||
int Http3Application::OnEndHeaders(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->EndHeaders(stream_id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnBeginPushPromise(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
int64_t push_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->BeginHeaders(stream_id, QUICSTREAM_HEADERS_KIND_PUSH);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnReceivePushPromise(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
int64_t push_id,
|
||||
int32_t token,
|
||||
nghttp3_rcbuf* name,
|
||||
nghttp3_rcbuf* value,
|
||||
uint8_t flags,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
if (!app->ReceiveHeader(stream_id, token, name, value, flags))
|
||||
return NGHTTP3_ERR_CALLBACK_FAILURE;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnEndPushPromise(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
int64_t push_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->EndHeaders(stream_id, push_id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnCancelPush(
|
||||
nghttp3_conn* conn,
|
||||
int64_t push_id,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->CancelPush(push_id, stream_id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnSendStopSending(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->SendStopSending(stream_id, app_error_code);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnPushStream(
|
||||
nghttp3_conn* conn,
|
||||
int64_t push_id,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->PushStream(push_id, stream_id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Http3Application::OnEndStream(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
app->EndStream(stream_id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
ssize_t Http3Application::OnReadData(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
nghttp3_vec* vec,
|
||||
size_t veccnt,
|
||||
uint32_t* pflags,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data) {
|
||||
Http3Application* app = static_cast<Http3Application*>(conn_user_data);
|
||||
return app->ReadData(stream_id, vec, veccnt, pflags);
|
||||
}
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
@@ -0,0 +1,333 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_HTTP3_APPLICATION_H_
|
||||
#define SRC_QUIC_NODE_QUIC_HTTP3_APPLICATION_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "node.h"
|
||||
#include "node_http_common.h"
|
||||
#include "node_mem.h"
|
||||
#include "node_quic_session.h"
|
||||
#include "node_quic_stream-inl.h"
|
||||
#include "node_quic_util.h"
|
||||
#include "v8.h"
|
||||
#include <ngtcp2/ngtcp2.h>
|
||||
#include <nghttp3/nghttp3.h>
|
||||
|
||||
#include <string>
|
||||
namespace node {
|
||||
|
||||
namespace quic {
|
||||
|
||||
constexpr uint64_t DEFAULT_QPACK_MAX_TABLE_CAPACITY = 4096;
|
||||
constexpr uint64_t DEFAULT_QPACK_BLOCKED_STREAMS = 100;
|
||||
constexpr size_t DEFAULT_MAX_HEADER_LIST_SIZE = 65535;
|
||||
constexpr size_t DEFAULT_MAX_PUSHES = 65535;
|
||||
|
||||
struct Http3RcBufferPointerTraits {
|
||||
typedef nghttp3_rcbuf rcbuf_t;
|
||||
typedef nghttp3_vec vector_t;
|
||||
|
||||
static void inc(rcbuf_t* buf) {
|
||||
nghttp3_rcbuf_incref(buf);
|
||||
}
|
||||
static void dec(rcbuf_t* buf) {
|
||||
nghttp3_rcbuf_decref(buf);
|
||||
}
|
||||
static vector_t get_vec(const rcbuf_t* buf) {
|
||||
return nghttp3_rcbuf_get_buf(buf);
|
||||
}
|
||||
static bool is_static(const rcbuf_t* buf) {
|
||||
return nghttp3_rcbuf_is_static(buf);
|
||||
}
|
||||
};
|
||||
|
||||
struct Http3HeadersTraits {
|
||||
typedef nghttp3_nv nv_t;
|
||||
static const uint8_t kNoneFlag = NGHTTP3_NV_FLAG_NONE;
|
||||
};
|
||||
|
||||
using Http3ConnectionPointer = DeleteFnPtr<nghttp3_conn, nghttp3_conn_del>;
|
||||
using Http3RcBufferPointer = NgRcBufPointer<Http3RcBufferPointerTraits>;
|
||||
using Http3Headers = NgHeaders<Http3HeadersTraits>;
|
||||
|
||||
struct Http3HeaderTraits {
|
||||
typedef Http3RcBufferPointer rcbufferpointer_t;
|
||||
typedef QuicApplication allocator_t;
|
||||
|
||||
static const char* ToHttpHeaderName(int32_t token);
|
||||
};
|
||||
|
||||
using Http3Header = NgHeader<Http3HeaderTraits>;
|
||||
|
||||
struct Http3ApplicationConfig : public nghttp3_conn_settings {
|
||||
Http3ApplicationConfig() {
|
||||
nghttp3_conn_settings_default(this);
|
||||
qpack_max_table_capacity = DEFAULT_QPACK_MAX_TABLE_CAPACITY;
|
||||
qpack_blocked_streams = DEFAULT_QPACK_BLOCKED_STREAMS;
|
||||
max_header_list_size = DEFAULT_MAX_HEADER_LIST_SIZE;
|
||||
max_pushes = DEFAULT_MAX_PUSHES;
|
||||
}
|
||||
uint64_t max_header_pairs = DEFAULT_MAX_HEADER_LIST_PAIRS;
|
||||
uint64_t max_header_length = DEFAULT_MAX_HEADER_LENGTH;
|
||||
};
|
||||
|
||||
class Http3Application;
|
||||
using Http3MemoryManager =
|
||||
mem::NgLibMemoryManager<Http3Application, nghttp3_mem>;
|
||||
|
||||
// Http3Application is used whenever the h3 alpn identifier is used.
|
||||
// It causes the QuicSession to apply HTTP/3 semantics to the connection,
|
||||
// including handling of headers and other HTTP/3 specific processing.
|
||||
class Http3Application final :
|
||||
public QuicApplication,
|
||||
public Http3MemoryManager {
|
||||
public:
|
||||
explicit Http3Application(QuicSession* session);
|
||||
|
||||
bool Initialize() override;
|
||||
|
||||
void StopTrackingMemory(void* ptr) override {
|
||||
Http3MemoryManager::StopTrackingMemory(ptr);
|
||||
}
|
||||
|
||||
bool ReceiveStreamData(
|
||||
int64_t stream_id,
|
||||
int fin,
|
||||
const uint8_t* data,
|
||||
size_t datalen,
|
||||
uint64_t offset) override;
|
||||
|
||||
void AcknowledgeStreamData(
|
||||
int64_t stream_id,
|
||||
uint64_t offset,
|
||||
size_t datalen) override;
|
||||
|
||||
void StreamClose(int64_t stream_id, uint64_t app_error_code) override;
|
||||
|
||||
void StreamReset(
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code) override;
|
||||
|
||||
void ResumeStream(int64_t stream_id) override;
|
||||
|
||||
void ExtendMaxStreamData(int64_t stream_id, uint64_t max_data) override;
|
||||
|
||||
bool SubmitInformation(
|
||||
int64_t stream_id,
|
||||
v8::Local<v8::Array> headers) override;
|
||||
|
||||
bool SubmitHeaders(
|
||||
int64_t stream_id,
|
||||
v8::Local<v8::Array> headers,
|
||||
uint32_t flags) override;
|
||||
|
||||
bool SubmitTrailers(
|
||||
int64_t stream_id,
|
||||
v8::Local<v8::Array> headers) override;
|
||||
|
||||
BaseObjectPtr<QuicStream> SubmitPush(
|
||||
int64_t id,
|
||||
v8::Local<v8::Array> headers) override;
|
||||
|
||||
// Implementation for mem::NgLibMemoryManager
|
||||
void CheckAllocatedSize(size_t previous_size) const;
|
||||
void IncreaseAllocatedSize(size_t size);
|
||||
void DecreaseAllocatedSize(size_t size);
|
||||
|
||||
SET_SELF_SIZE(Http3Application)
|
||||
SET_MEMORY_INFO_NAME(Http3Application)
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
|
||||
private:
|
||||
template <typename M = uint64_t, typename T>
|
||||
void SetConfig(int idx, M T::*member);
|
||||
|
||||
nghttp3_conn* connection() const { return connection_.get(); }
|
||||
BaseObjectPtr<QuicStream> FindOrCreateStream(int64_t stream_id);
|
||||
|
||||
bool CreateAndBindControlStream();
|
||||
bool CreateAndBindQPackStreams();
|
||||
int64_t CreateAndBindPushStream(int64_t push_id);
|
||||
|
||||
int GetStreamData(StreamData* stream_data) override;
|
||||
|
||||
bool BlockStream(int64_t stream_id) override;
|
||||
bool StreamCommit(StreamData* stream_data, size_t datalen) override;
|
||||
bool ShouldSetFin(const StreamData& data) override;
|
||||
bool SubmitPushPromise(
|
||||
int64_t id,
|
||||
int64_t* push_id,
|
||||
int64_t* stream_id,
|
||||
const Http3Headers& headers);
|
||||
bool SubmitInformation(int64_t id, const Http3Headers& headers);
|
||||
bool SubmitTrailers(int64_t id, const Http3Headers& headers);
|
||||
bool SubmitHeaders(int64_t id, const Http3Headers& headers, int32_t flags);
|
||||
|
||||
ssize_t ReadData(
|
||||
int64_t stream_id,
|
||||
nghttp3_vec* vec,
|
||||
size_t veccnt,
|
||||
uint32_t* pflags);
|
||||
|
||||
void AckedStreamData(int64_t stream_id, size_t datalen);
|
||||
void StreamClosed(int64_t stream_id, uint64_t app_error_code);
|
||||
void ReceiveData(int64_t stream_id, const uint8_t* data, size_t datalen);
|
||||
void DeferredConsume(int64_t stream_id, size_t consumed);
|
||||
void BeginHeaders(
|
||||
int64_t stream_id,
|
||||
QuicStreamHeadersKind kind = QUICSTREAM_HEADERS_KIND_NONE);
|
||||
bool ReceiveHeader(
|
||||
int64_t stream_id,
|
||||
int32_t token,
|
||||
nghttp3_rcbuf* name,
|
||||
nghttp3_rcbuf* value,
|
||||
uint8_t flags);
|
||||
void EndHeaders(int64_t stream_id, int64_t push_id = 0);
|
||||
void CancelPush(int64_t push_id, int64_t stream_id);
|
||||
void SendStopSending(int64_t stream_id, uint64_t app_error_code);
|
||||
void PushStream(int64_t push_id, int64_t stream_id);
|
||||
void EndStream(int64_t stream_id);
|
||||
|
||||
bool is_control_stream(int64_t stream_id) const {
|
||||
return stream_id == control_stream_id_ ||
|
||||
stream_id == qpack_dec_stream_id_ ||
|
||||
stream_id == qpack_enc_stream_id_;
|
||||
}
|
||||
|
||||
nghttp3_mem alloc_info_;
|
||||
Http3ConnectionPointer connection_;
|
||||
int64_t control_stream_id_;
|
||||
int64_t qpack_enc_stream_id_;
|
||||
int64_t qpack_dec_stream_id_;
|
||||
size_t current_nghttp3_memory_ = 0;
|
||||
|
||||
Http3ApplicationConfig config_;
|
||||
|
||||
void CreateConnection();
|
||||
|
||||
static const nghttp3_conn_callbacks callbacks_[2];
|
||||
|
||||
static int OnAckedStreamData(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
size_t datalen,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnStreamClose(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnReceiveData(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
const uint8_t* data,
|
||||
size_t datalen,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnDeferredConsume(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
size_t consumed,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnBeginHeaders(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnBeginTrailers(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnReceiveHeader(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
int32_t token,
|
||||
nghttp3_rcbuf* name,
|
||||
nghttp3_rcbuf* value,
|
||||
uint8_t flags,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnEndHeaders(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnBeginPushPromise(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
int64_t push_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnReceivePushPromise(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
int64_t push_id,
|
||||
int32_t token,
|
||||
nghttp3_rcbuf* name,
|
||||
nghttp3_rcbuf* value,
|
||||
uint8_t flags,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnEndPushPromise(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
int64_t push_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnCancelPush(
|
||||
nghttp3_conn* conn,
|
||||
int64_t push_id,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnSendStopSending(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
uint64_t app_error_code,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static int OnPushStream(
|
||||
nghttp3_conn* conn,
|
||||
int64_t push_id,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data);
|
||||
|
||||
static int OnEndStream(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
|
||||
static ssize_t OnReadData(
|
||||
nghttp3_conn* conn,
|
||||
int64_t stream_id,
|
||||
nghttp3_vec* vec,
|
||||
size_t veccnt,
|
||||
uint32_t* pflags,
|
||||
void* conn_user_data,
|
||||
void* stream_user_data);
|
||||
};
|
||||
|
||||
} // namespace quic
|
||||
|
||||
} // namespace node
|
||||
|
||||
#endif // NODE_WANT_INTERNALS
|
||||
#endif // SRC_QUIC_NODE_QUIC_HTTP3_APPLICATION_H_
|
||||
@@ -0,0 +1,614 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_SESSION_INL_H_
|
||||
#define SRC_QUIC_NODE_QUIC_SESSION_INL_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "debug_utils-inl.h"
|
||||
#include "node_crypto.h"
|
||||
#include "node_crypto_common.h"
|
||||
#include "node_quic_crypto.h"
|
||||
#include "node_quic_session.h"
|
||||
#include "node_quic_socket-inl.h"
|
||||
#include "node_quic_stream-inl.h"
|
||||
|
||||
#include <openssl/ssl.h>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace node {
|
||||
|
||||
namespace quic {
|
||||
|
||||
void QuicSessionConfig::GenerateStatelessResetToken(
|
||||
QuicSession* session,
|
||||
const QuicCID& cid) {
|
||||
transport_params.stateless_reset_token_present = 1;
|
||||
StatelessResetToken token(
|
||||
transport_params.stateless_reset_token,
|
||||
session->socket()->session_reset_secret(),
|
||||
cid);
|
||||
Debug(session, "Generated stateless reset token %s for CID %s", token, cid);
|
||||
}
|
||||
|
||||
void QuicSessionConfig::GeneratePreferredAddressToken(
|
||||
ConnectionIDStrategy connection_id_strategy,
|
||||
QuicSession* session,
|
||||
QuicCID* pscid) {
|
||||
connection_id_strategy(session, pscid->cid(), kScidLen);
|
||||
transport_params.preferred_address.cid = **pscid;
|
||||
|
||||
StatelessResetToken(
|
||||
transport_params.preferred_address.stateless_reset_token,
|
||||
session->socket()->session_reset_secret(),
|
||||
*pscid);
|
||||
}
|
||||
|
||||
void QuicSessionConfig::set_original_connection_id(const QuicCID& ocid) {
|
||||
if (ocid) {
|
||||
transport_params.original_connection_id = *ocid;
|
||||
transport_params.original_connection_id_present = 1;
|
||||
}
|
||||
}
|
||||
|
||||
void QuicSessionConfig::set_qlog(const ngtcp2_qlog_settings& qlog_) {
|
||||
qlog = qlog_;
|
||||
}
|
||||
|
||||
QuicCryptoContext::QuicCryptoContext(
|
||||
QuicSession* session,
|
||||
BaseObjectPtr<crypto::SecureContext> secure_context,
|
||||
ngtcp2_crypto_side side,
|
||||
uint32_t options) :
|
||||
session_(session),
|
||||
secure_context_(secure_context),
|
||||
side_(side),
|
||||
options_(options) {
|
||||
ssl_.reset(SSL_new(secure_context_->ctx_.get()));
|
||||
CHECK(ssl_);
|
||||
}
|
||||
|
||||
void QuicCryptoContext::Initialize() {
|
||||
InitializeTLS(session(), ssl_);
|
||||
}
|
||||
|
||||
// Cancels and frees any remaining outbound handshake data
|
||||
// at each crypto level.
|
||||
uint64_t QuicCryptoContext::Cancel() {
|
||||
uint64_t len = handshake_[0].Cancel();
|
||||
len += handshake_[1].Cancel();
|
||||
len += handshake_[2].Cancel();
|
||||
return len;
|
||||
}
|
||||
|
||||
v8::MaybeLocal<v8::Value> QuicCryptoContext::ocsp_response() const {
|
||||
Environment* env = session()->env();
|
||||
return crypto::GetSSLOCSPResponse(
|
||||
env,
|
||||
ssl_.get(),
|
||||
v8::Undefined(env->isolate()));
|
||||
}
|
||||
|
||||
ngtcp2_crypto_level QuicCryptoContext::read_crypto_level() const {
|
||||
return from_ossl_level(SSL_quic_read_level(ssl_.get()));
|
||||
}
|
||||
|
||||
ngtcp2_crypto_level QuicCryptoContext::write_crypto_level() const {
|
||||
return from_ossl_level(SSL_quic_write_level(ssl_.get()));
|
||||
}
|
||||
|
||||
// TLS Keylogging is enabled per-QuicSession by attaching an handler to the
|
||||
// "keylog" event. Each keylog line is emitted to JavaScript where it can
|
||||
// be routed to whatever destination makes sense. Typically, this will be
|
||||
// to a keylog file that can be consumed by tools like Wireshark to intercept
|
||||
// and decrypt QUIC network traffic.
|
||||
void QuicCryptoContext::Keylog(const char* line) {
|
||||
if (UNLIKELY(session_->state_[IDX_QUIC_SESSION_STATE_KEYLOG_ENABLED] == 1))
|
||||
session_->listener()->OnKeylog(line, strlen(line));
|
||||
}
|
||||
|
||||
void QuicCryptoContext::OnClientHelloDone() {
|
||||
// Continue the TLS handshake when this function exits
|
||||
// otherwise it will stall and fail.
|
||||
TLSHandshakeScope handshake(this, &in_client_hello_);
|
||||
// Disable the callback at this point so we don't loop continuously
|
||||
session_->state_[IDX_QUIC_SESSION_STATE_CLIENT_HELLO_ENABLED] = 0;
|
||||
}
|
||||
|
||||
// Following a pause in the handshake for OCSP or client hello, we kickstart
|
||||
// the handshake again here by triggering ngtcp2 to serialize data.
|
||||
void QuicCryptoContext::ResumeHandshake() {
|
||||
// We haven't received any actual new handshake data but calling
|
||||
// this will trigger the handshake to continue.
|
||||
Receive(read_crypto_level(), 0, nullptr, 0);
|
||||
session_->SendPendingData();
|
||||
}
|
||||
|
||||
// For 0RTT, this sets the TLS session data from the given buffer.
|
||||
bool QuicCryptoContext::set_session(crypto::SSLSessionPointer session) {
|
||||
if (side_ == NGTCP2_CRYPTO_SIDE_CLIENT && session != nullptr) {
|
||||
early_data_ =
|
||||
SSL_SESSION_get_max_early_data(session.get()) == 0xffffffffUL;
|
||||
}
|
||||
return crypto::SetTLSSession(ssl_, std::move(session));
|
||||
}
|
||||
|
||||
v8::MaybeLocal<v8::Array> QuicCryptoContext::hello_ciphers() const {
|
||||
return crypto::GetClientHelloCiphers(session()->env(), ssl_);
|
||||
}
|
||||
|
||||
v8::MaybeLocal<v8::Value> QuicCryptoContext::cipher_name() const {
|
||||
return crypto::GetCipherName(session()->env(), ssl_);
|
||||
}
|
||||
|
||||
v8::MaybeLocal<v8::Value> QuicCryptoContext::cipher_version() const {
|
||||
return crypto::GetCipherVersion(session()->env(), ssl_);
|
||||
}
|
||||
|
||||
const char* QuicCryptoContext::servername() const {
|
||||
return crypto::GetServerName(ssl_.get());
|
||||
}
|
||||
|
||||
const char* QuicCryptoContext::hello_alpn() const {
|
||||
return crypto::GetClientHelloALPN(ssl_);
|
||||
}
|
||||
|
||||
const char* QuicCryptoContext::hello_servername() const {
|
||||
return crypto::GetClientHelloServerName(ssl_);
|
||||
}
|
||||
|
||||
v8::MaybeLocal<v8::Object> QuicCryptoContext::ephemeral_key() const {
|
||||
return crypto::GetEphemeralKey(session()->env(), ssl_);
|
||||
}
|
||||
|
||||
v8::MaybeLocal<v8::Value> QuicCryptoContext::peer_cert(bool abbreviated) const {
|
||||
return crypto::GetPeerCert(
|
||||
session()->env(),
|
||||
ssl_,
|
||||
abbreviated,
|
||||
session()->is_server());
|
||||
}
|
||||
|
||||
v8::MaybeLocal<v8::Value> QuicCryptoContext::cert() const {
|
||||
return crypto::GetCert(session()->env(), ssl_);
|
||||
}
|
||||
|
||||
std::string QuicCryptoContext::selected_alpn() const {
|
||||
const unsigned char* alpn_buf = nullptr;
|
||||
unsigned int alpnlen;
|
||||
SSL_get0_alpn_selected(ssl_.get(), &alpn_buf, &alpnlen);
|
||||
return alpnlen ?
|
||||
std::string(reinterpret_cast<const char*>(alpn_buf), alpnlen) :
|
||||
std::string();
|
||||
}
|
||||
|
||||
bool QuicCryptoContext::early_data() const {
|
||||
return
|
||||
(early_data_ &&
|
||||
SSL_get_early_data_status(ssl_.get()) == SSL_EARLY_DATA_ACCEPTED) ||
|
||||
SSL_get_max_early_data(ssl_.get()) == 0xffffffffUL;
|
||||
}
|
||||
|
||||
void QuicCryptoContext::set_tls_alert(int err) {
|
||||
Debug(session(), "TLS Alert [%d]: %s", err, SSL_alert_type_string_long(err));
|
||||
session_->set_last_error(QuicError(QUIC_ERROR_CRYPTO, err));
|
||||
}
|
||||
|
||||
// Derives and installs the initial keying material for a newly
|
||||
// created session.
|
||||
bool QuicCryptoContext::SetupInitialKey(const QuicCID& dcid) {
|
||||
Debug(session(), "Deriving and installing initial keys");
|
||||
return DeriveAndInstallInitialKey(*session(), dcid);
|
||||
}
|
||||
|
||||
QuicApplication::QuicApplication(QuicSession* session) : session_(session) {}
|
||||
|
||||
void QuicApplication::set_stream_fin(int64_t stream_id) {
|
||||
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
|
||||
CHECK(stream);
|
||||
stream->set_fin_sent();
|
||||
}
|
||||
|
||||
ssize_t QuicApplication::WriteVStream(
|
||||
QuicPathStorage* path,
|
||||
uint8_t* buf,
|
||||
ssize_t* ndatalen,
|
||||
const StreamData& stream_data) {
|
||||
CHECK_LE(stream_data.count, kMaxVectorCount);
|
||||
return ngtcp2_conn_writev_stream(
|
||||
session()->connection(),
|
||||
&path->path,
|
||||
buf,
|
||||
session()->max_packet_length(),
|
||||
ndatalen,
|
||||
stream_data.remaining > 0 ?
|
||||
NGTCP2_WRITE_STREAM_FLAG_MORE :
|
||||
NGTCP2_WRITE_STREAM_FLAG_NONE,
|
||||
stream_data.id,
|
||||
stream_data.fin,
|
||||
stream_data.buf,
|
||||
stream_data.count,
|
||||
uv_hrtime());
|
||||
}
|
||||
|
||||
std::unique_ptr<QuicPacket> QuicApplication::CreateStreamDataPacket() {
|
||||
return QuicPacket::Create(
|
||||
"stream data",
|
||||
session()->max_packet_length());
|
||||
}
|
||||
|
||||
Environment* QuicApplication::env() const {
|
||||
return session()->env();
|
||||
}
|
||||
|
||||
// Every QUIC session will have multiple CIDs associated with it.
|
||||
void QuicSession::AssociateCID(const QuicCID& cid) {
|
||||
socket()->AssociateCID(cid, scid_);
|
||||
}
|
||||
|
||||
void QuicSession::DisassociateCID(const QuicCID& cid) {
|
||||
if (is_server())
|
||||
socket()->DisassociateCID(cid);
|
||||
}
|
||||
|
||||
void QuicSession::StartHandshake() {
|
||||
if (crypto_context_->is_handshake_started() || is_server())
|
||||
return;
|
||||
crypto_context_->handshake_started();
|
||||
SendPendingData();
|
||||
}
|
||||
|
||||
void QuicSession::ExtendMaxStreamData(int64_t stream_id, uint64_t max_data) {
|
||||
Debug(this,
|
||||
"Extending max stream %" PRId64 " data to %" PRIu64,
|
||||
stream_id, max_data);
|
||||
application_->ExtendMaxStreamData(stream_id, max_data);
|
||||
}
|
||||
|
||||
void QuicSession::ExtendMaxStreamsRemoteUni(uint64_t max_streams) {
|
||||
Debug(this, "Extend remote max unidirectional streams: %" PRIu64,
|
||||
max_streams);
|
||||
application_->ExtendMaxStreamsRemoteUni(max_streams);
|
||||
}
|
||||
|
||||
void QuicSession::ExtendMaxStreamsRemoteBidi(uint64_t max_streams) {
|
||||
Debug(this, "Extend remote max bidirectional streams: %" PRIu64,
|
||||
max_streams);
|
||||
application_->ExtendMaxStreamsRemoteBidi(max_streams);
|
||||
}
|
||||
|
||||
void QuicSession::ExtendMaxStreamsUni(uint64_t max_streams) {
|
||||
Debug(this, "Setting max unidirectional streams to %" PRIu64, max_streams);
|
||||
state_[IDX_QUIC_SESSION_STATE_MAX_STREAMS_UNI] =
|
||||
static_cast<double>(max_streams);
|
||||
}
|
||||
|
||||
void QuicSession::ExtendMaxStreamsBidi(uint64_t max_streams) {
|
||||
Debug(this, "Setting max bidirectional streams to %" PRIu64, max_streams);
|
||||
state_[IDX_QUIC_SESSION_STATE_MAX_STREAMS_BIDI] =
|
||||
static_cast<double>(max_streams);
|
||||
}
|
||||
|
||||
// Extends the stream-level flow control by the given number of bytes.
|
||||
void QuicSession::ExtendStreamOffset(int64_t stream_id, size_t amount) {
|
||||
Debug(this, "Extending max stream %" PRId64 " offset by %" PRId64 " bytes",
|
||||
stream_id, amount);
|
||||
ngtcp2_conn_extend_max_stream_offset(
|
||||
connection(),
|
||||
stream_id,
|
||||
amount);
|
||||
}
|
||||
|
||||
// Extends the connection-level flow control for the entire session by
|
||||
// the given number of bytes.
|
||||
void QuicSession::ExtendOffset(size_t amount) {
|
||||
Debug(this, "Extending session offset by %" PRId64 " bytes", amount);
|
||||
ngtcp2_conn_extend_max_offset(connection(), amount);
|
||||
}
|
||||
|
||||
// Copies the local transport params into the given struct for serialization.
|
||||
void QuicSession::GetLocalTransportParams(ngtcp2_transport_params* params) {
|
||||
CHECK(!is_flag_set(QUICSESSION_FLAG_DESTROYED));
|
||||
ngtcp2_conn_get_local_transport_params(connection(), params);
|
||||
}
|
||||
|
||||
// Gets the QUIC version negotiated for this QuicSession
|
||||
uint32_t QuicSession::negotiated_version() const {
|
||||
CHECK(!is_flag_set(QUICSESSION_FLAG_DESTROYED));
|
||||
return ngtcp2_conn_get_negotiated_version(connection());
|
||||
}
|
||||
|
||||
// The HandshakeCompleted function is called by ngtcp2 once it
|
||||
// determines that the TLS Handshake is done. The only thing we
|
||||
// need to do at this point is let the javascript side know.
|
||||
void QuicSession::HandshakeCompleted() {
|
||||
RemoteTransportParamsDebug transport_params(this);
|
||||
Debug(this, "Handshake is completed. %s", transport_params);
|
||||
RecordTimestamp(&QuicSessionStats::handshake_completed_at);
|
||||
if (is_server()) HandshakeConfirmed();
|
||||
listener()->OnHandshakeCompleted();
|
||||
}
|
||||
|
||||
void QuicSession::HandshakeConfirmed() {
|
||||
Debug(this, "Handshake is confirmed");
|
||||
RecordTimestamp(&QuicSessionStats::handshake_confirmed_at);
|
||||
state_[IDX_QUIC_SESSION_STATE_HANDSHAKE_CONFIRMED] = 1;
|
||||
}
|
||||
|
||||
bool QuicSession::is_handshake_completed() const {
|
||||
DCHECK(!is_flag_set(QUICSESSION_FLAG_DESTROYED));
|
||||
return ngtcp2_conn_get_handshake_completed(connection());
|
||||
}
|
||||
|
||||
void QuicSession::InitApplication() {
|
||||
Debug(this, "Initializing application handler for ALPN %s",
|
||||
alpn().c_str() + 1);
|
||||
application_->Initialize();
|
||||
}
|
||||
|
||||
// When a QuicSession hits the idle timeout, it is to be silently and
|
||||
// immediately closed without attempting to send any additional data to
|
||||
// the peer. All existing streams are abandoned and closed.
|
||||
void QuicSession::OnIdleTimeout() {
|
||||
if (!is_flag_set(QUICSESSION_FLAG_DESTROYED)) {
|
||||
state_[IDX_QUIC_SESSION_STATE_IDLE_TIMEOUT] = 1;
|
||||
Debug(this, "Idle timeout");
|
||||
SilentClose();
|
||||
}
|
||||
}
|
||||
|
||||
// Captures the error code and family information from a received
|
||||
// connection close frame.
|
||||
void QuicSession::GetConnectionCloseInfo() {
|
||||
ngtcp2_connection_close_error_code close_code;
|
||||
ngtcp2_conn_get_connection_close_error_code(connection(), &close_code);
|
||||
set_last_error(QuicError(close_code));
|
||||
}
|
||||
|
||||
// Removes the given connection id from the QuicSession.
|
||||
void QuicSession::RemoveConnectionID(const QuicCID& cid) {
|
||||
if (!is_flag_set(QUICSESSION_FLAG_DESTROYED))
|
||||
DisassociateCID(cid);
|
||||
}
|
||||
|
||||
QuicCID QuicSession::dcid() const {
|
||||
return QuicCID(ngtcp2_conn_get_dcid(connection()));
|
||||
}
|
||||
|
||||
// The retransmit timer allows us to trigger retransmission
|
||||
// of packets in case they are considered lost. The exact amount
|
||||
// of time is determined internally by ngtcp2 according to the
|
||||
// guidelines established by the QUIC spec but we use a libuv
|
||||
// timer to actually monitor. Here we take the calculated timeout
|
||||
// and extend out the libuv timer.
|
||||
void QuicSession::UpdateRetransmitTimer(uint64_t timeout) {
|
||||
DCHECK_NOT_NULL(retransmit_);
|
||||
retransmit_->Update(timeout);
|
||||
}
|
||||
|
||||
void QuicSession::CheckAllocatedSize(size_t previous_size) const {
|
||||
CHECK_GE(current_ngtcp2_memory_, previous_size);
|
||||
}
|
||||
|
||||
void QuicSession::IncreaseAllocatedSize(size_t size) {
|
||||
current_ngtcp2_memory_ += size;
|
||||
}
|
||||
|
||||
void QuicSession::DecreaseAllocatedSize(size_t size) {
|
||||
current_ngtcp2_memory_ -= size;
|
||||
}
|
||||
|
||||
uint64_t QuicSession::max_data_left() const {
|
||||
return ngtcp2_conn_get_max_data_left(connection());
|
||||
}
|
||||
|
||||
uint64_t QuicSession::max_local_streams_uni() const {
|
||||
return ngtcp2_conn_get_max_local_streams_uni(connection());
|
||||
}
|
||||
|
||||
void QuicSession::set_last_error(QuicError error) {
|
||||
last_error_ = error;
|
||||
}
|
||||
|
||||
void QuicSession::set_last_error(int32_t family, uint64_t code) {
|
||||
set_last_error({ family, code });
|
||||
}
|
||||
|
||||
void QuicSession::set_last_error(int32_t family, int code) {
|
||||
set_last_error({ family, code });
|
||||
}
|
||||
|
||||
bool QuicSession::is_in_closing_period() const {
|
||||
return ngtcp2_conn_is_in_closing_period(connection());
|
||||
}
|
||||
|
||||
bool QuicSession::is_in_draining_period() const {
|
||||
return ngtcp2_conn_is_in_draining_period(connection());
|
||||
}
|
||||
|
||||
bool QuicSession::HasStream(int64_t id) const {
|
||||
return streams_.find(id) != std::end(streams_);
|
||||
}
|
||||
|
||||
bool QuicSession::allow_early_data() const {
|
||||
// TODO(@jasnell): For now, we always allow early data.
|
||||
// Later there will be reasons we do not want to allow
|
||||
// it, such as lack of available system resources.
|
||||
return true;
|
||||
}
|
||||
|
||||
void QuicSession::SetSessionTicketAppData(
|
||||
const SessionTicketAppData& app_data) {
|
||||
application_->SetSessionTicketAppData(app_data);
|
||||
}
|
||||
|
||||
SessionTicketAppData::Status QuicSession::GetSessionTicketAppData(
|
||||
const SessionTicketAppData& app_data,
|
||||
SessionTicketAppData::Flag flag) {
|
||||
return application_->GetSessionTicketAppData(app_data, flag);
|
||||
}
|
||||
|
||||
bool QuicSession::is_gracefully_closing() const {
|
||||
return is_flag_set(QUICSESSION_FLAG_GRACEFUL_CLOSING);
|
||||
}
|
||||
|
||||
bool QuicSession::is_destroyed() const {
|
||||
return is_flag_set(QUICSESSION_FLAG_DESTROYED);
|
||||
}
|
||||
|
||||
bool QuicSession::is_stateless_reset() const {
|
||||
return is_flag_set(QUICSESSION_FLAG_STATELESS_RESET);
|
||||
}
|
||||
|
||||
bool QuicSession::is_server() const {
|
||||
return crypto_context_->side() == NGTCP2_CRYPTO_SIDE_SERVER;
|
||||
}
|
||||
|
||||
void QuicSession::StartGracefulClose() {
|
||||
set_flag(QUICSESSION_FLAG_GRACEFUL_CLOSING);
|
||||
RecordTimestamp(&QuicSessionStats::closing_at);
|
||||
}
|
||||
|
||||
// The connection ID Strategy is a function that generates
|
||||
// connection ID values. By default these are generated randomly.
|
||||
void QuicSession::set_connection_id_strategy(ConnectionIDStrategy strategy) {
|
||||
CHECK_NOT_NULL(strategy);
|
||||
connection_id_strategy_ = strategy;
|
||||
}
|
||||
|
||||
void QuicSession::set_preferred_address_strategy(
|
||||
PreferredAddressStrategy strategy) {
|
||||
preferred_address_strategy_ = strategy;
|
||||
}
|
||||
|
||||
QuicSocket* QuicSession::socket() const {
|
||||
return socket_.get();
|
||||
}
|
||||
|
||||
// Indicates that the stream is blocked from transmitting any
|
||||
// data. The specific handling of this is application specific.
|
||||
// By default, we keep track of statistics but leave it up to
|
||||
// the application to perform specific handling.
|
||||
void QuicSession::StreamDataBlocked(int64_t stream_id) {
|
||||
IncrementStat(&QuicSessionStats::block_count);
|
||||
listener_->OnStreamBlocked(stream_id);
|
||||
}
|
||||
|
||||
// When a server advertises a preferred address in its initial
|
||||
// transport parameters, ngtcp2 on the client side will trigger
|
||||
// the OnSelectPreferredAdddress callback which will call this.
|
||||
// The paddr argument contains the advertised preferred address.
|
||||
// If the new address is going to be used, it needs to be copied
|
||||
// over to dest, otherwise dest is left alone. There are two
|
||||
// possible strategies that we currently support via user
|
||||
// configuration: use the preferred address or ignore it.
|
||||
void QuicSession::SelectPreferredAddress(
|
||||
const PreferredAddress& preferred_address) {
|
||||
CHECK(!is_server());
|
||||
preferred_address_strategy_(this, preferred_address);
|
||||
}
|
||||
|
||||
// This variant of SendPacket is used by QuicApplication
|
||||
// instances to transmit a packet and update the network
|
||||
// path used at the same time.
|
||||
bool QuicSession::SendPacket(
|
||||
std::unique_ptr<QuicPacket> packet,
|
||||
const ngtcp2_path_storage& path) {
|
||||
UpdateEndpoint(path.path);
|
||||
return SendPacket(std::move(packet));
|
||||
}
|
||||
|
||||
void QuicSession::set_local_address(const ngtcp2_addr* addr) {
|
||||
DCHECK(!is_flag_set(QUICSESSION_FLAG_DESTROYED));
|
||||
ngtcp2_conn_set_local_addr(connection(), addr);
|
||||
}
|
||||
|
||||
// Set the transport parameters received from the remote peer
|
||||
void QuicSession::set_remote_transport_params() {
|
||||
DCHECK(!is_flag_set(QUICSESSION_FLAG_DESTROYED));
|
||||
ngtcp2_conn_get_remote_transport_params(connection(), &transport_params_);
|
||||
set_flag(QUICSESSION_FLAG_HAS_TRANSPORT_PARAMS);
|
||||
}
|
||||
|
||||
void QuicSession::StopIdleTimer() {
|
||||
CHECK_NOT_NULL(idle_);
|
||||
idle_->Stop();
|
||||
}
|
||||
|
||||
void QuicSession::StopRetransmitTimer() {
|
||||
CHECK_NOT_NULL(retransmit_);
|
||||
retransmit_->Stop();
|
||||
}
|
||||
|
||||
// Called by the OnVersionNegotiation callback when a version
|
||||
// negotiation frame has been received by the client. The sv
|
||||
// parameter is an array of versions supported by the remote peer.
|
||||
void QuicSession::VersionNegotiation(const uint32_t* sv, size_t nsv) {
|
||||
CHECK(!is_server());
|
||||
if (!is_flag_set(QUICSESSION_FLAG_DESTROYED))
|
||||
listener()->OnVersionNegotiation(NGTCP2_PROTO_VER, sv, nsv);
|
||||
}
|
||||
|
||||
// Every QUIC session has a remote address and local address.
|
||||
// Those endpoints can change through the lifetime of a connection,
|
||||
// so whenever a packet is successfully processed, or when a
|
||||
// response is to be sent, we have to keep track of the path
|
||||
// and update as we go.
|
||||
void QuicSession::UpdateEndpoint(const ngtcp2_path& path) {
|
||||
remote_address_.Update(path.remote.addr, path.remote.addrlen);
|
||||
local_address_.Update(path.local.addr, path.local.addrlen);
|
||||
|
||||
// If the updated remote address is IPv6, set the flow label
|
||||
if (remote_address_.family() == AF_INET6) {
|
||||
// TODO(@jasnell): Currently, this reuses the session reset secret.
|
||||
// That may or may not be a good idea, we need to verify and may
|
||||
// need to have a distinct secret for flow labels.
|
||||
uint32_t flow_label =
|
||||
GenerateFlowLabel(
|
||||
local_address_,
|
||||
remote_address_,
|
||||
scid_,
|
||||
socket()->session_reset_secret(),
|
||||
NGTCP2_STATELESS_RESET_TOKENLEN);
|
||||
remote_address_.set_flow_label(flow_label);
|
||||
}
|
||||
}
|
||||
|
||||
// Submits information headers only if the selected application
|
||||
// supports headers.
|
||||
bool QuicSession::SubmitInformation(
|
||||
int64_t stream_id,
|
||||
v8::Local<v8::Array> headers) {
|
||||
return application_->SubmitInformation(stream_id, headers);
|
||||
}
|
||||
|
||||
// Submits initial headers only if the selected application
|
||||
// supports headers. For http3, for instance, this is the
|
||||
// method used to submit both request and response headers.
|
||||
bool QuicSession::SubmitHeaders(
|
||||
int64_t stream_id,
|
||||
v8::Local<v8::Array> headers,
|
||||
uint32_t flags) {
|
||||
return application_->SubmitHeaders(stream_id, headers, flags);
|
||||
}
|
||||
|
||||
// Submits trailing headers only if the selected application
|
||||
// supports headers.
|
||||
bool QuicSession::SubmitTrailers(
|
||||
int64_t stream_id,
|
||||
v8::Local<v8::Array> headers) {
|
||||
return application_->SubmitTrailers(stream_id, headers);
|
||||
}
|
||||
|
||||
// Submits a new push stream
|
||||
BaseObjectPtr<QuicStream> QuicSession::SubmitPush(
|
||||
int64_t stream_id,
|
||||
v8::Local<v8::Array> headers) {
|
||||
return application_->SubmitPush(stream_id, headers);
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_SESSION_INL_H_
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,232 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_SOCKET_INL_H_
|
||||
#define SRC_QUIC_NODE_QUIC_SOCKET_INL_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "node_quic_socket.h"
|
||||
#include "node_sockaddr.h"
|
||||
#include "node_quic_session.h"
|
||||
#include "node_crypto.h"
|
||||
#include "debug_utils-inl.h"
|
||||
|
||||
namespace node {
|
||||
|
||||
using crypto::EntropySource;
|
||||
|
||||
namespace quic {
|
||||
|
||||
std::unique_ptr<QuicPacket> QuicPacket::Create(
|
||||
const char* diagnostic_label,
|
||||
size_t len) {
|
||||
return std::make_unique<QuicPacket>(diagnostic_label, len);
|
||||
}
|
||||
|
||||
std::unique_ptr<QuicPacket> QuicPacket::Copy(
|
||||
const std::unique_ptr<QuicPacket>& other) {
|
||||
return std::make_unique<QuicPacket>(*other.get());
|
||||
}
|
||||
|
||||
void QuicPacket::set_length(size_t len) {
|
||||
CHECK_LE(len, data_.size());
|
||||
data_.resize(len);
|
||||
}
|
||||
|
||||
int QuicEndpoint::Send(
|
||||
uv_buf_t* buf,
|
||||
size_t len,
|
||||
const sockaddr* addr) {
|
||||
int ret = static_cast<int>(udp_->Send(buf, len, addr));
|
||||
if (ret == 0)
|
||||
IncrementPendingCallbacks();
|
||||
return ret;
|
||||
}
|
||||
|
||||
int QuicEndpoint::ReceiveStart() {
|
||||
return udp_->RecvStart();
|
||||
}
|
||||
|
||||
int QuicEndpoint::ReceiveStop() {
|
||||
return udp_->RecvStop();
|
||||
}
|
||||
|
||||
void QuicEndpoint::WaitForPendingCallbacks() {
|
||||
if (!has_pending_callbacks()) {
|
||||
listener_->OnEndpointDone(this);
|
||||
return;
|
||||
}
|
||||
waiting_for_callbacks_ = true;
|
||||
}
|
||||
|
||||
void QuicSocket::AssociateCID(
|
||||
const QuicCID& cid,
|
||||
const QuicCID& scid) {
|
||||
if (cid && scid)
|
||||
dcid_to_scid_[cid] = scid;
|
||||
}
|
||||
|
||||
void QuicSocket::DisassociateCID(const QuicCID& cid) {
|
||||
if (cid) {
|
||||
Debug(this, "Removing association for cid %s", cid);
|
||||
dcid_to_scid_.erase(cid);
|
||||
}
|
||||
}
|
||||
|
||||
void QuicSocket::AssociateStatelessResetToken(
|
||||
const StatelessResetToken& token,
|
||||
BaseObjectPtr<QuicSession> session) {
|
||||
Debug(this, "Associating stateless reset token %s", token);
|
||||
token_map_[token] = session;
|
||||
}
|
||||
|
||||
const SocketAddress& QuicSocket::local_address() {
|
||||
CHECK(preferred_endpoint_);
|
||||
return preferred_endpoint_->local_address();
|
||||
}
|
||||
|
||||
void QuicSocket::DisassociateStatelessResetToken(
|
||||
const StatelessResetToken& token) {
|
||||
Debug(this, "Removing stateless reset token %s", token);
|
||||
token_map_.erase(token);
|
||||
}
|
||||
|
||||
// StopListening is called when the QuicSocket is no longer
|
||||
// accepting new server connections. Typically, this is called
|
||||
// when the QuicSocket enters a graceful closing state where
|
||||
// existing sessions are allowed to close naturally but new
|
||||
// sessions are rejected.
|
||||
void QuicSocket::StopListening() {
|
||||
if (is_flag_set(QUICSOCKET_FLAGS_SERVER_LISTENING)) {
|
||||
Debug(this, "Stop listening");
|
||||
set_flag(QUICSOCKET_FLAGS_SERVER_LISTENING, false);
|
||||
// It is important to not call ReceiveStop here as there
|
||||
// is ongoing traffic being exchanged by the peers.
|
||||
}
|
||||
}
|
||||
|
||||
void QuicSocket::ReceiveStart() {
|
||||
for (const auto& endpoint : endpoints_)
|
||||
CHECK_EQ(endpoint->ReceiveStart(), 0);
|
||||
}
|
||||
|
||||
void QuicSocket::ReceiveStop() {
|
||||
for (const auto& endpoint : endpoints_)
|
||||
CHECK_EQ(endpoint->ReceiveStop(), 0);
|
||||
}
|
||||
|
||||
void QuicSocket::RemoveSession(
|
||||
const QuicCID& cid,
|
||||
const SocketAddress& addr) {
|
||||
DecrementSocketAddressCounter(addr);
|
||||
sessions_.erase(cid);
|
||||
}
|
||||
|
||||
void QuicSocket::ReportSendError(int error) {
|
||||
listener_->OnError(error);
|
||||
}
|
||||
|
||||
void QuicSocket::IncrementStatelessResetCounter(const SocketAddress& addr) {
|
||||
reset_counts_[addr]++;
|
||||
}
|
||||
|
||||
void QuicSocket::IncrementSocketAddressCounter(const SocketAddress& addr) {
|
||||
addr_counts_[addr]++;
|
||||
}
|
||||
|
||||
void QuicSocket::DecrementSocketAddressCounter(const SocketAddress& addr) {
|
||||
auto it = addr_counts_.find(addr);
|
||||
if (it == std::end(addr_counts_))
|
||||
return;
|
||||
it->second--;
|
||||
// Remove the address if the counter reaches zero again.
|
||||
if (it->second == 0) {
|
||||
addr_counts_.erase(addr);
|
||||
reset_counts_.erase(addr);
|
||||
}
|
||||
}
|
||||
|
||||
size_t QuicSocket::GetCurrentSocketAddressCounter(const SocketAddress& addr) {
|
||||
auto it = addr_counts_.find(addr);
|
||||
return it == std::end(addr_counts_) ? 0 : it->second;
|
||||
}
|
||||
|
||||
size_t QuicSocket::GetCurrentStatelessResetCounter(const SocketAddress& addr) {
|
||||
auto it = reset_counts_.find(addr);
|
||||
return it == std::end(reset_counts_) ? 0 : it->second;
|
||||
}
|
||||
|
||||
void QuicSocket::set_server_busy(bool on) {
|
||||
Debug(this, "Turning Server Busy Response %s", on ? "on" : "off");
|
||||
set_flag(QUICSOCKET_FLAGS_SERVER_BUSY, on);
|
||||
listener_->OnServerBusy(on);
|
||||
}
|
||||
|
||||
bool QuicSocket::is_diagnostic_packet_loss(double prob) const {
|
||||
if (LIKELY(prob == 0.0)) return false;
|
||||
unsigned char c = 255;
|
||||
EntropySource(&c, 1);
|
||||
return (static_cast<double>(c) / 255) < prob;
|
||||
}
|
||||
|
||||
void QuicSocket::set_diagnostic_packet_loss(double rx, double tx) {
|
||||
rx_loss_ = rx;
|
||||
tx_loss_ = tx;
|
||||
}
|
||||
|
||||
bool QuicSocket::ToggleStatelessReset() {
|
||||
set_flag(
|
||||
QUICSOCKET_FLAGS_DISABLE_STATELESS_RESET,
|
||||
!is_flag_set(QUICSOCKET_FLAGS_DISABLE_STATELESS_RESET));
|
||||
return !is_flag_set(QUICSOCKET_FLAGS_DISABLE_STATELESS_RESET);
|
||||
}
|
||||
|
||||
void QuicSocket::set_validated_address(const SocketAddress& addr) {
|
||||
if (is_option_set(QUICSOCKET_OPTIONS_VALIDATE_ADDRESS_LRU)) {
|
||||
// Remove the oldest item if we've hit the LRU limit
|
||||
validated_addrs_.push_back(SocketAddress::Hash()(addr));
|
||||
if (validated_addrs_.size() > kMaxValidateAddressLru)
|
||||
validated_addrs_.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
bool QuicSocket::is_validated_address(const SocketAddress& addr) const {
|
||||
if (is_option_set(QUICSOCKET_OPTIONS_VALIDATE_ADDRESS_LRU)) {
|
||||
auto res = std::find(std::begin(validated_addrs_),
|
||||
std::end(validated_addrs_),
|
||||
SocketAddress::Hash()(addr));
|
||||
return res != std::end(validated_addrs_);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void QuicSocket::AddSession(
|
||||
const QuicCID& cid,
|
||||
BaseObjectPtr<QuicSession> session) {
|
||||
sessions_[cid] = session;
|
||||
IncrementSocketAddressCounter(session->remote_address());
|
||||
IncrementStat(
|
||||
session->is_server() ?
|
||||
&QuicSocketStats::server_sessions :
|
||||
&QuicSocketStats::client_sessions);
|
||||
}
|
||||
|
||||
void QuicSocket::AddEndpoint(
|
||||
BaseObjectPtr<QuicEndpoint> endpoint_,
|
||||
bool preferred) {
|
||||
Debug(this, "Adding %sendpoint", preferred ? "preferred " : "");
|
||||
if (preferred || endpoints_.empty())
|
||||
preferred_endpoint_ = endpoint_;
|
||||
endpoints_.emplace_back(endpoint_);
|
||||
if (is_flag_set(QUICSOCKET_FLAGS_SERVER_LISTENING))
|
||||
endpoint_->ReceiveStart();
|
||||
}
|
||||
|
||||
void QuicSocket::SessionReady(BaseObjectPtr<QuicSession> session) {
|
||||
listener_->OnSessionReady(session);
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_SOCKET_INL_H_
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,618 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_SOCKET_H_
|
||||
#define SRC_QUIC_NODE_QUIC_SOCKET_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "base_object.h"
|
||||
#include "node.h"
|
||||
#include "node_crypto.h"
|
||||
#include "node_internals.h"
|
||||
#include "ngtcp2/ngtcp2.h"
|
||||
#include "node_quic_state.h"
|
||||
#include "node_quic_session.h"
|
||||
#include "node_quic_util.h"
|
||||
#include "node_sockaddr.h"
|
||||
#include "env.h"
|
||||
#include "udp_wrap.h"
|
||||
#include "v8.h"
|
||||
#include "uv.h"
|
||||
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace node {
|
||||
|
||||
using v8::Context;
|
||||
using v8::FunctionCallbackInfo;
|
||||
using v8::Local;
|
||||
using v8::Object;
|
||||
using v8::Value;
|
||||
|
||||
namespace quic {
|
||||
|
||||
enum QuicSocketOptions : uint32_t {
|
||||
// When enabled the QuicSocket will validate the address
|
||||
// using a RETRY packet to the peer.
|
||||
QUICSOCKET_OPTIONS_VALIDATE_ADDRESS = 0x1,
|
||||
|
||||
// When enabled, and the VALIDATE_ADDRESS option is also
|
||||
// set, the QuicSocket will use an LRU cache to track
|
||||
// validated addresses. Address validation will be skipped
|
||||
// if the address is currently in the cache.
|
||||
QUICSOCKET_OPTIONS_VALIDATE_ADDRESS_LRU = 0x2,
|
||||
};
|
||||
|
||||
#define SOCKET_STATS(V) \
|
||||
V(CREATED_AT, created_at, "Created At") \
|
||||
V(BOUND_AT, bound_at, "Bound At") \
|
||||
V(LISTEN_AT, listen_at, "Listen At") \
|
||||
V(BYTES_RECEIVED, bytes_received, "Bytes Received") \
|
||||
V(BYTES_SENT, bytes_sent, "Bytes Sent") \
|
||||
V(PACKETS_RECEIVED, packets_received, "Packets Received") \
|
||||
V(PACKETS_IGNORED, packets_ignored, "Packets Ignored") \
|
||||
V(PACKETS_SENT, packets_sent, "Packets Sent") \
|
||||
V(SERVER_SESSIONS, server_sessions, "Server Sessions") \
|
||||
V(CLIENT_SESSIONS, client_sessions, "Client Sessions") \
|
||||
V(STATELESS_RESET_COUNT, stateless_reset_count, "Stateless Reset Count") \
|
||||
V(SERVER_BUSY_COUNT, server_busy_count, "Server Busy Count")
|
||||
|
||||
#define V(name, _, __) IDX_QUIC_SOCKET_STATS_##name,
|
||||
enum QuicSocketStatsIdx : int {
|
||||
SOCKET_STATS(V)
|
||||
IDX_QUIC_SOCKET_STATS_COUNT
|
||||
};
|
||||
#undef V
|
||||
|
||||
#define V(_, name, __) uint64_t name;
|
||||
struct QuicSocketStats {
|
||||
SOCKET_STATS(V)
|
||||
};
|
||||
#undef V
|
||||
|
||||
struct QuicSocketStatsTraits {
|
||||
using Stats = QuicSocketStats;
|
||||
using Base = QuicSocket;
|
||||
|
||||
template <typename Fn>
|
||||
static void ToString(const Base& ptr, Fn&& add_field);
|
||||
};
|
||||
|
||||
class QuicSocket;
|
||||
class QuicEndpoint;
|
||||
|
||||
// This is the generic interface for objects that control QuicSocket
|
||||
// instances. The default `JSQuicSocketListener` emits events to
|
||||
// JavaScript
|
||||
class QuicSocketListener {
|
||||
public:
|
||||
virtual ~QuicSocketListener();
|
||||
|
||||
virtual void OnError(ssize_t code);
|
||||
virtual void OnSessionReady(BaseObjectPtr<QuicSession> session);
|
||||
virtual void OnServerBusy(bool busy);
|
||||
virtual void OnEndpointDone(QuicEndpoint* endpoint);
|
||||
virtual void OnDestroy();
|
||||
|
||||
QuicSocket* socket() { return socket_.get(); }
|
||||
|
||||
private:
|
||||
BaseObjectWeakPtr<QuicSocket> socket_;
|
||||
QuicSocketListener* previous_listener_ = nullptr;
|
||||
friend class QuicSocket;
|
||||
};
|
||||
|
||||
class JSQuicSocketListener : public QuicSocketListener {
|
||||
public:
|
||||
void OnError(ssize_t code) override;
|
||||
void OnSessionReady(BaseObjectPtr<QuicSession> session) override;
|
||||
void OnServerBusy(bool busy) override;
|
||||
void OnEndpointDone(QuicEndpoint* endpoint) override;
|
||||
void OnDestroy() override;
|
||||
};
|
||||
|
||||
// A serialized QuicPacket to be sent by a QuicSocket instance.
|
||||
class QuicPacket : public MemoryRetainer {
|
||||
public:
|
||||
// Creates a new QuicPacket. By default the packet will be
|
||||
// stack allocated with a max size of NGTCP2_MAX_PKTLEN_IPV4.
|
||||
// If a larger packet size is specified, it will be heap
|
||||
// allocated. Generally speaking, a QUIC packet should never
|
||||
// be larger than the current MTU to avoid IP fragmentation.
|
||||
//
|
||||
// The content of a QuicPacket is provided by ngtcp2. The
|
||||
// typical use pattern is to create a QuicPacket instance
|
||||
// and then pass a pointer to it's internal buffer and max
|
||||
// size in to an ngtcp2 function that serializes the data.
|
||||
// ngtcp2 will fill the buffer as much as possible then return
|
||||
// the number of bytes serialized. User code is then responsible
|
||||
// for calling set_length() to set the final length of the
|
||||
// QuicPacket prior to sending it off to the QuicSocket.
|
||||
//
|
||||
// The diagnostic label is used in NODE_DEBUG_NATIVE output
|
||||
// to differentiate send operations. This should always be
|
||||
// a statically allocated string or nullptr (in which case
|
||||
// the value "unspecified" is used in the debug output).
|
||||
//
|
||||
// Instances of std::unique_ptr<QuicPacket> are moved through
|
||||
// QuicSocket and ultimately become the responsibility of the
|
||||
// SendWrap instance. When the SendWrap is cleaned up, the
|
||||
// QuicPacket instance will be freed.
|
||||
static inline std::unique_ptr<QuicPacket> Create(
|
||||
const char* diagnostic_label = nullptr,
|
||||
size_t len = NGTCP2_MAX_PKTLEN_IPV4);
|
||||
|
||||
// Copy the data of the QuicPacket to a new one. Currently,
|
||||
// this is only used when retransmitting close connection
|
||||
// packets from a QuicServer.
|
||||
static inline std::unique_ptr<QuicPacket> Copy(
|
||||
const std::unique_ptr<QuicPacket>& other);
|
||||
|
||||
QuicPacket(const char* diagnostic_label, size_t len);
|
||||
QuicPacket(const QuicPacket& other);
|
||||
uint8_t* data() { return data_.data(); }
|
||||
size_t length() const { return data_.size(); }
|
||||
uv_buf_t buf() const {
|
||||
return uv_buf_init(
|
||||
const_cast<char*>(reinterpret_cast<const char*>(data_.data())),
|
||||
length());
|
||||
}
|
||||
inline void set_length(size_t len);
|
||||
const char* diagnostic_label() const;
|
||||
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
SET_MEMORY_INFO_NAME(QuicPacket);
|
||||
SET_SELF_SIZE(QuicPacket);
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> data_;
|
||||
const char* diagnostic_label_ = nullptr;
|
||||
};
|
||||
|
||||
// QuicEndpointListener listens to events generated by a QuicEndpoint.
|
||||
class QuicEndpointListener {
|
||||
public:
|
||||
virtual void OnError(QuicEndpoint* endpoint, ssize_t error) = 0;
|
||||
virtual void OnReceive(
|
||||
ssize_t nread,
|
||||
AllocatedBuffer buf,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr,
|
||||
unsigned int flags) = 0;
|
||||
virtual ReqWrap<uv_udp_send_t>* OnCreateSendWrap(size_t msg_size) = 0;
|
||||
virtual void OnSendDone(ReqWrap<uv_udp_send_t>* wrap, int status) = 0;
|
||||
virtual void OnBind(QuicEndpoint* endpoint) = 0;
|
||||
virtual void OnEndpointDone(QuicEndpoint* endpoint) = 0;
|
||||
};
|
||||
|
||||
// A QuicEndpoint wraps a UDPBaseWrap. A single QuicSocket may
|
||||
// have multiple QuicEndpoints, the lifecycles of which are
|
||||
// attached to the QuicSocket.
|
||||
class QuicEndpoint : public BaseObject,
|
||||
public UDPListener {
|
||||
public:
|
||||
static void Initialize(
|
||||
Environment* env,
|
||||
Local<Object> target,
|
||||
Local<Context> context);
|
||||
|
||||
QuicEndpoint(
|
||||
QuicState* quic_state,
|
||||
Local<Object> wrap,
|
||||
QuicSocket* listener,
|
||||
Local<Object> udp_wrap);
|
||||
|
||||
const SocketAddress& local_address() const {
|
||||
local_address_ = udp_->GetSockName();
|
||||
return local_address_;
|
||||
}
|
||||
|
||||
// Implementation for UDPListener
|
||||
uv_buf_t OnAlloc(size_t suggested_size) override;
|
||||
|
||||
void OnRecv(ssize_t nread,
|
||||
const uv_buf_t& buf,
|
||||
const sockaddr* addr,
|
||||
unsigned int flags) override;
|
||||
|
||||
ReqWrap<uv_udp_send_t>* CreateSendWrap(size_t msg_size) override;
|
||||
|
||||
void OnSendDone(ReqWrap<uv_udp_send_t>* wrap, int status) override;
|
||||
|
||||
void OnAfterBind() override;
|
||||
|
||||
inline int ReceiveStart();
|
||||
|
||||
inline int ReceiveStop();
|
||||
|
||||
inline int Send(
|
||||
uv_buf_t* buf,
|
||||
size_t len,
|
||||
const sockaddr* addr);
|
||||
|
||||
void IncrementPendingCallbacks() { pending_callbacks_++; }
|
||||
void DecrementPendingCallbacks() { pending_callbacks_--; }
|
||||
bool has_pending_callbacks() { return pending_callbacks_ > 0; }
|
||||
inline void WaitForPendingCallbacks();
|
||||
|
||||
QuicState* quic_state() const { return quic_state_.get(); }
|
||||
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
SET_MEMORY_INFO_NAME(QuicEndpoint)
|
||||
SET_SELF_SIZE(QuicEndpoint)
|
||||
|
||||
private:
|
||||
mutable SocketAddress local_address_;
|
||||
BaseObjectWeakPtr<QuicSocket> listener_;
|
||||
UDPWrapBase* udp_;
|
||||
BaseObjectPtr<AsyncWrap> strong_ptr_;
|
||||
size_t pending_callbacks_ = 0;
|
||||
bool waiting_for_callbacks_ = false;
|
||||
BaseObjectPtr<QuicState> quic_state_;
|
||||
};
|
||||
|
||||
// QuicSocket manages the flow of data from the UDP socket to the
|
||||
// QuicSession. It is responsible for managing the lifecycle of the
|
||||
// UDP sockets, listening for new server QuicSession instances, and
|
||||
// passing data two and from the remote peer.
|
||||
class QuicSocket : public AsyncWrap,
|
||||
public QuicEndpointListener,
|
||||
public mem::NgLibMemoryManager<QuicSocket, ngtcp2_mem>,
|
||||
public StatsBase<QuicSocketStatsTraits> {
|
||||
public:
|
||||
static void Initialize(
|
||||
Environment* env,
|
||||
Local<Object> target,
|
||||
Local<Context> context);
|
||||
|
||||
QuicSocket(
|
||||
QuicState* quic_state,
|
||||
Local<Object> wrap,
|
||||
// A retry token should only be valid for a small window of time.
|
||||
// The retry_token_expiration specifies the number of seconds a
|
||||
// retry token is permitted to be valid.
|
||||
uint64_t retry_token_expiration,
|
||||
// To prevent malicious clients from opening too many concurrent
|
||||
// connections, we limit the maximum number per remote sockaddr.
|
||||
size_t max_connections,
|
||||
size_t max_connections_per_host,
|
||||
size_t max_stateless_resets_per_host
|
||||
= DEFAULT_MAX_STATELESS_RESETS_PER_HOST,
|
||||
uint32_t options = 0,
|
||||
QlogMode qlog = QlogMode::kDisabled,
|
||||
const uint8_t* session_reset_secret = nullptr,
|
||||
bool disable_session_reset = false);
|
||||
|
||||
~QuicSocket() override;
|
||||
|
||||
// Returns the default/preferred local address. Additional
|
||||
// QuicEndpoint instances may be associated with the
|
||||
// QuicSocket bound to other local addresses.
|
||||
inline const SocketAddress& local_address();
|
||||
|
||||
void MaybeClose();
|
||||
|
||||
inline void AddSession(
|
||||
const QuicCID& cid,
|
||||
BaseObjectPtr<QuicSession> session);
|
||||
|
||||
inline void AssociateCID(
|
||||
const QuicCID& cid,
|
||||
const QuicCID& scid);
|
||||
|
||||
inline void DisassociateCID(
|
||||
const QuicCID& cid);
|
||||
|
||||
inline void AssociateStatelessResetToken(
|
||||
const StatelessResetToken& token,
|
||||
BaseObjectPtr<QuicSession> session);
|
||||
|
||||
inline void DisassociateStatelessResetToken(
|
||||
const StatelessResetToken& token);
|
||||
|
||||
void Listen(
|
||||
BaseObjectPtr<crypto::SecureContext> context,
|
||||
const sockaddr* preferred_address = nullptr,
|
||||
const std::string& alpn = NGTCP2_ALPN_H3,
|
||||
uint32_t options = 0);
|
||||
|
||||
inline void ReceiveStart();
|
||||
|
||||
inline void ReceiveStop();
|
||||
|
||||
inline void RemoveSession(
|
||||
const QuicCID& cid,
|
||||
const SocketAddress& addr);
|
||||
|
||||
inline void ReportSendError(int error);
|
||||
|
||||
int SendPacket(
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr,
|
||||
std::unique_ptr<QuicPacket> packet,
|
||||
BaseObjectPtr<QuicSession> session = BaseObjectPtr<QuicSession>());
|
||||
|
||||
inline void SessionReady(BaseObjectPtr<QuicSession> session);
|
||||
|
||||
inline void set_server_busy(bool on);
|
||||
|
||||
inline void set_diagnostic_packet_loss(double rx = 0.0, double tx = 0.0);
|
||||
|
||||
inline void StopListening();
|
||||
|
||||
// Toggles whether or not stateless reset is enabled or not.
|
||||
// Returns true if stateless reset is enabled, false if it
|
||||
// is not.
|
||||
inline bool ToggleStatelessReset();
|
||||
|
||||
BaseObjectPtr<crypto::SecureContext> server_secure_context() const {
|
||||
return server_secure_context_;
|
||||
}
|
||||
|
||||
QuicState* quic_state() { return quic_state_.get(); }
|
||||
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
SET_MEMORY_INFO_NAME(QuicSocket)
|
||||
SET_SELF_SIZE(QuicSocket)
|
||||
|
||||
// Implementation for mem::NgLibMemoryManager
|
||||
void CheckAllocatedSize(size_t previous_size) const;
|
||||
|
||||
void IncreaseAllocatedSize(size_t size);
|
||||
|
||||
void DecreaseAllocatedSize(size_t size);
|
||||
|
||||
const uint8_t* session_reset_secret() { return reset_token_secret_; }
|
||||
|
||||
// Implementation for QuicListener
|
||||
ReqWrap<uv_udp_send_t>* OnCreateSendWrap(size_t msg_size) override;
|
||||
|
||||
// Implementation for QuicListener
|
||||
void OnSendDone(ReqWrap<uv_udp_send_t>* wrap, int status) override;
|
||||
|
||||
// Implementation for QuicListener
|
||||
void OnBind(QuicEndpoint* endpoint) override;
|
||||
|
||||
// Implementation for QuicListener
|
||||
void OnReceive(
|
||||
ssize_t nread,
|
||||
AllocatedBuffer buf,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr,
|
||||
unsigned int flags) override;
|
||||
|
||||
// Implementation for QuicListener
|
||||
void OnError(QuicEndpoint* endpoint, ssize_t error) override;
|
||||
|
||||
// Implementation for QuicListener
|
||||
void OnEndpointDone(QuicEndpoint* endpoint) override;
|
||||
|
||||
// Serializes and transmits a RETRY packet to the connected peer.
|
||||
bool SendRetry(
|
||||
const QuicCID& dcid,
|
||||
const QuicCID& scid,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr);
|
||||
|
||||
// Serializes and transmits a Stateless Reset to the connected peer.
|
||||
bool SendStatelessReset(
|
||||
const QuicCID& cid,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr,
|
||||
size_t source_len);
|
||||
|
||||
// Serializes and transmits a Version Negotiation packet to the
|
||||
// connected peer.
|
||||
void SendVersionNegotiation(
|
||||
uint32_t version,
|
||||
const QuicCID& dcid,
|
||||
const QuicCID& scid,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr);
|
||||
|
||||
void PushListener(QuicSocketListener* listener);
|
||||
|
||||
void RemoveListener(QuicSocketListener* listener);
|
||||
|
||||
inline void AddEndpoint(
|
||||
BaseObjectPtr<QuicEndpoint> endpoint,
|
||||
bool preferred = false);
|
||||
|
||||
void ImmediateConnectionClose(
|
||||
const QuicCID& scid,
|
||||
const QuicCID& dcid,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr,
|
||||
int64_t reason = NGTCP2_INVALID_TOKEN);
|
||||
|
||||
private:
|
||||
static void OnAlloc(
|
||||
uv_handle_t* handle,
|
||||
size_t suggested_size,
|
||||
uv_buf_t* buf);
|
||||
|
||||
void OnSend(int status, QuicPacket* packet);
|
||||
|
||||
inline void set_validated_address(const SocketAddress& addr);
|
||||
|
||||
inline bool is_validated_address(const SocketAddress& addr) const;
|
||||
|
||||
bool MaybeStatelessReset(
|
||||
const QuicCID& dcid,
|
||||
const QuicCID& scid,
|
||||
ssize_t nread,
|
||||
const uint8_t* data,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr,
|
||||
unsigned int flags);
|
||||
|
||||
BaseObjectPtr<QuicSession> AcceptInitialPacket(
|
||||
uint32_t version,
|
||||
const QuicCID& dcid,
|
||||
const QuicCID& scid,
|
||||
ssize_t nread,
|
||||
const uint8_t* data,
|
||||
const SocketAddress& local_addr,
|
||||
const SocketAddress& remote_addr,
|
||||
unsigned int flags);
|
||||
|
||||
BaseObjectPtr<QuicSession> FindSession(const QuicCID& cid);
|
||||
|
||||
inline void IncrementSocketAddressCounter(const SocketAddress& addr);
|
||||
|
||||
inline void DecrementSocketAddressCounter(const SocketAddress& addr);
|
||||
|
||||
inline void IncrementStatelessResetCounter(const SocketAddress& addr);
|
||||
|
||||
inline size_t GetCurrentSocketAddressCounter(const SocketAddress& addr);
|
||||
|
||||
inline size_t GetCurrentStatelessResetCounter(const SocketAddress& addr);
|
||||
|
||||
// Returns true if, and only if, diagnostic packet loss is enabled
|
||||
// and the current packet should be artificially considered lost.
|
||||
inline bool is_diagnostic_packet_loss(double prob) const;
|
||||
|
||||
bool is_stateless_reset_disabled() {
|
||||
return is_flag_set(QUICSOCKET_FLAGS_DISABLE_STATELESS_RESET);
|
||||
}
|
||||
|
||||
enum QuicSocketFlags : uint32_t {
|
||||
QUICSOCKET_FLAGS_NONE = 0x0,
|
||||
|
||||
// Indicates that the QuicSocket has entered a graceful
|
||||
// closing phase, indicating that no additional
|
||||
QUICSOCKET_FLAGS_GRACEFUL_CLOSE = 0x1,
|
||||
QUICSOCKET_FLAGS_WAITING_FOR_CALLBACKS = 0x2,
|
||||
QUICSOCKET_FLAGS_SERVER_LISTENING = 0x4,
|
||||
QUICSOCKET_FLAGS_SERVER_BUSY = 0x8,
|
||||
QUICSOCKET_FLAGS_DISABLE_STATELESS_RESET = 0x10
|
||||
};
|
||||
|
||||
void set_flag(QuicSocketFlags flag, bool on = true) {
|
||||
if (on)
|
||||
flags_ |= flag;
|
||||
else
|
||||
flags_ &= ~flag;
|
||||
}
|
||||
|
||||
bool is_flag_set(QuicSocketFlags flag) const {
|
||||
return flags_ & flag;
|
||||
}
|
||||
|
||||
void set_option(QuicSocketOptions option, bool on = true) {
|
||||
if (on)
|
||||
options_ |= option;
|
||||
else
|
||||
options_ &= ~option;
|
||||
}
|
||||
|
||||
bool is_option_set(QuicSocketOptions option) const {
|
||||
return options_ & option;
|
||||
}
|
||||
|
||||
ngtcp2_mem alloc_info_;
|
||||
|
||||
std::vector<BaseObjectPtr<QuicEndpoint>> endpoints_;
|
||||
SocketAddress::Map<BaseObjectWeakPtr<QuicEndpoint>> bound_endpoints_;
|
||||
BaseObjectWeakPtr<QuicEndpoint> preferred_endpoint_;
|
||||
|
||||
uint32_t flags_ = QUICSOCKET_FLAGS_NONE;
|
||||
uint32_t options_;
|
||||
uint32_t server_options_;
|
||||
|
||||
size_t max_connections_ = DEFAULT_MAX_CONNECTIONS;
|
||||
size_t max_connections_per_host_ = DEFAULT_MAX_CONNECTIONS_PER_HOST;
|
||||
size_t current_ngtcp2_memory_ = 0;
|
||||
size_t max_stateless_resets_per_host_ = DEFAULT_MAX_STATELESS_RESETS_PER_HOST;
|
||||
|
||||
uint64_t retry_token_expiration_;
|
||||
|
||||
// Used to specify diagnostic packet loss probabilities
|
||||
double rx_loss_ = 0.0;
|
||||
double tx_loss_ = 0.0;
|
||||
|
||||
QuicSocketListener* listener_;
|
||||
JSQuicSocketListener default_listener_;
|
||||
QuicSessionConfig server_session_config_;
|
||||
QlogMode qlog_ = QlogMode::kDisabled;
|
||||
BaseObjectPtr<crypto::SecureContext> server_secure_context_;
|
||||
std::string server_alpn_;
|
||||
QuicCID::Map<BaseObjectPtr<QuicSession>> sessions_;
|
||||
QuicCID::Map<QuicCID> dcid_to_scid_;
|
||||
|
||||
uint8_t token_secret_[kTokenSecretLen];
|
||||
uint8_t reset_token_secret_[NGTCP2_STATELESS_RESET_TOKENLEN];
|
||||
|
||||
// Counts the number of active connections per remote
|
||||
// address. A custom std::hash specialization for
|
||||
// sockaddr instances is used. Values are incremented
|
||||
// when a QuicSession is added to the socket, and
|
||||
// decremented when the QuicSession is removed. If the
|
||||
// value reaches the value of max_connections_per_host_,
|
||||
// attempts to create new connections will be ignored
|
||||
// until the value falls back below the limit.
|
||||
SocketAddress::Map<size_t> addr_counts_;
|
||||
|
||||
// Counts the number of stateless resets sent per
|
||||
// remote address.
|
||||
// TODO(@jasnell): this counter persists through the
|
||||
// lifetime of the QuicSocket, and therefore can become
|
||||
// a possible risk. Specifically, a malicious peer could
|
||||
// attempt the local peer to count an increasingly large
|
||||
// number of remote addresses. Need to mitigate the
|
||||
// potential risk.
|
||||
SocketAddress::Map<size_t> reset_counts_;
|
||||
|
||||
// Counts the number of retry attempts sent per
|
||||
// remote address.
|
||||
|
||||
StatelessResetToken::Map<QuicSession> token_map_;
|
||||
|
||||
// The validated_addrs_ vector is used as an LRU cache for
|
||||
// validated addresses only when the VALIDATE_ADDRESS_LRU
|
||||
// option is set.
|
||||
typedef size_t SocketAddressHash;
|
||||
std::deque<SocketAddressHash> validated_addrs_;
|
||||
|
||||
class SendWrap : public ReqWrap<uv_udp_send_t> {
|
||||
public:
|
||||
SendWrap(QuicState* quic_state,
|
||||
v8::Local<v8::Object> req_wrap_obj,
|
||||
size_t total_length_);
|
||||
|
||||
void set_packet(std::unique_ptr<QuicPacket> packet) {
|
||||
packet_ = std::move(packet);
|
||||
}
|
||||
|
||||
QuicPacket* packet() { return packet_.get(); }
|
||||
|
||||
void set_session(BaseObjectPtr<QuicSession> session) { session_ = session; }
|
||||
|
||||
size_t total_length() const { return total_length_; }
|
||||
|
||||
QuicState* quic_state() { return quic_state_.get(); }
|
||||
|
||||
SET_SELF_SIZE(SendWrap);
|
||||
std::string MemoryInfoName() const override;
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
|
||||
private:
|
||||
BaseObjectPtr<QuicSession> session_;
|
||||
std::unique_ptr<QuicPacket> packet_;
|
||||
size_t total_length_;
|
||||
BaseObjectPtr<QuicState> quic_state_;
|
||||
};
|
||||
|
||||
SendWrap* last_created_send_wrap_ = nullptr;
|
||||
BaseObjectPtr<QuicState> quic_state_;
|
||||
|
||||
friend class QuicSocketListener;
|
||||
};
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_SOCKET_H_
|
||||
@@ -0,0 +1,81 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_STATE_H_
|
||||
#define SRC_QUIC_NODE_QUIC_STATE_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "aliased_buffer.h"
|
||||
|
||||
namespace node {
|
||||
namespace quic {
|
||||
|
||||
enum QuicSessionConfigIndex : int {
|
||||
IDX_QUIC_SESSION_ACTIVE_CONNECTION_ID_LIMIT,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_LOCAL,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_REMOTE,
|
||||
IDX_QUIC_SESSION_MAX_STREAM_DATA_UNI,
|
||||
IDX_QUIC_SESSION_MAX_DATA,
|
||||
IDX_QUIC_SESSION_MAX_STREAMS_BIDI,
|
||||
IDX_QUIC_SESSION_MAX_STREAMS_UNI,
|
||||
IDX_QUIC_SESSION_MAX_IDLE_TIMEOUT,
|
||||
IDX_QUIC_SESSION_MAX_PACKET_SIZE,
|
||||
IDX_QUIC_SESSION_ACK_DELAY_EXPONENT,
|
||||
IDX_QUIC_SESSION_DISABLE_MIGRATION,
|
||||
IDX_QUIC_SESSION_MAX_ACK_DELAY,
|
||||
IDX_QUIC_SESSION_CONFIG_COUNT
|
||||
};
|
||||
|
||||
enum Http3ConfigIndex : int {
|
||||
IDX_HTTP3_QPACK_MAX_TABLE_CAPACITY,
|
||||
IDX_HTTP3_QPACK_BLOCKED_STREAMS,
|
||||
IDX_HTTP3_MAX_HEADER_LIST_SIZE,
|
||||
IDX_HTTP3_MAX_PUSHES,
|
||||
IDX_HTTP3_MAX_HEADER_PAIRS,
|
||||
IDX_HTTP3_MAX_HEADER_LENGTH,
|
||||
IDX_HTTP3_CONFIG_COUNT
|
||||
};
|
||||
|
||||
class QuicState : public BaseObject {
|
||||
public:
|
||||
explicit QuicState(Environment* env, v8::Local<v8::Object> obj)
|
||||
: BaseObject(env, obj),
|
||||
root_buffer(
|
||||
env->isolate(),
|
||||
sizeof(quic_state_internal)),
|
||||
quicsessionconfig_buffer(
|
||||
env->isolate(),
|
||||
offsetof(quic_state_internal, quicsessionconfig_buffer),
|
||||
IDX_QUIC_SESSION_CONFIG_COUNT + 1,
|
||||
root_buffer),
|
||||
http3config_buffer(
|
||||
env->isolate(),
|
||||
offsetof(quic_state_internal, http3config_buffer),
|
||||
IDX_HTTP3_CONFIG_COUNT + 1,
|
||||
root_buffer) {
|
||||
}
|
||||
|
||||
AliasedUint8Array root_buffer;
|
||||
AliasedFloat64Array quicsessionconfig_buffer;
|
||||
AliasedFloat64Array http3config_buffer;
|
||||
|
||||
bool warn_trace_tls = true;
|
||||
|
||||
static constexpr FastStringKey binding_data_name { "quic" };
|
||||
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
SET_SELF_SIZE(QuicState)
|
||||
SET_MEMORY_INFO_NAME(QuicState)
|
||||
|
||||
private:
|
||||
struct quic_state_internal {
|
||||
// doubles first so that they are always sizeof(double)-aligned
|
||||
double quicsessionconfig_buffer[IDX_QUIC_SESSION_CONFIG_COUNT + 1];
|
||||
double http3config_buffer[IDX_HTTP3_CONFIG_COUNT + 1];
|
||||
};
|
||||
};
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_STATE_H_
|
||||
@@ -0,0 +1,158 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_STREAM_INL_H_
|
||||
#define SRC_QUIC_NODE_QUIC_STREAM_INL_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "debug_utils-inl.h"
|
||||
#include "node_quic_session.h"
|
||||
#include "node_quic_stream.h"
|
||||
#include "node_quic_buffer-inl.h"
|
||||
|
||||
namespace node {
|
||||
namespace quic {
|
||||
|
||||
QuicStreamDirection QuicStream::direction() const {
|
||||
return stream_id_ & 0b10 ?
|
||||
QUIC_STREAM_UNIDIRECTIONAL :
|
||||
QUIC_STREAM_BIRECTIONAL;
|
||||
}
|
||||
|
||||
QuicStreamOrigin QuicStream::origin() const {
|
||||
return stream_id_ & 0b01 ?
|
||||
QUIC_STREAM_SERVER :
|
||||
QUIC_STREAM_CLIENT;
|
||||
}
|
||||
|
||||
bool QuicStream::is_flag_set(int32_t flag) const {
|
||||
return flags_ & (1 << flag);
|
||||
}
|
||||
|
||||
void QuicStream::set_flag(int32_t flag, bool on) {
|
||||
if (on)
|
||||
flags_ |= (1 << flag);
|
||||
else
|
||||
flags_ &= ~(1 << flag);
|
||||
}
|
||||
|
||||
void QuicStream::set_final_size(uint64_t final_size) {
|
||||
CHECK_EQ(GetStat(&QuicStreamStats::final_size), 0);
|
||||
SetStat(&QuicStreamStats::final_size, final_size);
|
||||
}
|
||||
|
||||
bool QuicStream::is_destroyed() const {
|
||||
return is_flag_set(QUICSTREAM_FLAG_DESTROYED);
|
||||
}
|
||||
|
||||
bool QuicStream::was_ever_writable() const {
|
||||
if (direction() == QUIC_STREAM_UNIDIRECTIONAL) {
|
||||
return session_->is_server() ?
|
||||
origin() == QUIC_STREAM_SERVER :
|
||||
origin() == QUIC_STREAM_CLIENT;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool QuicStream::is_writable() const {
|
||||
return was_ever_writable() && !streambuf_.is_ended();
|
||||
}
|
||||
|
||||
bool QuicStream::was_ever_readable() const {
|
||||
if (direction() == QUIC_STREAM_UNIDIRECTIONAL) {
|
||||
return session_->is_server() ?
|
||||
origin() == QUIC_STREAM_CLIENT :
|
||||
origin() == QUIC_STREAM_SERVER;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool QuicStream::is_readable() const {
|
||||
return was_ever_readable() && !is_flag_set(QUICSTREAM_FLAG_READ_CLOSED);
|
||||
}
|
||||
|
||||
void QuicStream::set_fin_sent() {
|
||||
CHECK(!is_writable());
|
||||
set_flag(QUICSTREAM_FLAG_FIN_SENT);
|
||||
}
|
||||
|
||||
bool QuicStream::is_write_finished() const {
|
||||
return is_flag_set(QUICSTREAM_FLAG_FIN_SENT) &&
|
||||
streambuf_.length() == 0;
|
||||
}
|
||||
|
||||
bool QuicStream::SubmitInformation(v8::Local<v8::Array> headers) {
|
||||
return session_->SubmitInformation(stream_id_, headers);
|
||||
}
|
||||
|
||||
bool QuicStream::SubmitHeaders(v8::Local<v8::Array> headers, uint32_t flags) {
|
||||
return session_->SubmitHeaders(stream_id_, headers, flags);
|
||||
}
|
||||
|
||||
bool QuicStream::SubmitTrailers(v8::Local<v8::Array> headers) {
|
||||
return session_->SubmitTrailers(stream_id_, headers);
|
||||
}
|
||||
|
||||
BaseObjectPtr<QuicStream> QuicStream::SubmitPush(
|
||||
v8::Local<v8::Array> headers) {
|
||||
return session_->SubmitPush(stream_id_, headers);
|
||||
}
|
||||
|
||||
void QuicStream::EndHeaders(int64_t push_id) {
|
||||
Debug(this, "End Headers");
|
||||
// Upon completion of a block of headers, convert the
|
||||
// vector of Header objects into an array of name+value
|
||||
// pairs, then call the on_stream_headers function.
|
||||
session()->application()->StreamHeaders(
|
||||
stream_id_,
|
||||
headers_kind_,
|
||||
headers_,
|
||||
push_id);
|
||||
headers_.clear();
|
||||
}
|
||||
|
||||
void QuicStream::set_headers_kind(QuicStreamHeadersKind kind) {
|
||||
headers_kind_ = kind;
|
||||
}
|
||||
|
||||
void QuicStream::BeginHeaders(QuicStreamHeadersKind kind) {
|
||||
Debug(this, "Beginning Headers");
|
||||
// Upon start of a new block of headers, ensure that any
|
||||
// previously collected ones are cleaned up.
|
||||
headers_.clear();
|
||||
set_headers_kind(kind);
|
||||
}
|
||||
|
||||
void QuicStream::Commit(size_t amount) {
|
||||
CHECK(!is_destroyed());
|
||||
streambuf_.Seek(amount);
|
||||
}
|
||||
|
||||
void QuicStream::ResetStream(uint64_t app_error_code) {
|
||||
// On calling shutdown, the stream will no longer be
|
||||
// readable or writable, all any pending data in the
|
||||
// streambuf_ will be canceled, and all data pending
|
||||
// to be acknowledged at the ngtcp2 level will be
|
||||
// abandoned.
|
||||
BaseObjectPtr<QuicSession> ptr(session_);
|
||||
set_flag(QUICSTREAM_FLAG_READ_CLOSED);
|
||||
session_->ResetStream(stream_id_, app_error_code);
|
||||
streambuf_.Cancel();
|
||||
streambuf_.End();
|
||||
}
|
||||
|
||||
void QuicStream::Schedule(Queue* queue) {
|
||||
if (!stream_queue_.IsEmpty()) // Already scheduled?
|
||||
return;
|
||||
queue->PushBack(this);
|
||||
}
|
||||
|
||||
void QuicStream::Unschedule() {
|
||||
stream_queue_.Remove();
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_STREAM_INL_H_
|
||||
@@ -0,0 +1,513 @@
|
||||
#include "node_quic_stream-inl.h" // NOLINT(build/include)
|
||||
#include "async_wrap-inl.h"
|
||||
#include "debug_utils-inl.h"
|
||||
#include "env-inl.h"
|
||||
#include "node.h"
|
||||
#include "node_buffer.h"
|
||||
#include "node_internals.h"
|
||||
#include "stream_base-inl.h"
|
||||
#include "node_sockaddr-inl.h"
|
||||
#include "node_http_common-inl.h"
|
||||
#include "node_quic_session-inl.h"
|
||||
#include "node_quic_socket-inl.h"
|
||||
#include "node_quic_util-inl.h"
|
||||
#include "v8.h"
|
||||
#include "uv.h"
|
||||
|
||||
#include <array>
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
|
||||
namespace node {
|
||||
|
||||
using v8::Array;
|
||||
using v8::Context;
|
||||
using v8::FunctionCallbackInfo;
|
||||
using v8::FunctionTemplate;
|
||||
using v8::Isolate;
|
||||
using v8::Local;
|
||||
using v8::Object;
|
||||
using v8::ObjectTemplate;
|
||||
using v8::String;
|
||||
using v8::Value;
|
||||
|
||||
namespace quic {
|
||||
|
||||
QuicStream::QuicStream(
|
||||
QuicSession* sess,
|
||||
Local<Object> wrap,
|
||||
int64_t stream_id,
|
||||
int64_t push_id)
|
||||
: AsyncWrap(sess->env(), wrap, AsyncWrap::PROVIDER_QUICSTREAM),
|
||||
StreamBase(sess->env()),
|
||||
StatsBase(sess->env(), wrap,
|
||||
HistogramOptions::ACK |
|
||||
HistogramOptions::RATE |
|
||||
HistogramOptions::SIZE),
|
||||
session_(sess),
|
||||
stream_id_(stream_id),
|
||||
push_id_(push_id),
|
||||
quic_state_(sess->quic_state()) {
|
||||
CHECK_NOT_NULL(sess);
|
||||
Debug(this, "Created");
|
||||
StreamBase::AttachToObject(GetObject());
|
||||
ngtcp2_transport_params params;
|
||||
ngtcp2_conn_get_local_transport_params(session()->connection(), ¶ms);
|
||||
IncrementStat(&QuicStreamStats::max_offset, params.initial_max_data);
|
||||
}
|
||||
|
||||
QuicStream::~QuicStream() {
|
||||
DebugStats();
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void QuicStreamStatsTraits::ToString(const QuicStream& ptr, Fn&& add_field) {
|
||||
#define V(_n, name, label) \
|
||||
add_field(label, ptr.GetStat(&QuicStreamStats::name));
|
||||
STREAM_STATS(V)
|
||||
#undef V
|
||||
}
|
||||
|
||||
// Acknowledge is called when ngtcp2 has received an acknowledgement
|
||||
// for one or more stream frames for this QuicStream. This will cause
|
||||
// data stored in the streambuf_ outbound queue to be consumed and may
|
||||
// result in the JavaScript callback for the write to be invoked.
|
||||
void QuicStream::Acknowledge(uint64_t offset, size_t datalen) {
|
||||
if (is_destroyed())
|
||||
return;
|
||||
|
||||
// ngtcp2 guarantees that offset must always be greater
|
||||
// than the previously received offset, but let's just
|
||||
// make sure that holds.
|
||||
CHECK_GE(offset, GetStat(&QuicStreamStats::max_offset_ack));
|
||||
SetStat(&QuicStreamStats::max_offset_ack, offset);
|
||||
|
||||
Debug(this, "Acknowledging %d bytes", datalen);
|
||||
|
||||
// Consumes the given number of bytes in the buffer. This may
|
||||
// have the side-effect of causing the onwrite callback to be
|
||||
// invoked if a complete chunk of buffered data has been acknowledged.
|
||||
streambuf_.Consume(datalen);
|
||||
|
||||
RecordAck(&QuicStreamStats::acked_at);
|
||||
}
|
||||
|
||||
// While not all QUIC applications will support headers, QuicStream
|
||||
// includes basic, generic support for storing them.
|
||||
bool QuicStream::AddHeader(std::unique_ptr<QuicHeader> header) {
|
||||
size_t len = header->length();
|
||||
QuicApplication* app = session()->application();
|
||||
// We cannot add the header if we've either reached
|
||||
// * the max number of header pairs or
|
||||
// * the max number of header bytes
|
||||
if (headers_.size() == app->max_header_pairs() ||
|
||||
current_headers_length_ + len > app->max_header_length()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
current_headers_length_ += header->length();
|
||||
Debug(this, "Header - %s", header.get());
|
||||
headers_.emplace_back(std::move(header));
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string QuicStream::diagnostic_name() const {
|
||||
return std::string("QuicStream ") + std::to_string(stream_id_) +
|
||||
" (" + std::to_string(static_cast<int64_t>(get_async_id())) +
|
||||
", " + session_->diagnostic_name() + ")";
|
||||
}
|
||||
|
||||
void QuicStream::Destroy() {
|
||||
if (is_destroyed())
|
||||
return;
|
||||
set_flag(QUICSTREAM_FLAG_DESTROYED);
|
||||
set_flag(QUICSTREAM_FLAG_READ_CLOSED);
|
||||
streambuf_.End();
|
||||
|
||||
// If there is data currently buffered in the streambuf_,
|
||||
// then cancel will call out to invoke an arbitrary
|
||||
// JavaScript callback (the on write callback). Within
|
||||
// that callback, however, the QuicStream will no longer
|
||||
// be usable to send or receive data.
|
||||
streambuf_.Cancel();
|
||||
CHECK_EQ(streambuf_.length(), 0);
|
||||
|
||||
// The QuicSession maintains a map of std::unique_ptrs to
|
||||
// QuicStream instances. Removing this here will cause
|
||||
// this QuicStream object to be deconstructed, so the
|
||||
// QuicStream object will no longer exist after this point.
|
||||
session_->RemoveStream(stream_id_);
|
||||
}
|
||||
|
||||
// Do shutdown is called when the JS stream writable side is closed.
|
||||
// If we're not within an ngtcp2 callback, this will trigger the
|
||||
// QuicSession to send any pending data. Any time after this is
|
||||
// called, a final stream frame will be sent for this QuicStream,
|
||||
// but it may not be sent right away.
|
||||
int QuicStream::DoShutdown(ShutdownWrap* req_wrap) {
|
||||
if (is_destroyed())
|
||||
return UV_EPIPE;
|
||||
|
||||
QuicSession::SendSessionScope send_scope(session(), true);
|
||||
|
||||
if (is_writable()) {
|
||||
Debug(this, "Shutdown writable side");
|
||||
RecordTimestamp(&QuicStreamStats::closing_at);
|
||||
streambuf_.End();
|
||||
session()->ResumeStream(stream_id_);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int QuicStream::DoWrite(
|
||||
WriteWrap* req_wrap,
|
||||
uv_buf_t* bufs,
|
||||
size_t nbufs,
|
||||
uv_stream_t* send_handle) {
|
||||
CHECK_NULL(send_handle);
|
||||
|
||||
// A write should not have happened if we've been destroyed or
|
||||
// the QuicStream is no longer (or was never) writable.
|
||||
if (is_destroyed() || !is_writable()) {
|
||||
req_wrap->Done(UV_EPIPE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Nothing to write.
|
||||
size_t length = get_length(bufs, nbufs);
|
||||
if (length == 0) {
|
||||
req_wrap->Done(0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
QuicSession::SendSessionScope send_scope(session(), true);
|
||||
|
||||
Debug(this, "Queuing %" PRIu64 " bytes of data from %d buffers",
|
||||
length, nbufs);
|
||||
IncrementStat(&QuicStreamStats::bytes_sent, static_cast<uint64_t>(length));
|
||||
|
||||
BaseObjectPtr<AsyncWrap> strong_ref{req_wrap->GetAsyncWrap()};
|
||||
// The list of buffers will be appended onto streambuf_ without
|
||||
// copying. Those will remain in the buffer until the serialized
|
||||
// stream frames are acknowledged.
|
||||
// This callback function will be invoked once this
|
||||
// complete batch of buffers has been acknowledged
|
||||
// by the peer. This will have the side effect of
|
||||
// blocking additional pending writes from the
|
||||
// javascript side, so writing data to the stream
|
||||
// will be throttled by how quickly the peer is
|
||||
// able to acknowledge stream packets. This is good
|
||||
// in the sense of providing back-pressure, but
|
||||
// also means that writes will be significantly
|
||||
// less performant unless written in batches.
|
||||
streambuf_.Push(
|
||||
bufs,
|
||||
nbufs,
|
||||
[req_wrap, strong_ref](int status) {
|
||||
req_wrap->Done(status);
|
||||
});
|
||||
|
||||
session()->ResumeStream(stream_id_);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool QuicStream::IsAlive() {
|
||||
return !is_destroyed() && !IsClosing();
|
||||
}
|
||||
|
||||
bool QuicStream::IsClosing() {
|
||||
return !is_writable() && !is_readable();
|
||||
}
|
||||
|
||||
int QuicStream::ReadStart() {
|
||||
CHECK(!is_destroyed());
|
||||
CHECK(is_readable());
|
||||
set_flag(QUICSTREAM_FLAG_READ_STARTED);
|
||||
set_flag(QUICSTREAM_FLAG_READ_PAUSED, false);
|
||||
IncrementStat(
|
||||
&QuicStreamStats::max_offset,
|
||||
inbound_consumed_data_while_paused_);
|
||||
session_->ExtendStreamOffset(id(), inbound_consumed_data_while_paused_);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int QuicStream::ReadStop() {
|
||||
CHECK(!is_destroyed());
|
||||
CHECK(is_readable());
|
||||
set_flag(QUICSTREAM_FLAG_READ_PAUSED);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void QuicStream::IncrementStats(size_t datalen) {
|
||||
uint64_t len = static_cast<uint64_t>(datalen);
|
||||
IncrementStat(&QuicStreamStats::bytes_received, len);
|
||||
RecordRate(&QuicStreamStats::received_at);
|
||||
RecordSize(len);
|
||||
}
|
||||
|
||||
void QuicStream::MemoryInfo(MemoryTracker* tracker) const {
|
||||
tracker->TrackField("buffer", &streambuf_);
|
||||
StatsBase::StatsMemoryInfo(tracker);
|
||||
tracker->TrackField("headers", headers_);
|
||||
}
|
||||
|
||||
BaseObjectPtr<QuicStream> QuicStream::New(
|
||||
QuicSession* session,
|
||||
int64_t stream_id,
|
||||
int64_t push_id) {
|
||||
Local<Object> obj;
|
||||
if (!session->env()
|
||||
->quicserverstream_instance_template()
|
||||
->NewInstance(session->env()->context()).ToLocal(&obj)) {
|
||||
return {};
|
||||
}
|
||||
BaseObjectPtr<QuicStream> stream =
|
||||
MakeDetachedBaseObject<QuicStream>(
|
||||
session,
|
||||
obj,
|
||||
stream_id,
|
||||
push_id);
|
||||
CHECK(stream);
|
||||
session->AddStream(stream);
|
||||
return stream;
|
||||
}
|
||||
|
||||
// Passes chunks of data on to the JavaScript side as soon as they are
|
||||
// received but only if we're still readable. The caller of this must have a
|
||||
// HandleScope.
|
||||
//
|
||||
// Note that this is pushing data to the JS side regardless of whether
|
||||
// anything is listening. For flow-control, we only send window updates
|
||||
// to the sending peer if the stream is in flowing mode, so the sender
|
||||
// should not be sending too much data.
|
||||
void QuicStream::ReceiveData(
|
||||
int fin,
|
||||
const uint8_t* data,
|
||||
size_t datalen,
|
||||
uint64_t offset) {
|
||||
CHECK(!is_destroyed());
|
||||
Debug(this, "Receiving %d bytes. Final? %s. Readable? %s",
|
||||
datalen,
|
||||
fin ? "yes" : "no",
|
||||
is_readable() ? "yes" : "no");
|
||||
|
||||
// If the QuicStream is not (or was never) readable, just ignore the chunk.
|
||||
if (!is_readable())
|
||||
return;
|
||||
|
||||
// ngtcp2 guarantees that datalen will only be 0 if fin is set.
|
||||
// Let's just make sure.
|
||||
CHECK(datalen > 0 || fin == 1);
|
||||
|
||||
// ngtcp2 guarantees that offset is always greater than the previously
|
||||
// received offset. Let's just make sure.
|
||||
CHECK_GE(offset, GetStat(&QuicStreamStats::max_offset_received));
|
||||
SetStat(&QuicStreamStats::max_offset_received, offset);
|
||||
|
||||
if (datalen > 0) {
|
||||
// IncrementStats will update the data_rx_rate_ and data_rx_size_
|
||||
// histograms. These will provide data necessary to detect and
|
||||
// prevent Slow Send DOS attacks specifically by allowing us to
|
||||
// see if a connection is sending very small chunks of data at very
|
||||
// slow speeds. It is important to emphasize, however, that slow send
|
||||
// rates may be perfectly legitimate so we cannot simply take blanket
|
||||
// action when slow rates are detected. Nor can we reliably define what
|
||||
// a slow rate even is! Will will need to determine some reasonable
|
||||
// default and allow user code to change the default as well as determine
|
||||
// what action to take. The current strategy will be to trigger an event
|
||||
// on the stream when data transfer rates are likely to be considered too
|
||||
// slow.
|
||||
IncrementStats(datalen);
|
||||
|
||||
while (datalen > 0) {
|
||||
uv_buf_t buf = EmitAlloc(datalen);
|
||||
size_t avail = std::min(static_cast<size_t>(buf.len), datalen);
|
||||
|
||||
// For now, we're allocating and copying. Once we determine if we can
|
||||
// safely switch to a non-allocated mode like we do with http2 streams,
|
||||
// we can make this branch more efficient by using the LIKELY
|
||||
// optimization. The way ngtcp2 currently works, however, we have
|
||||
// to memcpy here.
|
||||
if (UNLIKELY(buf.base == nullptr))
|
||||
buf.base = reinterpret_cast<char*>(const_cast<uint8_t*>(data));
|
||||
else
|
||||
memcpy(buf.base, data, avail);
|
||||
data += avail;
|
||||
datalen -= avail;
|
||||
// Capture read_paused before EmitRead in case user code callbacks
|
||||
// alter the state when EmitRead is called.
|
||||
bool read_paused = is_flag_set(QUICSTREAM_FLAG_READ_PAUSED);
|
||||
EmitRead(avail, buf);
|
||||
// Reading can be paused while we are processing. If that's
|
||||
// the case, we still want to acknowledge the current bytes
|
||||
// so that pausing does not throw off our flow control.
|
||||
if (read_paused) {
|
||||
inbound_consumed_data_while_paused_ += avail;
|
||||
} else {
|
||||
IncrementStat(&QuicStreamStats::max_offset, avail);
|
||||
session_->ExtendStreamOffset(id(), avail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// When fin != 0, we've received that last chunk of data for this
|
||||
// stream, indicating that the stream will no longer be readable.
|
||||
if (fin) {
|
||||
set_flag(QUICSTREAM_FLAG_FIN);
|
||||
set_final_size(offset + datalen);
|
||||
EmitRead(UV_EOF);
|
||||
}
|
||||
}
|
||||
|
||||
int QuicStream::DoPull(
|
||||
bob::Next<ngtcp2_vec> next,
|
||||
int options,
|
||||
ngtcp2_vec* data,
|
||||
size_t count,
|
||||
size_t max_count_hint) {
|
||||
return streambuf_.Pull(
|
||||
std::move(next),
|
||||
options,
|
||||
data,
|
||||
count,
|
||||
max_count_hint);
|
||||
}
|
||||
|
||||
// JavaScript API
|
||||
namespace {
|
||||
void QuicStreamGetID(const FunctionCallbackInfo<Value>& args) {
|
||||
QuicStream* stream;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
|
||||
args.GetReturnValue().Set(static_cast<double>(stream->id()));
|
||||
}
|
||||
|
||||
void OpenUnidirectionalStream(const FunctionCallbackInfo<Value>& args) {
|
||||
CHECK(!args.IsConstructCall());
|
||||
CHECK(args[0]->IsObject());
|
||||
QuicSession* session;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&session, args[0].As<Object>());
|
||||
|
||||
int64_t stream_id;
|
||||
if (!session->OpenUnidirectionalStream(&stream_id))
|
||||
return;
|
||||
|
||||
BaseObjectPtr<QuicStream> stream = QuicStream::New(session, stream_id);
|
||||
args.GetReturnValue().Set(stream->object());
|
||||
}
|
||||
|
||||
void OpenBidirectionalStream(const FunctionCallbackInfo<Value>& args) {
|
||||
CHECK(!args.IsConstructCall());
|
||||
CHECK(args[0]->IsObject());
|
||||
QuicSession* session;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&session, args[0].As<Object>());
|
||||
|
||||
int64_t stream_id;
|
||||
if (!session->OpenBidirectionalStream(&stream_id))
|
||||
return;
|
||||
|
||||
BaseObjectPtr<QuicStream> stream = QuicStream::New(session, stream_id);
|
||||
args.GetReturnValue().Set(stream->object());
|
||||
}
|
||||
|
||||
void QuicStreamDestroy(const FunctionCallbackInfo<Value>& args) {
|
||||
QuicStream* stream;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
|
||||
stream->Destroy();
|
||||
}
|
||||
|
||||
void QuicStreamReset(const FunctionCallbackInfo<Value>& args) {
|
||||
Environment* env = Environment::GetCurrent(args);
|
||||
QuicStream* stream;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
|
||||
|
||||
QuicError error(env, args[0], args[1], QUIC_ERROR_APPLICATION);
|
||||
|
||||
stream->ResetStream(
|
||||
error.family == QUIC_ERROR_APPLICATION ?
|
||||
error.code : static_cast<uint64_t>(NGTCP2_NO_ERROR));
|
||||
}
|
||||
|
||||
// Requests transmission of a block of informational headers. Not all
|
||||
// QUIC Applications will support headers. If headers are not supported,
|
||||
// This will set the return value to false, otherwise the return value
|
||||
// is set to true
|
||||
void QuicStreamSubmitInformation(const FunctionCallbackInfo<Value>& args) {
|
||||
QuicStream* stream;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
|
||||
CHECK(args[0]->IsArray());
|
||||
args.GetReturnValue().Set(stream->SubmitInformation(args[0].As<Array>()));
|
||||
}
|
||||
|
||||
// Requests transmission of a block of initial headers. Not all
|
||||
// QUIC Applications will support headers. If headers are not supported,
|
||||
// this will set the return value to false, otherwise the return value
|
||||
// is set to true. For http/3, these may be request or response headers.
|
||||
void QuicStreamSubmitHeaders(const FunctionCallbackInfo<Value>& args) {
|
||||
QuicStream* stream;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
|
||||
CHECK(args[0]->IsArray());
|
||||
uint32_t flags = QUICSTREAM_HEADER_FLAGS_NONE;
|
||||
CHECK(args[1]->Uint32Value(stream->env()->context()).To(&flags));
|
||||
args.GetReturnValue().Set(stream->SubmitHeaders(args[0].As<Array>(), flags));
|
||||
}
|
||||
|
||||
// Requests transmission of a block of trailing headers. Not all
|
||||
// QUIC Applications will support headers. If headers are not supported,
|
||||
// this will set the return value to false, otherwise the return value
|
||||
// is set to true.
|
||||
void QuicStreamSubmitTrailers(const FunctionCallbackInfo<Value>& args) {
|
||||
QuicStream* stream;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
|
||||
CHECK(args[0]->IsArray());
|
||||
args.GetReturnValue().Set(stream->SubmitTrailers(args[0].As<Array>()));
|
||||
}
|
||||
|
||||
// Requests creation of a push stream. Not all QUIC Applications will
|
||||
// support push streams. If pushes are not supported, the return value
|
||||
// will be undefined, otherwise the return value will be the created
|
||||
// QuicStream representing the push.
|
||||
void QuicStreamSubmitPush(const FunctionCallbackInfo<Value>& args) {
|
||||
QuicStream* stream;
|
||||
ASSIGN_OR_RETURN_UNWRAP(&stream, args.Holder());
|
||||
CHECK(args[0]->IsArray());
|
||||
BaseObjectPtr<QuicStream> push_stream =
|
||||
stream->SubmitPush(args[0].As<Array>());
|
||||
if (push_stream)
|
||||
args.GetReturnValue().Set(push_stream->object());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void QuicStream::Initialize(
|
||||
Environment* env,
|
||||
Local<Object> target,
|
||||
Local<Context> context) {
|
||||
Isolate* isolate = env->isolate();
|
||||
Local<String> class_name = FIXED_ONE_BYTE_STRING(isolate, "QuicStream");
|
||||
Local<FunctionTemplate> stream = FunctionTemplate::New(env->isolate());
|
||||
stream->SetClassName(class_name);
|
||||
stream->Inherit(AsyncWrap::GetConstructorTemplate(env));
|
||||
StreamBase::AddMethods(env, stream);
|
||||
Local<ObjectTemplate> streamt = stream->InstanceTemplate();
|
||||
streamt->SetInternalFieldCount(StreamBase::kInternalFieldCount);
|
||||
streamt->Set(env->owner_symbol(), Null(env->isolate()));
|
||||
env->SetProtoMethod(stream, "destroy", QuicStreamDestroy);
|
||||
env->SetProtoMethod(stream, "resetStream", QuicStreamReset);
|
||||
env->SetProtoMethod(stream, "id", QuicStreamGetID);
|
||||
env->SetProtoMethod(stream, "submitInformation", QuicStreamSubmitInformation);
|
||||
env->SetProtoMethod(stream, "submitHeaders", QuicStreamSubmitHeaders);
|
||||
env->SetProtoMethod(stream, "submitTrailers", QuicStreamSubmitTrailers);
|
||||
env->SetProtoMethod(stream, "submitPush", QuicStreamSubmitPush);
|
||||
env->set_quicserverstream_instance_template(streamt);
|
||||
target->Set(env->context(),
|
||||
class_name,
|
||||
stream->GetFunction(env->context()).ToLocalChecked()).FromJust();
|
||||
|
||||
env->SetMethod(target, "openBidirectionalStream", OpenBidirectionalStream);
|
||||
env->SetMethod(target, "openUnidirectionalStream", OpenUnidirectionalStream);
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
@@ -0,0 +1,407 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_STREAM_H_
|
||||
#define SRC_QUIC_NODE_QUIC_STREAM_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "memory_tracker.h"
|
||||
#include "async_wrap.h"
|
||||
#include "env.h"
|
||||
#include "node_http_common.h"
|
||||
#include "node_quic_state.h"
|
||||
#include "node_quic_util.h"
|
||||
#include "stream_base-inl.h"
|
||||
#include "util-inl.h"
|
||||
#include "v8.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace node {
|
||||
namespace quic {
|
||||
|
||||
class QuicSession;
|
||||
class QuicStream;
|
||||
class QuicApplication;
|
||||
|
||||
using QuicHeader = NgHeaderBase<QuicApplication>;
|
||||
|
||||
enum QuicStreamHeaderFlags : uint32_t {
|
||||
// No flags
|
||||
QUICSTREAM_HEADER_FLAGS_NONE = 0,
|
||||
|
||||
// Set if the initial headers are considered
|
||||
// terminal (that is, the stream should be closed
|
||||
// after transmitting the headers). If headers are
|
||||
// not supported by the QUIC Application, flag is
|
||||
// ignored.
|
||||
QUICSTREAM_HEADER_FLAGS_TERMINAL = 1
|
||||
};
|
||||
|
||||
enum QuicStreamHeadersKind : int {
|
||||
QUICSTREAM_HEADERS_KIND_NONE = 0,
|
||||
QUICSTREAM_HEADERS_KIND_INFORMATIONAL,
|
||||
QUICSTREAM_HEADERS_KIND_INITIAL,
|
||||
QUICSTREAM_HEADERS_KIND_TRAILING,
|
||||
QUICSTREAM_HEADERS_KIND_PUSH
|
||||
};
|
||||
|
||||
#define STREAM_STATS(V) \
|
||||
V(CREATED_AT, created_at, "Created At") \
|
||||
V(RECEIVED_AT, received_at, "Last Received At") \
|
||||
V(ACKED_AT, acked_at, "Last Acknowledged At") \
|
||||
V(CLOSING_AT, closing_at, "Closing At") \
|
||||
V(BYTES_RECEIVED, bytes_received, "Bytes Received") \
|
||||
V(BYTES_SENT, bytes_sent, "Bytes Sent") \
|
||||
V(MAX_OFFSET, max_offset, "Max Offset") \
|
||||
V(MAX_OFFSET_ACK, max_offset_ack, "Max Acknowledged Offset") \
|
||||
V(MAX_OFFSET_RECV, max_offset_received, "Max Received Offset") \
|
||||
V(FINAL_SIZE, final_size, "Final Size")
|
||||
|
||||
#define V(name, _, __) IDX_QUIC_STREAM_STATS_##name,
|
||||
enum QuicStreamStatsIdx : int {
|
||||
STREAM_STATS(V)
|
||||
IDX_QUIC_STREAM_STATS_COUNT
|
||||
};
|
||||
#undef V
|
||||
|
||||
#define V(_, name, __) uint64_t name;
|
||||
struct QuicStreamStats {
|
||||
STREAM_STATS(V)
|
||||
};
|
||||
#undef V
|
||||
|
||||
struct QuicStreamStatsTraits {
|
||||
using Stats = QuicStreamStats;
|
||||
using Base = QuicStream;
|
||||
|
||||
template <typename Fn>
|
||||
static void ToString(const Base& ptr, Fn&& add_field);
|
||||
};
|
||||
|
||||
enum QuicStreamStates : uint32_t {
|
||||
// QuicStream is fully open. Readable and Writable
|
||||
QUICSTREAM_FLAG_INITIAL = 0,
|
||||
|
||||
// QuicStream Read State is closed because a final stream frame
|
||||
// has been received from the peer or the QuicStream is unidirectional
|
||||
// outbound only (i.e. it was never readable)
|
||||
QUICSTREAM_FLAG_READ_CLOSED,
|
||||
|
||||
// JavaScript side has switched into flowing mode (Readable side)
|
||||
QUICSTREAM_FLAG_READ_STARTED,
|
||||
|
||||
// JavaScript side has paused the flow of data (Readable side)
|
||||
QUICSTREAM_FLAG_READ_PAUSED,
|
||||
|
||||
// QuicStream has received a final stream frame (Readable side)
|
||||
QUICSTREAM_FLAG_FIN,
|
||||
|
||||
// QuicStream has sent a final stream frame (Writable side)
|
||||
QUICSTREAM_FLAG_FIN_SENT,
|
||||
|
||||
// QuicStream has been destroyed
|
||||
QUICSTREAM_FLAG_DESTROYED
|
||||
};
|
||||
|
||||
enum QuicStreamDirection {
|
||||
// The QuicStream is readable and writable in both directions
|
||||
QUIC_STREAM_BIRECTIONAL,
|
||||
|
||||
// The QuicStream is writable and readable in only one direction.
|
||||
// The direction depends on the QuicStreamOrigin.
|
||||
QUIC_STREAM_UNIDIRECTIONAL
|
||||
};
|
||||
|
||||
enum QuicStreamOrigin {
|
||||
// The QuicStream was created by the server.
|
||||
QUIC_STREAM_SERVER,
|
||||
|
||||
// The QuicStream was created by the client.
|
||||
QUIC_STREAM_CLIENT
|
||||
};
|
||||
|
||||
// QuicStream's are simple data flows that, fortunately, do not
|
||||
// require much. They may be:
|
||||
//
|
||||
// * Bidirectional or Unidirectional
|
||||
// * Server or Client Initiated
|
||||
//
|
||||
// The flow direction and origin of the stream are important in
|
||||
// determining the write and read state (Open or Closed). Specifically:
|
||||
//
|
||||
// A Unidirectional stream originating with the Server is:
|
||||
//
|
||||
// * Server Writable (Open) but not Client Writable (Closed)
|
||||
// * Client Readable (Open) but not Server Readable (Closed)
|
||||
//
|
||||
// Likewise, a Unidirectional stream originating with the
|
||||
// Client is:
|
||||
//
|
||||
// * Client Writable (Open) but not Server Writable (Closed)
|
||||
// * Server Readable (Open) but not Client Readable (Closed)
|
||||
//
|
||||
// Bidirectional Stream States
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | | Initiated By | Initial Read State | Initial Write State |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | On Server | Server | Open | Open |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | On Server | Client | Open | Open |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | On Client | Server | Open | Open |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | On Client | Client | Open | Open |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
//
|
||||
// Unidirectional Stream States
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | | Initiated By | Initial Read State | Initial Write State |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | On Server | Server | Closed | Open |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | On Server | Client | Open | Closed |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | On Client | Server | Open | Closed |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
// | On Client | Client | Closed | Open |
|
||||
// +------------+--------------+--------------------+---------------------+
|
||||
//
|
||||
// All data sent via the QuicStream is buffered internally until either
|
||||
// receipt is acknowledged from the peer or attempts to send are abandoned.
|
||||
//
|
||||
// A QuicStream may be in a fully Closed (Read and Write) state but still
|
||||
// have unacknowledged data in it's outbound queue.
|
||||
//
|
||||
// A QuicStream is gracefully closed when (a) both Read and Write states
|
||||
// are Closed, (b) all queued data has been acknowledged.
|
||||
//
|
||||
// The JavaScript Writable side of the QuicStream may be shutdown before
|
||||
// all pending queued data has been serialized to frames. During this state,
|
||||
// no additional data may be queued to send.
|
||||
//
|
||||
// The Write state of a QuicStream will not be closed while there is still
|
||||
// pending writes on the JavaScript side.
|
||||
//
|
||||
// The QuicStream may be forcefully closed immediately using destroy(err).
|
||||
// This causes all queued data and pending JavaScript writes to be
|
||||
// abandoned, and causes the QuicStream to be immediately closed at the
|
||||
// ngtcp2 level.
|
||||
class QuicStream : public AsyncWrap,
|
||||
public bob::SourceImpl<ngtcp2_vec>,
|
||||
public StreamBase,
|
||||
public StatsBase<QuicStreamStatsTraits> {
|
||||
public:
|
||||
static void Initialize(
|
||||
Environment* env,
|
||||
v8::Local<v8::Object> target,
|
||||
v8::Local<v8::Context> context);
|
||||
|
||||
static BaseObjectPtr<QuicStream> New(
|
||||
QuicSession* session,
|
||||
int64_t stream_id,
|
||||
int64_t push_id = 0);
|
||||
|
||||
QuicStream(
|
||||
QuicSession* session,
|
||||
v8::Local<v8::Object> target,
|
||||
int64_t stream_id,
|
||||
int64_t push_id = 0);
|
||||
|
||||
~QuicStream() override;
|
||||
|
||||
std::string diagnostic_name() const override;
|
||||
|
||||
// The numeric identifier of the QuicStream.
|
||||
int64_t id() const { return stream_id_; }
|
||||
|
||||
// If the QuicStream is associated with a push promise,
|
||||
// the numeric identifier of the promise. Currently only
|
||||
// used by HTTP/3.
|
||||
int64_t push_id() const { return push_id_; }
|
||||
|
||||
QuicSession* session() const { return session_.get(); }
|
||||
|
||||
// A QuicStream can be either uni- or bi-directional.
|
||||
inline QuicStreamDirection direction() const;
|
||||
|
||||
// A QuicStream can be initiated by either the client
|
||||
// or the server.
|
||||
inline QuicStreamOrigin origin() const;
|
||||
|
||||
// The QuicStream has been destroyed and is no longer usable.
|
||||
inline bool is_destroyed() const;
|
||||
|
||||
// A QuicStream will not be writable if:
|
||||
// - The streambuf_ is ended
|
||||
// - It is a Unidirectional stream originating from the peer
|
||||
inline bool is_writable() const;
|
||||
|
||||
// A QuicStream will not be readable if:
|
||||
// - The QUICSTREAM_FLAG_READ_CLOSED flag is set or
|
||||
// - It is a Unidirectional stream originating from the local peer.
|
||||
inline bool is_readable() const;
|
||||
|
||||
// Records the fact that a final stream frame has been
|
||||
// serialized and sent to the peer. There still may be
|
||||
// unacknowledged data in the outbound queue, but no
|
||||
// additional frames may be sent for the stream other
|
||||
// than reset stream.
|
||||
inline void set_fin_sent();
|
||||
|
||||
// IsWriteFinished will return true if a final stream frame
|
||||
// has been sent and all data has been acknowledged (the
|
||||
// send buffer is empty).
|
||||
inline bool is_write_finished() const;
|
||||
|
||||
// Specifies the kind of headers currently being processed.
|
||||
inline void set_headers_kind(QuicStreamHeadersKind kind);
|
||||
|
||||
// Set the final size for the QuicStream
|
||||
inline void set_final_size(uint64_t final_size);
|
||||
|
||||
// The final size is the maximum amount of data that has been
|
||||
// acknowleged to have been received for a QuicStream.
|
||||
uint64_t final_size() const {
|
||||
return GetStat(&QuicStreamStats::final_size);
|
||||
}
|
||||
|
||||
// Marks the given data range as having been acknowledged.
|
||||
// This means that the data range may be released from
|
||||
// memory.
|
||||
void Acknowledge(uint64_t offset, size_t datalen);
|
||||
|
||||
// Destroy the QuicStream and render it no longer usable.
|
||||
void Destroy();
|
||||
|
||||
// Buffers chunks of data to be written to the QUIC connection.
|
||||
int DoWrite(
|
||||
WriteWrap* req_wrap,
|
||||
uv_buf_t* bufs,
|
||||
size_t nbufs,
|
||||
uv_stream_t* send_handle) override;
|
||||
|
||||
// Returns false if the header cannot be added. This will
|
||||
// typically only happen if a maximimum number of headers
|
||||
// has been reached.
|
||||
bool AddHeader(std::unique_ptr<QuicHeader> header);
|
||||
|
||||
// Some QUIC applications support headers, others do not.
|
||||
// The following methods allow consistent handling of
|
||||
// headers at the QuicStream level regardless of the
|
||||
// protocol. For applications that do not support headers,
|
||||
// these are simply not used.
|
||||
inline void BeginHeaders(
|
||||
QuicStreamHeadersKind kind = QUICSTREAM_HEADERS_KIND_NONE);
|
||||
|
||||
// Indicates an amount of unacknowledged data that has been
|
||||
// submitted to the QUIC connection.
|
||||
inline void Commit(size_t amount);
|
||||
|
||||
inline void EndHeaders(int64_t push_id = 0);
|
||||
|
||||
// Passes a chunk of data on to the QuicStream listener.
|
||||
void ReceiveData(
|
||||
int fin,
|
||||
const uint8_t* data,
|
||||
size_t datalen,
|
||||
uint64_t offset);
|
||||
|
||||
// Resets the QUIC stream, sending a signal to the peer that
|
||||
// no additional data will be transmitted for this stream.
|
||||
inline void ResetStream(uint64_t app_error_code = 0);
|
||||
|
||||
// Submits informational headers. Returns false if headers are not
|
||||
// supported on the underlying QuicApplication.
|
||||
inline bool SubmitInformation(v8::Local<v8::Array> headers);
|
||||
|
||||
// Submits initial headers. Returns false if headers are not
|
||||
// supported on the underlying QuicApplication.
|
||||
inline bool SubmitHeaders(v8::Local<v8::Array> headers, uint32_t flags);
|
||||
|
||||
// Submits trailing headers. Returns false if headers are not
|
||||
// supported on the underlying QuicApplication.
|
||||
inline bool SubmitTrailers(v8::Local<v8::Array> headers);
|
||||
|
||||
inline BaseObjectPtr<QuicStream> SubmitPush(v8::Local<v8::Array> headers);
|
||||
|
||||
// Required for StreamBase
|
||||
bool IsAlive() override;
|
||||
|
||||
// Required for StreamBase
|
||||
bool IsClosing() override;
|
||||
|
||||
// Required for StreamBase
|
||||
int ReadStart() override;
|
||||
|
||||
// Required for StreamBase
|
||||
int ReadStop() override;
|
||||
|
||||
// Required for StreamBase
|
||||
int DoShutdown(ShutdownWrap* req_wrap) override;
|
||||
|
||||
AsyncWrap* GetAsyncWrap() override { return this; }
|
||||
|
||||
QuicState* quic_state() { return quic_state_.get(); }
|
||||
|
||||
// Required for MemoryRetainer
|
||||
void MemoryInfo(MemoryTracker* tracker) const override;
|
||||
SET_MEMORY_INFO_NAME(QuicStream)
|
||||
SET_SELF_SIZE(QuicStream)
|
||||
|
||||
protected:
|
||||
int DoPull(
|
||||
bob::Next<ngtcp2_vec> next,
|
||||
int options,
|
||||
ngtcp2_vec* data,
|
||||
size_t count,
|
||||
size_t max_count_hint) override;
|
||||
|
||||
private:
|
||||
inline bool is_flag_set(int32_t flag) const;
|
||||
|
||||
inline void set_flag(int32_t flag, bool on = true);
|
||||
|
||||
// WasEverWritable returns true if it is a bidirectional stream,
|
||||
// or a Unidirectional stream originating from the local peer.
|
||||
// If was_ever_writable() is false, then no stream frames should
|
||||
// ever be sent from the local peer, including final stream frames.
|
||||
inline bool was_ever_writable() const;
|
||||
|
||||
// WasEverReadable returns true if it is a bidirectional stream,
|
||||
// or a Unidirectional stream originating from the remote
|
||||
// peer.
|
||||
inline bool was_ever_readable() const;
|
||||
|
||||
void IncrementStats(size_t datalen);
|
||||
|
||||
BaseObjectWeakPtr<QuicSession> session_;
|
||||
QuicBuffer streambuf_;
|
||||
|
||||
int64_t stream_id_ = 0;
|
||||
int64_t push_id_ = 0;
|
||||
uint32_t flags_ = QUICSTREAM_FLAG_INITIAL;
|
||||
size_t inbound_consumed_data_while_paused_ = 0;
|
||||
|
||||
std::vector<std::unique_ptr<QuicHeader>> headers_;
|
||||
QuicStreamHeadersKind headers_kind_;
|
||||
size_t current_headers_length_ = 0;
|
||||
|
||||
ListNode<QuicStream> stream_queue_;
|
||||
|
||||
BaseObjectPtr<QuicState> quic_state_;
|
||||
|
||||
public:
|
||||
// Linked List of QuicStream objects
|
||||
using Queue = ListHead<QuicStream, &QuicStream::stream_queue_>;
|
||||
|
||||
inline void Schedule(Queue* queue);
|
||||
|
||||
inline void Unschedule();
|
||||
};
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_STREAM_H_
|
||||
@@ -0,0 +1,473 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_UTIL_INL_H_
|
||||
#define SRC_QUIC_NODE_QUIC_UTIL_INL_H_
|
||||
|
||||
#include "debug_utils-inl.h"
|
||||
#include "node_internals.h"
|
||||
#include "node_quic_crypto.h"
|
||||
#include "node_quic_util.h"
|
||||
#include "memory_tracker-inl.h"
|
||||
#include "env-inl.h"
|
||||
#include "histogram-inl.h"
|
||||
#include "string_bytes.h"
|
||||
#include "util-inl.h"
|
||||
#include "uv.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace node {
|
||||
|
||||
namespace quic {
|
||||
|
||||
QuicPath::QuicPath(
|
||||
const SocketAddress& local,
|
||||
const SocketAddress& remote) {
|
||||
ngtcp2_addr_init(
|
||||
&this->local,
|
||||
local.data(),
|
||||
local.length(),
|
||||
const_cast<SocketAddress*>(&local));
|
||||
ngtcp2_addr_init(
|
||||
&this->remote,
|
||||
remote.data(),
|
||||
remote.length(),
|
||||
const_cast<SocketAddress*>(&remote));
|
||||
}
|
||||
|
||||
size_t QuicCID::Hash::operator()(const QuicCID& token) const {
|
||||
size_t hash = 0;
|
||||
for (size_t n = 0; n < token->datalen; n++) {
|
||||
hash ^= std::hash<uint8_t>{}(token->data[n]) + 0x9e3779b9 +
|
||||
(hash << 6) + (hash >> 2);
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
QuicCID& QuicCID::operator=(const QuicCID& cid) {
|
||||
if (this == &cid) return *this;
|
||||
this->~QuicCID();
|
||||
return *new(this) QuicCID(std::move(cid));
|
||||
}
|
||||
|
||||
bool QuicCID::operator==(const QuicCID& other) const {
|
||||
return memcmp(cid()->data, other.cid()->data, cid()->datalen) == 0;
|
||||
}
|
||||
|
||||
bool QuicCID::operator!=(const QuicCID& other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
std::string QuicCID::ToString() const {
|
||||
std::vector<char> dest(ptr_->datalen * 2 + 1);
|
||||
dest[dest.size() - 1] = '\0';
|
||||
size_t written = StringBytes::hex_encode(
|
||||
reinterpret_cast<const char*>(ptr_->data),
|
||||
ptr_->datalen,
|
||||
dest.data(),
|
||||
dest.size());
|
||||
return std::string(dest.data(), written);
|
||||
}
|
||||
|
||||
size_t GetMaxPktLen(const SocketAddress& addr) {
|
||||
return addr.family() == AF_INET6 ?
|
||||
NGTCP2_MAX_PKTLEN_IPV6 :
|
||||
NGTCP2_MAX_PKTLEN_IPV4;
|
||||
}
|
||||
|
||||
Timer::Timer(Environment* env, std::function<void()> fn)
|
||||
: env_(env),
|
||||
fn_(fn) {
|
||||
uv_timer_init(env_->event_loop(), &timer_);
|
||||
timer_.data = this;
|
||||
}
|
||||
|
||||
void Timer::Stop() {
|
||||
if (stopped_)
|
||||
return;
|
||||
stopped_ = true;
|
||||
|
||||
if (timer_.data == this) {
|
||||
uv_timer_stop(&timer_);
|
||||
timer_.data = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
// If the timer is not currently active, interval must be either 0 or greater.
|
||||
// If the timer is already active, interval is ignored.
|
||||
void Timer::Update(uint64_t interval) {
|
||||
if (stopped_)
|
||||
return;
|
||||
uv_timer_start(&timer_, OnTimeout, interval, interval);
|
||||
uv_unref(reinterpret_cast<uv_handle_t*>(&timer_));
|
||||
}
|
||||
|
||||
void Timer::Free(Timer* timer) {
|
||||
timer->env_->CloseHandle(
|
||||
reinterpret_cast<uv_handle_t*>(&timer->timer_),
|
||||
[&](uv_handle_t* timer) {
|
||||
Timer* t = ContainerOf(
|
||||
&Timer::timer_,
|
||||
reinterpret_cast<uv_timer_t*>(timer));
|
||||
delete t;
|
||||
});
|
||||
}
|
||||
|
||||
void Timer::OnTimeout(uv_timer_t* timer) {
|
||||
Timer* t = ContainerOf(&Timer::timer_, timer);
|
||||
t->fn_();
|
||||
}
|
||||
|
||||
QuicError::QuicError(
|
||||
int32_t family_,
|
||||
uint64_t code_) :
|
||||
family(family_),
|
||||
code(code_) {}
|
||||
|
||||
QuicError::QuicError(
|
||||
int32_t family_,
|
||||
int code_) :
|
||||
family(family_) {
|
||||
switch (family) {
|
||||
case QUIC_ERROR_CRYPTO:
|
||||
code_ |= NGTCP2_CRYPTO_ERROR;
|
||||
// Fall-through...
|
||||
case QUIC_ERROR_SESSION:
|
||||
code = ngtcp2_err_infer_quic_transport_error_code(code_);
|
||||
break;
|
||||
case QUIC_ERROR_APPLICATION:
|
||||
code = code_;
|
||||
break;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
|
||||
QuicError::QuicError(ngtcp2_connection_close_error_code ccec) :
|
||||
family(QUIC_ERROR_SESSION),
|
||||
code(ccec.error_code) {
|
||||
switch (ccec.type) {
|
||||
case NGTCP2_CONNECTION_CLOSE_ERROR_CODE_TYPE_APPLICATION:
|
||||
family = QUIC_ERROR_APPLICATION;
|
||||
break;
|
||||
case NGTCP2_CONNECTION_CLOSE_ERROR_CODE_TYPE_TRANSPORT:
|
||||
if (code & NGTCP2_CRYPTO_ERROR)
|
||||
family = QUIC_ERROR_CRYPTO;
|
||||
break;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
|
||||
QuicError::QuicError(
|
||||
Environment* env,
|
||||
v8::Local<v8::Value> codeArg,
|
||||
v8::Local<v8::Value> familyArg,
|
||||
int32_t family_) :
|
||||
family(family_),
|
||||
code(NGTCP2_NO_ERROR) {
|
||||
if (codeArg->IsBigInt()) {
|
||||
code = codeArg.As<v8::BigInt>()->Int64Value();
|
||||
} else if (codeArg->IsNumber()) {
|
||||
double num = 0;
|
||||
CHECK(codeArg->NumberValue(env->context()).To(&num));
|
||||
code = static_cast<uint64_t>(num);
|
||||
}
|
||||
if (familyArg->IsNumber()) {
|
||||
CHECK(familyArg->Int32Value(env->context()).To(&family));
|
||||
}
|
||||
}
|
||||
|
||||
const char* QuicError::family_name() {
|
||||
switch (family) {
|
||||
case QUIC_ERROR_SESSION:
|
||||
return "Session";
|
||||
case QUIC_ERROR_APPLICATION:
|
||||
return "Application";
|
||||
case QUIC_ERROR_CRYPTO:
|
||||
return "Crypto";
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
|
||||
const ngtcp2_cid* PreferredAddress::cid() const {
|
||||
return &paddr_->cid;
|
||||
}
|
||||
|
||||
const uint8_t* PreferredAddress::stateless_reset_token() const {
|
||||
return paddr_->stateless_reset_token;
|
||||
}
|
||||
|
||||
std::string PreferredAddress::ipv6_address() const {
|
||||
char host[NI_MAXHOST];
|
||||
// Return an empty string if unable to convert...
|
||||
if (uv_inet_ntop(AF_INET6, paddr_->ipv6_addr, host, sizeof(host)) != 0)
|
||||
return std::string();
|
||||
|
||||
return std::string(host);
|
||||
}
|
||||
std::string PreferredAddress::ipv4_address() const {
|
||||
char host[NI_MAXHOST];
|
||||
// Return an empty string if unable to convert...
|
||||
if (uv_inet_ntop(AF_INET, paddr_->ipv4_addr, host, sizeof(host)) != 0)
|
||||
return std::string();
|
||||
|
||||
return std::string(host);
|
||||
}
|
||||
|
||||
uint16_t PreferredAddress::ipv6_port() const {
|
||||
return paddr_->ipv6_port;
|
||||
}
|
||||
|
||||
uint16_t PreferredAddress::ipv4_port() const {
|
||||
return paddr_->ipv4_port;
|
||||
}
|
||||
|
||||
bool PreferredAddress::Use(int family) const {
|
||||
uv_getaddrinfo_t req;
|
||||
|
||||
if (!ResolvePreferredAddress(family, &req))
|
||||
return false;
|
||||
|
||||
dest_->addrlen = req.addrinfo->ai_addrlen;
|
||||
memcpy(dest_->addr, req.addrinfo->ai_addr, req.addrinfo->ai_addrlen);
|
||||
uv_freeaddrinfo(req.addrinfo);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PreferredAddress::ResolvePreferredAddress(
|
||||
int local_address_family,
|
||||
uv_getaddrinfo_t* req) const {
|
||||
int af;
|
||||
const uint8_t* binaddr;
|
||||
uint16_t port;
|
||||
switch (local_address_family) {
|
||||
case AF_INET:
|
||||
if (paddr_->ipv4_port > 0) {
|
||||
af = AF_INET;
|
||||
binaddr = paddr_->ipv4_addr;
|
||||
port = paddr_->ipv4_port;
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
case AF_INET6:
|
||||
if (paddr_->ipv6_port > 0) {
|
||||
af = AF_INET6;
|
||||
binaddr = paddr_->ipv6_addr;
|
||||
port = paddr_->ipv6_port;
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
|
||||
char host[NI_MAXHOST];
|
||||
if (uv_inet_ntop(af, binaddr, host, sizeof(host)) != 0)
|
||||
return false;
|
||||
|
||||
addrinfo hints{};
|
||||
hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
|
||||
hints.ai_family = af;
|
||||
hints.ai_socktype = SOCK_DGRAM;
|
||||
|
||||
// Unfortunately ngtcp2 requires the selection of the
|
||||
// preferred address to be synchronous, which means we
|
||||
// have to do a sync resolve using uv_getaddrinfo here.
|
||||
return
|
||||
uv_getaddrinfo(
|
||||
env_->event_loop(),
|
||||
req,
|
||||
nullptr,
|
||||
host,
|
||||
std::to_string(port).c_str(),
|
||||
&hints) == 0 &&
|
||||
req->addrinfo != nullptr;
|
||||
}
|
||||
|
||||
StatelessResetToken::StatelessResetToken(
|
||||
uint8_t* token,
|
||||
const uint8_t* secret,
|
||||
const QuicCID& cid) : token_(token) {
|
||||
GenerateResetToken(token, secret, cid);
|
||||
}
|
||||
|
||||
StatelessResetToken::StatelessResetToken(
|
||||
const uint8_t* secret,
|
||||
const QuicCID& cid)
|
||||
: token_(buf_) {
|
||||
GenerateResetToken(buf_, secret, cid);
|
||||
}
|
||||
|
||||
std::string StatelessResetToken::ToString() const {
|
||||
std::vector<char> dest(NGTCP2_STATELESS_RESET_TOKENLEN * 2 + 1);
|
||||
dest[dest.size() - 1] = '\0';
|
||||
size_t written = StringBytes::hex_encode(
|
||||
reinterpret_cast<const char*>(token_),
|
||||
NGTCP2_STATELESS_RESET_TOKENLEN,
|
||||
dest.data(),
|
||||
dest.size());
|
||||
return std::string(dest.data(), written);
|
||||
}
|
||||
|
||||
size_t StatelessResetToken::Hash::operator()(
|
||||
const StatelessResetToken& token) const {
|
||||
size_t hash = 0;
|
||||
for (size_t n = 0; n < NGTCP2_STATELESS_RESET_TOKENLEN; n++)
|
||||
hash ^= std::hash<uint8_t>{}(token.token_[n]) + 0x9e3779b9 +
|
||||
(hash << 6) + (hash >> 2);
|
||||
return hash;
|
||||
}
|
||||
|
||||
bool StatelessResetToken::operator==(const StatelessResetToken& other) const {
|
||||
return memcmp(data(), other.data(), NGTCP2_STATELESS_RESET_TOKENLEN) == 0;
|
||||
}
|
||||
|
||||
bool StatelessResetToken::operator!=(const StatelessResetToken& other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
StatsBase<T>::StatsBase(
|
||||
Environment* env,
|
||||
v8::Local<v8::Object> wrap,
|
||||
int options) {
|
||||
static constexpr uint64_t kMax = std::numeric_limits<int64_t>::max();
|
||||
|
||||
// Create the backing store for the statistics
|
||||
size_t size = sizeof(Stats);
|
||||
size_t count = size / sizeof(uint64_t);
|
||||
stats_store_ = v8::ArrayBuffer::NewBackingStore(env->isolate(), size);
|
||||
stats_ = new (stats_store_->Data()) Stats;
|
||||
|
||||
DCHECK_NOT_NULL(stats_);
|
||||
stats_->created_at = uv_hrtime();
|
||||
|
||||
// The stats buffer is exposed as a BigUint64Array on
|
||||
// the JavaScript side to allow statistics to be monitored.
|
||||
v8::Local<v8::ArrayBuffer> stats_buffer =
|
||||
v8::ArrayBuffer::New(env->isolate(), stats_store_);
|
||||
v8::Local<v8::BigUint64Array> stats_array =
|
||||
v8::BigUint64Array::New(stats_buffer, 0, count);
|
||||
USE(wrap->DefineOwnProperty(
|
||||
env->context(),
|
||||
env->stats_string(),
|
||||
stats_array,
|
||||
v8::PropertyAttribute::ReadOnly));
|
||||
|
||||
if (options & HistogramOptions::ACK) {
|
||||
ack_ = HistogramBase::New(env, 1, kMax);
|
||||
wrap->DefineOwnProperty(
|
||||
env->context(),
|
||||
env->ack_string(),
|
||||
ack_->object(),
|
||||
v8::PropertyAttribute::ReadOnly).Check();
|
||||
}
|
||||
|
||||
if (options & HistogramOptions::RATE) {
|
||||
rate_ = HistogramBase::New(env, 1, kMax);
|
||||
wrap->DefineOwnProperty(
|
||||
env->context(),
|
||||
env->rate_string(),
|
||||
rate_->object(),
|
||||
v8::PropertyAttribute::ReadOnly).Check();
|
||||
}
|
||||
|
||||
if (options & HistogramOptions::SIZE) {
|
||||
size_ = HistogramBase::New(env, 1, kMax);
|
||||
wrap->DefineOwnProperty(
|
||||
env->context(),
|
||||
env->size_string(),
|
||||
size_->object(),
|
||||
v8::PropertyAttribute::ReadOnly).Check();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void StatsBase<T>::IncrementStat(uint64_t Stats::*member, uint64_t amount) {
|
||||
static constexpr uint64_t kMax = std::numeric_limits<uint64_t>::max();
|
||||
stats_->*member += std::min(amount, kMax - stats_->*member);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void StatsBase<T>::SetStat(uint64_t Stats::*member, uint64_t value) {
|
||||
stats_->*member = value;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void StatsBase<T>::RecordTimestamp(uint64_t Stats::*member) {
|
||||
stats_->*member = uv_hrtime();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
uint64_t StatsBase<T>::GetStat(uint64_t Stats::*member) const {
|
||||
return stats_->*member;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline void StatsBase<T>::RecordRate(uint64_t Stats::*member) {
|
||||
CHECK(rate_);
|
||||
uint64_t received_at = GetStat(member);
|
||||
uint64_t now = uv_hrtime();
|
||||
if (received_at > 0)
|
||||
rate_->Record(now - received_at);
|
||||
SetStat(member, now);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline void StatsBase<T>::RecordSize(uint64_t val) {
|
||||
CHECK(size_);
|
||||
size_->Record(val);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline void StatsBase<T>::RecordAck(uint64_t Stats::*member) {
|
||||
CHECK(ack_);
|
||||
uint64_t acked_at = GetStat(member);
|
||||
uint64_t now = uv_hrtime();
|
||||
if (acked_at > 0)
|
||||
ack_->Record(now - acked_at);
|
||||
SetStat(member, now);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void StatsBase<T>::StatsMemoryInfo(MemoryTracker* tracker) const {
|
||||
tracker->TrackField("stats_store", stats_store_);
|
||||
tracker->TrackField("rate_histogram", rate_);
|
||||
tracker->TrackField("size_histogram", size_);
|
||||
tracker->TrackField("ack_histogram", ack_);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void StatsBase<T>::DebugStats() {
|
||||
StatsDebug stats_debug(static_cast<typename T::Base*>(this));
|
||||
Debug(static_cast<typename T::Base*>(this), "Destroyed. %s", stats_debug);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::string StatsBase<T>::StatsDebug::ToString() const {
|
||||
std::string out = "Statistics:\n";
|
||||
auto add_field = [&out](const char* name, uint64_t val) {
|
||||
out += " ";
|
||||
out += std::string(name);
|
||||
out += ": ";
|
||||
out += std::to_string(val);
|
||||
out += "\n";
|
||||
};
|
||||
add_field("Duration", uv_hrtime() - ptr->GetStat(&Stats::created_at));
|
||||
T::ToString(*ptr, add_field);
|
||||
return out;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
size_t get_length(const T* vec, size_t count) {
|
||||
CHECK_NOT_NULL(vec);
|
||||
size_t len = 0;
|
||||
for (size_t n = 0; n < count; n++)
|
||||
len += vec[n].len;
|
||||
return len;
|
||||
}
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_UTIL_INL_H_
|
||||
@@ -0,0 +1,428 @@
|
||||
#ifndef SRC_QUIC_NODE_QUIC_UTIL_H_
|
||||
#define SRC_QUIC_NODE_QUIC_UTIL_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include "node.h"
|
||||
#include "node_sockaddr.h"
|
||||
#include "uv.h"
|
||||
#include "v8.h"
|
||||
#include "histogram.h"
|
||||
#include "memory_tracker.h"
|
||||
|
||||
#include <ngtcp2/ngtcp2.h>
|
||||
#include <openssl/ssl.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace node {
|
||||
namespace quic {
|
||||
|
||||
// k-constants are used internally, all-caps constants
|
||||
// are exposed to javascript as constants (see node_quic.cc)
|
||||
|
||||
constexpr size_t kMaxSizeT = std::numeric_limits<size_t>::max();
|
||||
constexpr size_t kMaxValidateAddressLru = 10;
|
||||
constexpr size_t kMinInitialQuicPktSize = 1200;
|
||||
constexpr size_t kScidLen = NGTCP2_MAX_CIDLEN;
|
||||
constexpr size_t kTokenRandLen = 16;
|
||||
constexpr size_t kTokenSecretLen = 16;
|
||||
|
||||
constexpr uint64_t DEFAULT_ACTIVE_CONNECTION_ID_LIMIT = 2;
|
||||
constexpr uint64_t DEFAULT_MAX_CONNECTIONS =
|
||||
std::min<uint64_t>(kMaxSizeT, kMaxSafeJsInteger);
|
||||
constexpr uint64_t DEFAULT_MAX_CONNECTIONS_PER_HOST = 100;
|
||||
constexpr uint64_t DEFAULT_MAX_STREAM_DATA_BIDI_LOCAL = 256 * 1024;
|
||||
constexpr uint64_t DEFAULT_MAX_STREAM_DATA_BIDI_REMOTE = 256 * 1024;
|
||||
constexpr uint64_t DEFAULT_MAX_STREAM_DATA_UNI = 256 * 1024;
|
||||
constexpr uint64_t DEFAULT_MAX_DATA = 1 * 1024 * 1024;
|
||||
constexpr uint64_t DEFAULT_MAX_STATELESS_RESETS_PER_HOST = 10;
|
||||
constexpr uint64_t DEFAULT_MAX_STREAMS_BIDI = 100;
|
||||
constexpr uint64_t DEFAULT_MAX_STREAMS_UNI = 3;
|
||||
constexpr uint64_t DEFAULT_MAX_IDLE_TIMEOUT = 10;
|
||||
constexpr uint64_t DEFAULT_RETRYTOKEN_EXPIRATION = 10;
|
||||
constexpr uint64_t MIN_RETRYTOKEN_EXPIRATION = 1;
|
||||
constexpr uint64_t MAX_RETRYTOKEN_EXPIRATION = 60;
|
||||
constexpr uint64_t NGTCP2_APP_NOERROR = 0xff00;
|
||||
|
||||
constexpr int ERR_FAILED_TO_CREATE_SESSION = -1;
|
||||
|
||||
// The preferred address policy determines how a client QuicSession
|
||||
// handles a server-advertised preferred address. As suggested, the
|
||||
// preferred address is the address the server would prefer the
|
||||
// client to use for subsequent communication for a QuicSession.
|
||||
// The client may choose to ignore the preference but really shouldn't
|
||||
// without good reason. We currently only support two options but
|
||||
// additional options may be added later.
|
||||
enum SelectPreferredAddressPolicy : int {
|
||||
// Ignore the server-provided preferred address
|
||||
QUIC_PREFERRED_ADDRESS_IGNORE,
|
||||
|
||||
// Use the server-provided preferred address.
|
||||
// With this policy in effect, when a client
|
||||
// receives a preferred address from the server,
|
||||
// the client QuicSession will be automatically
|
||||
// switched to use the selected address if it
|
||||
// matches the current local address family.
|
||||
QUIC_PREFERRED_ADDRESS_USE
|
||||
};
|
||||
|
||||
// QUIC error codes generally fall into two distinct namespaces:
|
||||
// Connection Errors and Application Errors. Connection errors
|
||||
// are further subdivided into Crypto and non-Crypto. Application
|
||||
// errors are entirely specific to the QUIC application being
|
||||
// used. An easy rule of thumb is that Application errors are
|
||||
// semantically associated with the ALPN identifier negotiated
|
||||
// for the QuicSession. So, if a connection is closed with
|
||||
// family: QUIC_ERROR_APPLICATION and code: 123, you have to
|
||||
// look at the ALPN identifier to determine exactly what it
|
||||
// means. Connection (Session) and Crypto errors, on the other
|
||||
// hand, share the same meaning regardless of the ALPN.
|
||||
enum QuicErrorFamily : int32_t {
|
||||
QUIC_ERROR_SESSION,
|
||||
QUIC_ERROR_CRYPTO,
|
||||
QUIC_ERROR_APPLICATION
|
||||
};
|
||||
|
||||
|
||||
template <typename T> class StatsBase;
|
||||
|
||||
template <typename T, typename Q>
|
||||
struct StatsTraits {
|
||||
using Stats = T;
|
||||
using Base = Q;
|
||||
|
||||
template <typename Fn>
|
||||
static void ToString(const Q& ptr, Fn&& add_field);
|
||||
};
|
||||
|
||||
// StatsBase is a utility help for classes (like QuicSession)
|
||||
// that record performance statistics. The template takes a
|
||||
// single Traits argument (see QuicStreamStatsTraits in
|
||||
// node_quic_stream.h as an example). When the StatsBase
|
||||
// is deconstructed, collected statistics are output to
|
||||
// Debug automatically.
|
||||
template <typename T>
|
||||
class StatsBase {
|
||||
public:
|
||||
typedef typename T::Stats Stats;
|
||||
|
||||
// A StatsBase instance may have one of three histogram
|
||||
// instances. One that records rate of data flow, one
|
||||
// that records size of data chunk, and one that records
|
||||
// rate of data ackwowledgement. These may be used in
|
||||
// slightly different ways of different StatsBase
|
||||
// instances or may be turned off entirely.
|
||||
enum HistogramOptions {
|
||||
NONE = 0,
|
||||
RATE = 1,
|
||||
SIZE = 2,
|
||||
ACK = 4
|
||||
};
|
||||
|
||||
inline StatsBase(
|
||||
Environment* env,
|
||||
v8::Local<v8::Object> wrap,
|
||||
int options = HistogramOptions::NONE);
|
||||
|
||||
inline ~StatsBase() { if (stats_ != nullptr) stats_->~Stats(); }
|
||||
|
||||
// The StatsDebug utility is used when StatsBase is destroyed
|
||||
// to output statistical information to Debug. It is designed
|
||||
// to only incur a performance cost constructing the debug
|
||||
// output when Debug output is enabled.
|
||||
struct StatsDebug {
|
||||
typename T::Base* ptr;
|
||||
explicit StatsDebug(typename T::Base* ptr_) : ptr(ptr_) {}
|
||||
std::string ToString() const;
|
||||
};
|
||||
|
||||
// Increments the given stat field by the given amount or 1 if
|
||||
// no amount is specified.
|
||||
inline void IncrementStat(uint64_t Stats::*member, uint64_t amount = 1);
|
||||
|
||||
// Sets an entirely new value for the given stat field
|
||||
inline void SetStat(uint64_t Stats::*member, uint64_t value);
|
||||
|
||||
// Sets the given stat field to the current uv_hrtime()
|
||||
inline void RecordTimestamp(uint64_t Stats::*member);
|
||||
|
||||
// Gets the current value of the given stat field
|
||||
inline uint64_t GetStat(uint64_t Stats::*member) const;
|
||||
|
||||
// If the rate histogram is used, records the time elapsed
|
||||
// between now and the timestamp specified by the member
|
||||
// field.
|
||||
inline void RecordRate(uint64_t Stats::*member);
|
||||
|
||||
// If the size histogram is used, records the given size.
|
||||
inline void RecordSize(uint64_t val);
|
||||
|
||||
// If the ack rate histogram is used, records the time
|
||||
// elapsed between now and the timestamp specified by
|
||||
// the member field.
|
||||
inline void RecordAck(uint64_t Stats::*member);
|
||||
|
||||
inline void StatsMemoryInfo(MemoryTracker* tracker) const;
|
||||
|
||||
inline void DebugStats();
|
||||
|
||||
private:
|
||||
BaseObjectPtr<HistogramBase> rate_;
|
||||
BaseObjectPtr<HistogramBase> size_;
|
||||
BaseObjectPtr<HistogramBase> ack_;
|
||||
std::shared_ptr<v8::BackingStore> stats_store_;
|
||||
Stats* stats_ = nullptr;
|
||||
};
|
||||
|
||||
// PreferredAddress is a helper class used only when a client QuicSession
|
||||
// receives an advertised preferred address from a server. The helper provides
|
||||
// information about the preferred address. The Use() function is used to let
|
||||
// ngtcp2 know to use the preferred address for the given family.
|
||||
class PreferredAddress {
|
||||
public:
|
||||
PreferredAddress(
|
||||
Environment* env,
|
||||
ngtcp2_addr* dest,
|
||||
const ngtcp2_preferred_addr* paddr) :
|
||||
env_(env),
|
||||
dest_(dest),
|
||||
paddr_(paddr) {}
|
||||
|
||||
// When a preferred address is advertised by a server, the
|
||||
// advertisement also includes a new CID and (optionally)
|
||||
// a stateless reset token. If the preferred address is
|
||||
// selected, then the client QuicSession will make use of
|
||||
// these new values. Access to the cid and reset token
|
||||
// are provided via the PreferredAddress class only as a
|
||||
// convenience.
|
||||
inline const ngtcp2_cid* cid() const;
|
||||
|
||||
// The stateless reset token associated with the preferred
|
||||
// address CID
|
||||
inline const uint8_t* stateless_reset_token() const;
|
||||
|
||||
// A preferred address advertisement may include both an
|
||||
// IPv4 and IPv6 address. Only one of which will be used.
|
||||
|
||||
inline std::string ipv4_address() const;
|
||||
|
||||
inline uint16_t ipv4_port() const;
|
||||
|
||||
inline std::string ipv6_address() const;
|
||||
|
||||
inline uint16_t ipv6_port() const;
|
||||
|
||||
// Instructs the QuicSession to use the advertised
|
||||
// preferred address matching the given family. If
|
||||
// the advertisement does not include a matching
|
||||
// address, the preferred address is ignored.
|
||||
inline bool Use(int family = AF_INET) const;
|
||||
|
||||
private:
|
||||
inline bool ResolvePreferredAddress(
|
||||
int local_address_family,
|
||||
uv_getaddrinfo_t* req) const;
|
||||
|
||||
Environment* env_;
|
||||
mutable ngtcp2_addr* dest_;
|
||||
const ngtcp2_preferred_addr* paddr_;
|
||||
};
|
||||
|
||||
// QuicError is a helper class used to encapsulate basic
|
||||
// details about a QUIC protocol error. There are three
|
||||
// basic types of errors (see QuicErrorFamily)
|
||||
struct QuicError {
|
||||
int32_t family;
|
||||
uint64_t code;
|
||||
inline QuicError(
|
||||
int32_t family_ = QUIC_ERROR_SESSION,
|
||||
int code_ = NGTCP2_NO_ERROR);
|
||||
inline QuicError(
|
||||
int32_t family_ = QUIC_ERROR_SESSION,
|
||||
uint64_t code_ = NGTCP2_NO_ERROR);
|
||||
explicit inline QuicError(ngtcp2_connection_close_error_code code);
|
||||
inline QuicError(
|
||||
Environment* env,
|
||||
v8::Local<v8::Value> codeArg,
|
||||
v8::Local<v8::Value> familyArg = v8::Local<v8::Object>(),
|
||||
int32_t family_ = QUIC_ERROR_SESSION);
|
||||
inline const char* family_name();
|
||||
};
|
||||
|
||||
// Helper function that returns the maximum QUIC packet size for
|
||||
// the given socket address.
|
||||
inline size_t GetMaxPktLen(const SocketAddress& addr);
|
||||
|
||||
// QuicPath is a utility class that wraps ngtcp2_path to adapt
|
||||
// it to work with SocketAddress
|
||||
struct QuicPath : public ngtcp2_path {
|
||||
inline QuicPath(const SocketAddress& local, const SocketAddress& remote);
|
||||
};
|
||||
|
||||
struct QuicPathStorage : public ngtcp2_path_storage {
|
||||
QuicPathStorage() {
|
||||
ngtcp2_path_storage_zero(this);
|
||||
}
|
||||
};
|
||||
|
||||
// Simple wrapper for ngtcp2_cid that handles hex encoding
|
||||
// CIDs are used to identify QuicSession instances and may
|
||||
// be between 0 and 20 bytes in length.
|
||||
class QuicCID : public MemoryRetainer {
|
||||
public:
|
||||
// Empty constructor
|
||||
QuicCID() : ptr_(&cid_) {}
|
||||
|
||||
// Copy constructor
|
||||
QuicCID(const QuicCID& cid) : QuicCID(cid->data, cid->datalen) {}
|
||||
|
||||
// Copy constructor
|
||||
explicit QuicCID(const ngtcp2_cid& cid) : QuicCID(cid.data, cid.datalen) {}
|
||||
|
||||
// Wrap constructor
|
||||
explicit QuicCID(const ngtcp2_cid* cid) : ptr_(cid) {}
|
||||
|
||||
QuicCID(const uint8_t* cid, size_t len) : QuicCID() {
|
||||
ngtcp2_cid* ptr = this->cid();
|
||||
ngtcp2_cid_init(ptr, cid, len);
|
||||
ptr_ = ptr;
|
||||
}
|
||||
|
||||
struct Hash {
|
||||
inline size_t operator()(const QuicCID& cid) const;
|
||||
};
|
||||
|
||||
inline bool operator==(const QuicCID& other) const;
|
||||
inline bool operator!=(const QuicCID& other) const;
|
||||
inline QuicCID& operator=(const QuicCID& cid);
|
||||
const ngtcp2_cid& operator*() const { return *ptr_; }
|
||||
const ngtcp2_cid* operator->() const { return ptr_; }
|
||||
|
||||
inline std::string ToString() const;
|
||||
|
||||
const ngtcp2_cid* cid() const { return ptr_; }
|
||||
|
||||
const uint8_t* data() const { return ptr_->data; }
|
||||
|
||||
operator bool() const { return ptr_->datalen > 0; }
|
||||
|
||||
size_t length() const { return ptr_->datalen; }
|
||||
|
||||
ngtcp2_cid* cid() {
|
||||
CHECK_EQ(ptr_, &cid_);
|
||||
return &cid_;
|
||||
}
|
||||
|
||||
unsigned char* data() {
|
||||
return reinterpret_cast<unsigned char*>(cid()->data);
|
||||
}
|
||||
|
||||
void set_length(size_t length) {
|
||||
cid()->datalen = length;
|
||||
}
|
||||
|
||||
SET_NO_MEMORY_INFO()
|
||||
SET_MEMORY_INFO_NAME(QuicCID)
|
||||
SET_SELF_SIZE(QuicCID)
|
||||
|
||||
template <typename T>
|
||||
using Map = std::unordered_map<QuicCID, T, QuicCID::Hash>;
|
||||
|
||||
private:
|
||||
ngtcp2_cid cid_{};
|
||||
const ngtcp2_cid* ptr_;
|
||||
};
|
||||
|
||||
// Simple timer wrapper that is used to implement the internals
|
||||
// for idle and retransmission timeouts. Call Update to start or
|
||||
// reset the timer; Stop to halt the timer.
|
||||
class Timer final : public MemoryRetainer {
|
||||
public:
|
||||
inline explicit Timer(Environment* env, std::function<void()> fn);
|
||||
|
||||
// Stops the timer with the side effect of the timer no longer being usable.
|
||||
// It will be cleaned up and the Timer object will be destroyed.
|
||||
inline void Stop();
|
||||
|
||||
// If the timer is not currently active, interval must be either 0 or greater.
|
||||
// If the timer is already active, interval is ignored.
|
||||
inline void Update(uint64_t interval);
|
||||
|
||||
static inline void Free(Timer* timer);
|
||||
|
||||
SET_NO_MEMORY_INFO()
|
||||
SET_MEMORY_INFO_NAME(Timer)
|
||||
SET_SELF_SIZE(Timer)
|
||||
|
||||
private:
|
||||
static inline void OnTimeout(uv_timer_t* timer);
|
||||
|
||||
bool stopped_ = false;
|
||||
Environment* env_;
|
||||
std::function<void()> fn_;
|
||||
uv_timer_t timer_;
|
||||
};
|
||||
|
||||
using TimerPointer = DeleteFnPtr<Timer, Timer::Free>;
|
||||
|
||||
// A Stateless Reset Token is a mechanism by which a QUIC
|
||||
// endpoint can discreetly signal to a peer that it has
|
||||
// lost all state associated with a connection. This
|
||||
// helper class is used to both store received tokens and
|
||||
// provide storage when creating new tokens to send.
|
||||
class StatelessResetToken : public MemoryRetainer {
|
||||
public:
|
||||
inline StatelessResetToken(
|
||||
uint8_t* token,
|
||||
const uint8_t* secret,
|
||||
const QuicCID& cid);
|
||||
|
||||
inline StatelessResetToken(
|
||||
const uint8_t* secret,
|
||||
const QuicCID& cid);
|
||||
|
||||
explicit StatelessResetToken(
|
||||
const uint8_t* token)
|
||||
: token_(token) {}
|
||||
|
||||
inline std::string ToString() const;
|
||||
|
||||
const uint8_t* data() const { return token_; }
|
||||
|
||||
struct Hash {
|
||||
inline size_t operator()(const StatelessResetToken& token) const;
|
||||
};
|
||||
|
||||
inline bool operator==(const StatelessResetToken& other) const;
|
||||
inline bool operator!=(const StatelessResetToken& other) const;
|
||||
|
||||
SET_NO_MEMORY_INFO()
|
||||
SET_MEMORY_INFO_NAME(StatelessResetToken)
|
||||
SET_SELF_SIZE(StatelessResetToken)
|
||||
|
||||
template <typename T>
|
||||
using Map =
|
||||
std::unordered_map<
|
||||
StatelessResetToken,
|
||||
BaseObjectPtr<T>,
|
||||
StatelessResetToken::Hash>;
|
||||
|
||||
private:
|
||||
uint8_t buf_[NGTCP2_STATELESS_RESET_TOKENLEN]{};
|
||||
const uint8_t* token_;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
inline size_t get_length(const T*, size_t len);
|
||||
|
||||
} // namespace quic
|
||||
} // namespace node
|
||||
|
||||
#endif // NOE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_QUIC_NODE_QUIC_UTIL_H_
|
||||
@@ -201,6 +201,7 @@ void UDPWrap::Initialize(Local<Object> target,
|
||||
|
||||
Local<Object> constants = Object::New(env->isolate());
|
||||
NODE_DEFINE_CONSTANT(constants, UV_UDP_IPV6ONLY);
|
||||
NODE_DEFINE_CONSTANT(constants, UV_UDP_REUSEADDR);
|
||||
target->Set(context,
|
||||
env->constants_string(),
|
||||
constants).Check();
|
||||
|
||||
+10
@@ -331,6 +331,11 @@ constexpr size_t arraysize(const T (&)[N]) {
|
||||
return N;
|
||||
}
|
||||
|
||||
template <typename T, size_t N>
|
||||
constexpr size_t strsize(const T (&)[N]) {
|
||||
return N - 1;
|
||||
}
|
||||
|
||||
// Allocates an array of member type T. For up to kStackStorageSize items,
|
||||
// the stack is used, otherwise malloc().
|
||||
template <typename T, size_t kStackStorageSize = 1024>
|
||||
@@ -564,6 +569,11 @@ struct MallocedBuffer {
|
||||
size = new_size;
|
||||
}
|
||||
|
||||
void Realloc(size_t new_size) {
|
||||
Truncate(new_size);
|
||||
data = UncheckedRealloc(data, new_size);
|
||||
}
|
||||
|
||||
inline bool is_empty() const { return data == nullptr; }
|
||||
|
||||
MallocedBuffer() : data(nullptr), size(0) {}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
#include "quic/node_quic_buffer-inl.h"
|
||||
#include "node_bob-inl.h"
|
||||
#include "util-inl.h"
|
||||
#include "uv.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
using node::quic::QuicBuffer;
|
||||
using node::quic::QuicBufferChunk;
|
||||
using node::bob::Status;
|
||||
using node::bob::Options;
|
||||
using node::bob::Done;
|
||||
using ::testing::AssertionSuccess;
|
||||
using ::testing::AssertionFailure;
|
||||
|
||||
::testing::AssertionResult IsEqual(size_t actual, int expected) {
|
||||
return (static_cast<size_t>(expected) == actual) ? AssertionSuccess() :
|
||||
AssertionFailure() << actual << " is not equal to " << expected;
|
||||
}
|
||||
|
||||
TEST(QuicBuffer, Simple) {
|
||||
char data[100];
|
||||
memset(&data, 0, node::arraysize(data));
|
||||
uv_buf_t buf = uv_buf_init(data, node::arraysize(data));
|
||||
|
||||
bool done = false;
|
||||
|
||||
QuicBuffer buffer;
|
||||
buffer.Push(&buf, 1, [&](int status) {
|
||||
EXPECT_EQ(0, status);
|
||||
done = true;
|
||||
});
|
||||
|
||||
buffer.Consume(100);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 0));
|
||||
|
||||
// We have to move the read head forward in order to consume
|
||||
buffer.Seek(1);
|
||||
buffer.Consume(100);
|
||||
ASSERT_TRUE(done);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 0));
|
||||
}
|
||||
|
||||
TEST(QuicBuffer, ConsumeMore) {
|
||||
char data[100];
|
||||
memset(&data, 0, node::arraysize(data));
|
||||
uv_buf_t buf = uv_buf_init(data, node::arraysize(data));
|
||||
|
||||
bool done = false;
|
||||
|
||||
QuicBuffer buffer;
|
||||
buffer.Push(&buf, 1, [&](int status) {
|
||||
EXPECT_EQ(0, status);
|
||||
done = true;
|
||||
});
|
||||
|
||||
buffer.Seek(1);
|
||||
buffer.Consume(150); // Consume more than what was buffered
|
||||
ASSERT_TRUE(done);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 0));
|
||||
}
|
||||
|
||||
TEST(QuicBuffer, Multiple) {
|
||||
uv_buf_t bufs[] {
|
||||
uv_buf_init(const_cast<char*>("abcdefghijklmnopqrstuvwxyz"), 26),
|
||||
uv_buf_init(const_cast<char*>("zyxwvutsrqponmlkjihgfedcba"), 26)
|
||||
};
|
||||
|
||||
QuicBuffer buf;
|
||||
bool done = false;
|
||||
buf.Push(bufs, 2, [&](int status) { done = true; });
|
||||
|
||||
buf.Seek(2);
|
||||
ASSERT_TRUE(IsEqual(buf.remaining(), 50));
|
||||
ASSERT_TRUE(IsEqual(buf.length(), 52));
|
||||
|
||||
buf.Consume(25);
|
||||
ASSERT_TRUE(IsEqual(buf.length(), 27));
|
||||
|
||||
buf.Consume(25);
|
||||
ASSERT_TRUE(IsEqual(buf.length(), 2));
|
||||
|
||||
buf.Consume(2);
|
||||
ASSERT_TRUE(IsEqual(buf.length(), 0));
|
||||
}
|
||||
|
||||
TEST(QuicBuffer, Multiple2) {
|
||||
char* ptr = new char[100];
|
||||
memset(ptr, 0, 50);
|
||||
memset(ptr + 50, 1, 50);
|
||||
|
||||
uv_buf_t bufs[] = {
|
||||
uv_buf_init(ptr, 50),
|
||||
uv_buf_init(ptr + 50, 50)
|
||||
};
|
||||
|
||||
int count = 0;
|
||||
|
||||
QuicBuffer buffer;
|
||||
buffer.Push(
|
||||
bufs, node::arraysize(bufs),
|
||||
[&](int status) {
|
||||
count++;
|
||||
ASSERT_EQ(0, status);
|
||||
delete[] ptr;
|
||||
});
|
||||
buffer.Seek(node::arraysize(bufs));
|
||||
|
||||
buffer.Consume(25);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 75));
|
||||
buffer.Consume(25);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 50));
|
||||
buffer.Consume(25);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 25));
|
||||
buffer.Consume(25);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 0));
|
||||
|
||||
// The callback was only called once tho
|
||||
ASSERT_EQ(1, count);
|
||||
}
|
||||
|
||||
TEST(QuicBuffer, Cancel) {
|
||||
char* ptr = new char[100];
|
||||
memset(ptr, 0, 50);
|
||||
memset(ptr + 50, 1, 50);
|
||||
|
||||
uv_buf_t bufs[] = {
|
||||
uv_buf_init(ptr, 50),
|
||||
uv_buf_init(ptr + 50, 50)
|
||||
};
|
||||
|
||||
int count = 0;
|
||||
|
||||
QuicBuffer buffer;
|
||||
buffer.Push(
|
||||
bufs, node::arraysize(bufs),
|
||||
[&](int status) {
|
||||
count++;
|
||||
ASSERT_EQ(UV_ECANCELED, status);
|
||||
delete[] ptr;
|
||||
});
|
||||
|
||||
buffer.Seek(1);
|
||||
buffer.Consume(25);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 75));
|
||||
buffer.Cancel();
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 0));
|
||||
|
||||
// The callback was only called once tho
|
||||
ASSERT_EQ(1, count);
|
||||
}
|
||||
|
||||
TEST(QuicBuffer, Move) {
|
||||
QuicBuffer buffer1;
|
||||
QuicBuffer buffer2;
|
||||
|
||||
char data[100];
|
||||
memset(&data, 0, node::arraysize(data));
|
||||
uv_buf_t buf = uv_buf_init(data, node::arraysize(data));
|
||||
|
||||
buffer1.Push(&buf, 1);
|
||||
|
||||
ASSERT_TRUE(IsEqual(buffer1.length(), 100));
|
||||
|
||||
buffer2 = std::move(buffer1);
|
||||
ASSERT_TRUE(IsEqual(buffer1.length(), 0));
|
||||
ASSERT_TRUE(IsEqual(buffer2.length(), 100));
|
||||
}
|
||||
|
||||
TEST(QuicBuffer, QuicBufferChunk) {
|
||||
std::unique_ptr<QuicBufferChunk> chunk =
|
||||
std::make_unique<QuicBufferChunk>(100);
|
||||
memset(chunk->out(), 1, 100);
|
||||
|
||||
QuicBuffer buffer;
|
||||
buffer.Push(std::move(chunk));
|
||||
buffer.End();
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 100));
|
||||
|
||||
auto next = [&](
|
||||
int status,
|
||||
const ngtcp2_vec* data,
|
||||
size_t count,
|
||||
Done done) {
|
||||
ASSERT_EQ(status, Status::STATUS_END);
|
||||
ASSERT_TRUE(IsEqual(count, 1));
|
||||
ASSERT_NE(data, nullptr);
|
||||
done(100);
|
||||
};
|
||||
|
||||
ASSERT_TRUE(IsEqual(buffer.remaining(), 100));
|
||||
|
||||
ngtcp2_vec data[2];
|
||||
size_t len = sizeof(data) / sizeof(ngtcp2_vec);
|
||||
buffer.Pull(next, Options::OPTIONS_SYNC | Options::OPTIONS_END, data, len);
|
||||
|
||||
ASSERT_TRUE(IsEqual(buffer.remaining(), 0));
|
||||
|
||||
buffer.Consume(50);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 50));
|
||||
|
||||
buffer.Consume(50);
|
||||
ASSERT_TRUE(IsEqual(buffer.length(), 0));
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "quic/node_quic_util-inl.h"
|
||||
#include "node_sockaddr-inl.h"
|
||||
#include "util-inl.h"
|
||||
#include "ngtcp2/ngtcp2.h"
|
||||
#include "gtest/gtest.h"
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
using node::quic::QuicCID;
|
||||
|
||||
TEST(QuicCID, Simple) {
|
||||
ngtcp2_cid cid1;
|
||||
ngtcp2_cid cid2;
|
||||
uint8_t data1[3] = { 'a', 'b', 'c' };
|
||||
uint8_t data2[4] = { 1, 2, 3, 4 };
|
||||
ngtcp2_cid_init(&cid1, data1, 3);
|
||||
ngtcp2_cid_init(&cid2, data2, 4);
|
||||
|
||||
QuicCID qcid1(cid1);
|
||||
CHECK(qcid1);
|
||||
CHECK_EQ(qcid1.length(), 3);
|
||||
CHECK_EQ(qcid1.ToString(), "616263");
|
||||
|
||||
QuicCID qcid2(cid2);
|
||||
qcid1 = qcid2;
|
||||
CHECK_EQ(qcid1.ToString(), qcid2.ToString());
|
||||
|
||||
qcid1.set_length(5);
|
||||
memset(qcid1.data(), 1, 5);
|
||||
CHECK_EQ(qcid1.ToString(), "0101010101");
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
|
||||
#include "base_object-inl.h"
|
||||
#include "quic/node_quic_crypto.h"
|
||||
#include "quic/node_quic_util-inl.h"
|
||||
#include "node_sockaddr-inl.h"
|
||||
#include "util.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#include <openssl/ssl.h>
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
using node::quic::VerifyHostnameIdentity;
|
||||
|
||||
enum altname_type {
|
||||
TYPE_DNS,
|
||||
TYPE_IP,
|
||||
TYPE_URI
|
||||
};
|
||||
|
||||
struct altname {
|
||||
altname_type type;
|
||||
const char* name;
|
||||
};
|
||||
|
||||
void ToAltNamesMap(
|
||||
const altname* names,
|
||||
size_t names_len,
|
||||
std::unordered_multimap<std::string, std::string>* map) {
|
||||
for (size_t n = 0; n < names_len; n++) {
|
||||
switch (names[n].type) {
|
||||
case TYPE_DNS:
|
||||
map->emplace("dns", names[n].name);
|
||||
continue;
|
||||
case TYPE_IP:
|
||||
map->emplace("ip", names[n].name);
|
||||
continue;
|
||||
case TYPE_URI:
|
||||
map->emplace("uri", names[n].name);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_1) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(VerifyHostnameIdentity("a.com", std::string("a.com"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_2) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(VerifyHostnameIdentity("a.com", std::string("A.com"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_3_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string("b.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_4) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(VerifyHostnameIdentity("a.com", std::string("a.com."), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_5_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string(".a.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_6_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("8.8.8.8", std::string("8.8.8.8"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_7_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "8.8.8.8");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("8.8.8.8", std::string("8.8.8.8"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_8_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("uri", "8.8.8.8");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("8.8.8.8", std::string("8.8.8.8"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_9) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("ip", "8.8.8.8");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("8.8.8.8", std::string("8.8.8.8"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_10_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("ip", "8.8.8.8/24");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("8.8.8.8", std::string("8.8.8.8"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_11) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("b.a.com", std::string("*.a.com"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_12_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("ba.com", std::string("*.a.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_13_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("\n.a.com", std::string("*.a.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_14_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "omg.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("b.a.com", std::string("*.a.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_15_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("b.a.com", std::string("b*b.a.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_16_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("b.a.com", std::string(), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_17) {
|
||||
// TODO(@jasnell): This should test multiple CN's. The code is only
|
||||
// implemented to support one. Need to fix
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("foo.com", std::string("foo.com"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_18_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string("b.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_19_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string("b.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_20) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*.co.uk");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.co.uk", std::string("b.com"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_21_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string("a.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_22_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string("b.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_23) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string("b.com"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_24) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "A.COM");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string("b.com"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_25_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.com", std::string(), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_26) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("b.a.com", std::string(), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_27_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("c.b.a.com", std::string(), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_28) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*b.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("b.a.com", std::string(), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_29) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*b.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a-cb.a.com", std::string(), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_30_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*b.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.b.a.com", std::string(), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
|
||||
TEST(QuicCrypto, BasicCN_31) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "*b.a.com");
|
||||
altnames.emplace("dns", "a.b.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.b.a.com", std::string(), altnames), 0);
|
||||
}
|
||||
|
||||
|
||||
TEST(QuicCrypto, BasicCN_32) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("uri", "a.b.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.b.a.com", std::string(), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_33_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("uri", "*.b.a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.b.a.com", std::string(), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
// // Invalid URI
|
||||
// {
|
||||
// host: 'a.b.a.com', cert: {
|
||||
// subjectaltname: 'URI:http://[a.b.a.com]/',
|
||||
// subject: {}
|
||||
// }
|
||||
// },
|
||||
|
||||
TEST(QuicCrypto, BasicCN_35_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("ip", "127.0.0.1");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("a.b.a.com", std::string(), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_36) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("ip", "127.0.0.1");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("127.0.0.1", std::string(), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_37_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("ip", "127.0.0.1");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("127.0.0.2", std::string(), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_38_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("127.0.0.1", std::string(), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_39_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
altnames.emplace("dns", "a.com");
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity("localhost", std::string("localhost"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_40) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity(
|
||||
"xn--bcher-kva.example.com",
|
||||
std::string("*.example.com"), altnames), 0);
|
||||
}
|
||||
|
||||
TEST(QuicCrypto, BasicCN_41_Fail) {
|
||||
std::unordered_multimap<std::string, std::string> altnames;
|
||||
CHECK_EQ(
|
||||
VerifyHostnameIdentity(
|
||||
"xn--bcher-kva.example.com",
|
||||
std::string("xn--*.example.com"), altnames),
|
||||
X509_V_ERR_HOSTNAME_MISMATCH);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ This directory contains modules used to test the Node.js implementation.
|
||||
* [Report module](#report-module)
|
||||
* [tick module](#tick-module)
|
||||
* [tmpdir module](#tmpdir-module)
|
||||
* [UDP pair helper](#udp-pair-helper)
|
||||
* [WPT module](#wpt-module)
|
||||
|
||||
## Benchmark Module
|
||||
|
||||
@@ -20,9 +20,14 @@ function readFixtureKey(name, enc) {
|
||||
return fs.readFileSync(fixturesPath('keys', name), enc);
|
||||
}
|
||||
|
||||
function readFixtureKeys(enc, ...names) {
|
||||
return names.map((name) => readFixtureKey(name, enc));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
fixturesDir,
|
||||
path: fixturesPath,
|
||||
readSync: readFixtureSync,
|
||||
readKey: readFixtureKey
|
||||
readKey: readFixtureKey,
|
||||
readKeys: readFixtureKeys,
|
||||
};
|
||||
@@ -50,6 +50,7 @@ const noop = () => {};
|
||||
|
||||
const hasCrypto = Boolean(process.versions.openssl) &&
|
||||
!process.env.NODE_SKIP_CRYPTO;
|
||||
const hasQuic = hasCrypto && Boolean(process.versions.ngtcp2);
|
||||
|
||||
// Check for flags. Skip this for workers (both, the `cluster` module and
|
||||
// `worker_threads`) and child processes.
|
||||
@@ -675,6 +676,7 @@ const common = {
|
||||
getTTYfd,
|
||||
hasIntl,
|
||||
hasCrypto,
|
||||
hasQuic,
|
||||
hasMultiLocalhost,
|
||||
invalidArgTypeHelper,
|
||||
isAIX,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/* eslint-disable node-core/require-common-first, node-core/required-modules */
|
||||
'use strict';
|
||||
|
||||
// Common bits for all QUIC-related tests
|
||||
const { debuglog } = require('util');
|
||||
const { readKeys } = require('./fixtures');
|
||||
const { createWriteStream } = require('fs');
|
||||
const kHttp3Alpn = 'h3-27';
|
||||
|
||||
const [ key, cert, ca ] =
|
||||
readKeys(
|
||||
'binary',
|
||||
'agent1-key.pem',
|
||||
'agent1-cert.pem',
|
||||
'ca1-cert.pem');
|
||||
|
||||
const debug = debuglog('test');
|
||||
|
||||
const kServerPort = process.env.NODE_DEBUG_KEYLOG ? 5678 : 0;
|
||||
const kClientPort = process.env.NODE_DEBUG_KEYLOG ? 5679 : 0;
|
||||
|
||||
function setupKeylog(session) {
|
||||
if (process.env.NODE_DEBUG_KEYLOG) {
|
||||
const kl = createWriteStream(process.env.NODE_DEBUG_KEYLOG);
|
||||
session.on('keylog', kl.write.bind(kl));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug,
|
||||
kServerPort,
|
||||
kClientPort,
|
||||
setupKeylog,
|
||||
kHttp3Alpn,
|
||||
};
|
||||
@@ -16,6 +16,11 @@ if (common.hasIntl) {
|
||||
expected_keys.push('unicode');
|
||||
}
|
||||
|
||||
if (common.hasQuic) {
|
||||
expected_keys.push('ngtcp2');
|
||||
expected_keys.push('nghttp3');
|
||||
}
|
||||
|
||||
expected_keys.sort();
|
||||
const actual_keys = Object.keys(process.versions).sort();
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests the availability and correctness of internalBinding(quic)
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const { internalBinding } = require('internal/test/binding');
|
||||
|
||||
const quic = internalBinding('quic');
|
||||
assert(quic);
|
||||
|
||||
assert(quic.constants);
|
||||
|
||||
// Version numbers used to identify IETF drafts are created by
|
||||
// adding the draft number to 0xff0000, in this case 19 (25).
|
||||
assert.strictEqual(quic.constants.NGTCP2_PROTO_VER.toString(16), 'ff00001b');
|
||||
assert.strictEqual(quic.constants.NGTCP2_ALPN_H3, '\u0005h3-27');
|
||||
|
||||
// The following just tests for the presence of things we absolutely need.
|
||||
// They don't test the functionality of those things.
|
||||
|
||||
assert(quic.sessionConfig instanceof Float64Array);
|
||||
assert(quic.http3Config instanceof Float64Array);
|
||||
|
||||
assert(quic.QuicSocket);
|
||||
assert(quic.QuicEndpoint);
|
||||
assert(quic.QuicStream);
|
||||
|
||||
assert.strictEqual(typeof quic.createClientSession, 'function');
|
||||
assert.strictEqual(typeof quic.openBidirectionalStream, 'function');
|
||||
assert.strictEqual(typeof quic.openUnidirectionalStream, 'function');
|
||||
assert.strictEqual(typeof quic.setCallbacks, 'function');
|
||||
assert.strictEqual(typeof quic.initSecureContext, 'function');
|
||||
assert.strictEqual(typeof quic.initSecureContextClient, 'function');
|
||||
assert.strictEqual(typeof quic.silentCloseSession, 'function');
|
||||
@@ -0,0 +1,57 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
// Test that .connect() can be called multiple times with different servers.
|
||||
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const { once } = require('events');
|
||||
|
||||
(async function() {
|
||||
const servers = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const server = createQuicSocket();
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'meow' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall(() => {
|
||||
const stream = session.openStream({ halfOpen: true });
|
||||
stream.end('Hi!');
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('close', common.mustCall());
|
||||
|
||||
servers.push(server);
|
||||
}
|
||||
|
||||
await Promise.all(servers.map((server) => once(server, 'ready')));
|
||||
|
||||
const client = createQuicSocket({ client: { key, cert, ca, alpn: 'meow' } });
|
||||
|
||||
let done = 0;
|
||||
for (const server of servers) {
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
stream.on('data', common.mustCall(
|
||||
(chk) => assert.strictEqual(chk.toString(), 'Hi!')));
|
||||
stream.on('end', common.mustCall(() => {
|
||||
server.close();
|
||||
req.close();
|
||||
if (++done === servers.length) client.close();
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
}
|
||||
})().then(common.mustCall());
|
||||
@@ -0,0 +1,56 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
// Test that .connect() can be called multiple times with different servers.
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const { once } = require('events');
|
||||
|
||||
(async function() {
|
||||
const servers = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const server = createQuicSocket();
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'meow' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall(() => {
|
||||
const stream = session.openStream({ halfOpen: true });
|
||||
stream.end('Hi!');
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('close', common.mustCall());
|
||||
|
||||
servers.push(server);
|
||||
}
|
||||
|
||||
await Promise.all(servers.map((server) => once(server, 'ready')));
|
||||
|
||||
const client = createQuicSocket({ client: { key, cert, ca, alpn: 'meow' } });
|
||||
|
||||
for (const server of servers) {
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
const [ stream ] = await once(req, 'stream');
|
||||
stream.resume();
|
||||
await once(stream, 'end');
|
||||
|
||||
server.close();
|
||||
req.close();
|
||||
await once(req, 'close');
|
||||
}
|
||||
|
||||
client.close();
|
||||
|
||||
await once(client, 'close');
|
||||
})().then(common.mustCall());
|
||||
@@ -0,0 +1,57 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// This test ensures that when we don't define `preferredAddress`
|
||||
// on the server while the `preferredAddressPolicy` on the client
|
||||
// is `accpet`, it works as expected.
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const { createQuicSocket } = require('net');
|
||||
const { once } = require('events');
|
||||
|
||||
(async () => {
|
||||
const server = createQuicSocket();
|
||||
|
||||
let client;
|
||||
const options = { key, cert, ca, alpn: 'zzz' };
|
||||
server.listen(options);
|
||||
|
||||
server.on('session', common.mustCall((serverSession) => {
|
||||
serverSession.on('stream', common.mustCall(async (stream) => {
|
||||
stream.on('data', common.mustCall((data) => {
|
||||
assert.strictEqual(data.toString('utf8'), 'hello');
|
||||
}));
|
||||
|
||||
await once(stream, 'end');
|
||||
|
||||
stream.close();
|
||||
client.close();
|
||||
server.close();
|
||||
}));
|
||||
}));
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
client = createQuicSocket({ client: options });
|
||||
|
||||
const clientSession = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
preferredAddressPolicy: 'accept',
|
||||
});
|
||||
|
||||
await once(clientSession, 'secure');
|
||||
|
||||
const stream = clientSession.openStream();
|
||||
stream.end('hello');
|
||||
|
||||
await Promise.all([
|
||||
once(stream, 'close'),
|
||||
once(client, 'close'),
|
||||
once(server, 'close')]);
|
||||
})().then(common.mustCall());
|
||||
@@ -0,0 +1,372 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests a simple QUIC client/server round-trip
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const { internalBinding } = require('internal/test/binding');
|
||||
const {
|
||||
constants: {
|
||||
NGTCP2_NO_ERROR,
|
||||
QUIC_ERROR_APPLICATION,
|
||||
}
|
||||
} = internalBinding('quic');
|
||||
|
||||
const { Buffer } = require('buffer');
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug,
|
||||
} = require('../common/quic');
|
||||
|
||||
const filedata = fs.readFileSync(__filename, { encoding: 'utf8' });
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const kStatelessResetToken =
|
||||
Buffer.from('000102030405060708090A0B0C0D0E0F', 'hex');
|
||||
|
||||
let client;
|
||||
|
||||
const server = createQuicSocket({
|
||||
validateAddress: true,
|
||||
statelessResetSecret: kStatelessResetToken
|
||||
});
|
||||
|
||||
const unidata = ['I wonder if it worked.', 'test'];
|
||||
const kServerName = 'agent2'; // Intentionally the wrong servername
|
||||
const kALPN = 'zzz'; // ALPN can be overriden to whatever we want
|
||||
|
||||
const countdown = new Countdown(2, () => {
|
||||
debug('Countdown expired. Destroying sockets');
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen({
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
requestCert: true,
|
||||
rejectUnauthorized: false,
|
||||
alpn: kALPN,
|
||||
});
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
|
||||
assert.strictEqual(session.maxStreams.bidi, 100);
|
||||
assert.strictEqual(session.maxStreams.uni, 3);
|
||||
|
||||
{
|
||||
const {
|
||||
address,
|
||||
family,
|
||||
port
|
||||
} = session.remoteAddress;
|
||||
const endpoint = client.endpoints[0].address;
|
||||
assert.strictEqual(port, endpoint.port);
|
||||
assert.strictEqual(family, endpoint.family);
|
||||
debug(`QuicServerSession Client ${family} address ${address}:${port}`);
|
||||
}
|
||||
|
||||
session.on('usePreferredAddress', common.mustNotCall());
|
||||
|
||||
session.on('clientHello', common.mustCall(
|
||||
(alpn, servername, ciphers, cb) => {
|
||||
assert.strictEqual(alpn, kALPN);
|
||||
assert.strictEqual(servername, kServerName);
|
||||
assert.strictEqual(ciphers.length, 4);
|
||||
cb();
|
||||
}));
|
||||
|
||||
session.on('OCSPRequest', common.mustCall(
|
||||
(servername, context, cb) => {
|
||||
debug('QuicServerSession received a OCSP request');
|
||||
assert.strictEqual(servername, kServerName);
|
||||
|
||||
// This will be a SecureContext. By default it will
|
||||
// be the SecureContext used to create the QuicSession.
|
||||
// If the user wishes to do something with it, it can,
|
||||
// but if it wishes to pass in a new SecureContext,
|
||||
// it can pass it in as the second argument to the
|
||||
// callback below.
|
||||
assert(context);
|
||||
debug('QuicServerSession Certificate: ', context.getCertificate());
|
||||
debug('QuicServerSession Issuer: ', context.getIssuer());
|
||||
|
||||
// The callback can be invoked asynchronously
|
||||
setImmediate(() => {
|
||||
// The first argument is a potential error,
|
||||
// in which case the session will be destroyed
|
||||
// immediately.
|
||||
// The second is an optional new SecureContext
|
||||
// The third is the ocsp response.
|
||||
// All arguments are optional
|
||||
cb(null, null, Buffer.from('hello'));
|
||||
});
|
||||
}));
|
||||
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
debug('QuicServerSession TLS Handshake Complete');
|
||||
debug(' Server name: %s', servername);
|
||||
debug(' ALPN: %s', alpn);
|
||||
debug(' Cipher: %s, %s', cipher.name, cipher.version);
|
||||
assert.strictEqual(session.servername, servername);
|
||||
assert.strictEqual(servername, kServerName);
|
||||
assert.strictEqual(session.alpnProtocol, alpn);
|
||||
|
||||
assert.strictEqual(session.getPeerCertificate().subject.CN, 'agent1');
|
||||
|
||||
assert(session.authenticated);
|
||||
assert.strictEqual(session.authenticationError, undefined);
|
||||
|
||||
const uni = session.openStream({ halfOpen: true });
|
||||
assert(uni.unidirectional);
|
||||
assert(!uni.bidirectional);
|
||||
assert(uni.serverInitiated);
|
||||
assert(!uni.clientInitiated);
|
||||
assert(!uni.pending);
|
||||
uni.write(unidata[0], common.mustCall());
|
||||
uni.end(unidata[1], common.mustCall());
|
||||
uni.on('finish', common.mustCall());
|
||||
uni.on('end', common.mustCall());
|
||||
uni.on('data', common.mustNotCall());
|
||||
uni.on('close', common.mustCall(() => {
|
||||
assert.strictEqual(uni.finalSize, 0n);
|
||||
}));
|
||||
debug('Unidirectional, Server-initiated stream %d opened', uni.id);
|
||||
}));
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
debug('Bidirectional, Client-initiated stream %d received', stream.id);
|
||||
assert.strictEqual(stream.id, 0);
|
||||
assert.strictEqual(stream.session, session);
|
||||
assert(stream.bidirectional);
|
||||
assert(!stream.unidirectional);
|
||||
assert(stream.clientInitiated);
|
||||
assert(!stream.serverInitiated);
|
||||
assert(!stream.pending);
|
||||
|
||||
const file = fs.createReadStream(__filename);
|
||||
let data = '';
|
||||
file.pipe(stream);
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('blocked', common.mustNotCall());
|
||||
stream.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
|
||||
debug('Server: min data rate: %f', stream.dataRateHistogram.min);
|
||||
debug('Server: max data rate: %f', stream.dataRateHistogram.max);
|
||||
debug('Server: data rate 50%: %f',
|
||||
stream.dataRateHistogram.percentile(50));
|
||||
debug('Server: data rate 99%: %f',
|
||||
stream.dataRateHistogram.percentile(99));
|
||||
|
||||
debug('Server: min data size: %f', stream.dataSizeHistogram.min);
|
||||
debug('Server: max data size: %f', stream.dataSizeHistogram.max);
|
||||
debug('Server: data size 50%: %f',
|
||||
stream.dataSizeHistogram.percentile(50));
|
||||
debug('Server: data size 99%: %f',
|
||||
stream.dataSizeHistogram.percentile(99));
|
||||
});
|
||||
stream.on('end', common.mustCall(() => {
|
||||
assert.strictEqual(data, filedata);
|
||||
debug('Server received expected data for stream %d', stream.id);
|
||||
}));
|
||||
stream.on('finish', common.mustCall());
|
||||
stream.on('close', common.mustCall(() => {
|
||||
assert.strictEqual(typeof stream.duration, 'bigint');
|
||||
assert.strictEqual(typeof stream.bytesReceived, 'bigint');
|
||||
assert.strictEqual(typeof stream.bytesSent, 'bigint');
|
||||
assert.strictEqual(typeof stream.maxExtendedOffset, 'bigint');
|
||||
assert.strictEqual(stream.finalSize, BigInt(filedata.length));
|
||||
}));
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall(() => {
|
||||
const {
|
||||
code,
|
||||
family
|
||||
} = session.closeCode;
|
||||
debug(`Server session closed with code ${code} (family: ${family})`);
|
||||
assert.strictEqual(code, NGTCP2_NO_ERROR);
|
||||
|
||||
const err = {
|
||||
code: 'ERR_QUICSESSION_DESTROYED',
|
||||
name: 'Error'
|
||||
};
|
||||
assert.throws(() => session.ping(), { ...err });
|
||||
assert.throws(() => session.openStream(), {
|
||||
...err,
|
||||
message: 'Cannot call openStream after a QuicSession has been destroyed'
|
||||
});
|
||||
assert.throws(() => session.updateKey(), {
|
||||
...err,
|
||||
message: 'Cannot call updateKey after a QuicSession has been destroyed'
|
||||
});
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const endpoints = server.endpoints;
|
||||
for (const endpoint of endpoints) {
|
||||
const address = endpoint.address;
|
||||
debug('Server is listening on address %s:%d',
|
||||
address.address,
|
||||
address.port);
|
||||
}
|
||||
const endpoint = endpoints[0];
|
||||
|
||||
client = createQuicSocket({ client: { key, cert, ca, alpn: kALPN }
|
||||
});
|
||||
|
||||
client.on('close', common.mustCall(() => {
|
||||
debug('Client closing. Duration', client.duration);
|
||||
debug(' Bound duration',
|
||||
client.boundDuration);
|
||||
debug(' Bytes Sent/Received: %d/%d',
|
||||
client.bytesSent,
|
||||
client.bytesReceived);
|
||||
debug(' Packets Sent/Received: %d/%d',
|
||||
client.packetsSent,
|
||||
client.packetsReceived);
|
||||
debug(' Sessions:', client.clientSessions);
|
||||
}));
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: endpoint.address.port,
|
||||
servername: kServerName,
|
||||
requestOCSP: true,
|
||||
});
|
||||
|
||||
assert.strictEqual(req.servername, kServerName);
|
||||
|
||||
req.on('usePreferredAddress', common.mustNotCall());
|
||||
|
||||
req.on('OCSPResponse', common.mustCall((response) => {
|
||||
debug(`QuicClientSession OCSP response: "${response.toString()}"`);
|
||||
assert.strictEqual(response.toString(), 'hello');
|
||||
}));
|
||||
|
||||
req.on('sessionTicket', common.mustCall((ticket, params) => {
|
||||
debug('Session ticket received');
|
||||
assert(ticket instanceof Buffer);
|
||||
assert(params instanceof Buffer);
|
||||
debug(' Ticket: %s', ticket.toString('hex'));
|
||||
debug(' Params: %s', params.toString('hex'));
|
||||
}, 2));
|
||||
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
debug('QuicClientSession TLS Handshake Complete');
|
||||
debug(' Server name: %s', servername);
|
||||
debug(' ALPN: %s', alpn);
|
||||
debug(' Cipher: %s, %s', cipher.name, cipher.version);
|
||||
assert.strictEqual(servername, kServerName);
|
||||
assert.strictEqual(req.servername, kServerName);
|
||||
assert.strictEqual(alpn, kALPN);
|
||||
assert.strictEqual(req.alpnProtocol, kALPN);
|
||||
assert(req.ephemeralKeyInfo);
|
||||
assert.strictEqual(req.getPeerCertificate().subject.CN, 'agent1');
|
||||
|
||||
debug('Client, min handshake ack: %f',
|
||||
req.handshakeAckHistogram.min);
|
||||
debug('Client, max handshake ack: %f',
|
||||
req.handshakeAckHistogram.max);
|
||||
debug('Client, min handshake rate: %f',
|
||||
req.handshakeContinuationHistogram.min);
|
||||
debug('Client, max handshake rate: %f',
|
||||
req.handshakeContinuationHistogram.max);
|
||||
|
||||
// The server's identity won't be valid because the requested
|
||||
// SNI hostname does not match the certificate used.
|
||||
debug('QuicClientSession server is %sauthenticated',
|
||||
req.authenticated ? '' : 'not ');
|
||||
assert(!req.authenticated);
|
||||
assert.throws(() => { throw req.authenticationError; }, {
|
||||
code: 'ERR_QUIC_VERIFY_HOSTNAME_MISMATCH',
|
||||
message: 'Hostname mismatch'
|
||||
});
|
||||
|
||||
{
|
||||
const {
|
||||
address,
|
||||
family,
|
||||
port
|
||||
} = req.remoteAddress;
|
||||
const endpoint = server.endpoints[0].address;
|
||||
assert.strictEqual(port, endpoint.port);
|
||||
assert.strictEqual(family, endpoint.family);
|
||||
debug(`QuicClientSession Server ${family} address ${address}:${port}`);
|
||||
}
|
||||
|
||||
const file = fs.createReadStream(__filename);
|
||||
const stream = req.openStream();
|
||||
file.pipe(stream);
|
||||
let data = '';
|
||||
stream.resume();
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('blocked', common.mustNotCall());
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('finish', common.mustCall());
|
||||
stream.on('end', common.mustCall(() => {
|
||||
assert.strictEqual(data, filedata);
|
||||
debug('Client received expected data for stream %d', stream.id);
|
||||
}));
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Bidirectional, Client-initiated stream %d closed', stream.id);
|
||||
assert.strictEqual(stream.finalSize, BigInt(filedata.length));
|
||||
countdown.dec();
|
||||
}));
|
||||
debug('Bidirectional, Client-initiated stream %d opened', stream.id);
|
||||
}));
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
debug('Unidirectional, Server-initiated stream %d received', stream.id);
|
||||
let data = '';
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('end', common.mustCall(() => {
|
||||
assert.strictEqual(data, unidata.join(''));
|
||||
debug('Client received expected data for stream %d', stream.id);
|
||||
}));
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Unidirectional, Server-initiated stream %d closed', stream.id);
|
||||
assert.strictEqual(stream.finalSize, 26n);
|
||||
countdown.dec();
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall(() => {
|
||||
const {
|
||||
code,
|
||||
family
|
||||
} = req.closeCode;
|
||||
debug(`Client session closed with code ${code} (family: ${family})`);
|
||||
assert.strictEqual(code, NGTCP2_NO_ERROR);
|
||||
assert.strictEqual(family, QUIC_ERROR_APPLICATION);
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
server.on('close', () => {
|
||||
debug('Server closing. Duration', server.duration);
|
||||
debug(' Bound duration:',
|
||||
server.boundDuration);
|
||||
debug(' Listen duration:',
|
||||
server.listenDuration);
|
||||
debug(' Bytes Sent/Received: %d/%d',
|
||||
server.bytesSent,
|
||||
server.bytesReceived);
|
||||
debug(' Packets Sent/Received: %d/%d',
|
||||
server.packetsSent,
|
||||
server.packetsReceived);
|
||||
debug(' Sessions:', server.serverSessions);
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
// Test errors thrown when openStream is called incorrectly
|
||||
// or is not permitted
|
||||
|
||||
const { createHook } = require('async_hooks');
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
// Ensure that no QUICSTREAM instances are created during the test
|
||||
createHook({
|
||||
init(id, type) {
|
||||
assert.notStrictEqual(type, 'QUICSTREAM');
|
||||
}
|
||||
}).enable();
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const options = { key, cert, ca, alpn: 'zzz', maxStreamsUni: 0 };
|
||||
const server = createQuicSocket({ server: options });
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
const countdown = new Countdown(1, () => {
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen();
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('stream', common.mustNotCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
['z', 1, {}, [], null, Infinity, 1n].forEach((i) => {
|
||||
assert.throws(
|
||||
() => req.openStream({ halfOpen: i }),
|
||||
{ code: 'ERR_INVALID_ARG_TYPE' }
|
||||
);
|
||||
});
|
||||
|
||||
['', 1n, {}, [], false, 'zebra'].forEach((defaultEncoding) => {
|
||||
assert.throws(() => req.openStream({ defaultEncoding }), {
|
||||
code: 'ERR_INVALID_ARG_VALUE'
|
||||
});
|
||||
});
|
||||
|
||||
[-1, Number.MAX_SAFE_INTEGER + 1].forEach((highWaterMark) => {
|
||||
assert.throws(() => req.openStream({ highWaterMark }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
|
||||
['a', 1n, [], {}, false].forEach((highWaterMark) => {
|
||||
assert.throws(() => req.openStream({ highWaterMark }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
req.on('ready', common.mustCall());
|
||||
req.on('secure', common.mustCall());
|
||||
|
||||
// Unidirectional streams are not allowed. openStream will succeeed
|
||||
// but the stream will be destroyed immediately. The underlying
|
||||
// QuicStream C++ handle will not be created.
|
||||
req.openStream({
|
||||
halfOpen: true,
|
||||
highWaterMark: 10,
|
||||
defaultEncoding: 'utf16le'
|
||||
}).on('error', common.expectsError({
|
||||
code: 'ERR_QUICSTREAM_OPEN_FAILED'
|
||||
})).on('error', common.mustCall(() => countdown.dec()));
|
||||
}));
|
||||
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,243 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests error and input validation checks for QuicSocket.connect()
|
||||
|
||||
const common = require('../common');
|
||||
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const { createHook } = require('async_hooks');
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
// Ensure that a QuicClientSession handle is never created during the
|
||||
// error condition tests (ensures that argument and error validation)
|
||||
// is occurring before the underlying handle is created.
|
||||
createHook({
|
||||
init(id, type) {
|
||||
assert.notStrictEqual(type, 'QUICCLIENTSESSION');
|
||||
}
|
||||
}).enable();
|
||||
|
||||
const client = createQuicSocket();
|
||||
|
||||
// Test invalid minDHSize options argument
|
||||
['test', 1n, {}, [], false].forEach((minDHSize) => {
|
||||
assert.throws(() => client.connect({ minDHSize }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid port argument option
|
||||
[-1, 'test', 1n, {}, [], NaN, false, 65536].forEach((port) => {
|
||||
assert.throws(() => client.connect({ port }), {
|
||||
code: 'ERR_SOCKET_BAD_PORT'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid address argument option
|
||||
[-1, 10, 1n, {}, [], true].forEach((address) => {
|
||||
assert.throws(() => client.connect({ address }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test servername can't be IP address argument option
|
||||
[
|
||||
'0.0.0.0',
|
||||
'8.8.8.8',
|
||||
'127.0.0.1',
|
||||
'192.168.0.1',
|
||||
'::',
|
||||
'1::',
|
||||
'::1',
|
||||
'1::8',
|
||||
'1::7:8',
|
||||
'1:2:3:4:5:6:7:8',
|
||||
'1:2:3:4:5:6::8',
|
||||
'2001:0000:1234:0000:0000:C1C0:ABCD:0876',
|
||||
'3ffe:0b00:0000:0000:0001:0000:0000:000a',
|
||||
'a:0:0:0:0:0:0:0',
|
||||
'fe80::7:8%eth0',
|
||||
'fe80::7:8%1'
|
||||
].forEach((servername) => {
|
||||
assert.throws(() => client.connect({ servername }), {
|
||||
code: 'ERR_INVALID_ARG_VALUE'
|
||||
});
|
||||
});
|
||||
|
||||
[-1, 10, 1n, {}, [], true].forEach((servername) => {
|
||||
assert.throws(() => client.connect({ servername }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid remoteTransportParams argument option
|
||||
[-1, 'test', 1n, {}, []].forEach((remoteTransportParams) => {
|
||||
assert.throws(() => client.connect({ remoteTransportParams }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid sessionTicket argument option
|
||||
[-1, 'test', 1n, {}, []].forEach((sessionTicket) => {
|
||||
assert.throws(() => client.connect({ sessionTicket }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid alpn argument option
|
||||
[-1, 10, 1n, {}, [], true].forEach((alpn) => {
|
||||
assert.throws(() => client.connect({ alpn }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[
|
||||
'idleTimeout',
|
||||
'activeConnectionIdLimit',
|
||||
'maxAckDelay',
|
||||
'maxData',
|
||||
'maxPacketSize',
|
||||
'maxStreamDataBidiLocal',
|
||||
'maxStreamDataBidiRemote',
|
||||
'maxStreamDataUni',
|
||||
'maxStreamsBidi',
|
||||
'maxStreamsUni',
|
||||
'highWaterMark',
|
||||
].forEach((prop) => {
|
||||
assert.throws(() => client.connect({ [prop]: -1 }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
|
||||
assert.throws(
|
||||
() => client.connect({ [prop]: Number.MAX_SAFE_INTEGER + 1 }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
|
||||
['a', 1n, [], {}, false].forEach((val) => {
|
||||
assert.throws(() => client.connect({ [prop]: val }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// activeConnectionIdLimit must be between 2 and 8, inclusive
|
||||
[1, 9].forEach((activeConnectionIdLimit) => {
|
||||
assert.throws(() => client.connect({ activeConnectionIdLimit }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
|
||||
['a', 1n, 1, [], {}].forEach((ipv6Only) => {
|
||||
assert.throws(() => client.connect({ ipv6Only }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, false, [], {}].forEach((preferredAddressPolicy) => {
|
||||
assert.throws(() => client.connect({ preferredAddressPolicy }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, 'test', [], {}].forEach((qlog) => {
|
||||
assert.throws(() => client.connect({ qlog }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, 'test', [], {}].forEach((requestOCSP) => {
|
||||
assert.throws(() => client.connect({ requestOCSP }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, false, [], {}, 'aaa'].forEach((type) => {
|
||||
assert.throws(() => client.connect({ type }), {
|
||||
code: 'ERR_INVALID_ARG_VALUE'
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
[
|
||||
'qpackMaxTableCapacity',
|
||||
'qpackBlockedStreams',
|
||||
'maxHeaderListSize',
|
||||
'maxPushes',
|
||||
].forEach((prop) => {
|
||||
assert.throws(() => client.connect({ h3: { [prop]: -1 } }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
|
||||
assert.throws(
|
||||
() => client.connect({ h3: { [prop]: Number.MAX_SAFE_INTEGER + 1 } }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
|
||||
['a', 1n, [], {}, false].forEach((val) => {
|
||||
assert.throws(() => client.connect({ h3: { [prop]: val } }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
['', 1n, {}, [], false, 'zebra'].forEach((defaultEncoding) => {
|
||||
assert.throws(() => client.connect({ defaultEncoding }), {
|
||||
code: 'ERR_INVALID_ARG_VALUE'
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// Test that connect cannot be called after QuicSocket is closed.
|
||||
client.close();
|
||||
assert.throws(() => client.connect(), {
|
||||
code: 'ERR_QUICSOCKET_DESTROYED'
|
||||
});
|
||||
|
||||
// TODO(@jasnell): Test additional options:
|
||||
//
|
||||
// Client QuicSession Related:
|
||||
//
|
||||
// [x] idleTimeout - must be a number greater than zero
|
||||
// [x] ipv6Only - must be a boolean
|
||||
// [x] activeConnectionIdLimit - must be a number between 2 and 8
|
||||
// [x] maxAckDelay - must be a number greater than zero
|
||||
// [x] maxData - must be a number greater than zero
|
||||
// [x] maxPacketSize - must be a number greater than zero
|
||||
// [x] maxStreamDataBidiLocal - must be a number greater than zero
|
||||
// [x] maxStreamDataBidiRemote - must be a number greater than zero
|
||||
// [x] maxStreamDataUni - must be a number greater than zero
|
||||
// [x] maxStreamsBidi - must be a number greater than zero
|
||||
// [x] maxStreamsUni - must be a number greater than zero
|
||||
// [x] preferredAddressPolicy - must be eiher 'accept' or 'reject'
|
||||
// [x] qlog - must be a boolean
|
||||
// [x] requestOCSP - must be a boolean
|
||||
// [x] type - must be a string, either 'udp4' or 'udp6'
|
||||
//
|
||||
// HTTP/3 Related:
|
||||
//
|
||||
// [x] h3.qpackMaxTableCapacity - must be a number greater than zero
|
||||
// [x] h3.qpackBlockedStreams - must be a number greater than zero
|
||||
// [x] h3.maxHeaderListSize - must be a number greater than zero
|
||||
// [x] h3.maxPushes - must be a number greater than zero
|
||||
//
|
||||
// Secure Context Related:
|
||||
//
|
||||
// [ ] ca (certificate authority) - must be a string, string array,
|
||||
// Buffer, or Buffer array.
|
||||
// [ ] cert (cert chain) - must be a string, string array, Buffer, or
|
||||
// Buffer array.
|
||||
// [ ] ciphers - must be a string
|
||||
// [ ] clientCertEngine - must be a string
|
||||
// [ ] crl - must be a string, string array, Buffer, or Buffer array
|
||||
// [ ] dhparam - must be a string or Buffer
|
||||
// [ ] ecdhCurve - must be a string
|
||||
// [ ] honorCipherOrder - must be a boolean
|
||||
// [ ] key - must be a string, string array, Buffer, or Buffer array
|
||||
// [ ] passphrase - must be a string
|
||||
// [ ] pfx - must be a string, string array, Buffer, or Buffer array
|
||||
// [ ] secureOptions - must be a number
|
||||
// [x] minDHSize - must be a number
|
||||
@@ -0,0 +1,187 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Test QuicSocket constructor option errors
|
||||
|
||||
const common = require('../common');
|
||||
const async_hooks = require('async_hooks');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
|
||||
// Hook verifies that no QuicSocket handles are actually created.
|
||||
async_hooks.createHook({
|
||||
init: common.mustCallAtLeast((_, type) => {
|
||||
assert.notStrictEqual(type, 'QUICSOCKET');
|
||||
})
|
||||
}).enable();
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
// Test invalid QuicSocket options argument
|
||||
[1, 'test', false, 1n, null].forEach((i) => {
|
||||
assert.throws(() => createQuicSocket(i), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket port argument option
|
||||
[-1, 'test', 1n, {}, [], NaN, false].forEach((port) => {
|
||||
assert.throws(() => createQuicSocket({ endpoint: { port } }), {
|
||||
code: 'ERR_SOCKET_BAD_PORT'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket addressargument option
|
||||
[-1, 10, 1n, {}, [], NaN, false].forEach((address) => {
|
||||
assert.throws(() => createQuicSocket({ endpoint: { address } }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket type argument option
|
||||
[1, false, 1n, {}, null, NaN].forEach((type) => {
|
||||
assert.throws(() => createQuicSocket({ endpoint: { type } }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket ipv6Only argument option
|
||||
[1, NaN, 1n, null, {}, []].forEach((ipv6Only) => {
|
||||
assert.throws(() => createQuicSocket({ endpoint: { ipv6Only } }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket reuseAddr argument option
|
||||
[1, NaN, 1n, null, {}, []].forEach((reuseAddr) => {
|
||||
assert.throws(() => createQuicSocket({ endpoint: { reuseAddr } }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket lookup argument option
|
||||
[1, 1n, {}, [], 'test', true].forEach((lookup) => {
|
||||
assert.throws(() => createQuicSocket({ lookup }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket validateAddress argument option
|
||||
[1, NaN, 1n, null, {}, []].forEach((validateAddress) => {
|
||||
assert.throws(() => createQuicSocket({ validateAddress }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket validateAddressLRU argument option
|
||||
[1, NaN, 1n, null, {}, []].forEach((validateAddressLRU) => {
|
||||
assert.throws(() => createQuicSocket({ validateAddressLRU }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket autoClose argument option
|
||||
[1, NaN, 1n, null, {}, []].forEach((autoClose) => {
|
||||
assert.throws(() => createQuicSocket({ autoClose }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket qlog argument option
|
||||
[1, NaN, 1n, null, {}, []].forEach((qlog) => {
|
||||
assert.throws(() => createQuicSocket({ qlog }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// Test invalid QuicSocket retryTokenTimeout option
|
||||
[0, 61, NaN].forEach((retryTokenTimeout) => {
|
||||
assert.throws(() => createQuicSocket({ retryTokenTimeout }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket retryTokenTimeout option
|
||||
['test', null, 1n, {}, [], false].forEach((retryTokenTimeout) => {
|
||||
assert.throws(() => createQuicSocket({ retryTokenTimeout }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket maxConnectionsPerHost option
|
||||
[0, Number.MAX_SAFE_INTEGER + 1, NaN].forEach((maxConnectionsPerHost) => {
|
||||
assert.throws(() => createQuicSocket({ maxConnectionsPerHost }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket maxConnectionsPerHost option
|
||||
[
|
||||
'test',
|
||||
null,
|
||||
1n,
|
||||
{},
|
||||
[],
|
||||
false
|
||||
].forEach((maxConnectionsPerHost) => {
|
||||
assert.throws(() => createQuicSocket({ maxConnectionsPerHost }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket maxConnections option
|
||||
[0, Number.MAX_SAFE_INTEGER + 1, NaN].forEach((maxConnections) => {
|
||||
assert.throws(() => createQuicSocket({ maxConnections }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket maxConnectionsPerHost option
|
||||
[
|
||||
'test',
|
||||
null,
|
||||
1n,
|
||||
{},
|
||||
[],
|
||||
false
|
||||
].forEach((maxConnections) => {
|
||||
assert.throws(() => createQuicSocket({ maxConnections }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket maxStatelessResetsPerHost option
|
||||
[0, Number.MAX_SAFE_INTEGER + 1, NaN].forEach((maxStatelessResetsPerHost) => {
|
||||
assert.throws(() => createQuicSocket({ maxStatelessResetsPerHost }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid QuicSocket maxStatelessResetsPerHost option
|
||||
[
|
||||
'test',
|
||||
null,
|
||||
1n,
|
||||
{},
|
||||
[],
|
||||
false
|
||||
].forEach((maxStatelessResetsPerHost) => {
|
||||
assert.throws(() => createQuicSocket({ maxStatelessResetsPerHost }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, false, 'test'].forEach((options) => {
|
||||
assert.throws(() => createQuicSocket({ endpoint: options }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
assert.throws(() => createQuicSocket({ client: options }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
assert.throws(() => createQuicSocket({ server: options }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests error and input validation checks for QuicSocket.connect()
|
||||
|
||||
const common = require('../common');
|
||||
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
// Test invalid callback function
|
||||
{
|
||||
const server = createQuicSocket();
|
||||
[1, 1n].forEach((cb) => {
|
||||
assert.throws(() => server.listen({}, cb), {
|
||||
code: 'ERR_INVALID_CALLBACK'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Test QuicSocket is already listening
|
||||
{
|
||||
const server = createQuicSocket();
|
||||
server.listen();
|
||||
assert.throws(() => server.listen(), {
|
||||
code: 'ERR_QUICSOCKET_LISTENING'
|
||||
});
|
||||
server.close();
|
||||
}
|
||||
|
||||
// Test QuicSocket listen after destroy error
|
||||
{
|
||||
const server = createQuicSocket();
|
||||
server.close();
|
||||
assert.throws(() => server.listen(), {
|
||||
code: 'ERR_QUICSOCKET_DESTROYED'
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
// Test incorrect ALPN
|
||||
const server = createQuicSocket();
|
||||
[1, 1n, true, {}, [], null].forEach((alpn) => {
|
||||
assert.throws(() => server.listen({ alpn }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
// Test invalid idle timeout
|
||||
[
|
||||
'idleTimeout',
|
||||
'activeConnectionIdLimit',
|
||||
'maxAckDelay',
|
||||
'maxData',
|
||||
'maxPacketSize',
|
||||
'maxStreamDataBidiLocal',
|
||||
'maxStreamDataBidiRemote',
|
||||
'maxStreamDataUni',
|
||||
'maxStreamsBidi',
|
||||
'maxStreamsUni',
|
||||
'highWaterMark',
|
||||
].forEach((prop) => {
|
||||
assert.throws(() => server.listen({ [prop]: -1 }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
|
||||
assert.throws(
|
||||
() => server.listen({ [prop]: Number.MAX_SAFE_INTEGER + 1 }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
|
||||
['a', 1n, [], {}, false].forEach((val) => {
|
||||
assert.throws(() => server.listen({ [prop]: val }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, 'test', {}, []].forEach((rejectUnauthorized) => {
|
||||
assert.throws(() => server.listen({ rejectUnauthorized }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, 'test', {}, []].forEach((requestCert) => {
|
||||
assert.throws(() => server.listen({ requestCert }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, 'test', {}, []].forEach((requestCert) => {
|
||||
assert.throws(() => server.listen({ requestCert }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, 'test', false].forEach((preferredAddress) => {
|
||||
assert.throws(() => server.listen({ preferredAddress }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
|
||||
[1, 1n, null, false, {}, []].forEach((address) => {
|
||||
assert.throws(() => server.listen({ preferredAddress: { address } }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[-1].forEach((port) => {
|
||||
assert.throws(() => server.listen({ preferredAddress: { port } }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 'test', false, null, {}, []].forEach((type) => {
|
||||
assert.throws(() => server.listen({ preferredAddress: { type } }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, false, [], {}, null].forEach((ciphers) => {
|
||||
assert.throws(() => server.listen({ ciphers }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, false, [], {}, null].forEach((groups) => {
|
||||
assert.throws(() => server.listen({ groups }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
['', 1n, {}, [], false, 'zebra'].forEach((defaultEncoding) => {
|
||||
assert.throws(() => server.listen({ defaultEncoding }), {
|
||||
code: 'ERR_INVALID_ARG_VALUE'
|
||||
});
|
||||
});
|
||||
|
||||
// Make sure that after all of the validation checks, the socket
|
||||
// is not actually marked as listening at all.
|
||||
assert.strictEqual(typeof server.listening, 'boolean');
|
||||
assert(!server.listening);
|
||||
}
|
||||
|
||||
|
||||
// Options to check
|
||||
// * [x] alpn
|
||||
// * [x] idleTimeout
|
||||
// * [x] activeConnectionIdLimit
|
||||
// * [x] maxAckDelay
|
||||
// * [x] maxData
|
||||
// * [x] maxPacketSize
|
||||
// * [x] maxStreamsBidi
|
||||
// * [x] maxStreamsUni
|
||||
// * [x] maxStreamDataBidiLocal
|
||||
// * [x] maxStreamDataBidiRemote
|
||||
// * [x] maxStreamDataUni
|
||||
// * [x] preferredAddress
|
||||
// * [x] requestCert
|
||||
// * [x] rejectUnauthorized
|
||||
|
||||
// SecureContext Options
|
||||
// * [ ] ca
|
||||
// * [ ] cert
|
||||
// * [x] ciphers
|
||||
// * [ ] clientCertEngine
|
||||
// * [ ] crl
|
||||
// * [ ] dhparam
|
||||
// * [ ] groups
|
||||
// * [ ] ecdhCurve
|
||||
// * [ ] honorCipherOrder
|
||||
// * [ ] key
|
||||
// * [ ] passphrase
|
||||
// * [ ] pfx
|
||||
// * [ ] secureOptions
|
||||
// * [ ] sessionIdContext
|
||||
@@ -0,0 +1,157 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests a simple QUIC HTTP/3 client/server round-trip
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
|
||||
const {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug,
|
||||
kHttp3Alpn,
|
||||
kServerPort,
|
||||
kClientPort,
|
||||
setupKeylog,
|
||||
} = require('../common/quic');
|
||||
|
||||
const filedata = fs.readFileSync(__filename, { encoding: 'utf8' });
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
let client;
|
||||
const server = createQuicSocket({ endpoint: { port: kServerPort } });
|
||||
|
||||
const kServerName = 'agent2'; // Intentionally the wrong servername
|
||||
|
||||
const countdown = new Countdown(1, () => {
|
||||
debug('Countdown expired. Destroying sockets');
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen({
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
alpn: kHttp3Alpn,
|
||||
});
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
|
||||
assert.strictEqual(session.maxStreams.bidi, 100);
|
||||
assert.strictEqual(session.maxStreams.uni, 3);
|
||||
|
||||
setupKeylog(session);
|
||||
|
||||
session.on('secure', common.mustCall((_, alpn) => {
|
||||
debug('QuicServerSession handshake completed');
|
||||
assert.strictEqual(session.alpnProtocol, alpn);
|
||||
}));
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
debug('Bidirectional, Client-initiated stream %d received', stream.id);
|
||||
const file = fs.createReadStream(__filename);
|
||||
let data = '';
|
||||
|
||||
assert(stream.submitInitialHeaders({ ':status': '200' }));
|
||||
|
||||
file.pipe(stream);
|
||||
stream.setEncoding('utf8');
|
||||
|
||||
stream.on('initialHeaders', common.mustCall((headers) => {
|
||||
const expected = [
|
||||
[ ':path', '/' ],
|
||||
[ ':authority', 'localhost' ],
|
||||
[ ':scheme', 'https' ],
|
||||
[ ':method', 'POST' ]
|
||||
];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
debug('Received expected request headers');
|
||||
}));
|
||||
stream.on('informationalHeaders', common.mustNotCall());
|
||||
stream.on('trailingHeaders', common.mustNotCall());
|
||||
|
||||
stream.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
stream.on('end', common.mustCall(() => {
|
||||
assert.strictEqual(data, filedata);
|
||||
debug('Server received expected data for stream %d', stream.id);
|
||||
}));
|
||||
stream.on('close', common.mustCall());
|
||||
stream.on('finish', common.mustCall());
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server is listening on port %d', server.endpoints[0].address.port);
|
||||
client = createQuicSocket({
|
||||
endpoint: { port: kClientPort },
|
||||
client: { key, cert, ca, alpn: kHttp3Alpn }
|
||||
});
|
||||
|
||||
client.on('close', common.mustCall());
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port,
|
||||
servername: kServerName,
|
||||
h3: { maxPushes: 10 }
|
||||
});
|
||||
debug('QuicClientSession Created');
|
||||
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
debug('QuicClientSession handshake completed');
|
||||
|
||||
const file = fs.createReadStream(__filename);
|
||||
const stream = req.openStream();
|
||||
|
||||
assert(stream.submitInitialHeaders({
|
||||
':method': 'POST',
|
||||
':scheme': 'https',
|
||||
':authority': 'localhost',
|
||||
':path': '/',
|
||||
}));
|
||||
file.pipe(stream);
|
||||
let data = '';
|
||||
stream.resume();
|
||||
stream.setEncoding('utf8');
|
||||
|
||||
stream.on('initialHeaders', common.mustCall((headers) => {
|
||||
const expected = [
|
||||
[ ':status', '200' ]
|
||||
];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
debug('Received expected response headers');
|
||||
}));
|
||||
stream.on('informationalHeaders', common.mustNotCall());
|
||||
stream.on('trailingHeaders', common.mustNotCall());
|
||||
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('finish', common.mustCall());
|
||||
stream.on('end', common.mustCall(() => {
|
||||
assert.strictEqual(data, filedata);
|
||||
debug('Client received expected data for stream %d', stream.id);
|
||||
}));
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Bidirectional, Client-initiated stream %d closed', stream.id);
|
||||
countdown.dec();
|
||||
}));
|
||||
debug('Bidirectional, Client-initiated stream %d opened', stream.id);
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,157 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests a simple QUIC HTTP/3 client/server round-trip
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const { key, cert, ca, kHttp3Alpn } = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
let client;
|
||||
const server = createQuicSocket();
|
||||
|
||||
const countdown = new Countdown(2, () => {
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
const options = { key, cert, ca, alpn: kHttp3Alpn };
|
||||
|
||||
server.listen(options);
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
assert(stream.submitInitialHeaders({ ':status': '200' }));
|
||||
|
||||
[-1, Number.MAX_SAFE_INTEGER + 1].forEach((highWaterMark) => {
|
||||
assert.throws(() => stream.pushStream({}, { highWaterMark }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
['', 1n, {}, [], false].forEach((highWaterMark) => {
|
||||
assert.throws(() => stream.pushStream({}, { highWaterMark }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
['', 1, 1n, true, [], {}, 'zebra'].forEach((defaultEncoding) => {
|
||||
assert.throws(() => stream.pushStream({}, { defaultEncoding }), {
|
||||
code: 'ERR_INVALID_ARG_VALUE'
|
||||
});
|
||||
});
|
||||
|
||||
const push = stream.pushStream({
|
||||
':method': 'GET',
|
||||
':scheme': 'https',
|
||||
':authority': 'localhost',
|
||||
':path': '/foo'
|
||||
});
|
||||
assert(push);
|
||||
push.submitInitialHeaders({ ':status': '200' });
|
||||
push.end('testing');
|
||||
push.on('close', common.mustCall());
|
||||
push.on('finish', common.mustCall());
|
||||
|
||||
stream.end('hello world');
|
||||
stream.resume();
|
||||
stream.on('end', common.mustCall());
|
||||
stream.on('close', common.mustCall());
|
||||
stream.on('finish', common.mustCall());
|
||||
|
||||
stream.on('initialHeaders', common.mustCall((headers) => {
|
||||
const expected = [
|
||||
[ ':path', '/' ],
|
||||
[ ':authority', 'localhost' ],
|
||||
[ ':scheme', 'https' ],
|
||||
[ ':method', 'POST' ]
|
||||
];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
}));
|
||||
stream.on('informationalHeaders', common.mustNotCall());
|
||||
stream.on('trailingHeaders', common.mustNotCall());
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
client = createQuicSocket({ client: options });
|
||||
client.on('close', common.mustCall());
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port,
|
||||
maxStreamsUni: 10,
|
||||
h3: { maxPushes: 10 }
|
||||
});
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
let data = '';
|
||||
|
||||
stream.on('initialHeaders', common.mustCall((headers) => {
|
||||
const expected = [
|
||||
[':status', '200']
|
||||
];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
}));
|
||||
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('end', common.mustCall(() => {
|
||||
assert.strictEqual(data, 'testing');
|
||||
}));
|
||||
stream.on('close', common.mustCall(() => {
|
||||
countdown.dec();
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = req.openStream();
|
||||
|
||||
stream.on('pushHeaders', common.mustCall((headers, push_id) => {
|
||||
const expected = [
|
||||
[ ':path', '/foo' ],
|
||||
[ ':authority', 'localhost' ],
|
||||
[ ':scheme', 'https' ],
|
||||
[ ':method', 'GET' ]
|
||||
];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
assert.strictEqual(push_id, 0);
|
||||
}));
|
||||
|
||||
assert(stream.submitInitialHeaders({
|
||||
':method': 'POST',
|
||||
':scheme': 'https',
|
||||
':authority': 'localhost',
|
||||
':path': '/',
|
||||
}));
|
||||
|
||||
stream.end('hello world');
|
||||
stream.resume();
|
||||
stream.on('finish', common.mustCall());
|
||||
stream.on('end', common.mustCall());
|
||||
|
||||
stream.on('initialHeaders', common.mustCall((headers) => {
|
||||
const expected = [
|
||||
[ ':status', '200' ]
|
||||
];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
}));
|
||||
stream.on('informationalHeaders', common.mustNotCall());
|
||||
stream.on('trailingHeaders', common.mustNotCall());
|
||||
|
||||
stream.on('close', common.mustCall(() => {
|
||||
countdown.dec();
|
||||
}));
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,109 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests a simple QUIC HTTP/3 client/server round-trip
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const { key, cert, ca, kHttp3Alpn } = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
let client;
|
||||
const server = createQuicSocket();
|
||||
|
||||
const countdown = new Countdown(1, () => {
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
const options = { key, cert, ca, alpn: kHttp3Alpn };
|
||||
|
||||
server.listen(options);
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
assert(stream.submitInitialHeaders({ ':status': '200' }));
|
||||
|
||||
stream.submitTrailingHeaders({ 'a': 1 });
|
||||
stream.end('hello world');
|
||||
stream.resume();
|
||||
stream.on('end', common.mustCall());
|
||||
stream.on('close', common.mustCall());
|
||||
stream.on('finish', common.mustCall());
|
||||
|
||||
stream.on('initialHeaders', common.mustCall((headers) => {
|
||||
const expected = [
|
||||
[ ':path', '/' ],
|
||||
[ ':authority', 'localhost' ],
|
||||
[ ':scheme', 'https' ],
|
||||
[ ':method', 'POST' ]
|
||||
];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
}));
|
||||
|
||||
stream.on('trailingHeaders', common.mustCall((headers) => {
|
||||
const expected = [ [ 'b', '2' ] ];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
}));
|
||||
|
||||
stream.on('informationalHeaders', common.mustNotCall());
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
client = createQuicSocket({ client: options });
|
||||
client.on('close', common.mustCall());
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port,
|
||||
maxStreamsUni: 10,
|
||||
h3: { maxPushes: 10 }
|
||||
});
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = req.openStream();
|
||||
|
||||
stream.on('trailingHeaders', common.mustCall((headers) => {
|
||||
const expected = [ [ 'a', '1' ] ];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
}));
|
||||
|
||||
assert(stream.submitInitialHeaders({
|
||||
':method': 'POST',
|
||||
':scheme': 'https',
|
||||
':authority': 'localhost',
|
||||
':path': '/',
|
||||
}));
|
||||
|
||||
stream.submitTrailingHeaders({ 'b': 2 });
|
||||
stream.end('hello world');
|
||||
stream.resume();
|
||||
stream.on('finish', common.mustCall());
|
||||
stream.on('end', common.mustCall());
|
||||
|
||||
stream.on('initialHeaders', common.mustCall((headers) => {
|
||||
const expected = [
|
||||
[ ':status', '200' ]
|
||||
];
|
||||
assert.deepStrictEqual(expected, headers);
|
||||
}));
|
||||
stream.on('informationalHeaders', common.mustNotCall());
|
||||
|
||||
stream.on('close', common.mustCall(() => {
|
||||
countdown.dec();
|
||||
}));
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,73 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const { once } = require('events');
|
||||
|
||||
const kALPN = 'zzz';
|
||||
const idleTimeout = common.platformTimeout(1);
|
||||
const options = { key, cert, ca, alpn: kALPN };
|
||||
|
||||
// Test idleTimeout. The test will hang and fail with a timeout
|
||||
// if the idleTimeout is not working correctly.
|
||||
|
||||
(async () => {
|
||||
const server = createQuicSocket({ server: options });
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
server.listen();
|
||||
server.on('session', common.mustCall());
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
const session = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
idleTimeout,
|
||||
});
|
||||
|
||||
await once(session, 'close');
|
||||
|
||||
assert(session.idleTimeout);
|
||||
client.close();
|
||||
server.close();
|
||||
|
||||
await Promise.all([
|
||||
once(client, 'close'),
|
||||
once(server, 'close')
|
||||
]);
|
||||
})().then(common.mustCall());
|
||||
|
||||
|
||||
(async () => {
|
||||
const server = createQuicSocket({ server: options });
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
server.listen({ idleTimeout });
|
||||
|
||||
server.on('session', common.mustCall(async (session) => {
|
||||
await once(session, 'close');
|
||||
assert(session.idleTimeout);
|
||||
client.close();
|
||||
server.close();
|
||||
await Promise.all([
|
||||
once(client, 'close'),
|
||||
once(server, 'close')
|
||||
]);
|
||||
}));
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
const session = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
await once(session, 'close');
|
||||
})().then(common.mustCall());
|
||||
@@ -0,0 +1,140 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
|
||||
if (!common.hasIPv6)
|
||||
common.skip('missing ipv6');
|
||||
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const { once } = require('events');
|
||||
|
||||
const kALPN = 'zzz';
|
||||
|
||||
// Setting `type` to `udp4` while setting `ipv6Only` to `true` is possible
|
||||
// and it will throw an error.
|
||||
{
|
||||
const server = createQuicSocket({
|
||||
endpoint: {
|
||||
type: 'udp4',
|
||||
ipv6Only: true
|
||||
} });
|
||||
|
||||
server.on('error', common.mustCall((err) => {
|
||||
assert.strictEqual(err.code, 'EINVAL');
|
||||
assert.strictEqual(err.message, 'bind EINVAL 0.0.0.0');
|
||||
}));
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN });
|
||||
}
|
||||
|
||||
// Connecting ipv6 server by "127.0.0.1" should work when `ipv6Only`
|
||||
// is set to `false`.
|
||||
(async () => {
|
||||
const server = createQuicSocket({
|
||||
endpoint: {
|
||||
type: 'udp6',
|
||||
ipv6Only: false
|
||||
} });
|
||||
const client = createQuicSocket({ client: { key, cert, ca, alpn: kALPN } });
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN });
|
||||
|
||||
server.on('session', common.mustCall((serverSession) => {
|
||||
serverSession.on('stream', common.mustCall());
|
||||
}));
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
const session = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
await once(session, 'secure');
|
||||
|
||||
const stream = session.openStream({ halfOpen: true });
|
||||
stream.end('hello');
|
||||
|
||||
await once(stream, 'close');
|
||||
|
||||
client.close();
|
||||
server.close();
|
||||
|
||||
await Promise.allSettled([
|
||||
once(client, 'close'),
|
||||
once(server, 'close')
|
||||
]);
|
||||
})().then(common.mustCall());
|
||||
|
||||
// When the `ipv6Only` set to `true`, a client cann't connect to it
|
||||
// through "127.0.0.1".
|
||||
(async () => {
|
||||
const server = createQuicSocket({
|
||||
endpoint: {
|
||||
type: 'udp6',
|
||||
ipv6Only: true
|
||||
} });
|
||||
const client = createQuicSocket({ client: { key, cert, ca, alpn: kALPN } });
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN });
|
||||
server.on('session', common.mustNotCall());
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
const session = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
idleTimeout: common.platformTimeout(1),
|
||||
});
|
||||
|
||||
session.on('secure', common.mustNotCall());
|
||||
|
||||
await once(session, 'close');
|
||||
|
||||
client.close();
|
||||
server.close();
|
||||
|
||||
await Promise.allSettled([
|
||||
once(client, 'close'),
|
||||
once(server, 'close')
|
||||
]);
|
||||
})();
|
||||
|
||||
// Creating the QuicSession fails when connect type does not match the
|
||||
// the connect IP address...
|
||||
(async () => {
|
||||
const server = createQuicSocket({ endpoint: { type: 'udp6' } });
|
||||
const client = createQuicSocket({ client: { key, cert, ca, alpn: kALPN } });
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN });
|
||||
server.on('session', common.mustNotCall());
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
const session = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
type: 'udp6',
|
||||
idleTimeout: common.platformTimeout(1),
|
||||
});
|
||||
|
||||
session.on('error', common.mustCall((err) => {
|
||||
assert.strictEqual(err.code, 'ERR_QUICCLIENTSESSION_FAILED');
|
||||
client.close();
|
||||
server.close();
|
||||
}));
|
||||
|
||||
session.on('secure', common.mustNotCall());
|
||||
session.on('close', common.mustCall());
|
||||
|
||||
await Promise.allSettled([
|
||||
once(client, 'close'),
|
||||
once(server, 'close')
|
||||
]);
|
||||
})().then(common.mustCall());
|
||||
@@ -0,0 +1,67 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests QUIC keylogging
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const { once } = require('events');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const kKeylogs = [
|
||||
/^CLIENT_HANDSHAKE_TRAFFIC_SECRET .*/,
|
||||
/^SERVER_HANDSHAKE_TRAFFIC_SECRET .*/,
|
||||
/^QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET .*/,
|
||||
/^QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET .*/,
|
||||
/^CLIENT_TRAFFIC_SECRET_0 .*/,
|
||||
/^SERVER_TRAFFIC_SECRET_0 .*/,
|
||||
/^QUIC_CLIENT_TRAFFIC_SECRET_0 .*/,
|
||||
/^QUIC_SERVER_TRAFFIC_SECRET_0 .*/,
|
||||
];
|
||||
|
||||
const options = { key, cert, ca, alpn: 'zzz' };
|
||||
|
||||
(async () => {
|
||||
const server = createQuicSocket({ server: options });
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
const kServerKeylogs = Array.from(kKeylogs);
|
||||
const kClientKeylogs = Array.from(kKeylogs);
|
||||
|
||||
server.listen();
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('keylog', common.mustCall((line) => {
|
||||
assert.match(line.toString(), kServerKeylogs.shift());
|
||||
}, kServerKeylogs.length));
|
||||
}));
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
req.on('keylog', common.mustCall((line) => {
|
||||
assert.match(line.toString(), kClientKeylogs.shift());
|
||||
}, kClientKeylogs.length));
|
||||
|
||||
await once(req, 'secure');
|
||||
|
||||
server.close();
|
||||
client.close();
|
||||
|
||||
await Promise.allSettled([
|
||||
once(server, 'close'),
|
||||
once(client, 'close')
|
||||
]);
|
||||
|
||||
assert.strictEqual(kServerKeylogs.length, 0);
|
||||
assert.strictEqual(kClientKeylogs.length, 0);
|
||||
})().then(common.mustCall());
|
||||
@@ -0,0 +1,86 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
const assert = require('assert');
|
||||
const Countdown = require('../common/countdown');
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const kServerName = 'agent2';
|
||||
const kALPN = 'zzz';
|
||||
|
||||
// QuicSockets must throw errors when maxConnectionsPerHost is not a
|
||||
// safe integer or is out of range.
|
||||
{
|
||||
[-1, 0, Number.MAX_SAFE_INTEGER + 1, 1.1].forEach((maxConnectionsPerHost) => {
|
||||
assert.throws(() => createQuicSocket({ maxConnectionsPerHost }), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Test that new client sessions will be closed when it exceeds
|
||||
// maxConnectionsPerHost.
|
||||
{
|
||||
const kMaxConnectionsPerHost = 5;
|
||||
const kIdleTimeout = 0;
|
||||
|
||||
let client;
|
||||
let server;
|
||||
|
||||
const countdown = new Countdown(kMaxConnectionsPerHost + 1, () => {
|
||||
client.close();
|
||||
server.close();
|
||||
});
|
||||
|
||||
function connect() {
|
||||
return client.connect({
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
servername: kServerName,
|
||||
alpn: kALPN,
|
||||
idleTimeout: kIdleTimeout,
|
||||
});
|
||||
}
|
||||
|
||||
server = createQuicSocket({ maxConnectionsPerHost: kMaxConnectionsPerHost });
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN, idleTimeout: kIdleTimeout });
|
||||
|
||||
server.on('session', common.mustCall(() => {}, kMaxConnectionsPerHost));
|
||||
|
||||
server.on('close', common.mustCall(() => {
|
||||
assert.strictEqual(server.serverBusyCount, 1n);
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
client = createQuicSocket();
|
||||
|
||||
const sessions = [];
|
||||
|
||||
for (let i = 0; i < kMaxConnectionsPerHost; i += 1) {
|
||||
const req = connect();
|
||||
req.on('error', common.mustNotCall());
|
||||
req.on('close', common.mustCall(() => countdown.dec()));
|
||||
sessions.push(req);
|
||||
}
|
||||
|
||||
const extra = connect();
|
||||
extra.on('error', console.log);
|
||||
extra.on('close', common.mustCall(() => {
|
||||
countdown.dec();
|
||||
// Shutdown the remaining open sessions.
|
||||
setImmediate(common.mustCall(() => {
|
||||
for (const req of sessions)
|
||||
req.close();
|
||||
}));
|
||||
}));
|
||||
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
// Test that shutting down a process containing an active QUIC server behaves
|
||||
// well. We use Workers because they have a more clearly defined shutdown
|
||||
// sequence and we can stop execution at any point.
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
const { Worker, workerData } = require('worker_threads');
|
||||
|
||||
if (workerData == null) {
|
||||
new Worker(__filename, { workerData: { removeFromSocket: true } });
|
||||
new Worker(__filename, { workerData: { removeFromSocket: false } });
|
||||
return;
|
||||
}
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const options = { key, cert, ca, alpn: 'meow' };
|
||||
|
||||
const server = createQuicSocket({ server: options });
|
||||
|
||||
server.listen();
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = session.openStream({ halfOpen: false });
|
||||
stream.write('Hi!');
|
||||
stream.on('data', common.mustNotCall());
|
||||
stream.on('finish', common.mustNotCall());
|
||||
stream.on('close', common.mustNotCall());
|
||||
stream.on('end', common.mustNotCall());
|
||||
}));
|
||||
|
||||
session.on('close', common.mustNotCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
req.on('stream', common.mustCall(() => {
|
||||
if (workerData.removeFromSocket)
|
||||
req.removeFromSocket();
|
||||
process.exit(); // Exits the worker thread
|
||||
}));
|
||||
|
||||
req.on('close', common.mustNotCall());
|
||||
}));
|
||||
|
||||
server.on('close', common.mustNotCall());
|
||||
@@ -0,0 +1,66 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const { makeUDPPair } = require('../common/udppair');
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
const { kUDPHandleForTesting } = require('internal/quic/core');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const { serverSide, clientSide } = makeUDPPair();
|
||||
|
||||
const server = createQuicSocket({
|
||||
validateAddress: true,
|
||||
endpoint: { [kUDPHandleForTesting]: serverSide._handle },
|
||||
qlog: true
|
||||
});
|
||||
|
||||
serverSide.afterBind();
|
||||
server.listen({ key, cert, ca, alpn: 'meow' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
gatherQlog(session, 'server');
|
||||
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = session.openStream({ halfOpen: true });
|
||||
stream.end('Hi!');
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const client = createQuicSocket({
|
||||
endpoint: { [kUDPHandleForTesting]: clientSide._handle },
|
||||
client: { key, cert, ca, alpn: 'meow' },
|
||||
qlog: true
|
||||
});
|
||||
clientSide.afterBind();
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port,
|
||||
qlog: true
|
||||
});
|
||||
|
||||
gatherQlog(req, 'client');
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
stream.resume();
|
||||
stream.on('end', common.mustCall(() => {
|
||||
req.close();
|
||||
}));
|
||||
}));
|
||||
}));
|
||||
|
||||
function gatherQlog(session, id) {
|
||||
let log = '';
|
||||
session.on('qlog', (chunk) => log += chunk);
|
||||
session.on('close', common.mustCall(() => {
|
||||
const { qlog_version, traces } = JSON.parse(log);
|
||||
assert.strictEqual(typeof qlog_version, 'string');
|
||||
assert.strictEqual(typeof traces[0].events, 'object');
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests multiple aspects of QuicSocket multiple endpoint support
|
||||
|
||||
const common = require('../common');
|
||||
const { once } = require('events');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
async function Test1(options, address) {
|
||||
const server = createQuicSocket(options);
|
||||
assert.strictEqual(server.endpoints.length, 1);
|
||||
assert.strictEqual(server.endpoints[0].bound, false);
|
||||
assert.deepStrictEqual({}, server.endpoints[0].address);
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'zzz' });
|
||||
|
||||
await once(server, 'ready');
|
||||
assert.strictEqual(server.endpoints.length, 1);
|
||||
const endpoint = server.endpoints[0];
|
||||
assert.strictEqual(endpoint.bound, true);
|
||||
assert.strictEqual(endpoint.destroyed, false);
|
||||
assert.strictEqual(typeof endpoint.address.port, 'number');
|
||||
assert.strictEqual(endpoint.address.address, address);
|
||||
server.close();
|
||||
assert.strictEqual(endpoint.destroyed, true);
|
||||
}
|
||||
|
||||
async function Test2() {
|
||||
// Creates a server with multiple endpoints (one on udp4 and udp6)
|
||||
const server = createQuicSocket({ endpoint: { type: 'udp6' } });
|
||||
server.addEndpoint();
|
||||
assert.strictEqual(server.endpoints.length, 2);
|
||||
assert.strictEqual(server.endpoints[0].bound, false);
|
||||
assert.deepStrictEqual({}, server.endpoints[0].address);
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'zzz' });
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
assert.strictEqual(server.endpoints.length, 2);
|
||||
|
||||
{
|
||||
const endpoint = server.endpoints[0];
|
||||
assert.strictEqual(endpoint.bound, true);
|
||||
assert.strictEqual(endpoint.destroyed, false);
|
||||
assert.strictEqual(endpoint.address.family, 'IPv6');
|
||||
assert.strictEqual(typeof endpoint.address.port, 'number');
|
||||
assert.strictEqual(endpoint.address.address, '::');
|
||||
}
|
||||
|
||||
{
|
||||
const endpoint = server.endpoints[1];
|
||||
assert.strictEqual(endpoint.bound, true);
|
||||
assert.strictEqual(endpoint.destroyed, false);
|
||||
assert.strictEqual(endpoint.address.family, 'IPv4');
|
||||
assert.strictEqual(typeof endpoint.address.port, 'number');
|
||||
assert.strictEqual(endpoint.address.address, '0.0.0.0');
|
||||
}
|
||||
|
||||
server.close();
|
||||
for (const endpoint of server.endpoints)
|
||||
assert.strictEqual(endpoint.destroyed, true);
|
||||
}
|
||||
|
||||
const tests = [
|
||||
Test1({}, '0.0.0.0'),
|
||||
Test1({ endpoint: { port: 0 } }, '0.0.0.0'),
|
||||
Test1({ endpoint: { address: '127.0.0.1', port: 0 } }, '127.0.0.1'),
|
||||
Test1({ endpoint: { address: 'localhost', port: 0 } }, '127.0.0.1')
|
||||
];
|
||||
|
||||
if (common.hasIPv6) {
|
||||
tests.push(
|
||||
Test1({ endpoint: { type: 'udp6' } }, '::'),
|
||||
Test1({ endpoint: { type: 'udp6', address: 'localhost' } }, '::1'),
|
||||
Test2());
|
||||
}
|
||||
|
||||
Promise.all(tests);
|
||||
@@ -0,0 +1,59 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
// Test that opening a stream works even if the session isn’t ready yet.
|
||||
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const { once } = require('events');
|
||||
const options = { key, cert, ca, alpn: 'meow' };
|
||||
|
||||
(async () => {
|
||||
const server = createQuicSocket({ server: options });
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
server.listen();
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
// The server can create a stream immediately without waiting
|
||||
// for the secure event... however, the data will not actually
|
||||
// be transmitted until the handshake is completed.
|
||||
const stream = session.openStream({ halfOpen: true });
|
||||
stream.on('close', common.mustCall());
|
||||
stream.on('error', console.log);
|
||||
stream.end('hello');
|
||||
|
||||
session.on('stream', common.mustNotCall());
|
||||
}));
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
const [ stream ] = await once(req, 'stream');
|
||||
|
||||
let data = '';
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('end', common.mustCall());
|
||||
|
||||
await once(stream, 'close');
|
||||
|
||||
assert.strictEqual(data, 'hello');
|
||||
|
||||
server.close();
|
||||
client.close();
|
||||
|
||||
await Promise.all([
|
||||
once(server, 'close'),
|
||||
once(client, 'close')
|
||||
]);
|
||||
|
||||
})().then(common.mustCall());
|
||||
@@ -0,0 +1,64 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
// Test that opening a stream works even if the session isn’t ready yet.
|
||||
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
const { once } = require('events');
|
||||
const options = { key, cert, ca, alpn: 'meow' };
|
||||
|
||||
(async () => {
|
||||
const server = createQuicSocket({ server: options });
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
server.listen();
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('stream', common.mustCall(async (stream) => {
|
||||
let data = '';
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
await once(stream, 'end');
|
||||
assert.strictEqual(data, 'Hello!');
|
||||
}));
|
||||
}));
|
||||
|
||||
await once(server, 'ready');
|
||||
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
// In this case, the QuicStream is usable but corked
|
||||
// until the underlying internal QuicStream handle
|
||||
// has been created, which will not happen until
|
||||
// after the TLS handshake has been completed.
|
||||
const stream = req.openStream({ halfOpen: true });
|
||||
stream.end('Hello!');
|
||||
stream.on('error', common.mustNotCall());
|
||||
stream.resume();
|
||||
assert(!req.allowEarlyData);
|
||||
assert(!req.handshakeComplete);
|
||||
assert(stream.pending);
|
||||
|
||||
await once(stream, 'ready');
|
||||
|
||||
assert(req.handshakeComplete);
|
||||
assert(!stream.pending);
|
||||
|
||||
await once(stream, 'close');
|
||||
|
||||
server.close();
|
||||
client.close();
|
||||
|
||||
await Promise.all([
|
||||
once(server, 'close'),
|
||||
once(client, 'close')
|
||||
]);
|
||||
})().then(common.mustCall());
|
||||
@@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
|
||||
// Tests a simple QUIC client/server round-trip
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const { Buffer } = require('buffer');
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug,
|
||||
} = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const options = { key, cert, ca, alpn: 'zzz' };
|
||||
|
||||
const server = createQuicSocket({ server: options });
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
const countdown = new Countdown(2, () => {
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen();
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall(() => {
|
||||
assert(session.usingEarlyData);
|
||||
}));
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
stream.resume();
|
||||
}));
|
||||
}, 2));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
const stream = req.openStream({ halfOpen: true });
|
||||
stream.end('hello');
|
||||
stream.resume();
|
||||
stream.on('close', () => countdown.dec());
|
||||
|
||||
req.on('sessionTicket', common.mustCall((ticket, params) => {
|
||||
assert(ticket instanceof Buffer);
|
||||
assert(params instanceof Buffer);
|
||||
debug(' Ticket: %s', ticket.toString('hex'));
|
||||
debug(' Params: %s', params.toString('hex'));
|
||||
|
||||
// Destroy this initial client session...
|
||||
req.destroy();
|
||||
|
||||
// Wait a tick then start a new one.
|
||||
setImmediate(newSession, ticket, params);
|
||||
}, 1));
|
||||
|
||||
function newSession(sessionTicket, remoteTransportParams) {
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
sessionTicket,
|
||||
remoteTransportParams,
|
||||
autoStart: false,
|
||||
});
|
||||
|
||||
assert(req.allowEarlyData);
|
||||
|
||||
const stream = req.openStream({ halfOpen: true });
|
||||
stream.end('hello');
|
||||
stream.on('error', common.mustNotCall());
|
||||
stream.on('close', common.mustCall(() => countdown.dec()));
|
||||
|
||||
req.startHandshake();
|
||||
|
||||
// TODO(@jasnell): There's a slight bug in here in that
|
||||
// calling end() will uncork the stream, causing data to
|
||||
// be flushed to the C++ layer, which will trigger a
|
||||
// SendPendingData that will start the handshake. That
|
||||
// has the effect of short circuiting the intent of
|
||||
// manual startHandshake(), which makes it not use 0RTT
|
||||
// for the stream data.
|
||||
|
||||
req.on('secure', common.mustCall(() => {
|
||||
// TODO(@jasnell): This will be false for now because no
|
||||
// early data was sent. Once we actually start making
|
||||
// use of early data on the client side, this should be
|
||||
// true when the early data was accepted.
|
||||
assert(!req.usingEarlyData);
|
||||
}));
|
||||
}
|
||||
}));
|
||||
@@ -0,0 +1,86 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
const fs = require('fs');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const variants = [];
|
||||
for (const variant of ['sendFD', 'sendFile', 'sendFD+fileHandle']) {
|
||||
for (const offset of [-1, 0, 100]) {
|
||||
for (const length of [-1, 100]) {
|
||||
variants.push({ variant, offset, length });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const { variant, offset, length } of variants) {
|
||||
const server = createQuicSocket();
|
||||
let fd;
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'meow' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = session.openStream({ halfOpen: false });
|
||||
|
||||
stream.on('data', common.mustNotCall());
|
||||
stream.on('finish', common.mustCall());
|
||||
stream.on('close', common.mustCall());
|
||||
stream.on('end', common.mustCall());
|
||||
|
||||
if (variant === 'sendFD') {
|
||||
fd = fs.openSync(__filename, 'r');
|
||||
stream.sendFD(fd, { offset, length });
|
||||
} else if (variant === 'sendFD+fileHandle') {
|
||||
fs.promises.open(__filename, 'r').then(common.mustCall((handle) => {
|
||||
fd = handle;
|
||||
stream.sendFD(handle, { offset, length });
|
||||
}));
|
||||
} else {
|
||||
assert.strictEqual(variant, 'sendFile');
|
||||
stream.sendFile(__filename, { offset, length });
|
||||
}
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const client = createQuicSocket({
|
||||
client: { key, cert, ca, alpn: 'meow' } });
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
const data = [];
|
||||
stream.on('data', (chunk) => data.push(chunk));
|
||||
stream.on('end', common.mustCall(() => {
|
||||
let expectedContent = fs.readFileSync(__filename);
|
||||
if (offset !== -1) expectedContent = expectedContent.slice(offset);
|
||||
if (length !== -1) expectedContent = expectedContent.slice(0, length);
|
||||
assert.deepStrictEqual(Buffer.concat(data), expectedContent);
|
||||
|
||||
stream.end();
|
||||
client.close();
|
||||
server.close();
|
||||
if (fd !== undefined) {
|
||||
if (fd.close) fd.close().then(common.mustCall());
|
||||
else fs.closeSync(fd);
|
||||
}
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('close', common.mustCall());
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
const fs = require('fs');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const server = createQuicSocket();
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'meow' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = session.openStream({ halfOpen: false });
|
||||
|
||||
fs.open = common.mustCall(fs.open);
|
||||
fs.close = common.mustCall(fs.close);
|
||||
|
||||
stream.sendFile(__filename);
|
||||
stream.destroy(); // Destroy the stream before opening the fd finishes.
|
||||
|
||||
session.close();
|
||||
server.close();
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const client = createQuicSocket({ client: { key, cert, ca, alpn: 'meow' } });
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
req.on('stream', common.mustNotCall());
|
||||
|
||||
req.on('close', common.mustCall(() => client.close()));
|
||||
}));
|
||||
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,49 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const path = require('path');
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const server = createQuicSocket();
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'meow' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = session.openStream({ halfOpen: true });
|
||||
const nonexistentPath = path.resolve(__dirname, 'nonexistent.file');
|
||||
|
||||
stream.sendFile(nonexistentPath, {
|
||||
onError: common.expectsError({
|
||||
code: 'ENOENT',
|
||||
syscall: 'open',
|
||||
path: nonexistentPath
|
||||
})
|
||||
});
|
||||
|
||||
session.close();
|
||||
server.close();
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const client = createQuicSocket({ client: { key, cert, ca, alpn: 'meow' } });
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
req.on('stream', common.mustNotCall());
|
||||
|
||||
req.on('close', common.mustCall(() => client.close()));
|
||||
}));
|
||||
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,49 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const path = require('path');
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const server = createQuicSocket();
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'meow' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = session.openStream({ halfOpen: false });
|
||||
const nonexistentPath = path.resolve(__dirname, 'nonexistent.file');
|
||||
|
||||
stream.on('error', common.expectsError({
|
||||
code: 'ENOENT',
|
||||
syscall: 'open',
|
||||
path: nonexistentPath
|
||||
}));
|
||||
|
||||
stream.sendFile(nonexistentPath);
|
||||
|
||||
session.close();
|
||||
server.close();
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const client = createQuicSocket({ client: { key, cert, ca, alpn: 'meow' } });
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
req.on('stream', common.mustNotCall());
|
||||
|
||||
req.on('close', common.mustCall(() => client.close()));
|
||||
}));
|
||||
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,81 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Test that destroying a QuicStream immediately and synchronously
|
||||
// after creation does not crash the process and closes the streams
|
||||
// abruptly on both ends of the connection.
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const fixtures = require('../common/fixtures');
|
||||
const key = fixtures.readKey('agent1-key.pem', 'binary');
|
||||
const cert = fixtures.readKey('agent1-cert.pem', 'binary');
|
||||
const ca = fixtures.readKey('ca1-cert.pem', 'binary');
|
||||
const { debuglog } = require('util');
|
||||
const debug = debuglog('test');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const kServerPort = process.env.NODE_DEBUG_KEYLOG ? 5678 : 0;
|
||||
const kClientPort = process.env.NODE_DEBUG_KEYLOG ? 5679 : 0;
|
||||
|
||||
const kServerName = 'agent2'; // Intentionally the wrong servername
|
||||
const kALPN = 'zzz'; // ALPN can be overriden to whatever we want
|
||||
|
||||
let client;
|
||||
const server = createQuicSocket({ endpoint: { port: kServerPort } });
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
|
||||
if (process.env.NODE_DEBUG_KEYLOG) {
|
||||
const kl = fs.createWriteStream(process.env.NODE_DEBUG_KEYLOG);
|
||||
session.on('keylog', kl.write.bind(kl));
|
||||
}
|
||||
|
||||
session.on('close', common.mustCall(() => {
|
||||
client.close();
|
||||
server.close();
|
||||
|
||||
assert.throws(() => server.close(), {
|
||||
code: 'ERR_QUICSOCKET_DESTROYED',
|
||||
name: 'Error',
|
||||
message: 'Cannot call close after a QuicSocket has been destroyed'
|
||||
});
|
||||
}));
|
||||
session.on('stream', common.mustNotCall());
|
||||
|
||||
// Prematurely destroy the session without waiting for the
|
||||
// handshake to complete.
|
||||
session.destroy();
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server is listening on port %d', server.endpoints[0].address.port);
|
||||
|
||||
client = createQuicSocket({
|
||||
endpoint: { port: kClientPort },
|
||||
client: { key, cert, ca, alpn: kALPN }
|
||||
});
|
||||
|
||||
client.on('close', common.mustCall(() => {
|
||||
debug('Client closing. Duration', client.duration);
|
||||
}));
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port,
|
||||
servername: kServerName,
|
||||
});
|
||||
|
||||
req.on('secure', common.mustNotCall());
|
||||
req.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
@@ -0,0 +1,19 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
{
|
||||
const socket = createQuicSocket();
|
||||
socket.close(common.mustCall());
|
||||
socket.on('close', common.mustCall());
|
||||
assert.throws(() => socket.close(), {
|
||||
code: 'ERR_QUICSOCKET_DESTROYED',
|
||||
message: 'Cannot call close after a QuicSocket has been destroyed'
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests that stream data is successfully transmitted under
|
||||
// packet loss conditions on the receiving end.
|
||||
|
||||
// TODO(@jasnell): We need an equivalent test that checks
|
||||
// transmission end random packet loss.
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug
|
||||
} = require('../common/quic');
|
||||
// TODO(@jasnell): There's currently a bug in pipeline when piping
|
||||
// a duplex back into to itself.
|
||||
// const { pipeline } = require('stream');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const kData = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
const options = { key, cert, ca, alpn: 'echo' };
|
||||
|
||||
const client = createQuicSocket({ client: options });
|
||||
const server = createQuicSocket({ server: options });
|
||||
|
||||
// Both client and server will drop received packets about 20% of the time
|
||||
// It is important to keep in mind that this will make the runtime of the
|
||||
// test non-deterministic. If we encounter flaky timeouts with this test,
|
||||
// the randomized packet loss will be the reason, but random packet loss
|
||||
// is exactly what is being tested. So if flaky timeouts do occur, it will
|
||||
// be best to extend the failure timeout for this test.
|
||||
server.setDiagnosticPacketLoss({ rx: 0.2 });
|
||||
client.setDiagnosticPacketLoss({ rx: 0.2 });
|
||||
|
||||
const countdown = new Countdown(1, () => {
|
||||
debug('Countdown expired. Destroying sockets');
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen();
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
debug('Bidirectional, Client-initiated stream %d received', stream.id);
|
||||
stream.on('data', (chunk) => stream.write(chunk));
|
||||
stream.on('end', () => stream.end());
|
||||
// TODO(@jasnell): There's currently a bug in pipeline when piping
|
||||
// a duplex back into to itself.
|
||||
// pipeline(stream, stream, common.mustCall((err) => {
|
||||
// assert(!err);
|
||||
// }));
|
||||
}));
|
||||
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server is listening on port %d', server.endpoints[0].address.port);
|
||||
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
debug('QuicClientSession TLS Handshake Complete');
|
||||
|
||||
const stream = req.openStream();
|
||||
|
||||
let n = 0;
|
||||
// This forces multiple stream packets to be sent out
|
||||
// rather than all the data being written in a single
|
||||
// packet.
|
||||
function sendChunk() {
|
||||
if (n < kData.length) {
|
||||
stream.write(kData[n++], common.mustCall());
|
||||
setImmediate(sendChunk);
|
||||
} else {
|
||||
stream.end();
|
||||
}
|
||||
}
|
||||
sendChunk();
|
||||
|
||||
let data = '';
|
||||
stream.resume();
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('end', common.mustCall(() => {
|
||||
debug('Received data: %s', kData);
|
||||
assert.strictEqual(data, kData);
|
||||
}));
|
||||
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Bidirectional, Client-initiated stream %d closed', stream.id);
|
||||
countdown.dec();
|
||||
}));
|
||||
|
||||
debug('Bidirectional, Client-initiated stream %d opened', stream.id);
|
||||
}));
|
||||
}));
|
||||
@@ -0,0 +1,109 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests that stream data is successfully transmitted under
|
||||
// packet loss conditions on the receiving end.
|
||||
|
||||
// TODO(@jasnell): We need an equivalent test that checks
|
||||
// transmission end random packet loss.
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug
|
||||
} = require('../common/quic');
|
||||
// TODO(@jasnell): There's currently a bug in pipeline when piping
|
||||
// a duplex back into to itself.
|
||||
// const { pipeline } = require('stream');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const kData = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
const options = { key, cert, ca, alpn: 'echo' };
|
||||
|
||||
const client = createQuicSocket({ client: options });
|
||||
const server = createQuicSocket({ server: options });
|
||||
|
||||
// Both client and server will drop transmitted packets about 20% of the time
|
||||
// It is important to keep in mind that this will make the runtime of the
|
||||
// test non-deterministic. If we encounter flaky timeouts with this test,
|
||||
// the randomized packet loss will be the reason, but random packet loss
|
||||
// is exactly what is being tested. So if flaky timeouts do occur, it will
|
||||
// be best to extend the failure timeout for this test.
|
||||
server.setDiagnosticPacketLoss({ tx: 0.2 });
|
||||
client.setDiagnosticPacketLoss({ tx: 0.2 });
|
||||
|
||||
const countdown = new Countdown(1, () => {
|
||||
debug('Countdown expired. Destroying sockets');
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen();
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
debug('Bidirectional, Client-initiated stream %d received', stream.id);
|
||||
stream.on('data', (chunk) => stream.write(chunk));
|
||||
stream.on('end', () => stream.end());
|
||||
// TODO(@jasnell): There's currently a bug in pipeline when piping
|
||||
// a duplex back into to itself.
|
||||
// pipeline(stream, stream, common.mustCall((err) => {
|
||||
// assert(!err);
|
||||
// }));
|
||||
}));
|
||||
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server is listening on port %d', server.endpoints[0].address.port);
|
||||
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
debug('QuicClientSession TLS Handshake Complete');
|
||||
|
||||
const stream = req.openStream();
|
||||
|
||||
let n = 0;
|
||||
// This forces multiple stream packets to be sent out
|
||||
// rather than all the data being written in a single
|
||||
// packet.
|
||||
function sendChunk() {
|
||||
if (n < kData.length) {
|
||||
stream.write(kData[n++], common.mustCall());
|
||||
setImmediate(sendChunk);
|
||||
} else {
|
||||
stream.end();
|
||||
}
|
||||
}
|
||||
sendChunk();
|
||||
|
||||
let data = '';
|
||||
stream.resume();
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('end', common.mustCall(() => {
|
||||
debug('Received data: %s', kData);
|
||||
assert.strictEqual(data, kData);
|
||||
}));
|
||||
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Bidirectional, Client-initiated stream %d closed', stream.id);
|
||||
countdown.dec();
|
||||
}));
|
||||
|
||||
debug('Bidirectional, Client-initiated stream %d opened', stream.id);
|
||||
}));
|
||||
}));
|
||||
@@ -0,0 +1,62 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests QUIC server busy support
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug,
|
||||
kServerPort,
|
||||
kClientPort
|
||||
} = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
const options = { key, cert, ca, alpn: 'zzz' };
|
||||
|
||||
let client;
|
||||
const server = createQuicSocket({
|
||||
endpoint: { port: kServerPort },
|
||||
server: options
|
||||
});
|
||||
|
||||
server.on('busy', common.mustCall((busy) => {
|
||||
assert.strictEqual(busy, true);
|
||||
}));
|
||||
|
||||
// When the server is set as busy, all connections
|
||||
// will be rejected with a SERVER_BUSY response.
|
||||
server.setServerBusy();
|
||||
server.listen();
|
||||
|
||||
server.on('close', common.mustCall());
|
||||
server.on('listening', common.mustCall());
|
||||
server.on('session', common.mustNotCall());
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server is listening on port %d', server.endpoints[0].address.port);
|
||||
client = createQuicSocket({
|
||||
endpoint: { port: kClientPort },
|
||||
client: options
|
||||
});
|
||||
|
||||
client.on('close', common.mustCall());
|
||||
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
req.on('secure', common.mustNotCall());
|
||||
|
||||
req.on('close', common.mustCall(() => {
|
||||
server.close();
|
||||
client.close();
|
||||
}));
|
||||
}));
|
||||
@@ -0,0 +1,154 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Test QuicSocket constructor option errors.
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const socket = createQuicSocket();
|
||||
assert(socket);
|
||||
|
||||
// Before listen is called, serverSecureContext is always undefined.
|
||||
assert.strictEqual(socket.serverSecureContext, undefined);
|
||||
|
||||
assert.deepStrictEqual(socket.endpoints.length, 1);
|
||||
|
||||
// Socket is not bound, so address should be empty
|
||||
assert.deepStrictEqual(socket.endpoints[0].address, {});
|
||||
|
||||
// Socket is not bound
|
||||
assert(!socket.bound);
|
||||
|
||||
// Socket is not pending
|
||||
assert(!socket.pending);
|
||||
|
||||
// Socket is not destroyed
|
||||
assert(!socket.destroyed);
|
||||
|
||||
assert.strictEqual(typeof socket.duration, 'bigint');
|
||||
assert.strictEqual(typeof socket.boundDuration, 'bigint');
|
||||
assert.strictEqual(typeof socket.listenDuration, 'bigint');
|
||||
assert.strictEqual(typeof socket.bytesReceived, 'bigint');
|
||||
assert.strictEqual(socket.bytesReceived, 0n);
|
||||
assert.strictEqual(socket.bytesSent, 0n);
|
||||
assert.strictEqual(socket.packetsReceived, 0n);
|
||||
assert.strictEqual(socket.packetsSent, 0n);
|
||||
assert.strictEqual(socket.serverSessions, 0n);
|
||||
assert.strictEqual(socket.clientSessions, 0n);
|
||||
|
||||
const endpoint = socket.endpoints[0];
|
||||
assert(endpoint);
|
||||
|
||||
// Will throw because the QuicSocket is not bound
|
||||
{
|
||||
const err = { code: 'EBADF' };
|
||||
assert.throws(() => endpoint.setTTL(1), err);
|
||||
assert.throws(() => endpoint.setMulticastTTL(1), err);
|
||||
assert.throws(() => endpoint.setBroadcast(), err);
|
||||
assert.throws(() => endpoint.setMulticastLoopback(), err);
|
||||
assert.throws(() => endpoint.setMulticastInterface('0.0.0.0'), err);
|
||||
// TODO(@jasnell): Verify behavior of add/drop membership then test
|
||||
// assert.throws(() => endpoint.addMembership(
|
||||
// '127.0.0.1', '127.0.0.1'), err);
|
||||
// assert.throws(() => endpoint.dropMembership(
|
||||
// '127.0.0.1', '127.0.0.1'), err);
|
||||
}
|
||||
|
||||
['test', null, {}, [], 1n, false].forEach((rx) => {
|
||||
assert.throws(() => socket.setDiagnosticPacketLoss({ rx }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
['test', null, {}, [], 1n, false].forEach((tx) => {
|
||||
assert.throws(() => socket.setDiagnosticPacketLoss({ tx }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
[
|
||||
{ rx: -1 },
|
||||
{ rx: 1.1 },
|
||||
{ tx: -1 },
|
||||
{ tx: 1.1 }
|
||||
].forEach((options) => {
|
||||
assert.throws(() => socket.setDiagnosticPacketLoss(options), {
|
||||
code: 'ERR_OUT_OF_RANGE'
|
||||
});
|
||||
});
|
||||
|
||||
[1, 1n, [], {}, null].forEach((args) => {
|
||||
assert.throws(() => socket.setServerBusy(args), {
|
||||
code: 'ERR_INVALID_ARG_TYPE'
|
||||
});
|
||||
});
|
||||
|
||||
socket.listen({ alpn: 'zzz' });
|
||||
assert(socket.pending);
|
||||
|
||||
socket.on('ready', common.mustCall(() => {
|
||||
assert(endpoint.bound);
|
||||
|
||||
// QuicSocket is already listening.
|
||||
assert.throws(() => socket.listen(), {
|
||||
code: 'ERR_QUICSOCKET_LISTENING'
|
||||
});
|
||||
|
||||
assert.strictEqual(typeof endpoint.address.address, 'string');
|
||||
assert.strictEqual(typeof endpoint.address.port, 'number');
|
||||
assert.strictEqual(typeof endpoint.address.family, 'string');
|
||||
|
||||
if (!common.isWindows)
|
||||
assert.strictEqual(typeof endpoint.fd, 'number');
|
||||
|
||||
endpoint.setTTL(1);
|
||||
endpoint.setMulticastTTL(1);
|
||||
endpoint.setBroadcast();
|
||||
endpoint.setBroadcast(true);
|
||||
endpoint.setBroadcast(false);
|
||||
|
||||
endpoint.setMulticastLoopback();
|
||||
endpoint.setMulticastLoopback(true);
|
||||
endpoint.setMulticastLoopback(false);
|
||||
|
||||
endpoint.setMulticastInterface('0.0.0.0');
|
||||
|
||||
socket.setDiagnosticPacketLoss({ rx: 0.5, tx: 0.5 });
|
||||
|
||||
socket.destroy();
|
||||
assert(socket.destroyed);
|
||||
}));
|
||||
|
||||
socket.on('close', common.mustCall(() => {
|
||||
[
|
||||
'ref',
|
||||
'unref',
|
||||
'setTTL',
|
||||
'setMulticastTTL',
|
||||
'setBroadcast',
|
||||
'setMulticastLoopback',
|
||||
'setMulticastInterface',
|
||||
'addMembership',
|
||||
'dropMembership'
|
||||
].forEach((op) => {
|
||||
assert.throws(() => endpoint[op](), {
|
||||
code: 'ERR_QUICSOCKET_DESTROYED',
|
||||
message: `Cannot call ${op} after a QuicSocket has been destroyed`
|
||||
});
|
||||
});
|
||||
|
||||
[
|
||||
'setServerBusy',
|
||||
].forEach((op) => {
|
||||
assert.throws(() => socket[op](), {
|
||||
code: 'ERR_QUICSOCKET_DESTROYED',
|
||||
message: `Cannot call ${op} after a QuicSocket has been destroyed`
|
||||
});
|
||||
});
|
||||
}));
|
||||
@@ -0,0 +1,122 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug,
|
||||
kServerPort,
|
||||
kClientPort,
|
||||
setupKeylog
|
||||
} = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
let client;
|
||||
const server = createQuicSocket({ endpoint: { port: kServerPort } });
|
||||
|
||||
const kServerName = 'agent1';
|
||||
const kALPN = 'zzz';
|
||||
|
||||
const countdown = new Countdown(2, () => {
|
||||
debug('Countdown expired. Destroying sockets');
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
|
||||
setupKeylog(session);
|
||||
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const uni = session.openStream({ halfOpen: true });
|
||||
|
||||
uni.write('hi', common.expectsError());
|
||||
|
||||
|
||||
uni.on('error', common.mustCall(() => {
|
||||
assert.strictEqual(uni.aborted, true);
|
||||
}));
|
||||
|
||||
uni.on('data', common.mustNotCall());
|
||||
uni.on('close', common.mustCall(() => {
|
||||
debug('Unidirectional, Server-initiated stream %d closed on server',
|
||||
uni.id);
|
||||
}));
|
||||
|
||||
uni.close(3);
|
||||
debug('Unidirectional, Server-initiated stream %d opened', uni.id);
|
||||
}));
|
||||
|
||||
session.on('stream', common.mustNotCall());
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server is listening on port %d', server.endpoints[0].address.port);
|
||||
client = createQuicSocket({
|
||||
endpoint: { port: kClientPort },
|
||||
client: { key, cert, ca, alpn: kALPN }
|
||||
});
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port,
|
||||
servername: kServerName,
|
||||
});
|
||||
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
debug('QuicClientSession TLS Handshake Complete');
|
||||
|
||||
const stream = req.openStream();
|
||||
|
||||
stream.write('hello', common.expectsError());
|
||||
stream.write('there', common.expectsError());
|
||||
|
||||
stream.on('error', common.mustCall(() => {
|
||||
assert.strictEqual(stream.aborted, true);
|
||||
}));
|
||||
|
||||
stream.on('end', common.mustNotCall());
|
||||
|
||||
stream.on('close', common.mustCall(() => {
|
||||
countdown.dec();
|
||||
}));
|
||||
|
||||
stream.close(1);
|
||||
|
||||
debug('Bidirectional, Client-initiated stream %d opened', stream.id);
|
||||
}));
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
debug('Unidirectional, Server-initiated stream %d received', stream.id);
|
||||
stream.on('abort', common.mustNotCall());
|
||||
stream.on('data', common.mustCall((chunk) => {
|
||||
assert.strictEqual(chunk.toString(), 'hi');
|
||||
}));
|
||||
stream.on('end', common.mustCall(() => {
|
||||
debug('Unidirectional, Server-initiated stream %d ended on client',
|
||||
stream.id);
|
||||
}));
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Unidirectional, Server-initiated stream %d closed on client',
|
||||
stream.id);
|
||||
countdown.dec();
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,75 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Test that destroying a QuicStream immediately and synchronously
|
||||
// after creation does not crash the process and closes the streams
|
||||
// abruptly on both ends of the connection.
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const assert = require('assert');
|
||||
const {
|
||||
debug,
|
||||
key,
|
||||
cert,
|
||||
ca
|
||||
} = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const options = { key, cert, ca, alpn: 'zzz' };
|
||||
|
||||
const server = createQuicSocket({ server: options });
|
||||
|
||||
server.listen();
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
stream.destroy();
|
||||
stream.on('close', common.mustCall());
|
||||
stream.on('error', common.mustNotCall());
|
||||
assert(stream.destroyed);
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server is listening on port %d', server.endpoints[0].address.port);
|
||||
|
||||
const client = createQuicSocket({ client: options });
|
||||
|
||||
client.on('close', common.mustCall(() => {
|
||||
debug('Client closing. Duration', client.duration);
|
||||
}));
|
||||
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
req.on('secure', common.mustCall(() => {
|
||||
debug('QuicClientSession TLS Handshake Complete');
|
||||
|
||||
const stream = req.openStream();
|
||||
stream.write('foo');
|
||||
// Do not explicitly end the stream here.
|
||||
|
||||
stream.on('finish', common.mustNotCall());
|
||||
stream.on('data', common.mustNotCall());
|
||||
stream.on('end', common.mustCall());
|
||||
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Stream closed on client side');
|
||||
assert(stream.destroyed);
|
||||
client.close();
|
||||
server.close();
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
@@ -0,0 +1,156 @@
|
||||
// Flags: --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Tests that both client and server can open
|
||||
// bidirectional and unidirectional streams,
|
||||
// and that the properties for each are set
|
||||
// accordingly.
|
||||
//
|
||||
// +------+----------------------------------+
|
||||
// | ID | Stream Type |
|
||||
// +------+----------------------------------+
|
||||
// | 0 | Client-Initiated, Bidirectional |
|
||||
// | | |
|
||||
// | 1 | Server-Initiated, Bidirectional |
|
||||
// | | |
|
||||
// | 2 | Client-Initiated, Unidirectional |
|
||||
// | | |
|
||||
// | 3 | Server-Initiated, Unidirectional |
|
||||
// +------+----------------------------------+
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const { debug, key, cert } = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
const options = { key, cert, alpn: 'zzz' };
|
||||
|
||||
let client;
|
||||
const server = createQuicSocket({ server: options });
|
||||
|
||||
const countdown = new Countdown(4, () => {
|
||||
debug('Countdown expired. Closing sockets');
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
const closeHandler = common.mustCall(() => countdown.dec(), 4);
|
||||
|
||||
server.listen();
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession created');
|
||||
session.on('secure', common.mustCall(() => {
|
||||
debug('QuicServerSession TLS Handshake Completed.');
|
||||
|
||||
([3, 1n, [], {}, null, 'meow']).forEach((halfOpen) => {
|
||||
assert.throws(() => session.openStream({ halfOpen }), {
|
||||
code: 'ERR_INVALID_ARG_TYPE',
|
||||
});
|
||||
});
|
||||
|
||||
const uni = session.openStream({ halfOpen: true });
|
||||
uni.end('test');
|
||||
debug('Unidirectional, Server-initiated stream %d opened', uni.id);
|
||||
|
||||
const bidi = session.openStream();
|
||||
bidi.end('test');
|
||||
bidi.resume();
|
||||
bidi.on('end', common.mustCall());
|
||||
debug('Bidirectional, Server-initiated stream %d opened', bidi.id);
|
||||
|
||||
assert.strictEqual(uni.id, 3);
|
||||
assert(uni.unidirectional);
|
||||
assert(uni.serverInitiated);
|
||||
assert(!uni.bidirectional);
|
||||
assert(!uni.clientInitiated);
|
||||
|
||||
assert.strictEqual(bidi.id, 1);
|
||||
assert(bidi.bidirectional);
|
||||
assert(bidi.serverInitiated);
|
||||
assert(!bidi.unidirectional);
|
||||
assert(!bidi.clientInitiated);
|
||||
}));
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
assert(stream.clientInitiated);
|
||||
assert(!stream.serverInitiated);
|
||||
switch (stream.id) {
|
||||
case 0:
|
||||
debug('Bidirectional, Client-initiated stream %d received', stream.id);
|
||||
assert(stream.bidirectional);
|
||||
assert(!stream.unidirectional);
|
||||
stream.end('test');
|
||||
break;
|
||||
case 2:
|
||||
debug('Unidirectional, Client-initiated stream %d receieved',
|
||||
stream.id);
|
||||
assert(stream.unidirectional);
|
||||
assert(!stream.bidirectional);
|
||||
break;
|
||||
}
|
||||
stream.resume();
|
||||
stream.on('end', common.mustCall());
|
||||
}, 2));
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server listening on port %d', server.endpoints[0].address.port);
|
||||
client = createQuicSocket({ client: options });
|
||||
const req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
req.on('secure', common.mustCall(() => {
|
||||
debug('QuicClientSession TLS Handshake Completed');
|
||||
const bidi = req.openStream();
|
||||
bidi.end('test');
|
||||
bidi.resume();
|
||||
bidi.on('close', closeHandler);
|
||||
assert.strictEqual(bidi.id, 0);
|
||||
debug('Bidirectional, Client-initiated stream %d opened', bidi.id);
|
||||
|
||||
assert(bidi.clientInitiated);
|
||||
assert(bidi.bidirectional);
|
||||
assert(!bidi.serverInitiated);
|
||||
assert(!bidi.unidirectional);
|
||||
|
||||
const uni = req.openStream({ halfOpen: true });
|
||||
uni.end('test');
|
||||
uni.on('close', closeHandler);
|
||||
assert.strictEqual(uni.id, 2);
|
||||
debug('Unidirectional, Client-initiated stream %d opened', uni.id);
|
||||
|
||||
assert(uni.clientInitiated);
|
||||
assert(!uni.bidirectional);
|
||||
assert(!uni.serverInitiated);
|
||||
assert(uni.unidirectional);
|
||||
}));
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
assert(stream.serverInitiated);
|
||||
assert(!stream.clientInitiated);
|
||||
switch (stream.id) {
|
||||
case 1:
|
||||
debug('Bidirectional, Server-initiated stream %d received', stream.id);
|
||||
assert(!stream.unidirectional);
|
||||
assert(stream.bidirectional);
|
||||
stream.end();
|
||||
break;
|
||||
case 3:
|
||||
debug('Unidirectional, Server-initiated stream %d received', stream.id);
|
||||
assert(stream.unidirectional);
|
||||
assert(!stream.bidirectional);
|
||||
}
|
||||
stream.resume();
|
||||
stream.on('end', common.mustCall());
|
||||
stream.on('close', closeHandler);
|
||||
}, 2));
|
||||
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
@@ -0,0 +1,108 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
debug,
|
||||
} = require('../common/quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
const { pipeline } = require('stream');
|
||||
|
||||
let req;
|
||||
let client;
|
||||
let client2;
|
||||
const server = createQuicSocket();
|
||||
|
||||
const options = { key, cert, ca, alpn: 'zzz' };
|
||||
const countdown = new Countdown(2, () => {
|
||||
debug('Countdown expired. Destroying sockets');
|
||||
req.close();
|
||||
server.close();
|
||||
client2.close();
|
||||
});
|
||||
|
||||
server.listen(options);
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
debug('Bidirectional, Client-initiated stream %d received', stream.id);
|
||||
pipeline(stream, stream, common.mustCall());
|
||||
|
||||
session.openStream({ halfOpen: true }).end('Hello from the server');
|
||||
}));
|
||||
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
debug('Server is listening on port %d', server.endpoints[0].address.port);
|
||||
|
||||
client = createQuicSocket({ client: options });
|
||||
client2 = createQuicSocket({ client: options });
|
||||
|
||||
req = client.connect({
|
||||
address: common.localhostIPv4,
|
||||
port: server.endpoints[0].address.port,
|
||||
});
|
||||
|
||||
client.on('close', common.mustCall());
|
||||
|
||||
req.on('secure', common.mustCall(() => {
|
||||
debug('QuicClientSession TLS Handshake Complete');
|
||||
|
||||
let data = '';
|
||||
|
||||
const stream = req.openStream();
|
||||
debug('Bidirectional, Client-initiated stream %d opened', stream.id);
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('end', common.mustCall(() => {
|
||||
assert.strictEqual(data, 'Hello from the client');
|
||||
debug('Client received expected data for stream %d', stream.id);
|
||||
}));
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Bidirectional, Client-initiated stream %d closed', stream.id);
|
||||
countdown.dec();
|
||||
}));
|
||||
// Send some data on one connection...
|
||||
stream.write('Hello ');
|
||||
|
||||
// Wait just a bit, then migrate to a different
|
||||
// QuicSocket and continue sending.
|
||||
setTimeout(common.mustCall(() => {
|
||||
req.setSocket(client2, (err) => {
|
||||
assert(!err);
|
||||
client.close();
|
||||
stream.end('from the client');
|
||||
});
|
||||
}), common.platformTimeout(100));
|
||||
}));
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
debug('Unidirectional, Server-initiated stream %d received', stream.id);
|
||||
let data = '';
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk) => data += chunk);
|
||||
stream.on('end', common.mustCall(() => {
|
||||
assert.strictEqual(data, 'Hello from the server');
|
||||
debug('Client received expected data for stream %d', stream.id);
|
||||
}));
|
||||
stream.on('close', common.mustCall(() => {
|
||||
debug('Unidirectional, Server-initiated stream %d closed', stream.id);
|
||||
countdown.dec();
|
||||
}));
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
server.on('close', common.mustCall());
|
||||
@@ -0,0 +1,76 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
// Testing stateless reset
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const { internalBinding } = require('internal/test/binding');
|
||||
const assert = require('assert');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const {
|
||||
kHandle,
|
||||
} = require('internal/stream_base_commons');
|
||||
const { silentCloseSession } = internalBinding('quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const kStatelessResetToken =
|
||||
Buffer.from('000102030405060708090A0B0C0D0E0F', 'hex');
|
||||
|
||||
let client;
|
||||
|
||||
const server = createQuicSocket({ statelessResetSecret: kStatelessResetToken });
|
||||
|
||||
server.listen({ key, cert, ca, alpn: 'zzz' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
// silentCloseSession is an internal-only testing tool
|
||||
// that allows us to prematurely destroy a QuicSession
|
||||
// without the proper communication flow with the connected
|
||||
// peer. We call this to simulate a local crash that loses
|
||||
// state, which should trigger the server to send a
|
||||
// stateless reset token to the client.
|
||||
silentCloseSession(session[kHandle]);
|
||||
}));
|
||||
|
||||
session.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('close', common.mustCall(() => {
|
||||
// Verify stats recording
|
||||
assert.strictEqual(server.statelessResetCount, 1n);
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const endpoint = server.endpoints[0];
|
||||
|
||||
client = createQuicSocket({ client: { key, cert, ca, alpn: 'zzz' } });
|
||||
|
||||
client.on('close', common.mustCall());
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: endpoint.address.port,
|
||||
servername: 'localhost',
|
||||
});
|
||||
|
||||
req.on('secure', common.mustCall(() => {
|
||||
const stream = req.openStream();
|
||||
stream.end('hello');
|
||||
stream.resume();
|
||||
stream.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall(() => {
|
||||
assert.strictEqual(req.statelessReset, true);
|
||||
server.close();
|
||||
client.close();
|
||||
}));
|
||||
|
||||
}));
|
||||
@@ -0,0 +1,61 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
// Tests that QUIC works properly when using a pair of mocked UDP ports.
|
||||
|
||||
const { makeUDPPair } = require('../common/udppair');
|
||||
const assert = require('assert');
|
||||
const { createQuicSocket } = require('net');
|
||||
const { kUDPHandleForTesting } = require('internal/quic/core');
|
||||
|
||||
const { key, cert, ca } = require('../common/quic');
|
||||
|
||||
const { serverSide, clientSide } = makeUDPPair();
|
||||
|
||||
const server = createQuicSocket({
|
||||
endpoint: { [kUDPHandleForTesting]: serverSide._handle }
|
||||
});
|
||||
|
||||
serverSide.afterBind();
|
||||
server.listen({ key, cert, ca, alpn: 'meow' });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall(() => {
|
||||
const stream = session.openStream({ halfOpen: false });
|
||||
stream.end('Hi!');
|
||||
stream.on('data', common.mustNotCall());
|
||||
stream.on('finish', common.mustCall());
|
||||
stream.on('close', common.mustNotCall());
|
||||
stream.on('end', common.mustNotCall());
|
||||
}));
|
||||
|
||||
session.on('close', common.mustNotCall());
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const client = createQuicSocket({
|
||||
endpoint: { [kUDPHandleForTesting]: clientSide._handle },
|
||||
client: { key, cert, ca, alpn: 'meow' }
|
||||
});
|
||||
clientSide.afterBind();
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: server.endpoints[0].address.port
|
||||
});
|
||||
|
||||
req.on('stream', common.mustCall((stream) => {
|
||||
stream.on('data', common.mustCall((data) => {
|
||||
assert.strictEqual(data.toString(), 'Hi!');
|
||||
}));
|
||||
|
||||
stream.on('end', common.mustCall());
|
||||
}));
|
||||
|
||||
req.on('close', common.mustNotCall());
|
||||
}));
|
||||
|
||||
server.on('close', common.mustNotCall());
|
||||
@@ -0,0 +1,152 @@
|
||||
// Flags: --expose-internals
|
||||
'use strict';
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
const { recordState } = require('../common/heap');
|
||||
const fixtures = require('../common/fixtures');
|
||||
const key = fixtures.readKey('agent1-key.pem', 'binary');
|
||||
const cert = fixtures.readKey('agent1-cert.pem', 'binary');
|
||||
const ca = fixtures.readKey('ca1-cert.pem', 'binary');
|
||||
|
||||
{
|
||||
const state = recordState();
|
||||
state.validateSnapshotNodes('Node / QuicStream', []);
|
||||
state.validateSnapshotNodes('Node / QuicSession', []);
|
||||
state.validateSnapshotNodes('Node / QuicSocket', []);
|
||||
}
|
||||
|
||||
const server = createQuicSocket({ port: 0, validateAddress: true });
|
||||
|
||||
server.listen({
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
rejectUnauthorized: false,
|
||||
maxCryptoBuffer: 4096,
|
||||
alpn: 'meow'
|
||||
});
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
session.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const stream = session.openStream({ halfOpen: false });
|
||||
|
||||
const state = recordState();
|
||||
|
||||
state.validateSnapshotNodes('Node / QuicSocket', [
|
||||
{
|
||||
children: [
|
||||
{ node_name: 'QuicSocket', edge_name: 'wrapped' },
|
||||
{ node_name: 'BigUint64Array', edge_name: 'stats_buffer' },
|
||||
{ node_name: 'Node / sessions', edge_name: 'sessions' },
|
||||
{ node_name: 'Node / dcid_to_scid', edge_name: 'dcid_to_scid' },
|
||||
]
|
||||
}
|
||||
], { loose: true });
|
||||
|
||||
state.validateSnapshotNodes('Node / QuicStream', [
|
||||
{
|
||||
children: [
|
||||
{ node_name: 'QuicStream', edge_name: 'wrapped' },
|
||||
{ node_name: 'BigUint64Array', edge_name: 'stats_buffer' },
|
||||
{ node_name: 'Node / QuicBuffer', edge_name: 'buffer' },
|
||||
{ node_name: 'Node / HistogramBase', edge_name: 'data_rx_rate' },
|
||||
{ node_name: 'Node / HistogramBase', edge_name: 'data_rx_size' },
|
||||
{ node_name: 'Node / HistogramBase', edge_name: 'data_rx_ack' }
|
||||
]
|
||||
}
|
||||
], { loose: true });
|
||||
|
||||
state.validateSnapshotNodes('Node / QuicBuffer', [
|
||||
{
|
||||
children: [
|
||||
{ node_name: 'Node / length', edge_name: 'length' }
|
||||
]
|
||||
}
|
||||
], { loose: true });
|
||||
|
||||
state.validateSnapshotNodes('Node / QuicSession', [
|
||||
{
|
||||
children: [
|
||||
{ node_name: 'QuicServerSession', edge_name: 'wrapped' },
|
||||
{ node_name: 'Node / QuicCryptoContext',
|
||||
edge_name: 'crypto_context' },
|
||||
{ node_name: 'Node / HistogramBase', edge_name: 'crypto_rx_ack' },
|
||||
{ node_name: 'Node / HistogramBase',
|
||||
edge_name: 'crypto_handshake_rate' },
|
||||
{ node_name: 'Node / Timer', edge_name: 'retransmit' },
|
||||
{ node_name: 'Node / Timer', edge_name: 'idle' },
|
||||
{ node_name: 'Node / QuicBuffer', edge_name: 'sendbuf' },
|
||||
{ node_name: 'Node / QuicBuffer', edge_name: 'txbuf' },
|
||||
{ node_name: 'Float64Array', edge_name: 'recovery_stats_buffer' },
|
||||
{ node_name: 'BigUint64Array', edge_name: 'stats_buffer' },
|
||||
{ node_name: 'Node / current_ngtcp2_memory',
|
||||
edge_name: 'current_ngtcp2_memory' },
|
||||
{ node_name: 'Node / streams', edge_name: 'streams' },
|
||||
{ node_name: 'Node / std::basic_string', edge_name: 'alpn' },
|
||||
{ node_name: 'Node / std::basic_string', edge_name: 'hostname' },
|
||||
{ node_name: 'Float64Array', edge_name: 'state' },
|
||||
]
|
||||
},
|
||||
{
|
||||
children: [
|
||||
{ node_name: 'QuicClientSession', edge_name: 'wrapped' },
|
||||
{ node_name: 'Node / QuicCryptoContext',
|
||||
edge_name: 'crypto_context' },
|
||||
{ node_name: 'Node / HistogramBase', edge_name: 'crypto_rx_ack' },
|
||||
{ node_name: 'Node / HistogramBase',
|
||||
edge_name: 'crypto_handshake_rate' },
|
||||
{ node_name: 'Node / Timer', edge_name: 'retransmit' },
|
||||
{ node_name: 'Node / Timer', edge_name: 'idle' },
|
||||
{ node_name: 'Node / QuicBuffer', edge_name: 'sendbuf' },
|
||||
{ node_name: 'Node / QuicBuffer', edge_name: 'txbuf' },
|
||||
{ node_name: 'Float64Array', edge_name: 'recovery_stats_buffer' },
|
||||
{ node_name: 'BigUint64Array', edge_name: 'stats_buffer' },
|
||||
{ node_name: 'Node / current_ngtcp2_memory',
|
||||
edge_name: 'current_ngtcp2_memory' },
|
||||
{ node_name: 'Node / streams', edge_name: 'streams' },
|
||||
{ node_name: 'Node / std::basic_string', edge_name: 'alpn' },
|
||||
{ node_name: 'Node / std::basic_string', edge_name: 'hostname' },
|
||||
{ node_name: 'Float64Array', edge_name: 'state' },
|
||||
]
|
||||
}
|
||||
], { loose: true });
|
||||
|
||||
state.validateSnapshotNodes('Node / QuicCryptoContext', [
|
||||
{
|
||||
children: [
|
||||
{ node_name: 'Node / rx_secret', edge_name: 'rx_secret' },
|
||||
{ node_name: 'Node / tx_secret', edge_name: 'tx_secret' },
|
||||
{ node_name: 'Node / QuicBuffer', edge_name: 'initial_crypto' },
|
||||
{ node_name: 'Node / QuicBuffer',
|
||||
edge_name: 'handshake_crypto' },
|
||||
{ node_name: 'Node / QuicBuffer', edge_name: 'app_crypto' },
|
||||
]
|
||||
}
|
||||
], { loose: true });
|
||||
|
||||
session.destroy();
|
||||
server.close();
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const client = createQuicSocket({
|
||||
port: 0,
|
||||
client: {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
alpn: 'meow'
|
||||
}
|
||||
});
|
||||
|
||||
client.connect({
|
||||
address: 'localhost',
|
||||
port: server.address.port
|
||||
}).on('close', common.mustCall(() => client.close()));
|
||||
}));
|
||||
@@ -45,6 +45,12 @@ const { getSystemErrorName } = require('util');
|
||||
delete providers.STREAMPIPE;
|
||||
delete providers.MESSAGEPORT;
|
||||
delete providers.WORKER;
|
||||
// TODO(danbev): Test for these
|
||||
delete providers.QUICCLIENTSESSION;
|
||||
delete providers.QUICSERVERSESSION;
|
||||
delete providers.QUICSENDWRAP;
|
||||
delete providers.QUICSOCKET;
|
||||
delete providers.QUICSTREAM;
|
||||
delete providers.JSUDPWRAP;
|
||||
if (!common.isMainThread)
|
||||
delete providers.INSPECTORJSBINDING;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const fixtures = require('../common/fixtures');
|
||||
const key = fixtures.readKey('agent1-key.pem', 'binary');
|
||||
const cert = fixtures.readKey('agent1-cert.pem', 'binary');
|
||||
const ca = fixtures.readKey('ca1-cert.pem', 'binary');
|
||||
const { debuglog } = require('util');
|
||||
const debug = debuglog('test');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
let client;
|
||||
|
||||
const server = createQuicSocket({ endpoint: { type: 'udp6' } });
|
||||
|
||||
const kALPN = 'zzz'; // ALPN can be overriden to whatever we want
|
||||
|
||||
const countdown = new Countdown(1, () => {
|
||||
debug('Countdown expired. Destroying sockets');
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN, preferredAddress: {
|
||||
port: common.PORT,
|
||||
address: '::',
|
||||
type: 'udp6',
|
||||
} });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
stream.end('hello world');
|
||||
stream.resume();
|
||||
stream.on('close', common.mustCall());
|
||||
stream.on('finish', common.mustCall());
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const endpoints = server.endpoints;
|
||||
for (const endpoint of endpoints) {
|
||||
const address = endpoint.address;
|
||||
debug('Server is listening on address %s:%d',
|
||||
address.address,
|
||||
address.port);
|
||||
}
|
||||
const endpoint = endpoints[0];
|
||||
|
||||
client = createQuicSocket({ endpoint: { type: 'udp6' }, client: {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
alpn: kALPN,
|
||||
preferredAddressPolicy: 'accept' } });
|
||||
|
||||
client.on('close', common.mustCall());
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: endpoint.address.port,
|
||||
servername: 'localhost',
|
||||
type: 'udp6',
|
||||
});
|
||||
|
||||
req.on('ready', common.mustCall(() => {
|
||||
req.on('usePreferredAddress', common.mustCall(({ address, port, type }) => {
|
||||
assert.strictEqual(address, '::');
|
||||
assert.strictEqual(port, common.PORT);
|
||||
assert.strictEqual(type, 'udp6');
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = req.openStream();
|
||||
stream.end('hello world');
|
||||
stream.resume();
|
||||
|
||||
stream.on('close', common.mustCall(() => {
|
||||
countdown.dec();
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
@@ -0,0 +1,93 @@
|
||||
// Flags: --expose-internals --no-warnings
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
if (!common.hasQuic)
|
||||
common.skip('missing quic');
|
||||
|
||||
const Countdown = require('../common/countdown');
|
||||
const assert = require('assert');
|
||||
const fixtures = require('../common/fixtures');
|
||||
const key = fixtures.readKey('agent1-key.pem', 'binary');
|
||||
const cert = fixtures.readKey('agent1-cert.pem', 'binary');
|
||||
const ca = fixtures.readKey('ca1-cert.pem', 'binary');
|
||||
const { debuglog } = require('util');
|
||||
const debug = debuglog('test');
|
||||
|
||||
const { createQuicSocket } = require('net');
|
||||
|
||||
let client;
|
||||
|
||||
const server = createQuicSocket();
|
||||
|
||||
const kALPN = 'zzz'; // ALPN can be overriden to whatever we want
|
||||
|
||||
const countdown = new Countdown(1, () => {
|
||||
debug('Countdown expired. Destroying sockets');
|
||||
server.close();
|
||||
client.close();
|
||||
});
|
||||
|
||||
server.listen({ key, cert, ca, alpn: kALPN, preferredAddress: {
|
||||
port: common.PORT,
|
||||
address: '0.0.0.0',
|
||||
type: 'udp4',
|
||||
} });
|
||||
|
||||
server.on('session', common.mustCall((session) => {
|
||||
debug('QuicServerSession Created');
|
||||
session.on('stream', common.mustCall((stream) => {
|
||||
stream.end('hello world');
|
||||
stream.resume();
|
||||
stream.on('close', common.mustCall());
|
||||
stream.on('finish', common.mustCall());
|
||||
}));
|
||||
}));
|
||||
|
||||
server.on('ready', common.mustCall(() => {
|
||||
const endpoints = server.endpoints;
|
||||
for (const endpoint of endpoints) {
|
||||
const address = endpoint.address;
|
||||
debug('Server is listening on address %s:%d',
|
||||
address.address,
|
||||
address.port);
|
||||
}
|
||||
const endpoint = endpoints[0];
|
||||
|
||||
client = createQuicSocket({ client: {
|
||||
key,
|
||||
cert,
|
||||
ca,
|
||||
alpn: kALPN,
|
||||
preferredAddressPolicy: 'accept' } });
|
||||
|
||||
client.on('close', common.mustCall());
|
||||
|
||||
const req = client.connect({
|
||||
address: 'localhost',
|
||||
port: endpoint.address.port,
|
||||
servername: 'localhost',
|
||||
});
|
||||
|
||||
req.on('ready', common.mustCall(() => {
|
||||
req.on('usePreferredAddress', common.mustCall(({ address, port, type }) => {
|
||||
assert.strictEqual(address, '0.0.0.0');
|
||||
assert.strictEqual(port, common.PORT);
|
||||
assert.strictEqual(type, 'udp4');
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('secure', common.mustCall((servername, alpn, cipher) => {
|
||||
const stream = req.openStream();
|
||||
stream.end('hello world');
|
||||
stream.resume();
|
||||
|
||||
stream.on('close', common.mustCall(() => {
|
||||
countdown.dec();
|
||||
}));
|
||||
}));
|
||||
|
||||
req.on('close', common.mustCall());
|
||||
}));
|
||||
|
||||
server.on('listening', common.mustCall());
|
||||
@@ -138,6 +138,10 @@ const customTypesMap = {
|
||||
'perf_hooks.html#perf_hooks_class_perf_hooks_performanceobserver',
|
||||
'PerformanceObserverEntryList':
|
||||
'perf_hooks.html#perf_hooks_class_performanceobserverentrylist',
|
||||
'QuicEndpoint': 'quic.html#quic_class_quicendpoint',
|
||||
'QuicSession': 'quic.html#quic_class_quicserversession_extends_quicsession',
|
||||
'QuicSocket': 'quic.html#quic_net_createquicsocket_options',
|
||||
'QuicStream': 'quic.html#quic_class_quicstream_extends_stream_duplex',
|
||||
|
||||
'readline.Interface': 'readline.html#readline_class_interface',
|
||||
|
||||
|
||||
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user