Skip to content

Commit b6d94f3

Browse files
pimterryaduh95
authored andcommitted
http2: don't fail response reads after clean RST_STREAM
Signed-off-by: Tim Perry <pimterry@gmail.com> PR-URL: #67558 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 4b806e1 commit b6d94f3

5 files changed

Lines changed: 261 additions & 11 deletions

File tree

‎lib/internal/http2/core.js‎

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,7 @@ const STREAM_FLAGS_HEAD_REQUEST = 0x8;
354354
const STREAM_FLAGS_ABORTED = 0x10;
355355
const STREAM_FLAGS_HAS_TRAILERS = 0x20;
356356
const STREAM_FLAGS_RST_DEFERRED = 0x40;
357+
const STREAM_FLAGS_CLEAN_REQUEST_RESET = 0x80;
357358

358359
const SESSION_FLAGS_PENDING = 0x0;
359360
const SESSION_FLAGS_READY = 0x1;
@@ -611,7 +612,8 @@ function streamNaturalCloseSettled(stream) {
611612
return (stream._readableState.endEmitted ||
612613
!!stream._readableState.errored) &&
613614
(stream._writableState.finished ||
614-
!!stream._writableState.errored);
615+
!!stream._writableState.errored ||
616+
!!(stream[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET));
615617
}
616618

