Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

‎doc/api/quic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
***Default:**`30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

‎lib/internal/quic/quic.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if(error!==undefined){
924925
error=convertQuicError(error);
926+
}elseif(this[kOwner]&&!this[kOwner].destroyed){
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
constresetCode=getQuicStreamState(this[kOwner]).resetCode;
933+
if(resetCode!==undefined&&resetCode>0n){
934+
error=newERR_QUIC_APPLICATION_ERROR(
935+
resetCode,`stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy ='drop-oldest',
50165028
drainingPeriodMultiplier =3,
50175029
maxDatagramSendAttempts =5,
5030+
streamIdleTimeout,
50185031
verifyPeer ='auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

‎lib/internal/quic/stats.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT!==undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED!==undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST!==undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT!==undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT!==undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT!==undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT!==undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
returnthis.#handle[this.#offset +IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
getstreamsIdleTimedOut(){
696+
assertIsQuicSessionStats(this);
697+
returnthis.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString(){
693702
returnJSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
}=this;
730740
return{
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
}=this;
811823

812824
return`QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
},opts)}`;
845858
}
846859

‎src/quic/application.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
voidEarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

‎src/quic/bindingdata.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

‎src/quic/data.cc‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
returnUndefined(env->isolate());
376376
}

‎src/quic/http3.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

