Skip to content

Commit 6728a1c

Browse files
authored
http2: flush final GOAWAY after pending writes
Keep the native close pending when an active socket write prevents the terminal GOAWAY from being serialized. Finish the close after the outgoing buffers become available, preserving the requested error code. Handle synchronous completion and transport errors without retrying writes to a failed transport or losing the socket close notification. Add a deterministic regression for default and custom GOAWAY codes, both inside and outside the receive callback. Fixes: nodejs#66832 Assisted-by: Codex Signed-off-by: Emerson Gomes <[email protected]> PR-URL: nodejs#66834 Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Tim Perry <[email protected]>
1 parent 4ad8171 commit 6728a1c

3 files changed

Lines changed: 124 additions & 15 deletions

File tree

‎src/node_http2.cc‎

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -848,19 +848,22 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
848848
return;
849849
set_closing();
850850

851+
pending_close_code_ = code;
852+
pending_close_socket_closed_ = socket_closed;
853+
851854
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
852855
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
853856
if (is_receiving()) {
854857
set_close_pending();
855-
pending_close_code_ = code;
856-
pending_close_socket_closed_ = socket_closed;
857858
return;
858859
}
859860

860861
FinishClose(code, socket_closed);
861862
}
862863

863-
void Http2Session::FinishClose(uint32_t code, bool socket_closed) {
864+
void Http2Session::FinishClose(uint32_t code,
865+
bool socket_closed,
866+
int write_status) {
864867
CHECK(is_closing());
865868

866869
// Stop reading on the i/o stream
@@ -869,15 +872,20 @@ void Http2Session::FinishClose(uint32_t code, bool socket_closed) {
869872
stream_->ReadStop();
870873
}
871874

872-
// If the socket is not closed, then attempt to send a closing GOAWAY
875+
// If the socket is still writable, attempt to send a closing GOAWAY
873876
// frame. There is no guarantee that this GOAWAY will be received by
874877
// the peer but the HTTP/2 spec recommends sending it anyway. We'll
875878
// make a best effort.
876-
if (!socket_closed) {
879+
if (!socket_closed && write_status == 0) {
877880
Debug(this, "terminating session with code %d", code);
878881
CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0);
879-
SendPendingData();
880-
} else if (stream_ != nullptr) {
882+
if (SendPendingData() != 0) {
883+
// An earlier write still owns the outgoing buffers. Keep the session
884+
// alive until its completion lets us flush the terminal GOAWAY.
885+
set_close_pending();
886+
return;
887+
}
888+
} else if (socket_closed && stream_ != nullptr) {
881889
// so that the previous listener of the socket, typically, JS code of a
882890
// (tls) socket will be notified of any activity later
883891
stream_->RemoveStreamListener(this);
@@ -912,10 +920,12 @@ void Http2Session::FinishClose(uint32_t code, bool socket_closed) {
912920
EmitStatistics();
913921
}
914922

915-
void Http2Session::MaybeFinishPendingClose() {
916-
if (!is_close_pending() || is_destroyed()) return;
923+
void Http2Session::MaybeFinishPendingClose(int status) {
924+
if (!is_close_pending() || is_destroyed() || is_receiving() || is_sending()) {
925+
return;
926+
}
917927
set_close_pending(false);
918-
FinishClose(pending_close_code_, pending_close_socket_closed_);
928+
FinishClose(pending_close_code_, pending_close_socket_closed_, status);
919929
}
920930

921931
// Locates an existing known stream by ID. nghttp2 has a similar method
@@ -1890,9 +1900,16 @@ void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
18901900
CHECK(is_write_in_progress());
18911901
set_write_in_progress(false);
18921902

1903+
// ClearOutgoing() may synchronously finish a pending close.
1904+
const bool close_pending = is_close_pending();
18931905
// Inform all pending writes about their completion.
18941906
ClearOutgoing(status);
18951907

1908+
if (close_pending || is_close_pending()) {
1909+
MaybeFinishPendingClose(status);
1910+
return;
1911+
}
1912+
18961913
if (is_reading_stopped() &&
18971914
!is_write_in_progress() &&
18981915
nghttp2_session_want_read(session_.get())) {
@@ -2007,7 +2024,7 @@ void Http2Session::ClearOutgoing(int status) {
20072024

20082025
// Now that we've finished sending queued data, if there are any pending
20092026
// RstStreams we should try sending again and then flush them one by one.
2010-
if (!pending_rst_streams_.empty()) {
2027+
if (status == 0 && !pending_rst_streams_.empty()) {
20112028
std::vector<int32_t> current_pending_rst_streams;
20122029
pending_rst_streams_.swap(current_pending_rst_streams);
20132030

@@ -2129,6 +2146,7 @@ uint8_t Http2Session::SendPendingData() {
21292146
set_write_in_progress(false);
21302147
ClearOutgoing(res.err);
21312148
MaybeNotifyGracefulCloseComplete();
2149+
MaybeFinishPendingClose(res.err);
21322150
}
21332151

21342152
MaybeStopReading();

‎src/node_http2.h‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,8 +1071,8 @@ class Http2Session : public AsyncWrap,
10711071
std::vector<uint8_t> outgoing_storage_;
10721072
size_t outgoing_length_ = 0;
10731073
std::vector<int32_t> pending_rst_streams_;
1074-
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
1075-
// callbacks are active.
1074+
// Saved arguments for Close() deferred while receiving data or waiting for
1075+
// an outgoing write to finish.
10761076
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
10771077
bool pending_close_socket_closed_ = false;
10781078
// Count streams that have been rejected while being opened. Exceeding a fixed
@@ -1089,8 +1089,8 @@ class Http2Session : public AsyncWrap,
10891089

10901090
void CopyDataIntoOutgoing(const uint8_t* src, size_t src_length);
10911091
void ClearOutgoing(int status);
1092-
void FinishClose(uint32_t code, bool socket_closed);
1093-
void MaybeFinishPendingClose();
1092+
void FinishClose(uint32_t code, bool socket_closed, int write_status = 0);
1093+
void MaybeFinishPendingClose(int status = 0);
10941094

10951095
void MaybeNotifyGracefulCloseComplete();
10961096

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
if (!common.hasCrypto)
5+
common.skip('missing crypto');
6+
7+
// Destroying a session while a socket write is pending must flush the final
8+
// GOAWAY before ending the socket, including when called from a stream handler.
9+
const assert = require('assert');
10+
const http2 = require('http2');
11+
const { Duplex } = require('stream');
12+
const {
13+
HeadersFrame,
14+
SettingsFrame,
15+
kClientMagic,
16+
kFakeRequestHeaders,
17+
} = require('../common/http2');
18+
19+
for (const [code, deferDestroy] of [
20+
[0, false],
21+
[http2.constants.NGHTTP2_REFUSED_STREAM, false],
22+
[0, true],
23+
[http2.constants.NGHTTP2_REFUSED_STREAM, true],
24+
]) {
25+
const output = [];
26+
let pendingWrite;
27+
const socket = new Duplex({
28+
read() {},
29+
write(chunk, encoding, callback) {
30+
output.push(Buffer.from(chunk));
31+
if (pendingWrite === undefined) {
32+
// Hold the initial SETTINGS write until the stream handler destroys
33+
// the session. No timers or large response bodies are needed.
34+
pendingWrite = callback;
35+
setImmediate(() => {
36+
socket.push(new HeadersFrame(1, kFakeRequestHeaders, 0, true).data);
37+
});
38+
} else {
39+
callback();
40+
}
41+
},
42+
});
43+
44+
const session = http2.performServerHandshake(socket);
45+
session.on('stream', common.mustCall((stream) => {
46+
assert.strictEqual(typeof pendingWrite, 'function');
47+
stream.on('close', common.mustCall());
48+
if (code !== 0) {
49+
stream.on('error', common.mustCall((err) => {
50+
assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_ERROR');
51+
}));
52+
}
53+
const destroy = common.mustCall(() => {
54+
session.destroy(code);
55+
assert.strictEqual(session.destroyed, true);
56+
setImmediate(common.mustCall(() => {
57+
const callback = pendingWrite;
58+
pendingWrite = null;
59+
callback();
60+
}));
61+
});
62+
if (deferDestroy)
63+
setImmediate(destroy);
64+
else
65+
destroy();
66+
}));
67+
session.on('close', common.mustCall());
68+
if (code !== 0) {
69+
session.on('error', common.mustCall((err) => {
70+
assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_ERROR');
71+
}));
72+
}
73+
74+
socket.on('finish', common.mustCall(() => {
75+
const data = Buffer.concat(output);
76+
let goaways = 0;
77+
for (let offset = 0; offset < data.length;) {
78+
const length = data.readUIntBE(offset, 3);
79+
assert(data.length >= offset + 9 + length);
80+
if (data[offset + 3] === 7) {
81+
goaways++;
82+
assert.strictEqual(data.readUInt32BE(offset + 9), 1);
83+
assert.strictEqual(data.readUInt32BE(offset + 13), code);
84+
}
85+
offset += 9 + length;
86+
}
87+
assert.strictEqual(goaways, 1);
88+
}));
89+
90+
socket.push(Buffer.concat([kClientMagic, new SettingsFrame().data]));
91+
}

0 commit comments

Comments
 (0)