h2lean 0.4.2 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -0
- package/lib/client-session.js +859 -73
- package/lib/client-stream.js +191 -15
- package/lib/client.js +33 -1
- package/lib/compat.js +76 -29
- package/lib/frames.js +23 -5
- package/lib/headers.js +190 -4
- package/lib/hpack.js +49 -2
- package/lib/server.js +9 -1
- package/lib/session.js +704 -49
- package/lib/stream.js +245 -20
- package/package.json +4 -3
package/lib/client-session.js
CHANGED
|
@@ -60,12 +60,62 @@
|
|
|
60
60
|
// -- ERR_HTTP2_STREAM_ERROR, RST_STREAM(PROTOCOL_ERROR), the session stays up
|
|
61
61
|
// (measured, tools/probe-client-status.js; this closes the empty-block
|
|
62
62
|
// divergence).
|
|
63
|
+
//
|
|
64
|
+
// KNOWN DIVERGENCE: a stream leaves _streams when its response ends (_dropStream on
|
|
65
|
+
// END_STREAM), while node keeps it in state.streams until the Duplex is destroyed. A
|
|
66
|
+
// RST_STREAM that arrives after END_STREAM therefore finds nothing here and is ignored,
|
|
67
|
+
// so a request whose body was never ended -- or whose response body is still buffered
|
|
68
|
+
// unread -- never closes: node reports aborted/finish/close, h2lean waits forever.
|
|
69
|
+
// _wireDone already tracks these streams for the graceful close; the reset path does not
|
|
70
|
+
// consult it. Pinned as the excluded shape in test/client/client-rst.test.js.
|
|
71
|
+
//
|
|
72
|
+
// KNOWN DIVERGENCE: settings() submits the seven standard settings only. node also takes
|
|
73
|
+
// a `customSettings` object of raw id/value pairs (validateSettings caps it at
|
|
74
|
+
// MAX_ADDITIONAL_SETTINGS = 10, updateSettingsBuffer puts the entries on the wire and
|
|
75
|
+
// getSettings reflects them back, including an enableConnectProtocol it stores as id 8).
|
|
76
|
+
// Here those entries are neither validated nor submitted, so a caller using them gets a
|
|
77
|
+
// SETTINGS frame without them rather than node's. The standard-object path -- argument
|
|
78
|
+
// checks, id-ordered payload, the (null, localSettings, duration) callback, the
|
|
79
|
+
// 'localSettings' event, the 'connect' deferral and the ten-pending-ACK limit -- is
|
|
80
|
+
// node's, measured on a live node 26 client against a raw frame-decoding peer.
|
|
81
|
+
//
|
|
82
|
+
// destroy() terminates the connection the way node's closeSession does: the derived code
|
|
83
|
+
// goes out as GOAWAY(last=0, code) before the socket goes, preceded by a RST_STREAM for
|
|
84
|
+
// every open stream but the last. Measured on a live node client for destroy(),
|
|
85
|
+
// destroy(err), destroy(8) and destroy(err, 1) -- codes 0, 2, 8 and 1 -- for one to four
|
|
86
|
+
// open streams, after a graceful close() had already sent a goodbye, and with a stream
|
|
87
|
+
// destroyed beforehand. The resets carry each stream's own derived code, which is not
|
|
88
|
+
// always the goodbye's: destroy(err, 0) resets with INTERNAL_ERROR beside GOAWAY(0). The
|
|
89
|
+
// rule and its C++ caveat are at destroy() below; the shapes are pinned by
|
|
90
|
+
// test/client/client-destroy-goaway.test.js.
|
|
91
|
+
//
|
|
92
|
+
// An inbound GOAWAY branches on its code the way onGoawayData does (core.js:770-782):
|
|
93
|
+
// NO_ERROR begins the graceful close, a non-zero code destroys the session at once with
|
|
94
|
+
// ERR_HTTP2_SESSION_ERROR(code) and answers GOAWAY(NO_ERROR) -- no error condition on
|
|
95
|
+
// this side caused the shutdown. Every open stream errors and closes with the goaway
|
|
96
|
+
// code as its rstCode, and no RST_STREAM goes out: nghttp2 has already closed them, so
|
|
97
|
+
// closeSession's stream.destroy finds no handle to submit through (core.js:2526).
|
|
98
|
+
// Measured for codes 1, 2, 7 and 8, lastStreamID 0, 1, 3 and 5, and one to three open
|
|
99
|
+
// streams; pinned by test/client/client-goaway-inbound.test.js.
|
|
100
|
+
//
|
|
101
|
+
// The closed flag belongs to close() alone (core.js:1657). Neither goaway() nor destroy()
|
|
102
|
+
// sets it: a bare application goaway() leaves closed false and the next request() still
|
|
103
|
+
// reaches the wire, and a destroyed session reports closed false. Measured on a live
|
|
104
|
+
// node client for all three calls.
|
|
105
|
+
//
|
|
106
|
+
// KNOWN DIVERGENCE: an inbound NO_ERROR GOAWAY whose lastStreamID is below the open ids
|
|
107
|
+
// makes node refuse the unprocessed streams itself -- rstCode 7, ERR_HTTP2_STREAM_ERROR
|
|
108
|
+
// naming NGHTTP2_REFUSED_STREAM, and the session destroys once they are gone. Here they
|
|
109
|
+
// are not refused at all: rstCode stays 0, the streams stay open and the session stays
|
|
110
|
+
// closed-but-not-destroyed until the connection goes. Measured with two open requests
|
|
111
|
+
// and lastStreamID 0; the same shape with lastStreamID above them agrees on both arms
|
|
112
|
+
// and is pinned by test/client/client-goaway-inbound.test.js.
|
|
63
113
|
'use strict';
|
|
64
114
|
|
|
65
115
|
const { EventEmitter } = require('node:events');
|
|
66
116
|
const tls = require('node:tls');
|
|
67
117
|
const f = require('./frames');
|
|
68
|
-
const { Decoder, Encoder, HPackError } = require('./hpack');
|
|
118
|
+
const { Decoder, Encoder, HPackError, latin1 } = require('./hpack');
|
|
69
119
|
const FlatList = require('./flat-list');
|
|
70
120
|
// The process-wide inbound decode scratch, same shape and size as the server
|
|
71
121
|
// session's; the full why-sharing-is-safe argument lives with the server's
|
|
@@ -73,27 +123,38 @@ const FlatList = require('./flat-list');
|
|
|
73
123
|
// list: the two never meet the same fill, and coupling the client module to the
|
|
74
124
|
// server's scratch would buy nothing.
|
|
75
125
|
const FLAT = new FlatList(64);
|
|
76
|
-
const { nullProto, isFieldName, lowerName, CONNECTION_SPECIFIC, SINGLE_VALUE_FIELDS
|
|
77
|
-
|
|
126
|
+
const { nullProto, isFieldName, lowerName, neverNames, CONNECTION_SPECIFIC, SINGLE_VALUE_FIELDS,
|
|
127
|
+
KSensitiveHeaders } = require('./headers');
|
|
128
|
+
const { ClientHttp2Stream, AbortError } = require('./client-stream');
|
|
78
129
|
const { pieceByteAt, pieceSlice, pieceConcat, pieceEquals } = require('./pieces');
|
|
79
130
|
// The settings tables, defaults and buffer-path constants are the server's, reused
|
|
80
131
|
// verbatim so a client and a server in this one library never disagree about what a
|
|
81
132
|
// SETTINGS id means, what node advertises, or where the copy/reference break-even sits.
|
|
82
133
|
const {
|
|
83
134
|
OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID, ID_BY_SETTING, BODY_MIN, MAX_OUT_BATCH,
|
|
84
|
-
STAGE_MIN, MAX_SHAPES,
|
|
135
|
+
STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
|
|
136
|
+
strictSingleValueFields, hashBlock, hashPieces, kBoundSession,
|
|
137
|
+
proxySocketHandler, urlOrigin, parseAltSvc, parseOrigins, received, extError
|
|
85
138
|
} = require('./session');
|
|
86
139
|
|
|
87
140
|
const {
|
|
88
141
|
DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
|
|
89
|
-
WINDOW_UPDATE, CONTINUATION,
|
|
142
|
+
WINDOW_UPDATE, CONTINUATION, ALTSVC, ORIGIN,
|
|
90
143
|
F_END_STREAM, F_ACK, F_END_HEADERS, F_PADDED, F_PRIORITY,
|
|
91
|
-
NO_ERROR, PROTOCOL_ERROR, FRAME_SIZE_ERROR, COMPRESSION_ERROR, CANCEL,
|
|
144
|
+
NO_ERROR, PROTOCOL_ERROR, INTERNAL_ERROR, FRAME_SIZE_ERROR, COMPRESSION_ERROR, CANCEL, REFUSED_STREAM,
|
|
92
145
|
HEADER_LEN, PREFACE, PREFACE_LEN, readHeader, writeHeader, trimPadding
|
|
93
146
|
} = f;
|
|
94
147
|
|
|
95
148
|
const MAX_SETTINGS_ENTRIES = 32; // CVE-2020-11080; same bound as the server
|
|
96
149
|
const MAX_CONTINUATIONS = 8; // CVE-2024-28182; same bound as the server
|
|
150
|
+
// nghttp2 refuses a SETTINGS submit once ten frames are awaiting an ACK, and node
|
|
151
|
+
// turns that refusal into a destroyed session (core.js submitSettings: a false return
|
|
152
|
+
// from handle.settings() -> destroy(ERR_HTTP2_MAX_PENDING_SETTINGS_ACK)). Measured on
|
|
153
|
+
// a live node 26 client against a peer that never ACKs: the connection's own first
|
|
154
|
+
// SETTINGS plus nine settings() calls go out (ten frames), the tenth call submits
|
|
155
|
+
// nothing and destroys the session with that error; the call after it throws
|
|
156
|
+
// ERR_HTTP2_INVALID_SESSION because the session is already gone.
|
|
157
|
+
const MAX_PENDING_SETTINGS_ACK = 10;
|
|
97
158
|
// RFC 7540 6.9.2 / 6.5.2: what an endpoint that has not been told otherwise runs a
|
|
98
159
|
// stream's flow control with. The reason it matters here is ordering: a server writes
|
|
99
160
|
// its SETTINGS -- advertising its own window -- before it has read ours, so any stream it
|
|
@@ -115,11 +176,75 @@ function payloadMeaningless(method) {
|
|
|
115
176
|
|| method === 'OPTIONS' || method === 'TRACE';
|
|
116
177
|
}
|
|
117
178
|
|
|
179
|
+
// The ranges validateSettings applies (internal/http2/core.js), whose limits are
|
|
180
|
+
// kMaxInt = 2**32-1, kMaxInitialWindowSize = 2**31-1, kMaxFrameSize = 2**24-1 and
|
|
181
|
+
// kMaxStreams = 2**32-1. maxFrameSize is the only one with a non-zero floor: RFC 9113
|
|
182
|
+
// 6.5.2 defines SETTINGS_MAX_FRAME_SIZE as 16384..16777215.
|
|
183
|
+
const SETTINGS_RANGE = {
|
|
184
|
+
headerTableSize: [0, 0xffffffff],
|
|
185
|
+
initialWindowSize: [0, 0x7fffffff],
|
|
186
|
+
maxFrameSize: [16384, 0xffffff],
|
|
187
|
+
maxConcurrentStreams: [0, 0xffffffff],
|
|
188
|
+
maxHeaderListSize: [0, 0xffffffff],
|
|
189
|
+
maxHeaderSize: [0, 0xffffffff]
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
// ERR_HTTP2_INVALID_SETTING_VALUE is a TypeError, not ERR_OUT_OF_RANGE, and its message
|
|
193
|
+
// names the setting and the value only; .actual is always set and .min/.max only for a
|
|
194
|
+
// range check (internal/errors.js: the factory takes min/max defaulting to undefined).
|
|
195
|
+
// Measured on a live node 26 client: {maxFrameSize: 100} and {headerTableSize: -1} both
|
|
196
|
+
// report `Invalid value for setting "<name>": <value>`, and so does {enablePush: 1},
|
|
197
|
+
// which is a type check rather than a range one and carries no .min.
|
|
198
|
+
function invalidSetting(name, value, min, max) {
|
|
199
|
+
const err = new TypeError(`Invalid value for setting "${name}": ${value}`);
|
|
200
|
+
err.code = 'ERR_HTTP2_INVALID_SETTING_VALUE';
|
|
201
|
+
err.actual = value;
|
|
202
|
+
if (min !== undefined) {
|
|
203
|
+
err.min = min;
|
|
204
|
+
err.max = max;
|
|
205
|
+
}
|
|
206
|
+
return err;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// assertIsObject + validateSettings, in node's order. undefined is legal -- it submits an
|
|
210
|
+
// empty SETTINGS frame -- while null, a string and an array are ERR_INVALID_ARG_TYPE;
|
|
211
|
+
// a Buffer is an object whose setting properties are all undefined, so it passes and
|
|
212
|
+
// submits nothing (both measured). An unknown key is ignored, not refused.
|
|
213
|
+
function checkSettings(settings) {
|
|
214
|
+
if (settings === undefined) {
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (settings === null || typeof settings !== 'object' || Array.isArray(settings)) {
|
|
218
|
+
throw extError('ERR_INVALID_ARG_TYPE',
|
|
219
|
+
`The "settings" argument must be of type object. Received ${received(settings)}`);
|
|
220
|
+
}
|
|
221
|
+
for (const name of Object.keys(SETTINGS_RANGE)) {
|
|
222
|
+
const value = settings[name];
|
|
223
|
+
if (value === undefined) {
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
const [min, max] = SETTINGS_RANGE[name];
|
|
227
|
+
if (typeof value !== 'number' || value < min || value > max) {
|
|
228
|
+
throw invalidSetting(name, value, min, max);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
for (const name of ['enablePush', 'enableConnectProtocol']) {
|
|
232
|
+
if (settings[name] !== undefined && typeof settings[name] !== 'boolean') {
|
|
233
|
+
throw invalidSetting(name, settings[name]);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
118
238
|
// The request method request() fills ':method' from when the application did not
|
|
119
239
|
// supply one. Hoisted for reuse, not for speed: V8 interns string literals, so the
|
|
120
240
|
// measured position is unchanged (OPTIMIZATION.md item 36).
|
|
121
241
|
const DEFAULT_METHOD = 'GET';
|
|
122
242
|
|
|
243
|
+
// The estimate _encodeRequest just computed, read by its caller immediately after --
|
|
244
|
+
// the result-slot shape lib/frames.js and lib/headers.js use, for the same reason: no
|
|
245
|
+
// allocation per block. Only _encodeRequest writes it.
|
|
246
|
+
let sentBound = 0;
|
|
247
|
+
|
|
123
248
|
class ClientHttp2Session extends EventEmitter {
|
|
124
249
|
constructor(socket, options, scheme, authority) {
|
|
125
250
|
super();
|
|
@@ -133,7 +258,9 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
133
258
|
throw err;
|
|
134
259
|
}
|
|
135
260
|
socket[kBoundSession] = this;
|
|
136
|
-
this.
|
|
261
|
+
this._socket = socket;
|
|
262
|
+
// public `socket` returns node's safe Proxy, built lazily; close drops it (see session.js)
|
|
263
|
+
this._proxySocket = null;
|
|
137
264
|
this.type = 1; // NGHTTP2_SESSION_CLIENT
|
|
138
265
|
this.closed = false;
|
|
139
266
|
this.destroyed = false;
|
|
@@ -142,15 +269,57 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
142
269
|
// (_start), the way node's setupHandle fills them after 'secureConnect':
|
|
143
270
|
// before that node's getters read undefined.
|
|
144
271
|
this.pendingSettingsAck = true;
|
|
145
|
-
|
|
272
|
+
// node seeds `originSet` lazily from the TLS socket's servername/remoteAddress
|
|
273
|
+
// and adds the ORIGIN frames the server sent on top of it (encrypted
|
|
274
|
+
// connections only). It starts undefined; the getter builds it on first read,
|
|
275
|
+
// exactly as core.js does with initOriginSet.
|
|
276
|
+
this._originSet = undefined;
|
|
277
|
+
// maxOriginSetSize is client-only and validated by connect(); the server
|
|
278
|
+
// session leaves it undefined so ORIGIN frames over h2s accumulate unbounded.
|
|
279
|
+
this._maxOriginSetSize = opts.maxOriginSetSize;
|
|
146
280
|
// enablePush defaults to true on the client (node's initializeOptions sets
|
|
147
281
|
// NGHTTP2_SETTINGS_ENABLE_PUSH = 1 for clients; the server's OUR_DEFAULTS has
|
|
148
282
|
// false because a server does not receive pushes). The application can override
|
|
149
283
|
// via opts.settings.enablePush.
|
|
150
|
-
|
|
284
|
+
// node's localSettings reports what nghttp2 has in effect, not what
|
|
285
|
+
// getDefaultSettings() prints: a live node 26 client reports maxHeaderListSize and
|
|
286
|
+
// maxHeaderSize 4294967295 where getDefaultSettings() says 65535, and getSettings()
|
|
287
|
+
// (internal/http2/util.js) emits the eight keys in the order below -- maxHeaderSize
|
|
288
|
+
// is an alias of maxHeaderListSize, enableConnectProtocol a boolean, whether or not
|
|
289
|
+
// the application named either. The settings() callback hands this object out, so
|
|
290
|
+
// both the order and the numbers are observable. Nothing here is a guard: the client
|
|
291
|
+
// enforces no inbound header-list bound, and _advertised still decides what is sent.
|
|
292
|
+
this.localSettings = {
|
|
293
|
+
headerTableSize: OUR_DEFAULTS.headerTableSize,
|
|
294
|
+
enablePush: true,
|
|
295
|
+
initialWindowSize: OUR_DEFAULTS.initialWindowSize,
|
|
296
|
+
maxFrameSize: OUR_DEFAULTS.maxFrameSize,
|
|
297
|
+
maxConcurrentStreams: OUR_DEFAULTS.maxConcurrentStreams,
|
|
298
|
+
maxHeaderListSize: 4294967295,
|
|
299
|
+
maxHeaderSize: 4294967295,
|
|
300
|
+
enableConnectProtocol: false,
|
|
301
|
+
...opts.settings
|
|
302
|
+
};
|
|
303
|
+
if (typeof opts.settings?.maxHeaderSize === 'number'
|
|
304
|
+
&& opts.settings.maxHeaderListSize === undefined) {
|
|
305
|
+
this.localSettings.maxHeaderListSize = opts.settings.maxHeaderSize;
|
|
306
|
+
}
|
|
307
|
+
this.localSettings.maxHeaderSize = this.localSettings.maxHeaderListSize;
|
|
308
|
+
// SETTINGS submits awaiting an ACK, and the callbacks they owe, oldest first. The
|
|
309
|
+
// public pendingSettingsAck stays the boolean it has always been; node's own getter
|
|
310
|
+
// is `pendingAck > 0` (core.js), so the counter is what makes it accurate when more
|
|
311
|
+
// than one submit is outstanding.
|
|
312
|
+
this._settingsPending = 0;
|
|
313
|
+
this._settingsAcks = [];
|
|
151
314
|
this.remoteSettings = { ...PEER_DEFAULTS };
|
|
152
315
|
this._scheme = scheme || 'http';
|
|
153
316
|
this._authority = authority || 'localhost';
|
|
317
|
+
// The outbound header-block bound, the same option and the same coercion the server
|
|
318
|
+
// session takes: node's updateOptionsBuffer gates it on `typeof === 'number'` alone
|
|
319
|
+
// and writes it into a Uint32 slot (internal/http2/util.js:249), so a non-number is
|
|
320
|
+
// ignored and 200.9 behaves as 200. connect() passes its options through whole.
|
|
321
|
+
this._maxSendBlock = typeof opts.maxSendHeaderBlockLength === 'number'
|
|
322
|
+
? opts.maxSendHeaderBlockLength >>> 0 : MAX_SEND_BLOCK;
|
|
154
323
|
|
|
155
324
|
// Only what the application asked for is advertised (see session.js _advertised:
|
|
156
325
|
// a number we advertise is a number a peer plans around). Empty by default, which
|
|
@@ -298,6 +467,11 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
298
467
|
this._destroyScheduled = false;
|
|
299
468
|
this._goawayCode = null;
|
|
300
469
|
this._goawayLastStreamID = null;
|
|
470
|
+
// node's state.destroyCode, set by closeSession from destroy(error, code)
|
|
471
|
+
// (core.js:1246). A stream destroyed while the session is going away derives its
|
|
472
|
+
// rstCode from `goawayCode || destroyCode` (core.js:2503), so the number has to be
|
|
473
|
+
// kept separately from the error object the session reports.
|
|
474
|
+
this._destroyCode = NO_ERROR;
|
|
301
475
|
this._pings = new Map(); // 8-octet payload -> callback
|
|
302
476
|
this._pingSeq = 0;
|
|
303
477
|
// Response header shapes seen before: the cached object for a block whose bytes
|
|
@@ -349,9 +523,9 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
349
523
|
// false when the peer ignored ALPN (prior knowledge over TLS), 'h2c' on a
|
|
350
524
|
// plain socket. Reported as measured off the socket; node does not check the
|
|
351
525
|
// client side against a required value, and neither do we.
|
|
352
|
-
if (this.
|
|
526
|
+
if (this._socket.encrypted) {
|
|
353
527
|
this.encrypted = true;
|
|
354
|
-
this.alpnProtocol = this.
|
|
528
|
+
this.alpnProtocol = this._socket.alpnProtocol;
|
|
355
529
|
} else {
|
|
356
530
|
this.encrypted = false;
|
|
357
531
|
this.alpnProtocol = 'h2c';
|
|
@@ -393,6 +567,22 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
393
567
|
const q = this._queuedReq;
|
|
394
568
|
this._queuedReq = null;
|
|
395
569
|
for (const r of q) {
|
|
570
|
+
// node's requestOnConnect (internal/http2/core.js) opens with
|
|
571
|
+
// `if (session === undefined || session.destroyed) return;` -- and a
|
|
572
|
+
// destroyed stream has already cleared its own kSession (_destroy:2546).
|
|
573
|
+
// So a request the application abandoned while the socket was still
|
|
574
|
+
// connecting (req.destroy(), an aborted signal) submits nothing: the
|
|
575
|
+
// server never sees a stream for it. A session closed in the meantime
|
|
576
|
+
// refuses the request instead, with the same GOAWAY_SESSION error
|
|
577
|
+
// request() itself would have produced.
|
|
578
|
+
if (r.stream.destroyed) {
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
if (this.closed) {
|
|
582
|
+
r.stream.destroy(httpErr('ERR_HTTP2_GOAWAY_SESSION',
|
|
583
|
+
'New streams cannot be created after receiving a GOAWAY'));
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
396
586
|
this._enqueue(r);
|
|
397
587
|
} // respects the peer's concurrency limit
|
|
398
588
|
}
|
|
@@ -498,7 +688,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
498
688
|
if (!this._open) {
|
|
499
689
|
this._discardOut(); return;
|
|
500
690
|
}
|
|
501
|
-
if (this._writing || !this.
|
|
691
|
+
if (this._writing || !this._socket.writable) {
|
|
502
692
|
return;
|
|
503
693
|
}
|
|
504
694
|
this._writing = true;
|
|
@@ -506,7 +696,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
506
696
|
const batch = this._outQ;
|
|
507
697
|
this._outQ = [];
|
|
508
698
|
this._outLen = 0;
|
|
509
|
-
const s = this.
|
|
699
|
+
const s = this._socket;
|
|
510
700
|
if (batch.length === 1) {
|
|
511
701
|
// the common case: everything the batch holds went into one staging buffer, so
|
|
512
702
|
// there is nothing to coalesce and corking would only add a round trip through the
|
|
@@ -529,6 +719,12 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
529
719
|
// Dropping the batch is the whole release: the frames were never assembled into
|
|
530
720
|
// anything shared, so there is no tail to move down and nothing to reset.
|
|
531
721
|
this._writePending();
|
|
722
|
+
// The graceful-close gate counts _outLen, so a close() whose goodbye was still
|
|
723
|
+
// staged when the last stream closed has to be re-checked once the bytes leave.
|
|
724
|
+
// Nothing else runs after the final write: the peer's GOAWAY echo used to supply
|
|
725
|
+
// the second close() that re-checked it, and close() is a no-op the second time
|
|
726
|
+
// (core.js:1654).
|
|
727
|
+
this._maybeClose();
|
|
532
728
|
}
|
|
533
729
|
|
|
534
730
|
_discardOut() {
|
|
@@ -552,17 +748,31 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
552
748
|
}
|
|
553
749
|
this._frame(SETTINGS, 0, 0, body, true);
|
|
554
750
|
this.pendingSettingsAck = true;
|
|
751
|
+
this._settingsPending++;
|
|
752
|
+
// The connection's own first SETTINGS occupies a slot in the ACK queue with no
|
|
753
|
+
// callback, exactly as it occupies one in nghttp2's pending count: its ACK emits
|
|
754
|
+
// 'localSettings' and answers nothing else. Without the slot the first ACK would
|
|
755
|
+
// answer the application's first settings() call instead, and the callback would
|
|
756
|
+
// fire one ACK early (measured against a live node 26 client: event, callback, event).
|
|
757
|
+
this._settingsAcks.push({ cb: undefined, values: [] });
|
|
555
758
|
}
|
|
556
759
|
|
|
557
760
|
// request(): the node-shaped surface. Accepts an object, an array of pairs, or
|
|
558
761
|
// nothing; fills the request pseudo-headers from the session's scheme/authority
|
|
559
762
|
// unless the application supplied them; returns a ClientHttp2Stream.
|
|
560
763
|
request(headersParam, options) {
|
|
764
|
+
// Argument validation stays synchronous, but a session-state failure is deferred
|
|
765
|
+
// to the returned stream: node's request() captures it here and dispatches
|
|
766
|
+
// `process.nextTick(requestOnError)` -- `this.destroy(error)` -- instead of
|
|
767
|
+
// submitting (internal/http2/core.js:1836-1844, :1930-1931). The reason is in
|
|
768
|
+
// node's own comment: a retry issued from a stream callback must not throw
|
|
769
|
+
// before the session's lifecycle handlers have run.
|
|
770
|
+
let requestError;
|
|
561
771
|
if (this.destroyed) {
|
|
562
|
-
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
|
|
772
|
+
requestError = httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
|
|
773
|
+
} else if (this.closed) {
|
|
774
|
+
requestError = httpErr('ERR_HTTP2_GOAWAY_SESSION',
|
|
775
|
+
'New streams cannot be created after receiving a GOAWAY');
|
|
566
776
|
}
|
|
567
777
|
// No defensive copy of options: node spreads it because it validates and
|
|
568
778
|
// then MUTATES the copy (setAndValidatePriorityOptions, options.endStream =
|
|
@@ -610,19 +820,88 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
610
820
|
}
|
|
611
821
|
|
|
612
822
|
const stream = new ClientHttp2Stream(this, this._nextSid, {});
|
|
823
|
+
// node records what the application passed at this point (kSentHeaders / kRawHeaders,
|
|
824
|
+
// internal/http2/core.js:1902-1904); the getter folds it into the request map on read.
|
|
825
|
+
stream._sentSrc = headersParam;
|
|
613
826
|
this._trackClose(stream);
|
|
614
827
|
this._nextSid += 2; // the id is reserved now, HEADERS may wait
|
|
828
|
+
// RFC 8336: a 421 (Misdirected Request) answer removes the origin that request
|
|
829
|
+
// was sent to from `originSet`. node records the origin on the stream at
|
|
830
|
+
// request() time -- `stream[kOrigin] = ${scheme}://${authority}` (core.js), where
|
|
831
|
+
// `scheme`/`authority` are the values `prepareRequestHeadersObject`/`...Array`
|
|
832
|
+
// (util.js) resolved for this request: the application's own ':scheme', or
|
|
833
|
+
// `session[kProtocol].slice(0, -1)` when it gave none; and `getAuthority()`'s
|
|
834
|
+
// choice of ':authority', then 'host', then `session[kAuthority]`. The pseudo-
|
|
835
|
+
// headers are only filled into the outbound list later, in _sendRequest, so the
|
|
836
|
+
// same resolution is done here against the list as it stands.
|
|
837
|
+
let originScheme, originAuthority;
|
|
838
|
+
for (let i = 0; i < list.length; i += 2) {
|
|
839
|
+
const key = list[i];
|
|
840
|
+
if (key === ':scheme') {
|
|
841
|
+
if (originScheme === undefined) {
|
|
842
|
+
originScheme = list[i + 1];
|
|
843
|
+
}
|
|
844
|
+
} else if (key === ':authority') {
|
|
845
|
+
originAuthority = list[i + 1]; break;
|
|
846
|
+
} else if (key === 'host' && originAuthority === undefined) {
|
|
847
|
+
originAuthority = list[i + 1];
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
stream._origin = `${originScheme === undefined ? this._scheme : originScheme}`
|
|
851
|
+
+ `://${originAuthority === undefined ? this._authority : originAuthority}`;
|
|
615
852
|
stream.endAfterHeaders = endStream;
|
|
853
|
+
// node's ClientHttp2Session.request() reads options.waitForTrailers to set
|
|
854
|
+
// STREAM_FLAGS_HAS_TRAILERS on the stream, which is what defers the END_STREAM
|
|
855
|
+
// on the last DATA and emits 'wantTrailers'. The flag is only meaningful while
|
|
856
|
+
// the writable half is not already finished by HEADERS (a GET has nothing to
|
|
857
|
+
// trailer) -- node's C++ sets the flag unconditionally, but nghttp2 will not
|
|
858
|
+
// emit wantTrailers for a stream whose writable half is already ended, so h2lean
|
|
859
|
+
// mirrors that observable behaviour.
|
|
860
|
+
stream._waitForTrailers = !!(options && options.waitForTrailers) && !endStream;
|
|
616
861
|
if (endStream) {
|
|
617
862
|
stream.end();
|
|
618
863
|
}
|
|
864
|
+
// node's ClientHttp2Session.request() wires options.signal via
|
|
865
|
+
// internal/http2/core.js: `validateAbortSignal`, then an abort listener that
|
|
866
|
+
// destroys the stream with an AbortError whose cause is signal.reason. The
|
|
867
|
+
// listener is disposed on stream 'close'. An already-aborted signal destroys
|
|
868
|
+
// the stream immediately, without a wire frame. The error has to be an instance
|
|
869
|
+
// of the class, not merely named 'AbortError': _destroy derives CANCEL from
|
|
870
|
+
// `err instanceof AbortError` (core.js:2516) and INTERNAL_ERROR from anything else.
|
|
871
|
+
const signal = options && options.signal;
|
|
872
|
+
if (signal !== undefined && signal !== null) {
|
|
873
|
+
if (typeof signal !== 'object' || typeof signal.addEventListener !== 'function'
|
|
874
|
+
|| typeof signal.removeEventListener !== 'function'
|
|
875
|
+
|| typeof signal.aborted !== 'boolean') {
|
|
876
|
+
const err = new TypeError(
|
|
877
|
+
'The "options.signal" argument must be an instance of AbortSignal');
|
|
878
|
+
err.code = 'ERR_INVALID_ARG_TYPE';
|
|
879
|
+
throw err;
|
|
880
|
+
}
|
|
881
|
+
const aborter = () => {
|
|
882
|
+
stream.destroy(new AbortError(signal.reason));
|
|
883
|
+
};
|
|
884
|
+
if (signal.aborted) {
|
|
885
|
+
aborter();
|
|
886
|
+
} else {
|
|
887
|
+
signal.addEventListener('abort', aborter, { once: true });
|
|
888
|
+
stream.once('close', () => {
|
|
889
|
+
signal.removeEventListener('abort', aborter);
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
619
893
|
|
|
620
894
|
// hp: the original headersParam object. When the application reuses the same
|
|
621
895
|
// object across requests, the HPACK encoder produces identical bytes every time
|
|
622
896
|
// after the dynamic table stabilises, and _sendRequest can use _blocks to replay
|
|
623
897
|
// the encoded block without re-encoding. (The server's shareHeaders equivalent.)
|
|
624
898
|
const req = { stream, list, end: endStream, hp: headersParam };
|
|
625
|
-
if (
|
|
899
|
+
if (requestError !== undefined) {
|
|
900
|
+
// node's requestOnError: destroy the stream with the captured error on the
|
|
901
|
+
// next tick, and submit nothing. The id reserved above is never used -- the
|
|
902
|
+
// session is destroyed or past its GOAWAY mark, so no later request takes it.
|
|
903
|
+
process.nextTick(() => stream.destroy(requestError));
|
|
904
|
+
} else if (this._started) {
|
|
626
905
|
this._enqueue(req);
|
|
627
906
|
} else {
|
|
628
907
|
(this._queuedReq || (this._queuedReq = [])).push(req);
|
|
@@ -769,8 +1048,10 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
769
1048
|
const cached = hp !== undefined && hp !== null && typeof hp === 'object'
|
|
770
1049
|
? this._blocks.get(hp) : undefined;
|
|
771
1050
|
let block;
|
|
1051
|
+
let bound;
|
|
772
1052
|
if (cached !== undefined && cached.epoch === this._encoder.epoch) {
|
|
773
1053
|
block = cached.block;
|
|
1054
|
+
bound = cached.bound;
|
|
774
1055
|
} else {
|
|
775
1056
|
if (!list.includes(':path')) {
|
|
776
1057
|
list.push(':path', '/');
|
|
@@ -783,12 +1064,18 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
783
1064
|
}
|
|
784
1065
|
const ordered = orderPseudo(list);
|
|
785
1066
|
block = this._encodeRequest(ordered);
|
|
1067
|
+
bound = sentBound;
|
|
786
1068
|
if (hp !== undefined && hp !== null && typeof hp === 'object') {
|
|
787
|
-
this._blocks.set(hp, { epoch: this._encoder.epoch, block });
|
|
1069
|
+
this._blocks.set(hp, { epoch: this._encoder.epoch, block, bound });
|
|
788
1070
|
}
|
|
789
1071
|
}
|
|
790
1072
|
stream._sid = stream.id;
|
|
791
|
-
this._sendHeaders(stream.id, block, end)
|
|
1073
|
+
if (this._sendHeaders(stream.id, block, end, bound, true)) {
|
|
1074
|
+
// The HEADERS never reached the wire, so the stream never opened: no body may
|
|
1075
|
+
// follow it and _headersSent stays false. The deferred close in _refuseBlock is
|
|
1076
|
+
// what finishes the Duplex.
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
792
1079
|
// HEADERS is now queued; release any body the application wrote before the
|
|
793
1080
|
// socket connected (or before this queued request was framed). The DATA frames
|
|
794
1081
|
// land in _out behind the HEADERS, so the wire order stays HEADERS -> DATA.
|
|
@@ -808,9 +1095,17 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
808
1095
|
// encoded into -- never into a second one.
|
|
809
1096
|
const update = enc.takeSizeUpdate();
|
|
810
1097
|
let cap = 0;
|
|
1098
|
+
// nghttp2's outbound estimate, accumulated in the pass that already sizes the
|
|
1099
|
+
// scratch -- the same formula and the same string-length-not-octets rule
|
|
1100
|
+
// lib/headers.js encodeAt states. Published in a module slot rather than returned
|
|
1101
|
+
// alongside the buffer: the block cache below has to carry it too, and a second
|
|
1102
|
+
// return value would mean an object per request.
|
|
1103
|
+
let bound = 12;
|
|
811
1104
|
for (let i = 0; i < list.length; i += 2) {
|
|
812
1105
|
cap += Encoder.maxBytesOf(list[i], list[i + 1]);
|
|
1106
|
+
bound += 12 + list[i].length + list[i + 1].length;
|
|
813
1107
|
}
|
|
1108
|
+
sentBound = bound;
|
|
814
1109
|
// Without a size update the block IS the scratch: _sendHeaders runs before any later
|
|
815
1110
|
// encode can rewrite it, and _frame(owned=false) puts a stable copy in the batch.
|
|
816
1111
|
// With one, the old form was Buffer.concat([update, block]) -- a second allocation,
|
|
@@ -834,32 +1129,99 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
834
1129
|
return buf.subarray(0, off);
|
|
835
1130
|
}
|
|
836
1131
|
|
|
837
|
-
|
|
1132
|
+
// Returns true when the block was refused. `opening` says whether this HEADERS is the
|
|
1133
|
+
// one that opens the stream on the wire, which is what decides the refusal's shape:
|
|
1134
|
+
// nghttp2's prep-error path closes a stream-opening request HEADERS itself with
|
|
1135
|
+
// NGHTTP2_REFUSED_STREAM (nghttp2_session.c, session_prep_frame), while a trailer block
|
|
1136
|
+
// is refused on a stream that is already open and nghttp2 closes nothing -- so there
|
|
1137
|
+
// node's own deferred close(FRAME_SIZE_ERROR) is what lands. Both were measured on
|
|
1138
|
+
// v26.12.1 against a node server: the request refusal puts NOTHING on the wire (the
|
|
1139
|
+
// server sees no stream at all and its session closes with goawayCode 0) and reports
|
|
1140
|
+
// rstCode 7; the trailer refusal puts RST_STREAM(6) out and the peer reports
|
|
1141
|
+
// ERR_HTTP2_STREAM_ERROR / rstCode 6.
|
|
1142
|
+
_sendHeaders(sid, block, end, bound, opening) {
|
|
1143
|
+
if (bound + PRIORITY_SPECLEN > this._maxSendBlock) {
|
|
1144
|
+
this._refuseBlock(sid, opening ? REFUSED_STREAM : FRAME_SIZE_ERROR, !opening);
|
|
1145
|
+
return true;
|
|
1146
|
+
}
|
|
838
1147
|
const max = this.remoteSettings.maxFrameSize;
|
|
1148
|
+
// END_STREAM belongs on the HEADERS frame, not on the CONTINUATION that finishes the
|
|
1149
|
+
// block -- RFC 9113 6.2 / 5.1 / 8.1, the same rule lib/session.js sendHeaders states.
|
|
1150
|
+
const es = end ? F_END_STREAM : 0;
|
|
839
1151
|
if (block.length <= max) {
|
|
840
1152
|
// owned=false: the batch keeps a copy, because `block` may be the encoder
|
|
841
1153
|
// scratch; one memcpy, and the double allocation the old by-reference path cost
|
|
842
1154
|
// is gone.
|
|
843
|
-
this._frame(HEADERS, F_END_HEADERS |
|
|
844
|
-
return;
|
|
1155
|
+
this._frame(HEADERS, F_END_HEADERS | es, sid, block, false);
|
|
1156
|
+
return false;
|
|
845
1157
|
}
|
|
846
|
-
this._frame(HEADERS,
|
|
1158
|
+
this._frame(HEADERS, es, sid, block.subarray(0, max), false);
|
|
847
1159
|
let off = max;
|
|
848
1160
|
for (;;) {
|
|
849
1161
|
const n = Math.min(block.length - off, max);
|
|
850
1162
|
const last = off + n >= block.length;
|
|
851
|
-
this._frame(CONTINUATION, last ? F_END_HEADERS
|
|
1163
|
+
this._frame(CONTINUATION, last ? F_END_HEADERS : 0,
|
|
852
1164
|
sid, block.subarray(off, off + n), false);
|
|
853
1165
|
off += n;
|
|
854
1166
|
if (last) {
|
|
855
|
-
return;
|
|
1167
|
+
return false;
|
|
856
1168
|
}
|
|
857
1169
|
}
|
|
858
1170
|
}
|
|
859
1171
|
|
|
1172
|
+
// node's onFrameError (internal/http2/core.js:677): 'frameError' goes out synchronously
|
|
1173
|
+
// on the stream while the session still holds it, and the close is deferred a turn so a
|
|
1174
|
+
// GOAWAY already in flight can arrive first. `onWire` is whether this stream's HEADERS
|
|
1175
|
+
// reached the peer -- see _sendHeaders for why the two refusals differ.
|
|
1176
|
+
_refuseBlock(sid, code, onWire) {
|
|
1177
|
+
const stream = this._streams.get(sid);
|
|
1178
|
+
(stream === undefined ? this : stream).emit('frameError', HEADERS, FRAME_SIZE_ERROR, sid);
|
|
1179
|
+
setImmediate(() => {
|
|
1180
|
+
if (stream !== undefined && !stream.destroyed) {
|
|
1181
|
+
// closeStream (core.js:2071) records the code and finishes the writable half the
|
|
1182
|
+
// application left open. Recording it is what makes the destroy below derive the
|
|
1183
|
+
// error from this code instead of overriding it with INTERNAL_ERROR.
|
|
1184
|
+
stream._reset = true;
|
|
1185
|
+
stream._closeStream(code);
|
|
1186
|
+
// The RST_STREAM is submitted here with the refusal's own code, not left to the
|
|
1187
|
+
// Duplex's _destroy. node submits it from closeStream (core.js:2095) before the
|
|
1188
|
+
// destroy derives the error from rstCode, and the peer is measured to report the
|
|
1189
|
+
// code this stream closed with. Both branches drop the id, so the rstStream inside
|
|
1190
|
+
// _destroy finds nothing and puts no second reset on the wire.
|
|
1191
|
+
if (onWire) {
|
|
1192
|
+
this.rstStream(sid, code);
|
|
1193
|
+
} else {
|
|
1194
|
+
// nghttp2 closed the stream itself at prep time, so no RST_STREAM is
|
|
1195
|
+
// submitted for it at all -- a reset for a stream the peer never saw would
|
|
1196
|
+
// be a connection error (measured: the server arm sees nothing).
|
|
1197
|
+
this._dropStream(sid);
|
|
1198
|
+
}
|
|
1199
|
+
// No error argument: onStreamClose destroys with none (core.js:624) and _destroy
|
|
1200
|
+
// synthesizes ERR_HTTP2_STREAM_ERROR from rstCode, which is null for codes 0 and 8.
|
|
1201
|
+
stream.destroy();
|
|
1202
|
+
}
|
|
1203
|
+
this.close();
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
|
|
860
1207
|
// Flow-controlled send for the writable half of a stream. Called from the Duplex's
|
|
861
1208
|
// _write/_final and again from WINDOW_UPDATE / SETTINGS to resume a stalled body.
|
|
862
1209
|
_pump(stream) {
|
|
1210
|
+
// The peer reset this stream. nghttp2 refuses DATA and HEADERS on a closed stream
|
|
1211
|
+
// ("After calling close ... no DATA and HEADERS frames may be sent",
|
|
1212
|
+
// internal/http2/core.js), but closeStream called end() anyway, so the Duplex still
|
|
1213
|
+
// owes its 'finish'. Settle the writable here rather than frame an END_STREAM for a
|
|
1214
|
+
// stream the peer has already closed.
|
|
1215
|
+
if (stream._reset) {
|
|
1216
|
+
stream._pending = null;
|
|
1217
|
+
stream._pendingOff = 0;
|
|
1218
|
+
const cb = stream._writeCb;
|
|
1219
|
+
if (cb !== null) {
|
|
1220
|
+
stream._writeCb = null; cb();
|
|
1221
|
+
}
|
|
1222
|
+
stream._writableDone();
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
863
1225
|
// No bytes may leave before the stream's HEADERS: DATA on an unopened stream id
|
|
864
1226
|
// is a connection error, and nghttp2 answers it with GOAWAY(INTERNAL_ERROR). A
|
|
865
1227
|
// write() that arrives before 'connect' parks its payload in _pending and waits
|
|
@@ -868,6 +1230,12 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
868
1230
|
return;
|
|
869
1231
|
}
|
|
870
1232
|
const max = this.remoteSettings.maxFrameSize;
|
|
1233
|
+
// waitForTrailers defers the END_STREAM: the last DATA goes out without the flag,
|
|
1234
|
+
// 'wantTrailers' fires on the next tick, and sendTrailers() puts HEADERS with
|
|
1235
|
+
// END_STREAM later. Mirrors node's STREAM_FLAGS_HAS_TRAILERS path in core.js
|
|
1236
|
+
// finishWrite -- shutdownWritable is skipped so the wire stays open, and the
|
|
1237
|
+
// Duplex's 'finish' is still emitted because finishWrite itself runs.
|
|
1238
|
+
const deferEs = stream._waitForTrailers;
|
|
871
1239
|
while (stream._pending !== null) {
|
|
872
1240
|
const room = Math.min(this._connSendWin, stream._sendWin, max);
|
|
873
1241
|
if (room <= 0) {
|
|
@@ -876,7 +1244,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
876
1244
|
const avail = stream._pending.length - stream._pendingOff;
|
|
877
1245
|
const take = Math.min(room, avail);
|
|
878
1246
|
const finishedByte = (stream._pendingOff + take) === stream._pending.length;
|
|
879
|
-
const es = finishedByte && stream._writeCb === null && stream._finalCb !== null;
|
|
1247
|
+
const es = !deferEs && finishedByte && stream._writeCb === null && stream._finalCb !== null;
|
|
880
1248
|
const slice = (stream._pendingOff === 0 && take === stream._pending.length)
|
|
881
1249
|
? stream._pending : stream._pending.subarray(stream._pendingOff, stream._pendingOff + take);
|
|
882
1250
|
this._frame(DATA, es ? F_END_STREAM : 0, stream.id, slice, true);
|
|
@@ -893,6 +1261,15 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
893
1261
|
if (es) {
|
|
894
1262
|
stream._writableDone(); return;
|
|
895
1263
|
}
|
|
1264
|
+
if (deferEs && finishedByte && stream._finalCb !== null && stream._writeCb === null) {
|
|
1265
|
+
// node's client order: 'wantTrailers' fires from nghttp2's shutdown
|
|
1266
|
+
// callback and THEN the Duplex 'finish' runs via finishWrite's cb. Do
|
|
1267
|
+
// the same here: emit synchronously into the stream's emit queue, then
|
|
1268
|
+
// hand the writable back so the Duplex's _final callback runs after.
|
|
1269
|
+
emitWantTrailers(stream);
|
|
1270
|
+
stream._writableDone();
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
896
1273
|
break; // a further write may follow
|
|
897
1274
|
}
|
|
898
1275
|
}
|
|
@@ -903,11 +1280,59 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
903
1280
|
if (stream.endAfterHeaders) {
|
|
904
1281
|
stream._writableDone(); return;
|
|
905
1282
|
}
|
|
1283
|
+
if (deferEs) {
|
|
1284
|
+
emitWantTrailers(stream);
|
|
1285
|
+
stream._writableDone();
|
|
1286
|
+
return;
|
|
1287
|
+
}
|
|
906
1288
|
this._frame(DATA, F_END_STREAM, stream.id, null, false);
|
|
907
1289
|
stream._writableDone();
|
|
908
1290
|
}
|
|
909
1291
|
}
|
|
910
1292
|
|
|
1293
|
+
// Put a trailer HEADERS+END_STREAM block on the wire for a stream whose last DATA
|
|
1294
|
+
// withheld its END_STREAM flag (waitForTrailers). Called by ClientHttp2Stream.
|
|
1295
|
+
// sendTrailers(). Mirrors what the server path does in lib/stream.js: encode the
|
|
1296
|
+
// field lines through the session's HPACK encoder (never a pseudo-header) and hand
|
|
1297
|
+
// them to _sendHeaders with end=true.
|
|
1298
|
+
_sendTrailers(stream, trailers) {
|
|
1299
|
+
if (this.destroyed || stream.destroyed) {
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
const list = [];
|
|
1303
|
+
this._singlesSeen = [];
|
|
1304
|
+
const src = trailers === undefined || trailers === null ? {} : trailers;
|
|
1305
|
+
if (Array.isArray(src)) {
|
|
1306
|
+
for (let i = 0; i + 1 < src.length; i += 2) {
|
|
1307
|
+
this._addField(list, src[i], src[i + 1]);
|
|
1308
|
+
}
|
|
1309
|
+
} else {
|
|
1310
|
+
const keys = Object.keys(src);
|
|
1311
|
+
for (let i = 0; i < keys.length; i++) {
|
|
1312
|
+
this._addField(list, keys[i], src[keys[i]]);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
// RFC 9113 8.1: a trailer block carries no pseudo-header. _addField throws
|
|
1316
|
+
// ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED for one, and node does the same here.
|
|
1317
|
+
const block = this._encodeRequest(list);
|
|
1318
|
+
const bound = sentBound;
|
|
1319
|
+
if (block.length === 0) {
|
|
1320
|
+
// An empty trailer map is not a HEADERS frame: the END_STREAM that waitForTrailers
|
|
1321
|
+
// withheld from the body rides on a zero-length DATA instead (the same rule the
|
|
1322
|
+
// server path applies in lib/stream.js sendTrailers, measured against node). A
|
|
1323
|
+
// pending table-size update makes the block non-empty, so it is never dropped here.
|
|
1324
|
+
this._frame(DATA, F_END_STREAM, stream.id, null, false);
|
|
1325
|
+
} else {
|
|
1326
|
+
if (this._sendHeaders(stream.id, block, true, bound, false)) {
|
|
1327
|
+
// The END_STREAM this block carried never went out; _refuseBlock's deferred
|
|
1328
|
+
// close finishes the writable half instead.
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
stream._endSent = true;
|
|
1333
|
+
this._flush();
|
|
1334
|
+
}
|
|
1335
|
+
|
|
911
1336
|
// ---- inbound ----------------------------------------------------------------
|
|
912
1337
|
// The server's parse loop, mirrored: a frame that fits inside the chunk is handled
|
|
913
1338
|
// in place with no copy at all, and a straddling frame is kept as the views it
|
|
@@ -1102,13 +1527,13 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1102
1527
|
// per update.
|
|
1103
1528
|
if (this._wuLen !== 0) {
|
|
1104
1529
|
if (this._writing && this._open && this._started && this._outLen === 0
|
|
1105
|
-
&& this.
|
|
1530
|
+
&& this._socket.writable) {
|
|
1106
1531
|
// a copy, not a view -- the reason is the comment above -- taken through
|
|
1107
1532
|
// allocUnsafe rather than Buffer.from(subarray): the pooled allocation is the
|
|
1108
1533
|
// cheaper way to get a fresh buffer (OPTIMIZATION.md item 18)
|
|
1109
1534
|
const out = Buffer.allocUnsafe(this._wuLen);
|
|
1110
1535
|
this._wuBuf.copy(out, 0, 0, this._wuLen);
|
|
1111
|
-
this.
|
|
1536
|
+
this._socket.write(out);
|
|
1112
1537
|
} else {
|
|
1113
1538
|
this._need(this._wuLen);
|
|
1114
1539
|
this._wuBuf.copy(this._stage, this._stageLen, 0, this._wuLen);
|
|
@@ -1136,7 +1561,32 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1136
1561
|
if (len !== 0) {
|
|
1137
1562
|
return this._fatal(FRAME_SIZE_ERROR, 'SETTINGS ACK must be empty');
|
|
1138
1563
|
}
|
|
1139
|
-
this.
|
|
1564
|
+
if (this._settingsPending > 0) {
|
|
1565
|
+
this._settingsPending--;
|
|
1566
|
+
}
|
|
1567
|
+
this.pendingSettingsAck = this._settingsPending > 0;
|
|
1568
|
+
// node's settingsCallback (core.js): the ACK answers the oldest outstanding
|
|
1569
|
+
// submit, the callback gets (null, localSettings, duration) and 'localSettings'
|
|
1570
|
+
// is emitted on EVERY ack -- including the one for the connection's own first
|
|
1571
|
+
// SETTINGS frame, which has no callback. Measured on a live node 26 client
|
|
1572
|
+
// against a raw peer: two ACKs produced two 'localSettings' events and one
|
|
1573
|
+
// callback, in the order event, callback, event.
|
|
1574
|
+
const entry = this._settingsAcks.shift();
|
|
1575
|
+
if (entry !== undefined) {
|
|
1576
|
+
for (let i = 0; i < entry.values.length; i += 2) {
|
|
1577
|
+
this.localSettings[entry.values[i]] = entry.values[i + 1];
|
|
1578
|
+
}
|
|
1579
|
+
this.localSettings.maxHeaderSize = this.localSettings.maxHeaderListSize;
|
|
1580
|
+
if (typeof entry.cb === 'function') {
|
|
1581
|
+
// duration is not an elapsed time: node reports its monotonic clock reading
|
|
1582
|
+
// in milliseconds. Measured -- a submit 120 ms earlier answered with
|
|
1583
|
+
// 524545981.423 where Number(process.hrtime.bigint())/1e6 read
|
|
1584
|
+
// 524545981.445, and a second call 200 ms later tracked the clock again
|
|
1585
|
+
// rather than the interval. Matching the reading, not inventing a delta.
|
|
1586
|
+
entry.cb(null, this.localSettings, Number(process.hrtime.bigint()) / 1e6);
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
this.emit('localSettings', this.localSettings);
|
|
1140
1590
|
return this._open;
|
|
1141
1591
|
}
|
|
1142
1592
|
this._applySettings(buf, start, len);
|
|
@@ -1151,7 +1601,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1151
1601
|
return this._fatal(FRAME_SIZE_ERROR, 'PING payload must be 8 octets');
|
|
1152
1602
|
}
|
|
1153
1603
|
if (flags & F_ACK) {
|
|
1154
|
-
const key = buf
|
|
1604
|
+
const key = latin1(buf, start, start + 8);
|
|
1155
1605
|
const entry = this._pings.get(key);
|
|
1156
1606
|
if (entry !== undefined) {
|
|
1157
1607
|
this._pings.delete(key);
|
|
@@ -1217,6 +1667,46 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1217
1667
|
return this._open; // contents deprecated (RFC 9218)
|
|
1218
1668
|
case PUSH_PROMISE:
|
|
1219
1669
|
return this._beginPushPromise(sid, flags, buf, start, len);
|
|
1670
|
+
case ALTSVC: {
|
|
1671
|
+
// RFC 7807: an informational frame. Malformed content is discarded, never
|
|
1672
|
+
// fatal, so the existing "unknown type 10 is ignored" test stays green. The
|
|
1673
|
+
// event carries the decoded field value, the origin (a URL origin string, ''
|
|
1674
|
+
// for a frame on a specific stream) and the stream id.
|
|
1675
|
+
const a = parseAltSvc(buf, start, len);
|
|
1676
|
+
if (a !== null) {
|
|
1677
|
+
this.emit('altsvc', a.alt, a.origin, sid);
|
|
1678
|
+
}
|
|
1679
|
+
return this._open;
|
|
1680
|
+
}
|
|
1681
|
+
case ORIGIN: {
|
|
1682
|
+
// RFC 8336: the server asserts an origin is authoritative for this
|
|
1683
|
+
// connection. Only meaningful over TLS; malformed content is discarded,
|
|
1684
|
+
// never fatal. core.js's onOrigin adds every origin, applies the
|
|
1685
|
+
// maxOriginSetSize cap and destroys the session with
|
|
1686
|
+
// ERR_HTTP2_TOO_MANY_ORIGINS on overflow, then emits 'origin' once with
|
|
1687
|
+
// the whole array of origin strings.
|
|
1688
|
+
const os = parseOrigins(buf, start, len);
|
|
1689
|
+
if (os === null) {
|
|
1690
|
+
return this._open;
|
|
1691
|
+
}
|
|
1692
|
+
if (!this.encrypted || this.destroyed) {
|
|
1693
|
+
return this._open;
|
|
1694
|
+
}
|
|
1695
|
+
const set = this._initOriginSet();
|
|
1696
|
+
for (let i = 0; i < os.length; i++) {
|
|
1697
|
+
if (set.size >= this._maxOriginSetSize) {
|
|
1698
|
+
const err = new Error(
|
|
1699
|
+
'The server sent more ORIGIN frames than the allowed number of ' +
|
|
1700
|
+
`${this._maxOriginSetSize}`);
|
|
1701
|
+
err.code = 'ERR_HTTP2_TOO_MANY_ORIGINS';
|
|
1702
|
+
this.destroy(err);
|
|
1703
|
+
return this._open;
|
|
1704
|
+
}
|
|
1705
|
+
set.add(os[i]);
|
|
1706
|
+
}
|
|
1707
|
+
this.emit('origin', os);
|
|
1708
|
+
return this._open;
|
|
1709
|
+
}
|
|
1220
1710
|
default:
|
|
1221
1711
|
return this._open; // RFC 9113 5.5: discard unknown
|
|
1222
1712
|
}
|
|
@@ -1530,6 +2020,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1530
2020
|
}
|
|
1531
2021
|
const fields = flat.items;
|
|
1532
2022
|
const fcount = flat.count;
|
|
2023
|
+
const flags = this._decoder.neverCount > 0 ? this._decoder.neverFlags : null;
|
|
1533
2024
|
// maxReservedRemoteStreams: a pushed stream stays reserved until its
|
|
1534
2025
|
// response HEADERS arrive (measured: the count releases on the HEADERS,
|
|
1535
2026
|
// not on 'end'). Over the cap the promise is refused with RST_STREAM(CANCEL)
|
|
@@ -1551,7 +2042,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1551
2042
|
this._frame(RST_STREAM, 0, promisedSid, body, true);
|
|
1552
2043
|
return;
|
|
1553
2044
|
}
|
|
1554
|
-
const headers = this._toObject(fields, fcount);
|
|
2045
|
+
const headers = this._toObject(fields, fcount, neverNames(fields, fcount, flags));
|
|
1555
2046
|
// Create the pushed stream. Its writable half is pre-ended: the client never
|
|
1556
2047
|
// sends a request body for a push (node: writableEnded=true, writableFinished=true
|
|
1557
2048
|
// at the 'stream' event, measured v26.12.1).
|
|
@@ -1629,9 +2120,14 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1629
2120
|
const hit = shapes === null ? undefined : shapes.get(slot);
|
|
1630
2121
|
// where this response's field list comes from: the scratch's backing array
|
|
1631
2122
|
// on a decode, a cached copy on a shape hit -- both read by index, so the
|
|
1632
|
-
// valid length travels next to the list (same as the server session)
|
|
2123
|
+
// valid length travels next to the list (same as the server session).
|
|
2124
|
+
// blockFlags is the never-indexed marker of the same lines: the decoder's
|
|
2125
|
+
// list on a decode, the cached snapshot on a hit, null when there was none
|
|
2126
|
+
// -- neverNames() reads it where _toObject hangs the `sensitiveHeaders`
|
|
2127
|
+
// symbol node puts on every inbound header object.
|
|
1633
2128
|
let fields;
|
|
1634
2129
|
let fcount;
|
|
2130
|
+
let blockFlags;
|
|
1635
2131
|
try {
|
|
1636
2132
|
if (hit !== undefined && (block !== null
|
|
1637
2133
|
? hit.block.equals(block)
|
|
@@ -1639,6 +2135,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1639
2135
|
this._shapeHits++;
|
|
1640
2136
|
fields = hit.flat;
|
|
1641
2137
|
fcount = fields.length;
|
|
2138
|
+
blockFlags = hit.flags;
|
|
1642
2139
|
} else {
|
|
1643
2140
|
if (block !== null) {
|
|
1644
2141
|
this._decoder.decode(block, 0, block.length, flat);
|
|
@@ -1647,6 +2144,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1647
2144
|
}
|
|
1648
2145
|
fields = flat.items;
|
|
1649
2146
|
fcount = flat.count;
|
|
2147
|
+
blockFlags = this._decoder.neverCount > 0 ? this._decoder.neverFlags : null;
|
|
1650
2148
|
if (shapes !== null) {
|
|
1651
2149
|
if (++this._shapeMisses > 64 && this._shapeHits * 4 < this._shapeMisses) {
|
|
1652
2150
|
this._shapes = null;
|
|
@@ -1656,7 +2154,10 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1656
2154
|
}
|
|
1657
2155
|
shapes.set(slot, {
|
|
1658
2156
|
block: block !== null ? Buffer.from(block) : pieceConcat(pieces, from, to),
|
|
1659
|
-
flat: fields.slice(0, fcount)
|
|
2157
|
+
flat: fields.slice(0, fcount),
|
|
2158
|
+
// a snapshot copy, not the decoder's live array: the next decode
|
|
2159
|
+
// clears the array in place, and this entry must survive it
|
|
2160
|
+
flags: blockFlags !== null ? blockFlags.slice() : null
|
|
1660
2161
|
});
|
|
1661
2162
|
}
|
|
1662
2163
|
}
|
|
@@ -1694,7 +2195,19 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1694
2195
|
if (this._refuseHeaders(sid, stream, fields, fcount)) {
|
|
1695
2196
|
return;
|
|
1696
2197
|
}
|
|
1697
|
-
const headers = this._toObject(fields, fcount);
|
|
2198
|
+
const headers = this._toObject(fields, fcount, neverNames(fields, fcount, blockFlags));
|
|
2199
|
+
// RFC 8336 3.2 + core.js emitStreamEvent: a 421 (Misdirected Request) answer
|
|
2200
|
+
// deletes the origin the request carried from originSet, and it does so here --
|
|
2201
|
+
// before 'response' is scheduled, so a handler that reads `session.originSet`
|
|
2202
|
+
// from inside 'response' already sees the entry gone. The helper is called for
|
|
2203
|
+
// its lazy-seed side effect exactly as node's `session[kState].originSet =
|
|
2204
|
+
// initOriginSet(session)` assignment does: on the first 421 of a session the set
|
|
2205
|
+
// is created from the socket before the delete, and over h2c both stacks leave
|
|
2206
|
+
// the set unobservable (the getter is encrypted-gated). `:status` is a number by
|
|
2207
|
+
// now, so the comparison is node's numeric `status === 421`.
|
|
2208
|
+
if (headers[':status'] === 421) {
|
|
2209
|
+
this._initOriginSet().delete(stream._origin);
|
|
2210
|
+
}
|
|
1698
2211
|
stream._onHeaders(headers, end, flags);
|
|
1699
2212
|
if (end) {
|
|
1700
2213
|
this._dropStream(sid);
|
|
@@ -1748,8 +2261,15 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1748
2261
|
return true;
|
|
1749
2262
|
}
|
|
1750
2263
|
|
|
1751
|
-
|
|
2264
|
+
// node's toHeaderObject semantics for a response (or a trailer block or a
|
|
2265
|
+
// push promise): null prototype, :status coerced to a number, set-cookie
|
|
2266
|
+
// always an array, repeats joined -- and the never-indexed names under the
|
|
2267
|
+
// `sensitiveHeaders` symbol, assigned first so the shape tree of these
|
|
2268
|
+
// objects shares one symbol transition (the server side explains why in
|
|
2269
|
+
// session.js _toObject).
|
|
2270
|
+
_toObject(fields, count, sensitive) {
|
|
1752
2271
|
const o = nullProto();
|
|
2272
|
+
o[KSensitiveHeaders] = sensitive;
|
|
1753
2273
|
for (let i = 0; i < count; i += 2) {
|
|
1754
2274
|
const name = fields[i];
|
|
1755
2275
|
let value = fields[i + 1];
|
|
@@ -1904,23 +2424,27 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1904
2424
|
}
|
|
1905
2425
|
this._goawayCode = code;
|
|
1906
2426
|
this._goawayLastStreamID = lastStreamID;
|
|
1907
|
-
// Streams the peer refused to process (id above lastStreamID) may be retried;
|
|
1908
|
-
// for M1 we report them and stop opening new ones past the mark.
|
|
1909
|
-
if (lastStreamID < this._nextSid - 2) {
|
|
1910
|
-
this.closed = true;
|
|
1911
|
-
}
|
|
1912
2427
|
// node hands the third goaway argument as undefined when the peer sent no debug
|
|
1913
2428
|
// data (not an empty buffer), so the measured event shape matches only if we do.
|
|
1914
2429
|
this.emit('goaway', code, lastStreamID, debug === null || debug.length === 0
|
|
1915
2430
|
? undefined : debug);
|
|
1916
|
-
//
|
|
1917
|
-
//
|
|
1918
|
-
// "No new streams permitted, but existing streams may close naturally on
|
|
1919
|
-
// their own"
|
|
1920
|
-
//
|
|
1921
|
-
//
|
|
2431
|
+
// onGoawayData (core.js:770-782) branches on the code, and the branch is the whole
|
|
2432
|
+
// teardown rule. NO_ERROR begins the graceful shutdown regardless of the live
|
|
2433
|
+
// streams -- "No new streams permitted, but existing streams may close naturally on
|
|
2434
|
+
// their own"; closing only when the stream map was already empty left the session
|
|
2435
|
+
// open forever when the last stream ended after the GOAWAY arrived (measured on
|
|
2436
|
+
// live node: it closes, h2lean hung). A non-zero code destroys at once, carrying
|
|
2437
|
+
// ERR_HTTP2_SESSION_ERROR(code) but NO_ERROR on the wire -- node's comment gives the
|
|
2438
|
+
// reason: "there was no error condition on this side of the session that caused the
|
|
2439
|
+
// shutdown". Measured on a live node client for codes 1, 2, 7 and 8 and lastStreamID
|
|
2440
|
+
// 0, 1, 3 and 5: the session and every open stream error and close in that order,
|
|
2441
|
+
// destroyed true and closed false, GOAWAY(0,0) alone on the wire with no RST_STREAM.
|
|
2442
|
+
// Pinned by test/client/client-goaway-inbound.test.js.
|
|
1922
2443
|
if (code === NO_ERROR) {
|
|
1923
2444
|
this.close();
|
|
2445
|
+
} else {
|
|
2446
|
+
this.destroy(httpErr('ERR_HTTP2_SESSION_ERROR',
|
|
2447
|
+
`Session closed with error code ${code}`), NO_ERROR);
|
|
1924
2448
|
}
|
|
1925
2449
|
return this._open;
|
|
1926
2450
|
}
|
|
@@ -1957,6 +2481,9 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1957
2481
|
|
|
1958
2482
|
// ---- session API ------------------------------------------------------------
|
|
1959
2483
|
ping(payload, cb) {
|
|
2484
|
+
if (this.destroyed) {
|
|
2485
|
+
throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
|
|
2486
|
+
}
|
|
1960
2487
|
// node lets a caller pass the callback as the only argument: ping(cb).
|
|
1961
2488
|
if (typeof payload === 'function') {
|
|
1962
2489
|
cb = payload; payload = undefined;
|
|
@@ -1978,25 +2505,93 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
1978
2505
|
}
|
|
1979
2506
|
}
|
|
1980
2507
|
if (typeof cb === 'function') {
|
|
1981
|
-
this._pings.set(body
|
|
2508
|
+
this._pings.set(latin1(body, 0, 8), { cb, at: process.hrtime.bigint() });
|
|
1982
2509
|
}
|
|
1983
2510
|
this._frame(PING, 0, 0, body, true);
|
|
1984
2511
|
return body;
|
|
1985
2512
|
}
|
|
1986
2513
|
|
|
1987
|
-
settings(
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
2514
|
+
// node's settings() takes a settings OBJECT, not a SETTINGS payload (core.js
|
|
2515
|
+
// settings() -> submitSettings()). Only the entries the caller named go on the wire,
|
|
2516
|
+
// in ascending setting-id order rather than the object's key order: measured on a live
|
|
2517
|
+
// node 26 client against a raw peer, {headerTableSize, maxConcurrentStreams, enablePush}
|
|
2518
|
+
// arrived as headerTableSize=8192, enablePush=0, maxConcurrentStreams=7. The server
|
|
2519
|
+
// side's settings() (lib/session.js) re-advertises everything it has ever advertised
|
|
2520
|
+
// instead; this is the client following node, not the server's shape.
|
|
2521
|
+
settings(settings, cb) {
|
|
2522
|
+
if (this.destroyed) {
|
|
2523
|
+
throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
|
|
2524
|
+
}
|
|
2525
|
+
checkSettings(settings);
|
|
2526
|
+
// node validates the callback only when it is truthy, so settings({}, null) is legal.
|
|
2527
|
+
if (cb && typeof cb !== 'function') {
|
|
2528
|
+
throw extError('ERR_INVALID_ARG_TYPE',
|
|
2529
|
+
`The "callback" argument must be of type function. Received ${received(cb)}`);
|
|
2530
|
+
}
|
|
2531
|
+
const submit = () => {
|
|
2532
|
+
// submitSettings returns without submitting on a destroyed session, and the
|
|
2533
|
+
// 'connect' listener below can fire after one (core.js).
|
|
2534
|
+
if (this.destroyed) {
|
|
2535
|
+
return;
|
|
2536
|
+
}
|
|
2537
|
+
if (this._settingsPending >= MAX_PENDING_SETTINGS_ACK) {
|
|
2538
|
+
this.destroy(httpErr('ERR_HTTP2_MAX_PENDING_SETTINGS_ACK',
|
|
2539
|
+
'Maximum number of pending settings acknowledgements'));
|
|
2540
|
+
return;
|
|
1993
2541
|
}
|
|
1994
|
-
|
|
1995
|
-
|
|
2542
|
+
const entries = [];
|
|
2543
|
+
const values = [];
|
|
2544
|
+
if (settings) {
|
|
2545
|
+
// maxHeaderSize is the deprecated alias of maxHeaderListSize: it wins when the
|
|
2546
|
+
// two differ, and node warns exactly then (internal/http2/util.js
|
|
2547
|
+
// updateSettingsBuffer). The wire entry is id 6 either way.
|
|
2548
|
+
let listSize = settings.maxHeaderListSize;
|
|
2549
|
+
if (typeof settings.maxHeaderSize === 'number') {
|
|
2550
|
+
if (settings.maxHeaderSize !== listSize) {
|
|
2551
|
+
process.emitWarning('settings.maxHeaderSize overwrite settings.maxHeaderListSize');
|
|
2552
|
+
}
|
|
2553
|
+
listSize = settings.maxHeaderSize;
|
|
2554
|
+
}
|
|
2555
|
+
// ID_BY_SETTING is built from SETTINGS_BY_ID in id order, so walking its keys
|
|
2556
|
+
// produces the ascending order node submits in without a sort.
|
|
2557
|
+
for (const name of Object.keys(ID_BY_SETTING)) {
|
|
2558
|
+
const value = name === 'maxHeaderListSize' ? listSize : settings[name];
|
|
2559
|
+
if (value === undefined) {
|
|
2560
|
+
continue;
|
|
2561
|
+
}
|
|
2562
|
+
values.push(name, value);
|
|
2563
|
+
entries.push(ID_BY_SETTING[name], typeof value === 'boolean' ? (value ? 1 : 0) : value);
|
|
2564
|
+
}
|
|
2565
|
+
}
|
|
2566
|
+
const body = Buffer.allocUnsafe(entries.length * 3);
|
|
2567
|
+
for (let i = 0; i < entries.length; i += 2) {
|
|
2568
|
+
const at = i * 3;
|
|
2569
|
+
body.writeUInt16BE(entries[i], at);
|
|
2570
|
+
body.writeUInt32BE(entries[i + 1] >>> 0, at + 2);
|
|
2571
|
+
}
|
|
2572
|
+
// The values are applied when THIS submit's ACK arrives, not now: measured on a
|
|
2573
|
+
// live node 26 client for all seven settings, the first 'localSettings' event (the
|
|
2574
|
+
// ACK for the connection's own initial frame) still reports the old value and the
|
|
2575
|
+
// second reports the new one -- headerTableSize 8192 arrived as [4096, 8192],
|
|
2576
|
+
// maxHeaderListSize 1234 as [4294967295, 1234]. A setting takes effect when it is
|
|
2577
|
+
// acknowledged, so the queue entry carries what it will change.
|
|
2578
|
+
this._settingsAcks.push({ cb, values });
|
|
2579
|
+
this._frame(SETTINGS, 0, 0, body, true);
|
|
2580
|
+
this._settingsPending++;
|
|
2581
|
+
this.pendingSettingsAck = true;
|
|
2582
|
+
};
|
|
2583
|
+
// While connecting node defers the whole submit to 'connect' rather than refusing it.
|
|
2584
|
+
if (this.connecting) {
|
|
2585
|
+
this.once('connect', submit);
|
|
2586
|
+
return;
|
|
1996
2587
|
}
|
|
2588
|
+
submit();
|
|
1997
2589
|
}
|
|
1998
2590
|
|
|
1999
2591
|
goaway(code, lastStreamID, reason) {
|
|
2592
|
+
if (this.destroyed) {
|
|
2593
|
+
throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
|
|
2594
|
+
}
|
|
2000
2595
|
if (code === undefined) {
|
|
2001
2596
|
code = NO_ERROR;
|
|
2002
2597
|
}
|
|
@@ -2021,20 +2616,59 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
2021
2616
|
body.write(reason, 8);
|
|
2022
2617
|
}
|
|
2023
2618
|
this._frame(GOAWAY, 0, 0, body, true);
|
|
2024
|
-
|
|
2619
|
+
// No closed marking here: node's goaway() (core.js:1602-1618) validates and submits
|
|
2620
|
+
// and never touches SESSION_FLAGS_CLOSED. Measured on a live node client: after a
|
|
2621
|
+
// bare goaway() closed is false and the next request() still reaches the wire, where
|
|
2622
|
+
// h2lean marked it closed and refused the request with ERR_HTTP2_GOAWAY_SESSION.
|
|
2623
|
+
}
|
|
2624
|
+
|
|
2625
|
+
_initOriginSet() {
|
|
2626
|
+
// The client half of core.js's shared base: same lazy helper, same seed rule.
|
|
2627
|
+
// Reads `this.socket` (the proxySocket getter, the raw socket underneath) for
|
|
2628
|
+
// servername/remoteAddress/remotePort/remoteFamily.
|
|
2629
|
+
let set = this._originSet;
|
|
2630
|
+
if (set === undefined) {
|
|
2631
|
+
const socket = this.socket;
|
|
2632
|
+
set = this._originSet = new Set();
|
|
2633
|
+
let hostName = socket.servername;
|
|
2634
|
+
if (hostName === null || hostName === false || hostName === undefined) {
|
|
2635
|
+
hostName = socket.remoteFamily === 'IPv6'
|
|
2636
|
+
? `[${socket.remoteAddress}]`
|
|
2637
|
+
: socket.remoteAddress;
|
|
2638
|
+
}
|
|
2639
|
+
let originString = `https://${hostName}`;
|
|
2640
|
+
if (socket.remotePort != null) {
|
|
2641
|
+
originString += `:${socket.remotePort}`;
|
|
2642
|
+
}
|
|
2643
|
+
set.add(urlOrigin(originString));
|
|
2644
|
+
}
|
|
2645
|
+
return set;
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
get originSet() {
|
|
2649
|
+
// core.js's getter returns ArrayFrom(initOriginSet()) only for an encrypted,
|
|
2650
|
+
// live session; an h2c client gets undefined.
|
|
2651
|
+
if (!this.encrypted || this.destroyed) {
|
|
2652
|
+
return undefined;
|
|
2653
|
+
}
|
|
2654
|
+
return [...this._initOriginSet()];
|
|
2025
2655
|
}
|
|
2026
2656
|
|
|
2027
2657
|
close(code, cb) {
|
|
2028
2658
|
if (typeof code === 'function') {
|
|
2029
2659
|
cb = code; code = undefined;
|
|
2030
2660
|
}
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2661
|
+
// close() owns the closed flag, goaway() does not (core.js:1653-1657), and a second
|
|
2662
|
+
// close() is a no-op there -- the guard is what keeps the goodbye from going twice.
|
|
2663
|
+
if (this.closed || this.destroyed) {
|
|
2664
|
+
return;
|
|
2034
2665
|
}
|
|
2666
|
+
this.closed = true;
|
|
2667
|
+
this._closeRequested = true;
|
|
2668
|
+
this.goaway(code === undefined ? NO_ERROR : code);
|
|
2035
2669
|
this._maybeClose();
|
|
2036
2670
|
if (typeof cb === 'function') {
|
|
2037
|
-
if (this.
|
|
2671
|
+
if (this._streams.size === 0) {
|
|
2038
2672
|
process.nextTick(cb);
|
|
2039
2673
|
} else {
|
|
2040
2674
|
this.once('close', cb);
|
|
@@ -2082,12 +2716,75 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
2082
2716
|
}
|
|
2083
2717
|
}
|
|
2084
2718
|
|
|
2085
|
-
destroy(err) {
|
|
2719
|
+
destroy(err, code) {
|
|
2086
2720
|
if (this.destroyed) {
|
|
2087
2721
|
return;
|
|
2088
2722
|
}
|
|
2723
|
+
// node's destroy(error = NGHTTP2_NO_ERROR, code) normalizes before closeSession
|
|
2724
|
+
// (core.js:1622-1637): a number IS the code and builds ERR_HTTP2_SESSION_ERROR for
|
|
2725
|
+
// any non-zero value, and an error with no code implies INTERNAL_ERROR. Measured on
|
|
2726
|
+
// a live node client: destroy(8) reports 'Session closed with error code 8' on the
|
|
2727
|
+
// session and on the open stream, whose rstCode is 8; destroy(new Error('boom'), 1)
|
|
2728
|
+
// keeps the caller's error and gives the stream rstCode 1. The code is recorded for
|
|
2729
|
+
// the streams' _destroy derivation, which reads it as sessionCode.
|
|
2730
|
+
if (typeof err === 'number') {
|
|
2731
|
+
code = err;
|
|
2732
|
+
err = code !== NO_ERROR
|
|
2733
|
+
? httpErr('ERR_HTTP2_SESSION_ERROR', `Session closed with error code ${code}`)
|
|
2734
|
+
: undefined;
|
|
2735
|
+
}
|
|
2736
|
+
if (code === undefined && err != null) {
|
|
2737
|
+
code = INTERNAL_ERROR;
|
|
2738
|
+
}
|
|
2739
|
+
this._destroyCode = code === undefined ? NO_ERROR : code;
|
|
2740
|
+
// The goodbye is staged before the teardown, while goaway() still accepts a call.
|
|
2741
|
+
// node's closeSession terminates the nghttp2 session with this code
|
|
2742
|
+
// (core.js:1265 handle.destroy(code, socket.destroyed)), which puts
|
|
2743
|
+
// GOAWAY(lastStreamID, code) on the wire ahead of the socket going: measured on a
|
|
2744
|
+
// live node client for destroy(), destroy(err), destroy(8) and destroy(err, 1) --
|
|
2745
|
+
// codes 0, 2, 8 and 1, last=0 with no pushes -- and again after a graceful close()
|
|
2746
|
+
// had already sent one, so the goodbye is not conditional on the session being open.
|
|
2747
|
+
// Nothing goes out before the handshake (_started): a destroy while connecting was
|
|
2748
|
+
// measured to leave the peer with a bare socket close.
|
|
2749
|
+
//
|
|
2750
|
+
// The open streams are reset all but the last of them. Measured for one, two, three
|
|
2751
|
+
// and four open streams: N-1 RST_STREAM frames in ascending id order, then the
|
|
2752
|
+
// GOAWAY; one open stream produces no reset at all, and a stream the application had
|
|
2753
|
+
// already destroyed is not counted. Why the last one is exempt is in the C++ layer
|
|
2754
|
+
// (node_http2.cc / nghttp2), which was not read -- the rule here is the wire
|
|
2755
|
+
// measurement, not a derivation from it.
|
|
2756
|
+
if (this._started) {
|
|
2757
|
+
// A non-zero inbound GOAWAY has already closed the streams inside nghttp2, so the
|
|
2758
|
+
// stream.destroy closeSession runs finds no handle and submits no reset
|
|
2759
|
+
// (core.js:2526, `hasHandle ? kForceRstStream : kNoRstStream`). Measured: zero
|
|
2760
|
+
// RST_STREAM for one, two and three open streams and any lastStreamID. The nghttp2
|
|
2761
|
+
// half was not read; an inbound NO_ERROR GOAWAY leaves the processed streams'
|
|
2762
|
+
// handles alive, and a destroy(err) after one does reset them (RST(1,2) measured).
|
|
2763
|
+
if (this._goawayCode === null || this._goawayCode === NO_ERROR) {
|
|
2764
|
+
// The reset code is the stream's own derivation, not the goodbye's.
|
|
2765
|
+
// Http2Stream._destroy (core.js:2504-2521) reads sessionCode =
|
|
2766
|
+
// goawayCode || destroyCode and only falls back to the error when that is zero:
|
|
2767
|
+
// AbortError to CANCEL, anything else to INTERNAL_ERROR. Measured on a live node
|
|
2768
|
+
// client: destroy(new Error('boom'), 0) puts RST_STREAM(2) on the wire beside
|
|
2769
|
+
// GOAWAY(0), so an explicit zero code does not zero the resets.
|
|
2770
|
+
const sessionCode = this._goawayCode || this._destroyCode;
|
|
2771
|
+
let rst = sessionCode;
|
|
2772
|
+
if (err != null && !sessionCode) {
|
|
2773
|
+
rst = err instanceof AbortError ? CANCEL : INTERNAL_ERROR;
|
|
2774
|
+
}
|
|
2775
|
+
const open = [...this._streams.keys()];
|
|
2776
|
+
for (let i = 0; i < open.length - 1; i++) {
|
|
2777
|
+
const body = Buffer.allocUnsafe(4);
|
|
2778
|
+
body.writeUInt32BE(rst >>> 0, 0);
|
|
2779
|
+
this._frame(RST_STREAM, 0, open[i], body, true);
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
this.goaway(this._destroyCode);
|
|
2783
|
+
}
|
|
2089
2784
|
this.destroyed = true;
|
|
2090
|
-
|
|
2785
|
+
// closed stays false. node's destroy() never sets SESSION_FLAGS_CLOSED -- only
|
|
2786
|
+
// close() does (core.js:1657) -- and a live node client reports closed false both
|
|
2787
|
+
// synchronously and after the teardown, for destroy() and for an inbound GOAWAY.
|
|
2091
2788
|
this._open = false;
|
|
2092
2789
|
this._closeError = err || null;
|
|
2093
2790
|
this._destroyScheduled = true;
|
|
@@ -2119,8 +2816,31 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
2119
2816
|
}
|
|
2120
2817
|
// reassigned, not length-cleared (OPTIMIZATION.md item 38)
|
|
2121
2818
|
this._outboundQueue = [];
|
|
2122
|
-
const socket = this.
|
|
2123
|
-
|
|
2819
|
+
const socket = this._socket;
|
|
2820
|
+
// The goodbye has to reach the socket before it goes. destroy() used to drop the
|
|
2821
|
+
// staged batch outright (_discardOut), which is why the peer saw a bare close; the
|
|
2822
|
+
// batch is handed over here the way _fatal hands over its GOAWAY, and end() below
|
|
2823
|
+
// flushes it ahead of the FIN.
|
|
2824
|
+
this._commit();
|
|
2825
|
+
const batch = this._outQ;
|
|
2826
|
+
this._outQ = [];
|
|
2827
|
+
this._outLen = 0;
|
|
2828
|
+
// _commit drops the staging buffer only when it held bytes; _discardOut dropped it
|
|
2829
|
+
// either way, and so does this.
|
|
2830
|
+
this._stage = null;
|
|
2831
|
+
this._stageLen = 0;
|
|
2832
|
+
if (batch.length !== 0 && socket.writable && !socket.destroyed) {
|
|
2833
|
+
if (batch.length === 1) {
|
|
2834
|
+
socket.write(batch[0]);
|
|
2835
|
+
} else {
|
|
2836
|
+
socket.cork();
|
|
2837
|
+
for (let i = 0; i < batch.length - 1; i++) {
|
|
2838
|
+
socket.write(batch[i]);
|
|
2839
|
+
}
|
|
2840
|
+
socket.write(batch[batch.length - 1]);
|
|
2841
|
+
socket.uncork();
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2124
2844
|
if (!socket.destroyed) {
|
|
2125
2845
|
// Bytes already handed to the socket -- the GOAWAY a fatal inbound frame
|
|
2126
2846
|
// leaves with (_fatal) -- are flushed by end() before the FIN; an outright
|
|
@@ -2140,10 +2860,18 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
2140
2860
|
}
|
|
2141
2861
|
|
|
2142
2862
|
ref() {
|
|
2143
|
-
this.
|
|
2863
|
+
this._socket.ref(); return this;
|
|
2144
2864
|
}
|
|
2145
2865
|
unref() {
|
|
2146
|
-
this.
|
|
2866
|
+
this._socket.unref(); return this;
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
// node's session.socket: the safe Proxy, built once and cached; dropped on close.
|
|
2870
|
+
get socket() {
|
|
2871
|
+
if (this._proxySocket === null) {
|
|
2872
|
+
this._proxySocket = new Proxy(this, proxySocketHandler);
|
|
2873
|
+
}
|
|
2874
|
+
return this._proxySocket;
|
|
2147
2875
|
}
|
|
2148
2876
|
|
|
2149
2877
|
setTimeout(msecs, callback) {
|
|
@@ -2167,9 +2895,15 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
2167
2895
|
}
|
|
2168
2896
|
|
|
2169
2897
|
setNextStreamID(id) {
|
|
2898
|
+
if (this.destroyed) {
|
|
2899
|
+
throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
|
|
2900
|
+
}
|
|
2170
2901
|
this._nextSid = id; return this;
|
|
2171
2902
|
}
|
|
2172
2903
|
setLocalWindowSize(size) {
|
|
2904
|
+
if (this.destroyed) {
|
|
2905
|
+
throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
|
|
2906
|
+
}
|
|
2173
2907
|
// RFC 9113 6.9.2: the change rescales the peer's send windows retroactively, so the
|
|
2174
2908
|
// window we maintain moves by the same delta rather than only applying to streams
|
|
2175
2909
|
// opened from here on -- and _creditRecv()'s threshold is derived from it per call.
|
|
@@ -2181,15 +2915,21 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
2181
2915
|
// ---- teardown ---------------------------------------------------------------
|
|
2182
2916
|
// A client connection is keep-alive: finishing the last stream must NOT tear the
|
|
2183
2917
|
// session down, or the next request() on the same session would find it destroyed.
|
|
2184
|
-
// Only an explicit close()
|
|
2185
|
-
//
|
|
2186
|
-
//
|
|
2918
|
+
// Only an explicit close() (which sets _closeRequested), a peer GOAWAY that left
|
|
2919
|
+
// nothing live, or destroy() ends it -- then it ends once the outbound queue and the
|
|
2920
|
+
// open streams have both drained. The pre-connect request queue counts as live:
|
|
2921
|
+
// node's kMaybeDestroy refuses while state.pendingStreams is non-empty
|
|
2922
|
+
// (core.js:1689-1691), and a request still waiting for 'connect' is that set here.
|
|
2923
|
+
// Without it a close() before the socket connects destroys the session at the first
|
|
2924
|
+
// write callback and cancels the request, where node lets the drain refuse it with
|
|
2925
|
+
// ERR_HTTP2_GOAWAY_SESSION (test/upstream/client-destroy.test.js).
|
|
2187
2926
|
_maybeClose() {
|
|
2188
2927
|
if (this.destroyed || this._closeEmitted) {
|
|
2189
2928
|
return;
|
|
2190
2929
|
}
|
|
2191
2930
|
if (this._closeRequested && this._streams.size === 0 && this._wireDone.size === 0
|
|
2192
|
-
&& this._outboundQueue.length === 0 && this._outLen === 0
|
|
2931
|
+
&& this._outboundQueue.length === 0 && this._outLen === 0
|
|
2932
|
+
&& (this._queuedReq === null || this._queuedReq.length === 0)) {
|
|
2193
2933
|
this.destroy();
|
|
2194
2934
|
}
|
|
2195
2935
|
}
|
|
@@ -2270,7 +3010,7 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
2270
3010
|
const batch = this._outQ;
|
|
2271
3011
|
this._outQ = [];
|
|
2272
3012
|
this._outLen = 0;
|
|
2273
|
-
const socket = this.
|
|
3013
|
+
const socket = this._socket;
|
|
2274
3014
|
if (batch.length !== 0 && socket.writable && !socket.destroyed) {
|
|
2275
3015
|
if (batch.length === 1) {
|
|
2276
3016
|
socket.write(batch[0]);
|
|
@@ -2297,11 +3037,39 @@ class ClientHttp2Session extends EventEmitter {
|
|
|
2297
3037
|
}
|
|
2298
3038
|
|
|
2299
3039
|
_onSocketClose() {
|
|
2300
|
-
this.
|
|
3040
|
+
this._socket[kBoundSession] = undefined;
|
|
3041
|
+
this._proxySocket = undefined;
|
|
2301
3042
|
if (this._closeEmitted) {
|
|
2302
3043
|
return;
|
|
2303
3044
|
}
|
|
2304
3045
|
this.destroyed = true;
|
|
3046
|
+
// node's socketOnClose (internal/http2/core.js:3653) closes every live stream
|
|
3047
|
+
// and every pending one with NGHTTP2_CANCEL before it closes the session, and
|
|
3048
|
+
// CANCEL is not an error (core.js:2543), so the application sees 'close' with
|
|
3049
|
+
// rstCode 8 and no 'error'. Without this sweep a request whose HEADERS went out
|
|
3050
|
+
// but whose answer never came stayed in _streams forever: the session emitted
|
|
3051
|
+
// 'close' with the stream still live and never destroyed (measured on a server
|
|
3052
|
+
// that destroys its session from the 'stream' handler -- node reports req-close
|
|
3053
|
+
// 8, h2lean left req.destroyed false indefinitely).
|
|
3054
|
+
for (const stream of [...this._streams.values()]) {
|
|
3055
|
+
if (!stream.destroyed) {
|
|
3056
|
+
this._dropStream(stream.id);
|
|
3057
|
+
stream._onRst(CANCEL);
|
|
3058
|
+
}
|
|
3059
|
+
}
|
|
3060
|
+
for (const q of [this._queuedReq, this._outboundQueue]) {
|
|
3061
|
+
if (q === null) {
|
|
3062
|
+
continue;
|
|
3063
|
+
}
|
|
3064
|
+
for (const r of q) {
|
|
3065
|
+
if (!r.stream.destroyed) {
|
|
3066
|
+
r.stream._onRst(CANCEL);
|
|
3067
|
+
}
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
this._queuedReq = null;
|
|
3071
|
+
// reassigned, not length-cleared (OPTIMIZATION.md item 38)
|
|
3072
|
+
this._outboundQueue = [];
|
|
2305
3073
|
// destroy() owns the emission when it was called (fatal or graceful): its
|
|
2306
3074
|
// nextTick carries the error and runs after the streams' 'close'. Only the
|
|
2307
3075
|
// pure peer-FIN shape -- destroyed here, no destroy() pending -- defers to
|
|
@@ -2422,4 +3190,22 @@ function cancelErr(cause) {
|
|
|
2422
3190
|
return err;
|
|
2423
3191
|
}
|
|
2424
3192
|
|
|
3193
|
+
// Top-level emit helper for the deferred END_STREAM path: matches the module-level
|
|
3194
|
+
// `emit()` pattern used elsewhere so the process.nextTick call in _pump does not
|
|
3195
|
+
// capture a closure over the stream.
|
|
3196
|
+
function emitWantTrailers(stream) {
|
|
3197
|
+
// node's onStreamTrailers sets state.trailersReady first and only then looks at
|
|
3198
|
+
// whether the stream is still alive, and it closes the deferred END_STREAM itself
|
|
3199
|
+
// when the application never asked for the event: an empty trailer block. Without
|
|
3200
|
+
// that fallback a request written with waitForTrailers and no listener leaves the
|
|
3201
|
+
// message unfinished for good.
|
|
3202
|
+
stream._trailersReady = true;
|
|
3203
|
+
if (stream.destroyed) {
|
|
3204
|
+
return;
|
|
3205
|
+
}
|
|
3206
|
+
if (!stream.emit('wantTrailers')) {
|
|
3207
|
+
stream.sendTrailers({});
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
|
|
2425
3211
|
module.exports = { ClientHttp2Session };
|