diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e47a22d1c08ac..39018bccec7b45 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,7 +28,8 @@ release.
+12.8.1
12.8.0
12.7.0
12.6.0
@@ -37,6 +38,44 @@
* [io.js](CHANGELOG_IOJS.md)
* [Archive](CHANGELOG_ARCHIVE.md)
+
+## 2019-08-15, Version 12.8.1 (Current), @targos
+
+### Notable changes
+
+This is a security release.
+
+Node.js, as well as many other implementations of HTTP/2, have been found
+vulnerable to Denial of Service attacks.
+See https://github.com/Netflix/security-bulletins/blob/master/advisories/third-party/2019-002.md
+for more information.
+
+Vulnerabilities fixed:
+
+* **CVE-2019-9511 “Data Dribble”**: The attacker requests a large amount of data from a specified resource over multiple streams. They manipulate window size and stream priority to force the server to queue the data in 1-byte chunks. Depending on how efficiently this data is queued, this can consume excess CPU, memory, or both, potentially leading to a denial of service.
+* **CVE-2019-9512 “Ping Flood”**: The attacker sends continual pings to an HTTP/2 peer, causing the peer to build an internal queue of responses. Depending on how efficiently this data is queued, this can consume excess CPU, memory, or both, potentially leading to a denial of service.
+* **CVE-2019-9513 “Resource Loop”**: The attacker creates multiple request streams and continually shuffles the priority of the streams in a way that causes substantial churn to the priority tree. This can consume excess CPU, potentially leading to a denial of service.
+* **CVE-2019-9514 “Reset Flood”**: The attacker opens a number of streams and sends an invalid request over each stream that should solicit a stream of RST_STREAM frames from the peer. Depending on how the peer queues the RST_STREAM frames, this can consume excess memory, CPU, or both, potentially leading to a denial of service.
+* **CVE-2019-9515 “Settings Flood”**: The attacker sends a stream of SETTINGS frames to the peer. Since the RFC requires that the peer reply with one acknowledgement per SETTINGS frame, an empty SETTINGS frame is almost equivalent in behavior to a ping. Depending on how efficiently this data is queued, this can consume excess CPU, memory, or both, potentially leading to a denial of service.
+* **CVE-2019-9516 “0-Length Headers Leak”**: The attacker sends a stream of headers with a 0-length header name and 0-length header value, optionally Huffman encoded into 1-byte or greater headers. Some implementations allocate memory for these headers and keep the allocation alive until the session dies. This can consume excess memory, potentially leading to a denial of service.
+* **CVE-2019-9517 “Internal Data Buffering”**: The attacker opens the HTTP/2 window so the peer can send without constraint; however, they leave the TCP window closed so the peer cannot actually write (many of) the bytes on the wire. The attacker then sends a stream of requests for a large response object. Depending on how the servers queue the responses, this can consume excess memory, CPU, or both, potentially leading to a denial of service.
+* **CVE-2019-9518 “Empty Frames Flood”**: The attacker sends a stream of frames with an empty payload and without the end-of-stream flag. These frames can be DATA, HEADERS, CONTINUATION and/or PUSH_PROMISE. The peer spends time processing each frame disproportionate to attack bandwidth. This can consume excess CPU, potentially leading to a denial of service. (Discovered by Piotr Sikora of Google)
+
+### Commits
+
+* [[`bfeb5fc07f`](https://github.com/nodejs/node/commit/bfeb5fc07f)] - **deps**: update nghttp2 to 1.39.2 (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`08021fac59`](https://github.com/nodejs/node/commit/08021fac59)] - **http2**: allow security revert for Ping/Settings Flood (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`bbb4769cc1`](https://github.com/nodejs/node/commit/bbb4769cc1)] - **http2**: pause input processing if sending output (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`f64515b05e`](https://github.com/nodejs/node/commit/f64515b05e)] - **http2**: stop reading from socket if writes are in progress (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`ba332df5d2`](https://github.com/nodejs/node/commit/ba332df5d2)] - **http2**: consider 0-length non-end DATA frames an error (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`23b0db58ca`](https://github.com/nodejs/node/commit/23b0db58ca)] - **http2**: shrink default `vector::reserve()` allocations (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`4f10ac3623`](https://github.com/nodejs/node/commit/4f10ac3623)] - **http2**: handle 0-length headers better (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`a21a1c007b`](https://github.com/nodejs/node/commit/a21a1c007b)] - **http2**: limit number of invalid incoming frames (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`4570ed10d7`](https://github.com/nodejs/node/commit/4570ed10d7)] - **http2**: limit number of rejected stream openings (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`88726f2384`](https://github.com/nodejs/node/commit/88726f2384)] - **http2**: do not create ArrayBuffers when no DATA received (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`530004ef32`](https://github.com/nodejs/node/commit/530004ef32)] - **http2**: only call into JS when necessary for session events (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+* [[`58d8c9ef48`](https://github.com/nodejs/node/commit/58d8c9ef48)] - **http2**: improve JS-side debug logging (Anna Henningsen) [#29122](https://github.com/nodejs/node/pull/29122)
+
## 2019-08-06, Version 12.8.0 (Current), @BridgeAR
diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js
index 571ffaa8584007..45041250b8f72c 100644
--- a/lib/internal/http2/core.js
+++ b/lib/internal/http2/core.js
@@ -139,6 +139,26 @@ const { _connectionListener: httpConnectionListener } = http;
const debug = require('internal/util/debuglog').debuglog('http2');
const { getOptionValue } = require('internal/options');
+// TODO(addaleax): See if this can be made more efficient by figuring out
+// whether debugging is enabled before we perform any further steps. Currently,
+// this seems pretty fast, though.
+function debugStream(id, sessionType, message, ...args) {
+ debug('Http2Stream %s [Http2Session %s]: ' + message,
+ id, sessionName(sessionType), ...args);
+}
+
+function debugStreamObj(stream, message, ...args) {
+ debugStream(stream[kID], stream[kSession][kType], ...args);
+}
+
+function debugSession(sessionType, message, ...args) {
+ debug('Http2Session %s: ' + message, sessionName(sessionType), ...args);
+}
+
+function debugSessionObj(session, message, ...args) {
+ debugSession(session[kType], message, ...args);
+}
+
const kMaxFrameSize = (2 ** 24) - 1;
const kMaxInt = (2 ** 32) - 1;
const kMaxStreams = (2 ** 31) - 1;
@@ -158,6 +178,7 @@ const kID = Symbol('id');
const kInit = Symbol('init');
const kInfoHeaders = Symbol('sent-info-headers');
const kLocalSettings = Symbol('local-settings');
+const kNativeFields = Symbol('kNativeFields');
const kOptions = Symbol('options');
const kOwner = owner_symbol;
const kOrigin = Symbol('origin');
@@ -180,7 +201,15 @@ const {
paddingBuffer,
PADDING_BUF_FRAME_LENGTH,
PADDING_BUF_MAX_PAYLOAD_LENGTH,
- PADDING_BUF_RETURN_VALUE
+ PADDING_BUF_RETURN_VALUE,
+ kBitfield,
+ kSessionPriorityListenerCount,
+ kSessionFrameErrorListenerCount,
+ kSessionUint8FieldCount,
+ kSessionHasRemoteSettingsListeners,
+ kSessionRemoteSettingsIsUpToDate,
+ kSessionHasPingListeners,
+ kSessionHasAltsvcListeners,
} = binding;
const {
@@ -260,8 +289,7 @@ function onSessionHeaders(handle, id, cat, flags, headers) {
const type = session[kType];
session[kUpdateTimer]();
- debug(`Http2Stream ${id} [Http2Session ` +
- `${sessionName(type)}]: headers received`);
+ debugStream(id, type, 'headers received');
const streams = session[kState].streams;
const endOfStream = !!(flags & NGHTTP2_FLAG_END_STREAM);
@@ -321,8 +349,7 @@ function onSessionHeaders(handle, id, cat, flags, headers) {
const originSet = session[kState].originSet = initOriginSet(session);
originSet.delete(stream[kOrigin]);
}
- debug(`Http2Stream ${id} [Http2Session ` +
- `${sessionName(type)}]: emitting stream '${event}' event`);
+ debugStream(id, type, "emitting stream '%s' event", event);
process.nextTick(emit, stream, event, obj, flags, headers);
}
if (endOfStream) {
@@ -358,12 +385,82 @@ function submitRstStream(code) {
}
}
+// Keep track of the number/presence of JS event listeners. Knowing that there
+// are no listeners allows the C++ code to skip calling into JS for an event.
+function sessionListenerAdded(name) {
+ switch (name) {
+ case 'ping':
+ this[kNativeFields][kBitfield] |= 1 << kSessionHasPingListeners;
+ break;
+ case 'altsvc':
+ this[kNativeFields][kBitfield] |= 1 << kSessionHasAltsvcListeners;
+ break;
+ case 'remoteSettings':
+ this[kNativeFields][kBitfield] |= 1 << kSessionHasRemoteSettingsListeners;
+ break;
+ case 'priority':
+ this[kNativeFields][kSessionPriorityListenerCount]++;
+ break;
+ case 'frameError':
+ this[kNativeFields][kSessionFrameErrorListenerCount]++;
+ break;
+ }
+}
+
+function sessionListenerRemoved(name) {
+ switch (name) {
+ case 'ping':
+ if (this.listenerCount(name) > 0) return;
+ this[kNativeFields][kBitfield] &= ~(1 << kSessionHasPingListeners);
+ break;
+ case 'altsvc':
+ if (this.listenerCount(name) > 0) return;
+ this[kNativeFields][kBitfield] &= ~(1 << kSessionHasAltsvcListeners);
+ break;
+ case 'remoteSettings':
+ if (this.listenerCount(name) > 0) return;
+ this[kNativeFields][kBitfield] &=
+ ~(1 << kSessionHasRemoteSettingsListeners);
+ break;
+ case 'priority':
+ this[kNativeFields][kSessionPriorityListenerCount]--;
+ break;
+ case 'frameError':
+ this[kNativeFields][kSessionFrameErrorListenerCount]--;
+ break;
+ }
+}
+
+// Also keep track of listeners for the Http2Stream instances, as some events
+// are emitted on those objects.
+function streamListenerAdded(name) {
+ switch (name) {
+ case 'priority':
+ this[kSession][kNativeFields][kSessionPriorityListenerCount]++;
+ break;
+ case 'frameError':
+ this[kSession][kNativeFields][kSessionFrameErrorListenerCount]++;
+ break;
+ }
+}
+
+function streamListenerRemoved(name) {
+ switch (name) {
+ case 'priority':
+ this[kSession][kNativeFields][kSessionPriorityListenerCount]--;
+ break;
+ case 'frameError':
+ this[kSession][kNativeFields][kSessionFrameErrorListenerCount]--;
+ break;
+ }
+}
+
function onPing(payload) {
const session = this[kOwner];
if (session.destroyed)
return;
session[kUpdateTimer]();
- debug(`Http2Session ${sessionName(session[kType])}: new ping received`);
+ debugSessionObj(session, 'new ping received');
session.emit('ping', payload);
}
@@ -378,8 +475,7 @@ function onStreamClose(code) {
if (!stream || stream.destroyed)
return false;
- debug(`Http2Stream ${stream[kID]} [Http2Session ` +
- `${sessionName(stream[kSession][kType])}]: closed with code ${code}`);
+ debugStreamObj(stream, 'closed with code %d', code);
if (!stream.closed)
closeStream(stream, code, kNoRstStream);
@@ -416,8 +512,7 @@ function onSettings() {
if (session.destroyed)
return;
session[kUpdateTimer]();
- debug(`Http2Session ${sessionName(session[kType])}: new settings received`);
- session[kRemoteSettings] = undefined;
+ debugSessionObj(session, 'new settings received');
session.emit('remoteSettings', session.remoteSettings);
}
@@ -428,9 +523,9 @@ function onPriority(id, parent, weight, exclusive) {
const session = this[kOwner];
if (session.destroyed)
return;
- debug(`Http2Stream ${id} [Http2Session ` +
- `${sessionName(session[kType])}]: priority [parent: ${parent}, ` +
- `weight: ${weight}, exclusive: ${exclusive}]`);
+ debugStream(id, session[kType],
+ 'priority [parent: %d, weight: %d, exclusive: %s]',
+ parent, weight, exclusive);
const emitter = session[kState].streams.get(id) || session;
if (!emitter.destroyed) {
emitter[kUpdateTimer]();
@@ -444,8 +539,8 @@ function onFrameError(id, type, code) {
const session = this[kOwner];
if (session.destroyed)
return;
- debug(`Http2Session ${sessionName(session[kType])}: error sending frame ` +
- `type ${type} on stream ${id}, code: ${code}`);
+ debugSessionObj(session, 'error sending frame type %d on stream %d, code: %d',
+ type, id, code);
const emitter = session[kState].streams.get(id) || session;
emitter[kUpdateTimer]();
emitter.emit('frameError', type, code, id);
@@ -455,8 +550,8 @@ function onAltSvc(stream, origin, alt) {
const session = this[kOwner];
if (session.destroyed)
return;
- debug(`Http2Session ${sessionName(session[kType])}: altsvc received: ` +
- `stream: ${stream}, origin: ${origin}, alt: ${alt}`);
+ debugSessionObj(session, 'altsvc received: stream: %d, origin: %s, alt: %s',
+ stream, origin, alt);
session[kUpdateTimer]();
session.emit('altsvc', alt, origin, stream);
}
@@ -483,8 +578,7 @@ function onOrigin(origins) {
const session = this[kOwner];
if (session.destroyed)
return;
- debug('Http2Session %s: origin received: %j',
- sessionName(session[kType]), origins);
+ debugSessionObj(session, 'origin received: %j', origins);
session[kUpdateTimer]();
if (!session.encrypted || session.destroyed)
return undefined;
@@ -504,8 +598,8 @@ function onGoawayData(code, lastStreamID, buf) {
const session = this[kOwner];
if (session.destroyed)
return;
- debug(`Http2Session ${sessionName(session[kType])}: goaway ${code} ` +
- `received [last stream id: ${lastStreamID}]`);
+ debugSessionObj(session, 'goaway %d received [last stream id: %d]',
+ code, lastStreamID);
const state = session[kState];
state.goawayCode = code;
@@ -560,8 +654,7 @@ function requestOnConnect(headers, options) {
return;
}
- debug(`Http2Session ${sessionName(session[kType])}: connected, ` +
- 'initializing request');
+ debugSessionObj(session, 'connected, initializing request');
let streamOptions = 0;
if (options.endStream)
@@ -650,13 +743,13 @@ function settingsCallback(cb, ack, duration) {
this[kState].pendingAck--;
this[kLocalSettings] = undefined;
if (ack) {
- debug(`Http2Session ${sessionName(this[kType])}: settings received`);
+ debugSessionObj(this, 'settings received');
const settings = this.localSettings;
if (typeof cb === 'function')
cb(null, settings, duration);
this.emit('localSettings', settings);
} else {
- debug(`Http2Session ${sessionName(this[kType])}: settings canceled`);
+ debugSessionObj(this, 'settings canceled');
if (typeof cb === 'function')
cb(new ERR_HTTP2_SETTINGS_CANCEL());
}
@@ -666,7 +759,7 @@ function settingsCallback(cb, ack, duration) {
function submitSettings(settings, callback) {
if (this.destroyed)
return;
- debug(`Http2Session ${sessionName(this[kType])}: submitting settings`);
+ debugSessionObj(this, 'submitting settings');
this[kUpdateTimer]();
updateSettingsBuffer(settings);
if (!this[kHandle].settings(settingsCallback.bind(this, callback))) {
@@ -700,7 +793,7 @@ function submitPriority(options) {
function submitGoaway(code, lastStreamID, opaqueData) {
if (this.destroyed)
return;
- debug(`Http2Session ${sessionName(this[kType])}: submitting goaway`);
+ debugSessionObj(this, 'submitting goaway');
this[kUpdateTimer]();
this[kHandle].goaway(code, lastStreamID, opaqueData);
}
@@ -831,7 +924,7 @@ function setupHandle(socket, type, options) {
'Internal HTTP/2 Failure. The socket is not connected. Please ' +
'report this as a bug in Node.js');
- debug(`Http2Session ${sessionName(type)}: setting up session handle`);
+ debugSession(type, 'setting up session handle');
this[kState].flags |= SESSION_FLAGS_READY;
updateOptionsBuffer(options);
@@ -843,6 +936,10 @@ function setupHandle(socket, type, options) {
handle.consume(socket._handle);
this[kHandle] = handle;
+ if (this[kNativeFields])
+ handle.fields.set(this[kNativeFields]);
+ else
+ this[kNativeFields] = handle.fields;
if (socket.encrypted) {
this[kAlpnProtocol] = socket.alpnProtocol;
@@ -884,6 +981,7 @@ function finishSessionDestroy(session, error) {
session[kProxySocket] = undefined;
session[kSocket] = undefined;
session[kHandle] = undefined;
+ session[kNativeFields] = new Uint8Array(kSessionUint8FieldCount);
socket[kSession] = undefined;
socket[kServer] = undefined;
@@ -963,6 +1061,7 @@ class Http2Session extends EventEmitter {
this[kProxySocket] = null;
this[kSocket] = socket;
this[kTimeout] = null;
+ this[kHandle] = undefined;
// Do not use nagle's algorithm
if (typeof socket.setNoDelay === 'function')
@@ -987,7 +1086,12 @@ class Http2Session extends EventEmitter {
setupFn();
}
- debug(`Http2Session ${sessionName(type)}: created`);
+ if (!this[kNativeFields])
+ this[kNativeFields] = new Uint8Array(kSessionUint8FieldCount);
+ this.on('newListener', sessionListenerAdded);
+ this.on('removeListener', sessionListenerRemoved);
+
+ debugSession(type, 'created');
}
// Returns undefined if the socket is not yet connected, true if the
@@ -1144,13 +1248,18 @@ class Http2Session extends EventEmitter {
// The settings currently in effect for the remote peer.
get remoteSettings() {
- const settings = this[kRemoteSettings];
- if (settings !== undefined)
- return settings;
+ if (this[kNativeFields][kBitfield] &
+ (1 << kSessionRemoteSettingsIsUpToDate)) {
+ const settings = this[kRemoteSettings];
+ if (settings !== undefined) {
+ return settings;
+ }
+ }
if (this.destroyed || this.connecting)
return {};
+ this[kNativeFields][kBitfield] |= (1 << kSessionRemoteSettingsIsUpToDate);
return this[kRemoteSettings] = getSettings(this[kHandle], true); // Remote
}
@@ -1163,7 +1272,7 @@ class Http2Session extends EventEmitter {
if (callback && typeof callback !== 'function')
throw new ERR_INVALID_CALLBACK(callback);
- debug(`Http2Session ${sessionName(this[kType])}: sending settings`);
+ debugSessionObj(this, 'sending settings');
this[kState].pendingAck++;
@@ -1204,7 +1313,7 @@ class Http2Session extends EventEmitter {
destroy(error = NGHTTP2_NO_ERROR, code) {
if (this.destroyed)
return;
- debug(`Http2Session ${sessionName(this[kType])}: destroying`);
+ debugSessionObj(this, 'destroying');
if (typeof error === 'number') {
code = error;
@@ -1261,7 +1370,7 @@ class Http2Session extends EventEmitter {
close(callback) {
if (this.closed || this.destroyed)
return;
- debug(`Http2Session ${sessionName(this[kType])}: marking session closed`);
+ debugSessionObj(this, 'marking session closed');
this[kState].flags |= SESSION_FLAGS_CLOSED;
if (typeof callback === 'function')
this.once('close', callback);
@@ -1329,6 +1438,12 @@ class ServerHttp2Session extends Http2Session {
constructor(options, socket, server) {
super(NGHTTP2_SESSION_SERVER, options, socket);
this[kServer] = server;
+ // This is a bit inaccurate because it does not reflect changes to
+ // number of listeners made after the session was created. This should
+ // not be an issue in practice. Additionally, the 'priority' event on
+ // server instances (or any other object) is fully undocumented.
+ this[kNativeFields][kSessionPriorityListenerCount] =
+ server.listenerCount('priority');
}
get server() {
@@ -1432,7 +1547,7 @@ class ClientHttp2Session extends Http2Session {
// Submits a new HTTP2 request to the connected peer. Returns the
// associated Http2Stream instance.
request(headers, options) {
- debug(`Http2Session ${sessionName(this[kType])}: initiating request`);
+ debugSessionObj(this, 'initiating request');
if (this.destroyed)
throw new ERR_HTTP2_INVALID_SESSION();
@@ -1641,6 +1756,9 @@ class Http2Stream extends Duplex {
this[kProxySocket] = null;
this.on('pause', streamOnPause);
+
+ this.on('newListener', streamListenerAdded);
+ this.on('removeListener', streamListenerRemoved);
}
[kUpdateTimer]() {
@@ -1832,8 +1950,7 @@ class Http2Stream extends Duplex {
if (this.pending) {
this.once('ready', () => this._final(cb));
} else if (handle !== undefined) {
- debug(`Http2Stream ${this[kID]} [Http2Session ` +
- `${sessionName(this[kSession][kType])}]: _final shutting down`);
+ debugStreamObj(this, '_final shutting down');
const req = new ShutdownWrap();
req.oncomplete = afterShutdown;
req.callback = cb;
@@ -1892,9 +2009,7 @@ class Http2Stream extends Duplex {
assertIsObject(headers, 'headers');
headers = Object.assign(Object.create(null), headers);
- const session = this[kSession];
- debug(`Http2Stream ${this[kID]} [Http2Session ` +
- `${sessionName(session[kType])}]: sending trailers`);
+ debugStreamObj(this, 'sending trailers');
this[kUpdateTimer]();
@@ -1947,8 +2062,7 @@ class Http2Stream extends Duplex {
const handle = this[kHandle];
const id = this[kID];
- debug(`Http2Stream ${this[kID] || ''} [Http2Session ` +
- `${sessionName(session[kType])}]: destroying stream`);
+ debugStream(this[kID] || 'pending', session[kType], 'destroying stream');
const state = this[kState];
const sessionCode = session[kState].goawayCode ||
@@ -2274,8 +2388,7 @@ class ServerHttp2Stream extends Http2Stream {
const session = this[kSession];
- debug(`Http2Stream ${this[kID]} [Http2Session ` +
- `${sessionName(session[kType])}]: initiating push stream`);
+ debugStreamObj(this, 'initiating push stream');
this[kUpdateTimer]();
@@ -2355,9 +2468,7 @@ class ServerHttp2Stream extends Http2Stream {
assertIsObject(options, 'options');
options = { ...options };
- const session = this[kSession];
- debug(`Http2Stream ${this[kID]} [Http2Session ` +
- `${sessionName(session[kType])}]: initiating response`);
+ debugStreamObj(this, 'initiating response');
this[kUpdateTimer]();
options.endStream = !!options.endStream;
@@ -2430,8 +2541,7 @@ class ServerHttp2Stream extends Http2Stream {
validateNumber(fd, 'fd');
- debug(`Http2Stream ${this[kID]} [Http2Session ` +
- `${sessionName(session[kType])}]: initiating response from fd`);
+ debugStreamObj(this, 'initiating response from fd');
this[kUpdateTimer]();
this.ownsFd = false;
@@ -2492,8 +2602,7 @@ class ServerHttp2Stream extends Http2Stream {
}
const session = this[kSession];
- debug(`Http2Stream ${this[kID]} [Http2Session ` +
- `${sessionName(session[kType])}]: initiating response from file`);
+ debugStreamObj(this, 'initiating response from file');
this[kUpdateTimer]();
this.ownsFd = true;
@@ -2527,9 +2636,7 @@ class ServerHttp2Stream extends Http2Stream {
assertIsObject(headers, 'headers');
headers = Object.assign(Object.create(null), headers);
- const session = this[kSession];
- debug(`Http2Stream ${this[kID]} [Http2Session ` +
- `${sessionName(session[kType])}]: sending additional headers`);
+ debugStreamObj(this, 'sending additional headers');
if (headers[HTTP2_HEADER_STATUS] != null) {
const statusCode = headers[HTTP2_HEADER_STATUS] |= 0;
@@ -2590,8 +2697,7 @@ function socketOnError(error) {
// we can do and the other side is fully within its rights to do so.
if (error.code === 'ECONNRESET' && session[kState].goawayCode !== null)
return session.destroy();
- debug(`Http2Session ${sessionName(session[kType])}: socket error [` +
- `${error.message}]`);
+ debugSessionObj(this, 'socket error [%s]', error.message);
session.destroy(error);
}
}
@@ -2609,7 +2715,7 @@ function sessionOnPriority(stream, parent, weight, exclusive) {
}
function sessionOnError(error) {
- if (this[kServer])
+ if (this[kServer] !== undefined)
this[kServer].emit('sessionError', error, this);
}
@@ -2636,7 +2742,8 @@ function connectionListener(socket) {
return httpConnectionListener.call(this, socket);
}
// Let event handler deal with the socket
- debug(`Unknown protocol from ${socket.remoteAddress}:${socket.remotePort}`);
+ debug('Unknown protocol from %s:%s',
+ socket.remoteAddress, socket.remotePort);
if (!this.emit('unknownProtocol', socket)) {
// We don't know what to do, so let's just tell the other side what's
// going on in a format that they *might* understand.
@@ -2657,8 +2764,10 @@ function connectionListener(socket) {
const session = new ServerHttp2Session(options, socket, this);
session.on('stream', sessionOnStream);
- session.on('priority', sessionOnPriority);
session.on('error', sessionOnError);
+ // Don't count our own internal listener.
+ session.on('priority', sessionOnPriority);
+ session[kNativeFields][kSessionPriorityListenerCount]--;
if (this.timeout)
session.setTimeout(this.timeout, sessionOnTimeout);
@@ -2761,7 +2870,7 @@ function setupCompat(ev) {
function socketOnClose() {
const session = this[kSession];
if (session !== undefined) {
- debug(`Http2Session ${sessionName(session[kType])}: socket closed`);
+ debugSessionObj(session, 'socket closed');
const err = session.connecting ? new ERR_SOCKET_CLOSED() : null;
const state = session[kState];
state.streams.forEach((stream) => stream.close(NGHTTP2_CANCEL));
diff --git a/src/env.h b/src/env.h
index 82ed066f9cde48..8647c5408f9eac 100644
--- a/src/env.h
+++ b/src/env.h
@@ -208,6 +208,7 @@ constexpr size_t kFsStatsBufferLength = kFsStatsFieldsNumber * 2;
V(family_string, "family") \
V(fatal_exception_string, "_fatalException") \
V(fd_string, "fd") \
+ V(fields_string, "fields") \
V(file_string, "file") \
V(fingerprint256_string, "fingerprint256") \
V(fingerprint_string, "fingerprint") \
diff --git a/src/node_http2.cc b/src/node_http2.cc
index 9d6c37373ff487..8cb1158b559dec 100644
--- a/src/node_http2.cc
+++ b/src/node_http2.cc
@@ -6,6 +6,7 @@
#include "node_http2.h"
#include "node_http2_state.h"
#include "node_perf.h"
+#include "node_revert.h"
#include "util-inl.h"
#include
@@ -25,6 +26,7 @@ using v8::ObjectTemplate;
using v8::String;
using v8::Uint32;
using v8::Uint32Array;
+using v8::Uint8Array;
using v8::Undefined;
using node::performance::PerformanceEntry;
@@ -149,6 +151,9 @@ Http2Options::Http2Options(Environment* env, nghttp2_session_type type) {
buffer[IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS]);
}
+ if (IsReverted(SECURITY_REVERT_CVE_2019_9512))
+ nghttp2_option_set_max_outbound_ack(options_, 10000);
+
// The padding strategy sets the mechanism by which we determine how much
// additional frame padding to apply to DATA and HEADERS frames. Currently
// this is set on a per-session basis, but eventually we may switch to
@@ -637,8 +642,17 @@ Http2Session::Http2Session(Environment* env,
// fails.
CHECK_EQ(fn(&session_, callbacks, this, *opts, *allocator_info), 0);
- outgoing_storage_.reserve(4096);
+ outgoing_storage_.reserve(1024);
outgoing_buffers_.reserve(32);
+
+ {
+ // Make the js_fields_ property accessible to JS land.
+ Local ab =
+ ArrayBuffer::New(env->isolate(), js_fields_, kSessionUint8FieldCount);
+ Local uint8_arr =
+ Uint8Array::New(ab, 0, kSessionUint8FieldCount);
+ USE(wrap->Set(env->context(), env->fields_string(), uint8_arr));
+ }
}
Http2Session::~Http2Session() {
@@ -857,31 +871,51 @@ ssize_t Http2Session::OnCallbackPadding(size_t frameLen,
// various callback functions. Each of these will typically result in a call
// out to JavaScript so this particular function is rather hot and can be
// quite expensive. This is a potential performance optimization target later.
-ssize_t Http2Session::Write(const uv_buf_t* bufs, size_t nbufs) {
- size_t total = 0;
- // Note that nghttp2_session_mem_recv is a synchronous operation that
- // will trigger a number of other callbacks. Those will, in turn have
+ssize_t Http2Session::ConsumeHTTP2Data() {
+ CHECK_NOT_NULL(stream_buf_.base);
+ CHECK_LT(stream_buf_offset_, stream_buf_.len);
+ size_t read_len = stream_buf_.len - stream_buf_offset_;
+
// multiple side effects.
- for (size_t n = 0; n < nbufs; n++) {
- Debug(this, "receiving %d bytes [wants data? %d]",
- bufs[n].len,
- nghttp2_session_want_read(session_));
- ssize_t ret =
- nghttp2_session_mem_recv(session_,
- reinterpret_cast(bufs[n].base),
- bufs[n].len);
- CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
-
- if (ret < 0)
- return ret;
+ Debug(this, "receiving %d bytes [wants data? %d]",
+ read_len,
+ nghttp2_session_want_read(session_));
+ flags_ &= ~SESSION_STATE_NGHTTP2_RECV_PAUSED;
+ ssize_t ret =
+ nghttp2_session_mem_recv(session_,
+ reinterpret_cast(stream_buf_.base) +
+ stream_buf_offset_,
+ read_len);
+ CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
+
+ if (flags_ & SESSION_STATE_NGHTTP2_RECV_PAUSED) {
+ CHECK_NE(flags_ & SESSION_STATE_READING_STOPPED, 0);
- total += ret;
+ CHECK_GT(ret, 0);
+ CHECK_LE(static_cast(ret), read_len);
+
+ if (static_cast(ret) < read_len) {
+ // Mark the remainder of the data as available for later consumption.
+ stream_buf_offset_ += ret;
+ return ret;
+ }
}
+
+ // We are done processing the current input chunk.
+ DecrementCurrentSessionMemory(stream_buf_.len);
+ stream_buf_offset_ = 0;
+ stream_buf_ab_.Reset();
+ stream_buf_allocation_.clear();
+ stream_buf_ = uv_buf_init(nullptr, 0);
+
+ if (ret < 0)
+ return ret;
+
// Send any data that was queued up while processing the received data.
if (!IsDestroyed()) {
SendPendingData();
}
- return total;
+ return ret;
}
@@ -911,11 +945,17 @@ int Http2Session::OnBeginHeadersCallback(nghttp2_session* handle,
if (UNLIKELY(!session->CanAddStream() ||
Http2Stream::New(session, id, frame->headers.cat) ==
nullptr)) {
+ if (session->rejected_stream_count_++ > 100 &&
+ !IsReverted(SECURITY_REVERT_CVE_2019_9514)) {
+ return NGHTTP2_ERR_CALLBACK_FAILURE;
+ }
// Too many concurrent streams being opened
nghttp2_submit_rst_stream(**session, NGHTTP2_FLAG_NONE, id,
NGHTTP2_ENHANCE_YOUR_CALM);
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
+
+ session->rejected_stream_count_ = 0;
} else if (!stream->IsDestroyed()) {
stream->StartHeaders(frame->headers.cat);
}
@@ -962,8 +1002,7 @@ int Http2Session::OnFrameReceive(nghttp2_session* handle,
frame->hd.type);
switch (frame->hd.type) {
case NGHTTP2_DATA:
- session->HandleDataFrame(frame);
- break;
+ return session->HandleDataFrame(frame);
case NGHTTP2_PUSH_PROMISE:
// Intentional fall-through, handled just like headers frames
case NGHTTP2_HEADERS:
@@ -1000,6 +1039,10 @@ int Http2Session::OnInvalidFrame(nghttp2_session* handle,
Http2Session* session = static_cast(user_data);
Debug(session, "invalid frame received, code: %d", lib_error_code);
+ if (session->invalid_frame_count_++ > 1000 &&
+ !IsReverted(SECURITY_REVERT_CVE_2019_9514)) {
+ return 1;
+ }
// If the error is fatal or if error code is ERR_STREAM_CLOSED... emit error
if (nghttp2_is_fatal(lib_error_code) ||
@@ -1033,7 +1076,8 @@ int Http2Session::OnFrameNotSent(nghttp2_session* handle,
// Do not report if the frame was not sent due to the session closing
if (error_code == NGHTTP2_ERR_SESSION_CLOSING ||
error_code == NGHTTP2_ERR_STREAM_CLOSED ||
- error_code == NGHTTP2_ERR_STREAM_CLOSING) {
+ error_code == NGHTTP2_ERR_STREAM_CLOSING ||
+ session->js_fields_[kSessionFrameErrorListenerCount] == 0) {
return 0;
}
@@ -1173,8 +1217,18 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
nghttp2_session_consume_stream(handle, id, avail);
else
stream->inbound_consumed_data_while_paused_ += avail;
+
+ // If we have a gathered a lot of data for output, try sending it now.
+ if (session->outgoing_length_ > 4096) session->SendPendingData();
} while (len != 0);
+ // If we are currently waiting for a write operation to finish, we should
+ // tell nghttp2 that we want to wait before we process more input data.
+ if (session->flags_ & SESSION_STATE_WRITE_IN_PROGRESS) {
+ session->flags_ |= SESSION_STATE_NGHTTP2_RECV_PAUSED;
+ return NGHTTP2_ERR_PAUSE;
+ }
+
return 0;
}
@@ -1248,7 +1302,13 @@ void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
return;
}
- CHECK(!session->stream_buf_ab_.IsEmpty());
+ Local ab;
+ if (session->stream_buf_ab_.IsEmpty()) {
+ ab = session->stream_buf_allocation_.ToArrayBuffer();
+ session->stream_buf_ab_.Reset(env->isolate(), ab);
+ } else {
+ ab = PersistentToLocal::Strong(session->stream_buf_ab_);
+ }
// There is a single large array buffer for the entire data read from the
// network; create a slice of that array buffer and emit it as the
@@ -1256,10 +1316,11 @@ void Http2StreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
size_t offset = buf.base - session->stream_buf_.base;
// Verify that the data offset is inside the current read buffer.
+ CHECK_GE(offset, session->stream_buf_offset_);
CHECK_LE(offset, session->stream_buf_.len);
CHECK_LE(offset + buf.len, session->stream_buf_.len);
- stream->CallJSOnreadMethod(nread, session->stream_buf_ab_, offset);
+ stream->CallJSOnreadMethod(nread, ab, offset);
}
@@ -1281,6 +1342,8 @@ void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
return;
std::vector headers(stream->move_headers());
+ DecrementCurrentSessionMemory(stream->current_headers_length_);
+ stream->current_headers_length_ = 0;
// The headers are passed in above as a queue of nghttp2_header structs.
// The following converts that into a JS array with the structure:
@@ -1316,6 +1379,7 @@ void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
// are considered advisory only, so this has no real effect other than to
// simply let user code know that the priority has changed.
void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
+ if (js_fields_[kSessionPriorityListenerCount] == 0) return;
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local context = env()->context();
@@ -1341,13 +1405,18 @@ void Http2Session::HandlePriorityFrame(const nghttp2_frame* frame) {
// Called by OnFrameReceived when a complete DATA frame has been received.
// If we know that this was the last DATA frame (because the END_STREAM flag
// is set), then we'll terminate the readable side of the StreamBase.
-void Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
+int Http2Session::HandleDataFrame(const nghttp2_frame* frame) {
int32_t id = GetFrameID(frame);
Debug(this, "handling data frame for stream %d", id);
Http2Stream* stream = FindStream(id);
- if (!stream->IsDestroyed() && frame->hd.flags & NGHTTP2_FLAG_END_STREAM)
+ if (!stream->IsDestroyed() && frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
stream->EmitRead(UV_EOF);
+ } else if (frame->hd.length == 0 &&
+ !IsReverted(SECURITY_REVERT_CVE_2019_9518)) {
+ return 1; // Consider 0-length frame without END_STREAM an error.
+ }
+ return 0;
}
@@ -1380,6 +1449,7 @@ void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
// Called by OnFrameReceived when a complete ALTSVC frame has been received.
void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) {
+ if (!(js_fields_[kBitfield] & (1 << kSessionHasAltsvcListeners))) return;
Isolate* isolate = env()->isolate();
HandleScope scope(isolate);
Local context = env()->context();
@@ -1458,6 +1528,7 @@ void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
return;
}
+ if (!(js_fields_[kBitfield] & (1 << kSessionHasPingListeners))) return;
// Notify the session that a ping occurred
arg = Buffer::Copy(env(),
reinterpret_cast(frame->ping.opaque_data),
@@ -1469,6 +1540,9 @@ void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
if (!ack) {
+ js_fields_[kBitfield] &= ~(1 << kSessionRemoteSettingsIsUpToDate);
+ if (!(js_fields_[kBitfield] & (1 << kSessionHasRemoteSettingsListeners)))
+ return;
// This is not a SETTINGS acknowledgement, notify and return
MakeCallback(env()->http2session_on_settings_function(), 0, nullptr);
return;
@@ -1502,9 +1576,23 @@ void Http2Session::HandleSettingsFrame(const nghttp2_frame* frame) {
void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) {
Debug(this, "write finished with status %d", status);
+ CHECK_NE(flags_ & SESSION_STATE_WRITE_IN_PROGRESS, 0);
+ flags_ &= ~SESSION_STATE_WRITE_IN_PROGRESS;
+
// Inform all pending writes about their completion.
ClearOutgoing(status);
+ if ((flags_ & SESSION_STATE_READING_STOPPED) &&
+ nghttp2_session_want_read(session_)) {
+ flags_ &= ~SESSION_STATE_READING_STOPPED;
+ stream_->ReadStart();
+ }
+
+ // If there is more incoming data queued up, consume it.
+ if (stream_buf_offset_ > 0) {
+ ConsumeHTTP2Data();
+ }
+
if (!(flags_ & SESSION_STATE_WRITE_SCHEDULED)) {
// Schedule a new write if nghttp2 wants to send data.
MaybeScheduleWrite();
@@ -1542,10 +1630,13 @@ void Http2Session::MaybeScheduleWrite() {
}
void Http2Session::MaybeStopReading() {
+ if (flags_ & SESSION_STATE_READING_STOPPED) return;
int want_read = nghttp2_session_want_read(session_);
Debug(this, "wants read? %d", want_read);
- if (want_read == 0)
+ if (want_read == 0 || (flags_ & SESSION_STATE_WRITE_IN_PROGRESS)) {
+ flags_ |= SESSION_STATE_READING_STOPPED;
stream_->ReadStop();
+ }
}
// Unset the sending state, finish up all current writes, and reset
@@ -1557,6 +1648,7 @@ void Http2Session::ClearOutgoing(int status) {
if (outgoing_buffers_.size() > 0) {
outgoing_storage_.clear();
+ outgoing_length_ = 0;
std::vector current_outgoing_buffers_;
current_outgoing_buffers_.swap(outgoing_buffers_);
@@ -1587,6 +1679,11 @@ void Http2Session::ClearOutgoing(int status) {
}
}
+void Http2Session::PushOutgoingBuffer(nghttp2_stream_write&& write) {
+ outgoing_length_ += write.buf.len;
+ outgoing_buffers_.emplace_back(std::move(write));
+}
+
// Queue a given block of data for sending. This always creates a copy,
// so it is used for the cases in which nghttp2 requests sending of a
// small chunk of data.
@@ -1599,7 +1696,7 @@ void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) {
// of the outgoing_buffers_ vector may invalidate the pointer.
// The correct base pointers will be set later, before writing to the
// underlying socket.
- outgoing_buffers_.emplace_back(nghttp2_stream_write {
+ PushOutgoingBuffer(nghttp2_stream_write {
uv_buf_init(nullptr, src_length)
});
}
@@ -1676,8 +1773,11 @@ uint8_t Http2Session::SendPendingData() {
chunks_sent_since_last_write_++;
+ CHECK_EQ(flags_ & SESSION_STATE_WRITE_IN_PROGRESS, 0);
+ flags_ |= SESSION_STATE_WRITE_IN_PROGRESS;
StreamWriteResult res = underlying_stream()->Write(*bufs, count);
if (!res.async) {
+ flags_ &= ~SESSION_STATE_WRITE_IN_PROGRESS;
ClearOutgoing(res.err);
}
@@ -1719,13 +1819,13 @@ int Http2Session::OnSendData(
if (write.buf.len <= length) {
// This write does not suffice by itself, so we can consume it completely.
length -= write.buf.len;
- session->outgoing_buffers_.emplace_back(std::move(write));
+ session->PushOutgoingBuffer(std::move(write));
stream->queue_.pop();
continue;
}
// Slice off `length` bytes of the first write in the queue.
- session->outgoing_buffers_.emplace_back(nghttp2_stream_write {
+ session->PushOutgoingBuffer(nghttp2_stream_write {
uv_buf_init(write.buf.base, length)
});
write.buf.base += length;
@@ -1735,7 +1835,7 @@ int Http2Session::OnSendData(
if (frame->data.padlen > 0) {
// Send padding if that was requested.
- session->outgoing_buffers_.emplace_back(nghttp2_stream_write {
+ session->PushOutgoingBuffer(nghttp2_stream_write {
uv_buf_init(const_cast(zero_bytes_256), frame->data.padlen - 1)
});
}
@@ -1772,7 +1872,6 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
Http2Scope h2scope(this);
CHECK_NOT_NULL(stream_);
Debug(this, "receiving %d bytes", nread);
- CHECK(stream_buf_ab_.IsEmpty());
AllocatedBuffer buf(env(), buf_);
// Only pass data on if nread > 0
@@ -1783,23 +1882,31 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
return;
}
+ statistics_.data_received += nread;
+
+ if (UNLIKELY(stream_buf_offset_ > 0)) {
+ // This is a very unlikely case, and should only happen if the ReadStart()
+ // call in OnStreamAfterWrite() immediately provides data. If that does
+ // happen, we concatenate the data we received with the already-stored
+ // pending input data, slicing off the already processed part.
+ AllocatedBuffer new_buf = env()->AllocateManaged(
+ stream_buf_.len - stream_buf_offset_ + nread);
+ memcpy(new_buf.data(),
+ stream_buf_.base + stream_buf_offset_,
+ stream_buf_.len - stream_buf_offset_);
+ memcpy(new_buf.data() + stream_buf_.len - stream_buf_offset_,
+ buf.data(),
+ nread);
+ buf = std::move(new_buf);
+ nread = buf.size();
+ stream_buf_offset_ = 0;
+ stream_buf_ab_.Reset();
+ DecrementCurrentSessionMemory(stream_buf_offset_);
+ }
+
// Shrink to the actual amount of used data.
buf.Resize(nread);
-
IncrementCurrentSessionMemory(nread);
- OnScopeLeave on_scope_leave([&]() {
- // Once finished handling this write, reset the stream buffer.
- // The memory has either been free()d or was handed over to V8.
- // We use `nread` instead of `buf.size()` here, because the buffer is
- // cleared as part of the `.ToArrayBuffer()` call below.
- DecrementCurrentSessionMemory(nread);
- stream_buf_ab_ = Local();
- stream_buf_ = uv_buf_init(nullptr, 0);
- });
-
- // Make sure that there was no read previously active.
- CHECK_NULL(stream_buf_.base);
- CHECK_EQ(stream_buf_.len, 0);
// Remember the current buffer, so that OnDataChunkReceived knows the
// offset of a DATA frame's data into the socket read buffer.
@@ -1807,12 +1914,12 @@ void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
Isolate* isolate = env()->isolate();
- // Create an array buffer for the read data. DATA frames will be emitted
- // as slices of this array buffer to avoid having to copy memory.
- stream_buf_ab_ = buf.ToArrayBuffer();
+ // Store this so we can create an ArrayBuffer for read data from it.
+ // DATA frames will be emitted as slices of that ArrayBuffer to avoid having
+ // to copy memory.
+ stream_buf_allocation_ = std::move(buf);
- statistics_.data_received += nread;
- ssize_t ret = Write(&stream_buf_, 1);
+ ssize_t ret = ConsumeHTTP2Data();
if (UNLIKELY(ret < 0)) {
Debug(this, "fatal error receiving data: %d", ret);
@@ -1875,7 +1982,7 @@ Http2Stream::Http2Stream(Http2Session* session,
if (max_header_pairs_ == 0) {
max_header_pairs_ = DEFAULT_MAX_HEADER_LIST_PAIRS;
}
- current_headers_.reserve(max_header_pairs_);
+ current_headers_.reserve(std::min(max_header_pairs_, 12u));
// Limit the number of header octets
max_header_length_ =
@@ -1905,6 +2012,7 @@ Http2Stream::~Http2Stream() {
if (session_ == nullptr)
return;
Debug(this, "tearing down stream");
+ session_->DecrementCurrentSessionMemory(current_headers_length_);
session_->RemoveStream(this);
session_ = nullptr;
}
@@ -1919,6 +2027,7 @@ std::string Http2Stream::diagnostic_name() const {
void Http2Stream::StartHeaders(nghttp2_headers_category category) {
Debug(this, "starting headers, category: %d", id_, category);
CHECK(!this->IsDestroyed());
+ session_->DecrementCurrentSessionMemory(current_headers_length_);
current_headers_length_ = 0;
current_headers_.clear();
current_headers_category_ = category;
@@ -2188,8 +2297,12 @@ bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
CHECK(!this->IsDestroyed());
if (this->statistics_.first_header == 0)
this->statistics_.first_header = uv_hrtime();
- size_t length = nghttp2_rcbuf_get_buf(name).len +
- nghttp2_rcbuf_get_buf(value).len + 32;
+ size_t name_len = nghttp2_rcbuf_get_buf(name).len;
+ if (name_len == 0 && !IsReverted(SECURITY_REVERT_CVE_2019_9516)) {
+ return true; // Ignore headers with empty names.
+ }
+ size_t value_len = nghttp2_rcbuf_get_buf(value).len;
+ size_t length = name_len + value_len + 32;
// A header can only be added if we have not exceeded the maximum number
// of headers and the session has memory available for it.
if (!session_->IsAvailableSessionMemory(length) ||
@@ -2205,6 +2318,7 @@ bool Http2Stream::AddHeader(nghttp2_rcbuf* name,
nghttp2_rcbuf_incref(name);
nghttp2_rcbuf_incref(value);
current_headers_length_ += length;
+ session_->IncrementCurrentSessionMemory(length);
return true;
}
@@ -2981,6 +3095,16 @@ void Initialize(Local |