‎src/quic/session.cc‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#defineNO_SIDE_EFFECTtrue
180181
#defineSIDE_EFFECTfalse
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
voidSession::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
voidSession::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
voidSession::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
voidSession::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (constauto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
voidSession::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

‎src/quic/session.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
staticconstexpruint64_tDEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
voidUpdatePacketTxTime();
571579
voidUpdateDataStats();
580+
voidCheckStreamIdleTimeout(uint64_t now);
572581
voidUpdatePath(const PathStorage& path);
573582

574583
voidProcessPendingBidiStreams();

‎src/quic/streams.cc‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_tStream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
boolStream::is_local_unidirectional() const {
13511357
returndirection() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
voidStream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

‎doc/api/quic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
***Default:**`30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

‎lib/internal/quic/quic.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if(error!==undefined){
924925
error=convertQuicError(error);
926+
}elseif(this[kOwner]&&!this[kOwner].destroyed){
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
constresetCode=getQuicStreamState(this[kOwner]).resetCode;
933+
if(resetCode!==undefined&&resetCode>0n){
934+
error=newERR_QUIC_APPLICATION_ERROR(
935+
resetCode,`stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy ='drop-oldest',
50165028
drainingPeriodMultiplier =3,
50175029
maxDatagramSendAttempts =5,
5030+
streamIdleTimeout,
50185031
verifyPeer ='auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

‎lib/internal/quic/stats.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT!==undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED!==undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST!==undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT!==undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT!==undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT!==undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT!==undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
returnthis.#handle[this.#offset +IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
getstreamsIdleTimedOut(){
696+
assertIsQuicSessionStats(this);
697+
returnthis.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString(){
693702
returnJSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
}=this;
730740
return{
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
}=this;
811823

812824
return`QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
},opts)}`;
845858
}
846859

‎src/quic/application.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
voidEarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

‎src/quic/bindingdata.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

‎src/quic/data.cc‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
returnUndefined(env->isolate());
376376
}

‎src/quic/http3.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

‎src/quic/session.cc‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#defineNO_SIDE_EFFECTtrue
180181
#defineSIDE_EFFECTfalse
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
voidSession::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
voidSession::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
voidSession::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
voidSession::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (constauto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
voidSession::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

‎src/quic/session.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
staticconstexpruint64_tDEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
voidUpdatePacketTxTime();
571579
voidUpdateDataStats();
580+
voidCheckStreamIdleTimeout(uint64_t now);
572581
voidUpdatePath(const PathStorage& path);
573582

574583
voidProcessPendingBidiStreams();

‎src/quic/streams.cc‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_tStream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
boolStream::is_local_unidirectional() const {
13511357
returndirection() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
voidStream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

‎doc/api/quic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
***Default:**`30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

‎lib/internal/quic/quic.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if(error!==undefined){
924925
error=convertQuicError(error);
926+
}elseif(this[kOwner]&&!this[kOwner].destroyed){
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
constresetCode=getQuicStreamState(this[kOwner]).resetCode;
933+
if(resetCode!==undefined&&resetCode>0n){
934+
error=newERR_QUIC_APPLICATION_ERROR(
935+
resetCode,`stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy ='drop-oldest',
50165028
drainingPeriodMultiplier =3,
50175029
maxDatagramSendAttempts =5,
5030+
streamIdleTimeout,
50185031
verifyPeer ='auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

‎lib/internal/quic/stats.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT!==undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED!==undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST!==undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT!==undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT!==undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT!==undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT!==undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
returnthis.#handle[this.#offset +IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
getstreamsIdleTimedOut(){
696+
assertIsQuicSessionStats(this);
697+
returnthis.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString(){
693702
returnJSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
}=this;
730740
return{
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
}=this;
811823

812824
return`QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
},opts)}`;
845858
}
846859

‎src/quic/application.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
voidEarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

‎src/quic/bindingdata.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

‎src/quic/data.cc‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
returnUndefined(env->isolate());
376376
}

‎src/quic/http3.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

‎src/quic/session.cc‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#defineNO_SIDE_EFFECTtrue
180181
#defineSIDE_EFFECTfalse
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
voidSession::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
voidSession::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
voidSession::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
voidSession::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (constauto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
voidSession::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

‎src/quic/session.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
staticconstexpruint64_tDEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
voidUpdatePacketTxTime();
571579
voidUpdateDataStats();
580+
voidCheckStreamIdleTimeout(uint64_t now);
572581
voidUpdatePath(const PathStorage& path);
573582

574583
voidProcessPendingBidiStreams();

‎src/quic/streams.cc‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_tStream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
boolStream::is_local_unidirectional() const {
13511357
returndirection() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
voidStream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

‎doc/api/quic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
***Default:**`30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

‎lib/internal/quic/quic.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if(error!==undefined){
924925
error=convertQuicError(error);
926+
}elseif(this[kOwner]&&!this[kOwner].destroyed){
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
constresetCode=getQuicStreamState(this[kOwner]).resetCode;
933+
if(resetCode!==undefined&&resetCode>0n){
934+
error=newERR_QUIC_APPLICATION_ERROR(
935+
resetCode,`stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy ='drop-oldest',
50165028
drainingPeriodMultiplier =3,
50175029
maxDatagramSendAttempts =5,
5030+
streamIdleTimeout,
50185031
verifyPeer ='auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

‎lib/internal/quic/stats.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT!==undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED!==undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST!==undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT!==undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT!==undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT!==undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT!==undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
returnthis.#handle[this.#offset +IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
getstreamsIdleTimedOut(){
696+
assertIsQuicSessionStats(this);
697+
returnthis.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString(){
693702
returnJSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
}=this;
730740
return{
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
}=this;
811823

812824
return`QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
},opts)}`;
845858
}
846859

‎src/quic/application.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
voidEarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

‎src/quic/bindingdata.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

‎src/quic/data.cc‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
returnUndefined(env->isolate());
376376
}

‎src/quic/http3.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

‎src/quic/session.cc‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#defineNO_SIDE_EFFECTtrue
180181
#defineSIDE_EFFECTfalse
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
voidSession::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
voidSession::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
voidSession::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
voidSession::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (constauto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
voidSession::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

‎src/quic/session.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
staticconstexpruint64_tDEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
voidUpdatePacketTxTime();
571579
voidUpdateDataStats();
580+
voidCheckStreamIdleTimeout(uint64_t now);
572581
voidUpdatePath(const PathStorage& path);
573582

574583
voidProcessPendingBidiStreams();

‎src/quic/streams.cc‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_tStream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
boolStream::is_local_unidirectional() const {
13511357
returndirection() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
voidStream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

‎doc/api/quic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
***Default:**`30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

‎lib/internal/quic/quic.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if(error!==undefined){
924925
error=convertQuicError(error);
926+
}elseif(this[kOwner]&&!this[kOwner].destroyed){
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
constresetCode=getQuicStreamState(this[kOwner]).resetCode;
933+
if(resetCode!==undefined&&resetCode>0n){
934+
error=newERR_QUIC_APPLICATION_ERROR(
935+
resetCode,`stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy ='drop-oldest',
50165028
drainingPeriodMultiplier =3,
50175029
maxDatagramSendAttempts =5,
5030+
streamIdleTimeout,
50185031
verifyPeer ='auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

‎lib/internal/quic/stats.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT!==undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED!==undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST!==undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT!==undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT!==undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT!==undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT!==undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
returnthis.#handle[this.#offset +IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
getstreamsIdleTimedOut(){
696+
assertIsQuicSessionStats(this);
697+
returnthis.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString(){
693702
returnJSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
}=this;
730740
return{
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
}=this;
811823

812824
return`QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
},opts)}`;
845858
}
846859

‎src/quic/application.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
voidEarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

‎src/quic/bindingdata.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

‎src/quic/data.cc‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
returnUndefined(env->isolate());
376376
}

‎src/quic/http3.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

‎src/quic/session.cc‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#defineNO_SIDE_EFFECTtrue
180181
#defineSIDE_EFFECTfalse
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
voidSession::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
voidSession::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
voidSession::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
voidSession::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (constauto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
voidSession::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

‎src/quic/session.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
staticconstexpruint64_tDEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
voidUpdatePacketTxTime();
571579
voidUpdateDataStats();
580+
voidCheckStreamIdleTimeout(uint64_t now);
572581
voidUpdatePath(const PathStorage& path);
573582

574583
voidProcessPendingBidiStreams();

‎src/quic/streams.cc‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_tStream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
boolStream::is_local_unidirectional() const {
13511357
returndirection() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
voidStream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

‎doc/api/quic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
***Default:**`30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

‎lib/internal/quic/quic.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if(error!==undefined){
924925
error=convertQuicError(error);
926+
}elseif(this[kOwner]&&!this[kOwner].destroyed){
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
constresetCode=getQuicStreamState(this[kOwner]).resetCode;
933+
if(resetCode!==undefined&&resetCode>0n){
934+
error=newERR_QUIC_APPLICATION_ERROR(
935+
resetCode,`stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy ='drop-oldest',
50165028
drainingPeriodMultiplier =3,
50175029
maxDatagramSendAttempts =5,
5030+
streamIdleTimeout,
50185031
verifyPeer ='auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

‎lib/internal/quic/stats.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT!==undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED!==undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST!==undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT!==undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT!==undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT!==undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT!==undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
returnthis.#handle[this.#offset +IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
getstreamsIdleTimedOut(){
696+
assertIsQuicSessionStats(this);
697+
returnthis.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString(){
693702
returnJSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
}=this;
730740
return{
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
}=this;
811823

812824
return`QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
},opts)}`;
845858
}
846859

‎src/quic/application.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
voidEarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

‎src/quic/bindingdata.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

‎src/quic/data.cc‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
returnUndefined(env->isolate());
376376
}

‎src/quic/http3.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

‎src/quic/session.cc‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#defineNO_SIDE_EFFECTtrue
180181
#defineSIDE_EFFECTfalse
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
voidSession::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
voidSession::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
voidSession::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
voidSession::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (constauto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
voidSession::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

‎src/quic/session.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
staticconstexpruint64_tDEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
voidUpdatePacketTxTime();
571579
voidUpdateDataStats();
580+
voidCheckStreamIdleTimeout(uint64_t now);
572581
voidUpdatePath(const PathStorage& path);
573582

574583
voidProcessPendingBidiStreams();

‎src/quic/streams.cc‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_tStream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
boolStream::is_local_unidirectional() const {
13511357
returndirection() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
voidStream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

‎doc/api/quic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
***Default:**`30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

‎lib/internal/quic/quic.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if(error!==undefined){
924925
error=convertQuicError(error);
926+
}elseif(this[kOwner]&&!this[kOwner].destroyed){
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
constresetCode=getQuicStreamState(this[kOwner]).resetCode;
933+
if(resetCode!==undefined&&resetCode>0n){
934+
error=newERR_QUIC_APPLICATION_ERROR(
935+
resetCode,`stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy ='drop-oldest',
50165028
drainingPeriodMultiplier =3,
50175029
maxDatagramSendAttempts =5,
5030+
streamIdleTimeout,
50185031
verifyPeer ='auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

‎lib/internal/quic/stats.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT!==undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED!==undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST!==undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT!==undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT!==undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT!==undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT!==undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
returnthis.#handle[this.#offset +IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
getstreamsIdleTimedOut(){
696+
assertIsQuicSessionStats(this);
697+
returnthis.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString(){
693702
returnJSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
}=this;
730740
return{
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
}=this;
811823

812824
return`QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
},opts)}`;
845858
}
846859

‎src/quic/application.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
voidEarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

‎src/quic/bindingdata.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

‎src/quic/data.cc‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
returnUndefined(env->isolate());
376376
}

‎src/quic/http3.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

‎src/quic/session.cc‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#defineNO_SIDE_EFFECTtrue
180181
#defineSIDE_EFFECTfalse
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
voidSession::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
voidSession::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
voidSession::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
voidSession::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (constauto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
voidSession::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

‎src/quic/session.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
staticconstexpruint64_tDEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
voidUpdatePacketTxTime();
571579
voidUpdateDataStats();
580+
voidCheckStreamIdleTimeout(uint64_t now);
572581
voidUpdatePath(const PathStorage& path);
573582

574583
voidProcessPendingBidiStreams();

‎src/quic/streams.cc‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_tStream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
boolStream::is_local_unidirectional() const {
13511357
returndirection() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
voidStream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 7652bd9

Browse files
jasnelladuh95
authored andcommitted
quic: add stream idle timeout
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode:Opus 4.6 PR-URL: #63483 Backport-PR-URL: #64675 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e493f04 commit 7652bd9

18 files changed

Lines changed: 516 additions & 34 deletions

‎doc/api/quic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,6 +1659,11 @@ added: v23.8.0
16591659

16601660
* Type: {bigint}
16611661

1662+
### `sessionStats.streamsIdleTimedOut`
1663+
1664+
* Type: {bigint} The total number of peer-initiated streams destroyed by the
1665+
stream idle timeout. Read only.
1666+
16621667
## Class: `QuicError`
16631668

16641669
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
30263031

30273032
This option is immutable after session creation.
30283033

3034+
#### `sessionOptions.streamIdleTimeout`
3035+
3036+
* Type: {bigint|number}
3037+
***Default:**`30000` (30 seconds)
3038+
3039+
The maximum time in milliseconds that a peer-initiated stream can be idle
3040+
(no data received) before it is automatically destroyed. This protects
3041+
against slowloris-style attacks where a remote peer opens streams but never
3042+
sends data, holding server resources indefinitely. Only peer-initiated
3043+
streams are checked — locally-initiated streams are the application's
3044+
responsibility. Set to `0` to disable.
3045+
3046+
The idle check runs as part of the normal send processing loop, so it adds
3047+
no additional timers or event loop overhead. The
3048+
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
3049+
destroyed by this mechanism.
3050+
30293051
#### `sessionOptions.maxDatagramSendAttempts`
30303052

30313053
* Type: {number}

‎lib/internal/quic/quic.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
436436
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
437437
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
438438
* **Default:** `3`.
439+
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
439440
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
440441
* datagram is retried before being abandoned. Range `1..255`.
441442
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
922923
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
923924
if(error!==undefined){
924925
error=convertQuicError(error);
926+
}elseif(this[kOwner]&&!this[kOwner].destroyed){
927+
// The stream is closing cleanly, but it may have been reset by the
928+
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
929+
// records the reset code in state.resetCode. If set, surface the
930+
// reset as the close error so stream.closed rejects -- the reset
931+
// was an abnormal termination even if the session closed cleanly.
932+
constresetCode=getQuicStreamState(this[kOwner]).resetCode;
933+
if(resetCode!==undefined&&resetCode>0n){
934+
error=newERR_QUIC_APPLICATION_ERROR(
935+
resetCode,`stream reset with code ${resetCode}`);
936+
}
925937
}
926938
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
927939
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
50155027
datagramDropPolicy ='drop-oldest',
50165028
drainingPeriodMultiplier =3,
50175029
maxDatagramSendAttempts =5,
5030+
streamIdleTimeout,
50185031
verifyPeer ='auto',
50195032
// HTTP/3 application-specific options. Nested under `application`
50205033
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
51365149
datagramDropPolicy,
51375150
drainingPeriodMultiplier,
51385151
maxDatagramSendAttempts,
5152+
streamIdleTimeout,
51395153
application,
51405154
onerror,
51415155
onstream,

‎lib/internal/quic/stats.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const {
101101
IDX_STATS_SESSION_DATAGRAMS_SENT,
102102
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
103103
IDX_STATS_SESSION_DATAGRAMS_LOST,
104+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
104105
IDX_STATS_SESSION_COUNT,
105106

106107
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
169170
assert(IDX_STATS_SESSION_DATAGRAMS_SENT!==undefined);
170171
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED!==undefined);
171172
assert(IDX_STATS_SESSION_DATAGRAMS_LOST!==undefined);
173+
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT!==undefined);
172174
assert(IDX_STATS_STREAM_CREATED_AT!==undefined);
173175
assert(IDX_STATS_STREAM_OPENED_AT!==undefined);
174176
assert(IDX_STATS_STREAM_RECEIVED_AT!==undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
689691
returnthis.#handle[this.#offset +IDX_STATS_SESSION_DATAGRAMS_LOST];
690692
}
691693

694+
/** @type {bigint} */
695+
getstreamsIdleTimedOut(){
696+
assertIsQuicSessionStats(this);
697+
returnthis.#handle[this.#offset +
698+
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
699+
}
700+
692701
toString(){
693702
returnJSONStringify(this.toJSON());
694703
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
726735
datagramsSent,
727736
datagramsAcknowledged,
728737
datagramsLost,
738+
streamsIdleTimedOut,
729739
}=this;
730740
return{
731741
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
762772
datagramsSent: `${datagramsSent}`,
763773
datagramsAcknowledged: `${datagramsAcknowledged}`,
764774
datagramsLost: `${datagramsLost}`,
775+
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
765776
};
766777
}
767778

@@ -807,6 +818,7 @@ class QuicSessionStats {
807818
datagramsSent,
808819
datagramsAcknowledged,
809820
datagramsLost,
821+
streamsIdleTimedOut,
810822
}=this;
811823

812824
return`QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
841853
datagramsSent,
842854
datagramsAcknowledged,
843855
datagramsLost,
856+
streamsIdleTimedOut,
844857
},opts)}`;
845858
}
846859

‎src/quic/application.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
724724

725725
voidEarlyDataRejected() override {
726726
// Destroy all open streams — ngtcp2 has already discarded their
727-
// internal state when it rejected the early data.
728-
session().DestroyAllStreams(QuicError::ForApplication(0));
727+
// internal state when it rejected the early data. Use the
728+
// application's internal error code since this is an error
729+
// condition (code 0 would be treated as a clean close).
730+
session().DestroyAllStreams(
731+
QuicError::ForApplication(GetInternalErrorCode()));
729732
if (!session().is_destroyed()) {
730733
session().EmitEarlyDataRejected();
731734
}

‎src/quic/bindingdata.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ class SessionManager;
113113
V(max_connections_total, "maxConnectionsTotal") \
114114
V(max_datagram_frame_size, "maxDatagramFrameSize") \
115115
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
116+
V(stream_idle_timeout, "streamIdleTimeout") \
116117
V(max_field_section_size, "maxFieldSectionSize") \
117118
V(max_header_length, "maxHeaderLength") \
118119
V(max_header_pairs, "maxHeaderPairs") \

‎src/quic/data.cc‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
365365

366366
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
367367
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
368-
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
368+
(type() == Type::APPLICATION &&
369+
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
369370
type() == Type::IDLE_CLOSE) {
370-
// Note that we only return undefined for *known* no-error application
371-
// codes. It is possible that other application types use other specific
372-
// no-error codes, but since we don't know which application is being used,
373-
// we'll just return the error code value for those below.
371+
// Application code 0 is the default no-error code for raw QUIC
372+
// applications (DefaultApplication::GetNoErrorCode() returns 0).
373+
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
374374
// Idle close is always clean — the session timed out normally.
375375
returnUndefined(env->isolate());
376376
}

‎src/quic/http3.cc‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
177177
// When 0-RTT is rejected, destroy the nghttp3 connection and all
178178
// open streams — ngtcp2 has discarded their internal state.
179179
// Reset started_ so Start() is called again via on_receive_rx_key
180-
// at 1RTT to recreate the nghttp3 connection.
180+
// at 1RTT to recreate the nghttp3 connection. Use the
181+
// application's internal error code since this is an error
182+
// condition (code 0 would be treated as a clean close).
181183
conn_.reset();
182184
started_ = false;
183-
session().DestroyAllStreams(QuicError::ForApplication(0));
185+
session().DestroyAllStreams(
186+
QuicError::ForApplication(GetInternalErrorCode()));
184187
if (!session().is_destroyed()) {
185188
session().EmitEarlyDataRejected();
186189
}

‎src/quic/session.cc‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
174174
V(DATAGRAMS_RECEIVED, datagrams_received) \
175175
V(DATAGRAMS_SENT, datagrams_sent) \
176176
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
177-
V(DATAGRAMS_LOST, datagrams_lost)
177+
V(DATAGRAMS_LOST, datagrams_lost) \
178+
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
178179

179180
#defineNO_SIDE_EFFECTtrue
180181
#defineSIDE_EFFECTfalse
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
617618
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
618619
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
619620
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
620-
!SET(max_datagram_send_attempts)) {
621+
!SET(max_datagram_send_attempts) ||
622+
!SET(stream_idle_timeout)) {
621623
return Nothing<Options>();
622624
}
623625

@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
28192821
DCHECK(!is_destroyed());
28202822
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
28212823
SendPendingDataScope send_scope(this);
2822-
ngtcp2_conn_shutdown_stream(*this,
2823-
0,
2824-
id,
2825-
error.type() == QuicError::Type::APPLICATION
2826-
? error.code()
2827-
: application().GetNoErrorCode());
2824+
// STOP_SENDING and RESET_STREAM frames carry application-level error
2825+
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
2826+
// application code: APPLICATION errors pass through directly; transport
2827+
// no-error maps to the application's no-error code; any other error
2828+
// maps to the application's internal error code.
2829+
error_code code;
2830+
if (error.type() == QuicError::Type::APPLICATION) {
2831+
code = error.code();
2832+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2833+
code = application().GetNoErrorCode();
2834+
} else {
2835+
code = application().GetInternalErrorCode();
2836+
}
2837+
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
28282838
}
28292839

2830-
voidSession::ShutdownStreamWrite(stream_id id, QuicError code) {
2840+
voidSession::ShutdownStreamWrite(stream_id id, QuicError error) {
28312841
DCHECK(!is_destroyed());
2832-
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
2842+
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
2843+
id, error);
28332844
SendPendingDataScope send_scope(this);
2834-
ngtcp2_conn_shutdown_stream_write(*this,
2835-
0,
2836-
id,
2837-
code.type() == QuicError::Type::APPLICATION
2838-
? code.code()
2839-
: application().GetNoErrorCode());
2845+
error_code code;
2846+
if (error.type() == QuicError::Type::APPLICATION) {
2847+
code = error.code();
2848+
} elseif (error.code() == NGTCP2_NO_ERROR) {
2849+
code = application().GetNoErrorCode();
2850+
} else {
2851+
code = application().GetInternalErrorCode();
2852+
}
2853+
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
28402854
}
28412855

28422856
voidSession::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
30353049
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
30363050
}
30373051

3052+
voidSession::CheckStreamIdleTimeout(uint64_t now) {
3053+
if (is_destroyed()) return;
3054+
uint64_t timeout = options().stream_idle_timeout;
3055+
if (timeout == 0) return;
3056+
3057+
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
3058+
auto all_streams = streams();
3059+
3060+
for (constauto& [id, stream] : all_streams) {
3061+
if (!stream) continue;
3062+
3063+
// Only check peer-initiated streams. Locally-initiated streams
3064+
// that haven't been written to are the application's concern.
3065+
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
3066+
3067+
uint64_t last_activity = stream->last_activity_timestamp();
3068+
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
3069+
Debug(this,
3070+
"Stream %" PRId64 " idle timeout exceeded, destroying",
3071+
id);
3072+
// Notify the peer before destroying. ShutdownStream sends both
3073+
// STOP_SENDING and RESET_STREAM as appropriate, using the
3074+
// application's no-error code for non-APPLICATION errors (since
3075+
// these frames carry application-level error codes per RFC 9000).
3076+
// Without this, the peer's stream sits orphaned until the
3077+
// session closes.
3078+
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
3079+
"stream idle timeout");
3080+
ShutdownStream(id, error);
3081+
stream->Destroy(error);
3082+
STAT_INCREMENT(Stats, streams_idle_timed_out);
3083+
}
3084+
}
3085+
}
3086+
30383087
voidSession::SendConnectionClose() {
30393088
// Method is a non-op if the session is already destroyed or the
30403089
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
31193168
if (is_destroyed()) return;
31203169
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
31213170
application().SendPendingData();
3171+
if (is_destroyed()) return;
3172+
CheckStreamIdleTimeout(uv_hrtime());
31223173
return;
31233174
}
31243175
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
31653216
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
31663217
Debug(this, "Updating timeout to %zu milliseconds", timeout);
31673218

3219+
// If a stream idle timeout is configured, ensure the timer fires at
3220+
// least that often so CheckStreamIdleTimeout runs. Without this, an
3221+
// idle session with idle streams might not fire the timer until the
3222+
// connection idle timeout, which could be much longer.
3223+
uint64_t stream_idle = options().stream_idle_timeout;
3224+
if (stream_idle > 0 && timeout > stream_idle) {
3225+
timeout = stream_idle;
3226+
}
3227+
31683228
// If timeout is zero here, it means our timer is less than a millisecond
31693229
// off from expiry. Let's bump the timer to 1.
31703230
impl_->timer_.Update(timeout == 0 ? 1 : timeout);

‎src/quic/session.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
227227
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
228228
uint8_t draining_period_multiplier = 3;
229229

230+
// The amount of time (in milliseconds) that a stream can be idle
231+
// (no data received) before it is automatically destroyed. This
232+
// protects against slowloris-style attacks where a peer opens streams
233+
// but never sends data, holding server resources indefinitely.
234+
// Only applies to peer-initiated streams. Set to 0 to disable.
235+
staticconstexpruint64_tDEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
236+
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
237+
230238
// An optional NEW_TOKEN from a previous connection to the same
231239
// server. When set, the token is included in the Initial packet
232240
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
569577
// Has to be called after certain operations that generate packets.
570578
voidUpdatePacketTxTime();
571579
voidUpdateDataStats();
580+
voidCheckStreamIdleTimeout(uint64_t now);
572581
voidUpdatePath(const PathStorage& path);
573582

574583
voidProcessPendingBidiStreams();

‎src/quic/streams.cc‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
12701270
// Headers were enqueued while the application was not yet known
12711271
// (headers_supported == 0), and the negotiated application does
12721272
// not support headers. This is a fatal mismatch.
1273-
Destroy(QuicError::ForApplication(0));
1273+
Destroy(QuicError::ForApplication(
1274+
session().application().GetInternalErrorCode()));
12741275
return;
12751276
}
12761277
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
13471348
return *session_;
13481349
}
13491350

1351+
uint64_tStream::last_activity_timestamp() const {
1352+
uint64_t ts = stats()->received_at;
1353+
return ts != 0 ? ts : stats()->created_at;
1354+
}
1355+
13501356
boolStream::is_local_unidirectional() const {
13511357
returndirection() == Direction::UNIDIRECTIONAL &&
13521358
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
16251631

16261632
voidStream::Destroy(QuicError error) {
16271633
if (stats()->destroyed_at != 0) return;
1634+
16281635
// Record the destroyed at timestamp before notifying the JavaScript side
16291636
// that the stream is being destroyed.
16301637
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);

0 commit comments

Comments
 (0)