617619
// Shared 'end'/'finish'/'error' listener for the natural-close path of
@@ -632,7 +634,9 @@ function maybeDestroyNaturalClose() {
632634
// Clean code = NO_ERROR or CANCEL.
633635
//
634636
// Natural close defers destroy until 'end' and 'finish' - nghttp2 can
635-
// fire on_stream_close ahead of our last frame leaving the socket.
637+
// fire on_stream_close ahead of our last frame leaving the socket. On the
638+
// client, a clean reset for a request after a response END_STREAM just defers
639+
// until 'end', so the buffered response stays readable, with writes ignored.
636640
function onStreamClose(code, peerReset) {
637641
const stream = this[kOwner];
638642
if (!stream || stream.destroyed)
@@ -672,7 +676,12 @@ function onStreamClose(code, peerReset) {
672676

673677
// Peer END_STREAMed - reads will complete. Only the writable half can
674678
// still be in flight at the protocol layer.
675-
if (peerReset) {
679+
const keepResponse = cleanCode &&
680+
stream[kSession][kType] === NGHTTP2_SESSION_CLIENT;
681+
if (peerReset && keepResponse) {
682+
stream[kState].flags |= STREAM_FLAGS_CLEAN_REQUEST_RESET;
683+
process.nextTick(settleWrite, stream);
684+
} else if (peerReset) {
676685
if (!cleanCode && !stream._writableState.finished) {
677686
stream.destroy(
678687
new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code));
@@ -2131,6 +2140,18 @@ function finishWrite(stream) {
21312140
cb(err);
21322141
}
21332142

2143+
// A write in flight may never get its native completion callback once the
2144+
// stream is closed; settle it so the Writable can make progress.
2145+
function settleWrite(stream, err) {
2146+
const state = stream[kState];
2147+
if (state.writeCb !== null) {
2148+
const writeCb = state.writeCb;
2149+
state.writeCb = null;
2150+
state.writePending = 0;
2151+
writeCb(err);
2152+
}
2153+
}
2154+
21342155
// Runs on the tick after a write was dispatched: if the write turned out to
21352156
// be the last chunk of an ending writable, shut the writable side down right
21362157
// away so the final DATA frame can include the END_STREAM flag.
@@ -2507,6 +2528,10 @@ class Http2Stream extends Duplex {
25072528
if (this.destroyed)
25082529
return;
25092530

2531+
// The server no longer wants the rest of the request; discard it quietly.
2532+
if (this[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET)
2533+
return cb();
2534+
25102535
this[kUpdateTimer]();
25112536
if (!this.headersSent)
25122537
this[kProceed]();
@@ -2594,6 +2619,8 @@ class Http2Stream extends Duplex {
25942619
this.once('ready', () => this._final(cb));
25952620
return;
25962621
}
2622+
if (this[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET)
2623+
return cb();
25972624
debugStreamObj(this, 'shutting down writable on _final');
25982625
shutdownWritable.call(this, cb);
25992626

@@ -2793,14 +2820,7 @@ class Http2Stream extends Duplex {
27932820
}
27942821
}
27952822

2796-
// A write in flight may never get its native completion callback once the
2797-
// stream tears down; settle it so the Writable can clean up.
2798-
if (state.writeCb !== null) {
2799-
const writeCb = state.writeCb;
2800-
state.writeCb = null;
2801-
state.writePending = 0;
2802-
writeCb(err);
2803-
}
2823+
settleWrite(this, err);
28042824
callback(err);
28052825
}
28062826
// The Http2Stream can be destroyed if it has closed and if the readable

‎test/common/README.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -884,6 +884,24 @@ socket.write(frame.data);
884884

885885
The serialized `Buffer` may be retrieved using the `frame.data` property.
886886

887+
### Class: `DataFrame`
888+
889+
The `http2.DataFrame` is a subclass of `http2.Frame` that serializes a `DATA`
890+
frame.
891+
892+
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
893+
894+
```js
895+
// id is the 32-bit stream identifier
896+
// payload is a Buffer containing the DATA payload
897+
// padlen is an 8-bit integer giving the number of padding bytes to include
898+
// final is a boolean indicating whether the End-of-stream flag should be set,
899+
// defaults to false.
900+
const frame = new http2.DataFrame(id, payload, padlen, final);
901+
902+
socket.write(frame.data);
903+
```
904+
887905
### Class: `HeadersFrame`
888906

889907
The `http2.HeadersFrame` is a subclass of `http2.Frame` that serializes a
@@ -903,6 +921,21 @@ const frame = new http2.HeadersFrame(id, payload, padlen, final);
903921
socket.write(frame.data);
904922
```
905923

924+
### Class: `RstStreamFrame`
925+
926+
The `http2.RstStreamFrame` is a subclass of `http2.Frame` that serializes an
927+
`RST_STREAM` frame.
928+
929+
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
930+
931+
```js
932+
// id is the 32-bit stream identifier
933+
// code is the 32-bit error code, defaults to 0 (NO_ERROR).
934+
const frame = new http2.RstStreamFrame(id, code);
935+
936+
socket.write(frame.data);
937+
```
938+
906939
### Class: `SettingsFrame`
907940

908941
The `http2.SettingsFrame` is a subclass of `http2.Frame` that serializes an

‎test/common/http2.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,33 @@ class HeadersFrame extends Frame {
9999
}
100100
}
101101

102+
class DataFrame extends Frame {
103+
constructor(id, payload, padlen = 0, final = false) {
104+
let len = payload.length;
105+
let flags = 0;
106+
if (final) flags |= FLAG_EOS;
107+
const buffers = [payload];
108+
if (padlen > 0) {
109+
buffers.unshift(Buffer.from([padlen]));
110+
buffers.push(PADDING.slice(0, padlen));
111+
len += padlen + 1;
112+
flags |= FLAG_PADDED;
113+
}
114+
super(len, 0, flags, id);
115+
buffers.unshift(this[kFrameData]);
116+
this[kFrameData] = Buffer.concat(buffers);
117+
}
118+
}
119+
120+
class RstStreamFrame extends Frame {
121+
constructor(id, code = 0) {
122+
super(4, 3, 0, id);
123+
const payload = Buffer.alloc(4);
124+
write32BE(payload, 0, code);
125+
this[kFrameData] = Buffer.concat([this[kFrameData], payload]);
126+
}
127+
}
128+
102129
class PingFrame extends Frame {
103130
constructor(ack = false) {
104131
const buffers = [Buffer.alloc(8)];
@@ -120,7 +147,9 @@ class AltSvcFrame extends Frame {
120147
module.exports = {
121148
Frame,
122149
AltSvcFrame,
150+
DataFrame,
123151
HeadersFrame,
152+
RstStreamFrame,
124153
SettingsFrame,
125154
PingFrame,
126155
kFakeRequestHeaders,
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
'use strict';
2+
3+
// RFC 9113 section 8.1 allows a server to send RST_STREAM(NO_ERROR) after a
4+
// complete response while the request is still open, and clients must not
5+
// discard the response because of it. This is how servers send clients a
6+
// response that cancels a request (e.g. politely rejecting an upload).
7+
// The response should still stay fully readable and end cleanly, while the
8+
// rest of the request is quietly discarded.
9+
// Refs: https://github.com/nodejs/node/issues/66693
10+
11+
const common = require('../common');
12+
if (!common.hasCrypto)
13+
common.skip('missing crypto');
14+
15+
const assert = require('assert');
16+
const http2 = require('http2');
17+
const { once } = require('events');
18+
19+
const body = 'upload rejected';
20+
21+
const server = http2.createServer();
22+
server.on('stream', common.mustCall((stream) => {
23+
stream.respond({ ':status': 413 });
24+
stream.once('data', common.mustCall(() => {
25+
stream.end(body);
26+
stream.close(http2.constants.NGHTTP2_NO_ERROR);
27+
}));
28+
}));
29+
30+
server.listen(0, common.mustCall(async () => {
31+
const session = http2.connect(`http://localhost:${server.address().port}`);
32+
const request = session.request({ ':method': 'POST' });
33+
request.on('error', common.mustNotCall());
34+
const [headers] = await once(request, 'response');
35+
assert.strictEqual(headers[':status'], 413);
36+
37+
// Keep uploading without reading the response. The reset arrives partway
38+
// through, and neither the write in flight then nor later ones may stall.
39+
const chunk = Buffer.alloc(16 * 1024);
40+
for (let i = 0; i < 20; i++) {
41+
await new Promise((resolve) => {
42+
request.write(chunk, common.mustSucceed(resolve));
43+
});
44+
}
45+
assert.strictEqual(request.closed, true);
46+
assert.strictEqual(request.rstCode, http2.constants.NGHTTP2_NO_ERROR);
47+
assert.strictEqual(request.destroyed, false);
48+
49+
request.end();
50+
await once(request, 'finish');
51+
52+
let received = '';
53+
request.setEncoding('utf8');
54+
request.on('data', (chunk) => { received += chunk; });
55+
request.on('end', common.mustCall());
56+
await once(request, 'close');
57+
assert.strictEqual(received, body);
58+
59+
session.close();
60+
server.close();
61+
}));
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
'use strict';
2+
3+
// A server may send the final DATA, trailers with END_STREAM and
4+
// RST_STREAM(NO_ERROR) together while the request is still open (RFC 9113
5+
// section 8.1), as gRPC servers do. A client that has paused partway through
6+
// the response must still be able to read the rest, and likewise for
7+
// RST_STREAM(CANCEL), which should only affect the request.
8+
// This closely reproduces https://github.com/nodejs/node/issues/66693
9+
// which requires some raw frame writes to match the reset behaviour.
10+
11+
const common = require('../common');
12+
if (!common.hasCrypto)
13+
common.skip('missing crypto');
14+
15+
const assert = require('assert');
16+
const http2 = require('http2');
17+
const net = require('net');
18+
const { once } = require('events');
19+
const { setImmediate: setImmediateAsync } = require('timers/promises');
20+
const h2test = require('../common/http2');
21+
22+
const first = Buffer.from('first chunk');
23+
const last = Buffer.from('last chunk');
24+
// HPACK: indexed :status 200.
25+
const responseHeaders = Buffer.from([0x88]);
26+
// HPACK: literal without indexing, grpc-status: 0.
27+
const responseTrailers = Buffer.concat([
28+
Buffer.from([0x00, 11]), Buffer.from('grpc-status'),
29+
Buffer.from([1]), Buffer.from('0'),
30+
]);
31+
const streamId = 1;
32+
const startRequest = 'start of request';
33+
const continueRequest = 'more of request';
34+
35+
async function startServer(code) {
36+
const server = net.createServer(common.mustCall((socket) => {
37+
// Client request -> response frames flow for the server:
38+
const replies = [
39+
[startRequest, [
40+
new h2test.HeadersFrame(streamId, responseHeaders),
41+
new h2test.DataFrame(streamId, first),
42+
]],
43+
[continueRequest, [
44+
new h2test.DataFrame(streamId, last),
45+
new h2test.HeadersFrame(streamId, responseTrailers, 0, true),
46+
new h2test.RstStreamFrame(streamId, code),
47+
]],
48+
];
49+
50+
let received = Buffer.alloc(0);
51+
socket.on('error', () => {});
52+
socket.on('data', (chunk) => {
53+
received = Buffer.concat([received, chunk]);
54+
while (replies.length > 0 && received.includes(replies[0][0])) {
55+
const [, frames] = replies.shift();
56+
socket.write(Buffer.concat(frames.map((frame) => frame.data)));
57+
}
58+
});
59+
60+
// Write settings to start the session:
61+
socket.write(new h2test.SettingsFrame().data);
62+
socket.write(new h2test.SettingsFrame(true).data);
63+
}));
64+
server.listen(0);
65+
await once(server, 'listening');
66+
return server;
67+
}
68+
69+
(async () => {
70+
for (const code of [
71+
http2.constants.NGHTTP2_NO_ERROR,
72+
http2.constants.NGHTTP2_CANCEL,
73+
]) {
74+
const server = await startServer(code);
75+
const session = http2.connect(`http://localhost:${server.address().port}`);
76+
const request = session.request({ ':method': 'POST' });
77+
request.on('error', common.mustNotCall());
78+
request.on('response', common.mustCall());
79+
80+
// Read the first response chunk, then stop reading.
81+
request.write(startRequest);
82+
const [chunk] = await once(request, 'data');
83+
assert.deepStrictEqual(chunk, first);
84+
request.pause();
85+
86+
// Trigger the last response chunk + trailers + RST_STREAM.
87+
request.write(continueRequest);
88+
const [trailers] = await once(request, 'trailers');
89+
assert.strictEqual(trailers['grpc-status'], '0');
90+
91+
while (!request.closed)
92+
await setImmediateAsync();
93+
assert.strictEqual(request.rstCode, code);
94+
assert.strictEqual(request.destroyed, false);
95+
96+
// Check that we can still read the response after the RST:
97+
const chunks = [];
98+
request.on('data', (chunk) => chunks.push(chunk));
99+
request.on('end', common.mustCall());
100+
request.resume();
101+
await once(request, 'close');
102+
assert.deepStrictEqual(Buffer.concat(chunks), last);
103+
104+
session.destroy();
105+
server.close();
106+
}
107+
})().then(common.mustCall());

0 commit comments

Comments
 (0)