Skip to content

Commit 6cfca8a

Browse files
committed
http2: submit Goaway frames & handle ECONNRESET
Currently http2 does not properly submit Goaway frames when a session is being destroyed. It also doesn't properly handle when the other party severs the connection after sending a Goaway frame, even though it should.
1 parent df511c6 commit 6cfca8a

14 files changed

+104
-107
lines changed

lib/internal/http2/core.js

Lines changed: 54 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -341,20 +341,25 @@ function onStreamClose(code) {
341341

342342
stream[kState].fd = -1;
343343
// Defer destroy we actually emit end.
344-
if (stream._readableState.endEmitted || code !== NGHTTP2_NO_ERROR) {
344+
if (!stream.readable || code !== NGHTTP2_NO_ERROR) {
345345
// If errored or ended, we can destroy immediately.
346-
stream[kMaybeDestroy](null, code);
346+
stream[kMaybeDestroy](code);
347347
} else {
348348
// Wait for end to destroy.
349349
stream.on('end', stream[kMaybeDestroy]);
350350
// Push a null so the stream can end whenever the client consumes
351351
// it completely.
352352
stream.push(null);
353-
// If the client hasn't tried to consume the stream and there is no
354-
// resume scheduled (which would indicate they would consume in the future),
355-
// then just dump the incoming data so that the stream can be destroyed.
356-
if (!stream[kState].didRead && !stream._readableState.resumeScheduled)
353+
354+
// If the user hasn't tried to consume the stream (and this is a server
355+
// session) then just dump the incoming data so that the stream can
356+
// be destroyed.
357+
if (stream[kSession][kType] === NGHTTP2_SESSION_SERVER &&
358+
!stream[kState].didRead &&
359+
stream.readableFlowing === null)
357360
stream.resume();
361+
else
362+
stream.read(0);
358363
}
359364
}
360365

@@ -379,7 +384,7 @@ function onStreamRead(nread, buf) {
379384
`${sessionName(stream[kSession][kType])}]: ending readable.`);
380385

381386
// defer this until we actually emit end
382-
if (stream._readableState.endEmitted) {
387+
if (!stream.readable) {
383388
stream[kMaybeDestroy]();
384389
} else {
385390
stream.on('end', stream[kMaybeDestroy]);
@@ -469,8 +474,7 @@ function onGoawayData(code, lastStreamID, buf) {
469474
// goaway using NGHTTP2_NO_ERROR because there was no error
470475
// condition on this side of the session that caused the
471476
// shutdown.
472-
session.destroy(new ERR_HTTP2_SESSION_ERROR(code),
473-
{ errorCode: NGHTTP2_NO_ERROR });
477+
session.destroy(new ERR_HTTP2_SESSION_ERROR(code), NGHTTP2_NO_ERROR);
474478
}
475479
}
476480

@@ -813,6 +817,21 @@ function emitClose(self, error) {
813817
self.emit('close');
814818
}
815819

820+
function finishSessionDestroy(session, error) {
821+
const socket = session[kSocket];
822+
if (!socket.destroyed)
823+
socket.destroy(error);
824+
825+
session[kProxySocket] = undefined;
826+
session[kSocket] = undefined;
827+
session[kHandle] = undefined;
828+
socket[kSession] = undefined;
829+
socket[kServer] = undefined;
830+
831+
// Finally, emit the close and error events (if necessary) on next tick.
832+
process.nextTick(emitClose, session, error);
833+
}
834+
816835
// Upon creation, the Http2Session takes ownership of the socket. The session
817836
// may not be ready to use immediately if the socket is not yet fully connected.
818837
// In that case, the Http2Session will wait for the socket to connect. Once
@@ -869,6 +888,8 @@ class Http2Session extends EventEmitter {
869888

870889
this[kState] = {
871890
flags: SESSION_FLAGS_PENDING,
891+
goawayCode: null,
892+
goawayLastStreamID: null,
872893
streams: new Map(),
873894
pendingStreams: new Set(),
874895
pendingAck: 0,
@@ -1171,25 +1192,13 @@ class Http2Session extends EventEmitter {
11711192
if (handle !== undefined)
11721193
handle.destroy(code, socket.destroyed);
11731194

1174-
// If there is no error, use setImmediate to destroy the socket on the
1195+
// If the socket is alive, use setImmediate to destroy the session on the
11751196
// next iteration of the event loop in order to give data time to transmit.
11761197
// Otherwise, destroy immediately.
1177-
if (!socket.destroyed) {
1178-
if (!error) {
1179-
setImmediate(socket.destroy.bind(socket));
1180-
} else {
1181-
socket.destroy(error);
1182-
}
1183-
}
1184-
1185-
this[kProxySocket] = undefined;
1186-
this[kSocket] = undefined;
1187-
this[kHandle] = undefined;
1188-
socket[kSession] = undefined;
1189-
socket[kServer] = undefined;
1190-
1191-
// Finally, emit the close and error events (if necessary) on next tick.
1192-
process.nextTick(emitClose, this, error);
1198+
if (!socket.destroyed)
1199+
setImmediate(finishSessionDestroy, this, error);
1200+
else
1201+
finishSessionDestroy(this, error);
11931202
}
11941203

11951204
// Closing the session will:
@@ -1441,11 +1450,8 @@ function afterDoStreamWrite(status, handle) {
14411450
}
14421451

14431452
function streamOnResume() {
1444-
if (!this.destroyed && !this.pending) {
1445-
if (!this[kState].didRead)
1446-
this[kState].didRead = true;
1453+
if (!this.destroyed)
14471454
this[kHandle].readStart();
1448-
}
14491455
}
14501456

14511457
function streamOnPause() {
@@ -1521,6 +1527,10 @@ class Http2Stream extends Duplex {
15211527
this[kSession] = session;
15221528
session[kState].pendingStreams.add(this);
15231529

1530+
// Allow our logic for determining whether any reads have happened to
1531+
// work in all situations. This is similar to what we do in _http_incoming.
1532+
this._readableState.readingMore = true;
1533+
15241534
this[kTimeout] = null;
15251535

15261536
this[kState] = {
@@ -1531,7 +1541,6 @@ class Http2Stream extends Duplex {
15311541
trailersReady: false
15321542
};
15331543

1534-
this.on('resume', streamOnResume);
15351544
this.on('pause', streamOnPause);
15361545
}
15371546

@@ -1725,6 +1734,10 @@ class Http2Stream extends Duplex {
17251734
this.push(null);
17261735
return;
17271736
}
1737+
if (!this[kState].didRead) {
1738+
this._readableState.readingMore = false;
1739+
this[kState].didRead = true;
1740+
}
17281741
if (!this.pending) {
17291742
streamOnResume.call(this);
17301743
} else {
@@ -1866,15 +1879,15 @@ class Http2Stream extends Duplex {
18661879
}
18671880
// The Http2Stream can be destroyed if it has closed and if the readable
18681881
// side has received the final chunk.
1869-
[kMaybeDestroy](error, code = NGHTTP2_NO_ERROR) {
1870-
if (error || code !== NGHTTP2_NO_ERROR) {
1871-
this.destroy(error);
1882+
[kMaybeDestroy](code = NGHTTP2_NO_ERROR) {
1883+
if (code !== NGHTTP2_NO_ERROR) {
1884+
this.destroy();
18721885
return;
18731886
}
18741887

18751888
// TODO(mcollina): remove usage of _*State properties
1876-
if (this._writableState.ended && this._writableState.pendingcb === 0) {
1877-
if (this._readableState.ended && this.closed) {
1889+
if (!this.writable) {
1890+
if (!this.readable && this.closed) {
18781891
this.destroy();
18791892
return;
18801893
}
@@ -1887,7 +1900,7 @@ class Http2Stream extends Duplex {
18871900
this[kSession][kType] === NGHTTP2_SESSION_SERVER &&
18881901
!(state.flags & STREAM_FLAGS_HAS_TRAILERS) &&
18891902
!state.didRead &&
1890-
!this._readableState.resumeScheduled) {
1903+
this.readableFlowing === null) {
18911904
this.close();
18921905
}
18931906
}
@@ -2477,6 +2490,10 @@ Object.defineProperty(Http2Session.prototype, 'setTimeout', setTimeout);
24772490
function socketOnError(error) {
24782491
const session = this[kSession];
24792492
if (session !== undefined) {
2493+
// We can ignore ECONNRESET after GOAWAY was received as there's nothing
2494+
// we can do and the other side is fully within its rights to do so.
2495+
if (error.code === 'ECONNRESET' && session[kState].goawayCode !== null)
2496+
return session.destroy();
24802497
debug(`Http2Session ${sessionName(session[kType])}: socket error [` +
24812498
`${error.message}]`);
24822499
session.destroy(error);

src/node_http2.cc

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -577,26 +577,28 @@ void Http2Session::EmitStatistics() {
577577
void Http2Session::Close(uint32_t code, bool socket_closed) {
578578
DEBUG_HTTP2SESSION(this, "closing session");
579579

580-
if (flags_ & SESSION_STATE_CLOSED)
580+
if (flags_ & SESSION_STATE_CLOSING)
581581
return;
582-
flags_ |= SESSION_STATE_CLOSED;
582+
flags_ |= SESSION_STATE_CLOSING;
583583

584584
// Stop reading on the i/o stream
585585
if (stream_ != nullptr)
586586
stream_->ReadStop();
587587

588588
// If the socket is not closed, then attempt to send a closing GOAWAY
589589
// frame. There is no guarantee that this GOAWAY will be received by
590-
// the peer but the HTTP/2 spec recommends sendinng it anyway. We'll
590+
// the peer but the HTTP/2 spec recommends sending it anyway. We'll
591591
// make a best effort.
592592
if (!socket_closed) {
593-
Http2Scope h2scope(this);
594593
DEBUG_HTTP2SESSION2(this, "terminating session with code %d", code);
595594
CHECK_EQ(nghttp2_session_terminate_session(session_, code), 0);
595+
SendPendingData();
596596
} else if (stream_ != nullptr) {
597597
stream_->RemoveStreamListener(this);
598598
}
599599

600+
flags_ |= SESSION_STATE_CLOSED;
601+
600602
// If there are outstanding pings, those will need to be canceled, do
601603
// so on the next iteration of the event loop to avoid calling out into
602604
// javascript since this may be called during garbage collection.
@@ -1355,25 +1357,32 @@ void Http2Session::MaybeScheduleWrite() {
13551357
}
13561358
}
13571359

1360+
void Http2Session::MaybeStopReading() {
1361+
int want_read = nghttp2_session_want_read(session_);
1362+
DEBUG_HTTP2SESSION2(this, "wants read? %d", want_read);
1363+
if (want_read == 0)
1364+
stream_->ReadStop();
1365+
}
1366+
13581367
// Unset the sending state, finish up all current writes, and reset
13591368
// storage for data and metadata that was associated with these writes.
13601369
void Http2Session::ClearOutgoing(int status) {
13611370
CHECK_NE(flags_ & SESSION_STATE_SENDING, 0);
13621371

1372+
flags_ &= ~SESSION_STATE_SENDING;
1373+
13631374
if (outgoing_buffers_.size() > 0) {
13641375
outgoing_storage_.clear();
13651376

1366-
for (const nghttp2_stream_write& wr : outgoing_buffers_) {
1377+
std::vector<nghttp2_stream_write> current_outgoing_buffers_;
1378+
current_outgoing_buffers_.swap(outgoing_buffers_);
1379+
for (const nghttp2_stream_write& wr : current_outgoing_buffers_) {
13671380
WriteWrap* wrap = wr.req_wrap;
13681381
if (wrap != nullptr)
13691382
wrap->Done(status);
13701383
}
1371-
1372-
outgoing_buffers_.clear();
13731384
}
13741385

1375-
flags_ &= ~SESSION_STATE_SENDING;
1376-
13771386
// Now that we've finished sending queued data, if there are any pending
13781387
// RstStreams we should try sending again and then flush them one by one.
13791388
if (pending_rst_streams_.size() > 0) {
@@ -1484,8 +1493,7 @@ uint8_t Http2Session::SendPendingData() {
14841493
ClearOutgoing(res.err);
14851494
}
14861495

1487-
DEBUG_HTTP2SESSION2(this, "wants data in return? %d",
1488-
nghttp2_session_want_read(session_));
1496+
MaybeStopReading();
14891497

14901498
return 0;
14911499
}
@@ -1618,8 +1626,7 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
16181626
};
16191627
MakeCallback(env()->error_string(), arraysize(argv), argv);
16201628
} else {
1621-
DEBUG_HTTP2SESSION2(this, "processed %d bytes. wants more? %d", ret,
1622-
nghttp2_session_want_read(session_));
1629+
MaybeStopReading();
16231630
}
16241631
}
16251632

src/node_http2.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -433,7 +433,8 @@ enum session_state_flags {
433433
SESSION_STATE_HAS_SCOPE = 0x1,
434434
SESSION_STATE_WRITE_SCHEDULED = 0x2,
435435
SESSION_STATE_CLOSED = 0x4,
436-
SESSION_STATE_SENDING = 0x8,
436+
SESSION_STATE_CLOSING = 0x8,
437+
SESSION_STATE_SENDING = 0x10,
437438
};
438439

439440
// This allows for 4 default-sized frames with their frame headers
@@ -619,7 +620,7 @@ class Http2Stream : public AsyncWrap,
619620

620621
inline bool IsClosed() const {
621622
return flags_ & NGHTTP2_STREAM_FLAG_CLOSED;
622-
}
623+
}
623624

624625
inline bool HasTrailers() const {
625626
return flags_ & NGHTTP2_STREAM_FLAG_TRAILERS;
@@ -827,6 +828,9 @@ class Http2Session : public AsyncWrap, public StreamListener {
827828
// Schedule a write if nghttp2 indicates it wants to write to the socket.
828829
void MaybeScheduleWrite();
829830

831+
// Stop reading if nghttp2 doesn't want to anymore.
832+
void MaybeStopReading();
833+
830834
// Returns pointer to the stream, or nullptr if stream does not exist
831835
inline Http2Stream* FindStream(int32_t id);
832836

test/parallel/parallel.status

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,6 @@ prefix parallel
88
# Postmortem debugging data is prone to accidental removal during V8 updates.
99
test-postmortem-metadata: PASS,FLAKY
1010

11-
# http2 has a few bugs that make these tests flaky and that are currently worked
12-
# on.
13-
test-http2-client-upload-reject: PASS,FLAKY
14-
test-http2-pipe: PASS,FLAKY
15-
test-http2-client-upload: PASS,FLAKY
16-
1711
[$system==win32]
1812

1913
[$system==linux]

test/parallel/test-http2-client-destroy.js

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -109,20 +109,14 @@ const Countdown = require('../common/countdown');
109109

110110
server.listen(0, common.mustCall(() => {
111111
const client = h2.connect(`http://localhost:${server.address().port}`);
112-
// On some platforms (e.g. windows), an ECONNRESET may occur at this
113-
// point -- or it may not. Do not make this a mustCall
114-
client.on('error', () => {});
115112

116113
client.on('close', () => {
117114
server.close();
118115
// calling destroy in here should not matter
119116
client.destroy();
120117
});
121118

122-
const req = client.request();
123-
// On some platforms (e.g. windows), an ECONNRESET may occur at this
124-
// point -- or it may not. Do not make this a mustCall
125-
req.on('error', () => {});
119+
client.request();
126120
}));
127121
}
128122

test/parallel/test-http2-server-close-callback.js

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,7 @@ const http2 = require('http2');
99
const server = http2.createServer();
1010

1111
server.listen(0, common.mustCall(() => {
12-
const client = http2.connect(`http://localhost:${server.address().port}`);
13-
client.on('error', (err) => {
14-
if (err.code !== 'ECONNRESET')
15-
throw err;
16-
});
12+
http2.connect(`http://localhost:${server.address().port}`);
1713
}));
1814

1915
server.on('session', common.mustCall((s) => {

test/parallel/test-http2-server-sessionerror.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,17 @@ server.on('session', common.mustCall((session) => {
3535
server.listen(0, common.mustCall(() => {
3636
const url = `http://localhost:${server.address().port}`;
3737
http2.connect(url)
38-
// An ECONNRESET error may occur depending on the platform (due largely
39-
// to differences in the timing of socket closing). Do not wrap this in
40-
// a common must call.
41-
.on('error', () => {})
38+
.on('error', common.expectsError({
39+
code: 'ERR_HTTP2_SESSION_ERROR',
40+
message: 'Session closed with error code 2',
41+
}))
4242
.on('close', () => {
4343
server.removeAllListeners('error');
4444
http2.connect(url)
45-
.on('error', () => {})
45+
.on('error', common.expectsError({
46+
code: 'ERR_HTTP2_SESSION_ERROR',
47+
message: 'Session closed with error code 2',
48+
}))
4649
.on('close', () => server.close());
4750
});
4851
}));

0 commit comments

Comments
 (0)