h2lean 0.19.9 → 0.19.14

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.
@@ -101,6 +101,14 @@ function extError(code, msg) {
101
101
  return err;
102
102
  }
103
103
 
104
+ // node's ERR_OUT_OF_RANGE is a RangeError, unlike the ERR_INVALID_ARG_TYPE above;
105
+ // the code and the message are not the whole surface, the constructor is too.
106
+ function rangeError(code, msg) {
107
+ const err = new RangeError(msg);
108
+ err.code = code;
109
+ return err;
110
+ }
111
+
104
112
  // ERR_HTTP2_INVALID_SESSION is defined off plain Error in node's internal/errors.js, not off
105
113
  // TypeError like the argument validators, so it needs its own constructor rather than extError.
106
114
  function invalidSession() {
@@ -769,6 +777,34 @@ function strictSingleValueFields(opts) {
769
777
  return v;
770
778
  }
771
779
 
780
+ // node's connectionWindowSize option, validated by validateSessionOptions
781
+ // (internal/http2/core.js) with validateInt32(value, name, 1, kMaxInitialWindowSize).
782
+ // The checks are in node's order: type, integer, then range; `undefined` is the one
783
+ // value that skips all of them, so null reaches the type check. ERR_INVALID_ARG_TYPE
784
+ // uses received() and ERR_OUT_OF_RANGE uses outOfRangeValue() above, the same two
785
+ // helpers the other validated options in this file use.
786
+ function validateConnectionWindowSize(opts) {
787
+ const value = opts.connectionWindowSize;
788
+ if (value === undefined) {
789
+ return;
790
+ }
791
+ const name = 'options.connectionWindowSize';
792
+ if (typeof value !== 'number') {
793
+ throw extError('ERR_INVALID_ARG_TYPE',
794
+ `The "${name}" property must be of type number. Received ${received(value)}`);
795
+ }
796
+ if (!Number.isInteger(value)) {
797
+ throw rangeError('ERR_OUT_OF_RANGE',
798
+ `The value of "${name}" is out of range. It must be an integer. `
799
+ + `Received ${outOfRangeValue(value)}`);
800
+ }
801
+ if (value < 1 || value > 2147483647) {
802
+ throw rangeError('ERR_OUT_OF_RANGE',
803
+ `The value of "${name}" is out of range. It must be >= 1 && <= 2147483647. `
804
+ + `Received ${outOfRangeValue(value)}`);
805
+ }
806
+ }
807
+
772
808
  // RFC 7541 4.1: the size of an entry is the length of its name plus the length of its value
773
809
  // plus 32 -- the computation RFC 9113 6.5.2 states SETTINGS_MAX_HEADER_LIST_SIZE in terms of.
774
810
  // That is the number node's `maxHeaderListSize` is compared against, measured on
@@ -795,20 +831,19 @@ const ENTRY_OVERHEAD = 32;
795
831
  // worst case -- 256 KiB held per session -- against a peer that stops reading.
796
832
  const MAX_OUT_BATCH = 256 * 1024;
797
833
 
798
- // How much a connection may make this session hold for answers it is not allowed to send. A body
834
+ // What a connection may make this session hold for answers it is not allowed to send. A body
799
835
  // that flow control will not pass is parked on its stream until the peer opens the window, which is
800
836
  // right per request and unbounded per connection: a client that never sends a WINDOW_UPDATE can
801
837
  // make the server keep a live stream plus its unsent body for every HEADERS it puts on the wire.
802
838
  // Measured with tools/probe-stream-concurrency.js -- 200 000 streams on one connection, a 14-byte
803
839
  // response each, no credit ever granted -- the session held 195 319 live streams and 170 MB after a
804
840
  // forced collection, i.e. 892 bytes per parked stream whose queue entry was 23 bytes: what costs
805
- // here is the stream record, not its payload. So the charge has both terms, and the number is then
806
- // a statement about memory rather than about one dimension of it -- at the measured cost, about
807
- // 8 000 parked streams per connection, the same order as the point where node's own session bound
808
- // stopped the identical flood (13 454 streams, same probe, maxSessionMemory left at its default).
809
- // The socket-queue half of the retention is not counted because it is already bounded absolutely by
810
- // MAX_OUT_BATCH above.
811
- const MAX_SESSION_HOLD = 8 * 1024 * 1024;
841
+ // here is the stream record, not its payload. So the charge has both terms. The ceiling is the
842
+ // same maxSessionMemory budget node uses for queued outbound bytes (node_http2.cc DoWrite):
843
+ // measured on v26.12.1 with 100 x 139837-byte responses, node served all 100 at m=1000 where a
844
+ // fixed 8 MiB ceiling refused 39, and the counts agree at m=1/10/100/1000 once the ceiling is
845
+ // the caller's option (the default is 10 MB). The socket-queue half of the retention is not
846
+ // counted because it is already bounded absolutely by MAX_OUT_BATCH above.
812
847
  const STREAM_HOLD_CHARGE = 1024;
813
848
 
814
849
  // Smallest payload that is worth queuing by reference instead of copying into the
@@ -824,12 +859,6 @@ const STAGE_MIN = 8192;
824
859
  // for reuse is bounded independently of how many sessions the server accepts.
825
860
  const MAX_STAGE_POOL = 32;
826
861
 
827
- // The 'stream' event carries node's options object. Two constants instead of a
828
- // literal per request: the payload never changes, and 1.9M requests is 1.9M
829
- // objects the young generation would otherwise have to collect.
830
- const OPT_END_STREAM = { endStream: true };
831
- const OPT_NO_END_STREAM = { endStream: false };
832
-
833
862
  // How long the teardown waits for the goodbye to reach the peer before the socket is
834
863
  // taken away anyway. The FIN is queued behind whatever we wrote, so a peer that stopped
835
864
  // reading would hold it forever -- node does not have that problem because its data sits
@@ -1043,22 +1072,15 @@ const DEFAULT_MAX_OUTSTANDING_PINGS = 10;
1043
1072
  // (util.js:279, MathMax(1, ...)) and multiplied by 1 000 000 by the C++ layer
1044
1073
  // (node_http2.cc:210), whose default is 10 000 000 (node_http2.h:40).
1045
1074
  const DEFAULT_MAX_SESSION_MEMORY = 10 * 1000 * 1000;
1046
- // node checks and charges sizeof(Http2Stream) per live stream
1047
- // (node_http2.cc:915/925) plus name.length + value.length + 32 per header
1048
- // (:2745). sizeof is a C++ compile-time constant: compiled against the v26.12.1
1049
- // headers it is 360 octets, not the ~800 an earlier indirect estimate assigned
1050
- // it. nghttp2 also charges its own per-stream allocation to the same budget
1051
- // (current_session_memory(), node_http2.h:792); h2lean has no nghttp2, so it
1052
- // adds a 131-octet allowance derived from the live trip point with this test's
1053
- // header block. The sum is a bound, not a byte-exact model: indexed
1054
- // pseudo-headers and nghttp2's hash-table growth move node's trip point.
1055
- const STREAM_MEM_CHARGE = 360 + 131;
1056
- // The session's own persistent buffers count against node's budget too: node
1057
- // includes sizeof(Http2Session) (760 octets in the same probe) in
1058
- // current_session_memory(). h2lean's JS counterpart is the pair of scratch
1059
- // buffers plus the first staging buffer; the header assembly buffer is charged
1060
- // when it is actually allocated, in _appendHdr.
1061
- const SESSION_MEM_CHARGE = HEADER_LEN + 6 + STAGE_MIN;
1075
+ // node charges sizeof(Http2Stream) (360 octets compiled against v26.12.1), its
1076
+ // own per-stream nghttp2 allocation, name.length + value.length + 32 per field
1077
+ // and the full length of every queued output buffer (node_http2.cc:915/925,
1078
+ // :2745, current_session_memory()). h2lean has none of those C++ objects, so it
1079
+ // does not invent equivalents for them: it charges the JS bytes it actually
1080
+ // holds -- the session's own buffers (HPACK scratch, split frame header, header
1081
+ // block assembly and staging) plus the bodies streams park while the peer
1082
+ // withholds credit. The trip point is therefore h2lean's real memory rather
1083
+ // than node's; DIVERGENCES.md records the difference.
1062
1084
  // nghttp2 answers a failed stream-open callback with this session error
1063
1085
  // (node_http2.cc:1073-1085, NGHTTP2_ERR_CALLBACK_FAILURE). Measured on a live
1064
1086
  // node 26 server: ERR_HTTP2_ERROR with this message on both 'sessionError' and
@@ -1233,6 +1255,14 @@ class Http2ServerSession extends EventEmitter {
1233
1255
  this._goawayCode = null;
1234
1256
  this._goawayLastStreamID = null;
1235
1257
  this.pendingSettingsAck = true;
1258
+ // node seeds a new stream's receive window from the initialWindowSize in effect at the
1259
+ // moment the stream opens: 65535 until our own SETTINGS is acked (the C++ default), then the
1260
+ // value we advertised. Measured on v26.12.1 with { initialWindowSize: 18 }: a HEADERS before
1261
+ // the ACK reports 65535 while one after it reports 18; the upshot is that a client which wrote
1262
+ // a default-window burst before our SETTINGS arrived is not punished for it. h2lean applies
1263
+ // opts.settings to localSettings at construction (the callback-side divergence documented at
1264
+ // settings()), so the pre-ACK default has to be tracked explicitly for this one window.
1265
+ this._settingsAcked = false;
1236
1266
  // node keeps the origin set in private state and exposes `session.originSet` through a getter
1237
1267
  // that returns a COPY of it -- or undefined unless the session is encrypted (measured on a live
1238
1268
  // node h2c server: `session.originSet` reads undefined there, whatever a peer sends). It is a
@@ -1301,14 +1331,22 @@ class Http2ServerSession extends EventEmitter {
1301
1331
  }
1302
1332
  this._addCustomEntries(built.rest);
1303
1333
  this.remoteSettings = { ...PEER_DEFAULTS };
1334
+ // connectionWindowSize is the connection-level RECEIVE window (validateSessionOptions
1335
+ // validates it at createServer/connect/handshake time). node reports the option as
1336
+ // effectiveLocalWindowSize even below the default, but the live window cannot shrink:
1337
+ // measured on v26.12.1, { connectionWindowSize: 1 } reports eff=1/local=65535 and
1338
+ // sends no WINDOW_UPDATE, while larger options raise both and announce the difference
1339
+ // with one WINDOW_UPDATE(stream 0) in _start().
1340
+ const connectionWindowSize = opts.connectionWindowSize === undefined
1341
+ ? 65535 : opts.connectionWindowSize;
1304
1342
  this.state = {
1305
- // SETTINGS_INITIAL_WINDOW_SIZE is per-stream: node's connection receive
1306
- // window stays at 65535 (measured at 'session' on the running binary with
1307
- // { initialWindowSize: 16384 }), and only new streams take the setting.
1308
- effectiveLocalWindowSize: 65535,
1343
+ // SETTINGS_INITIAL_WINDOW_SIZE is per-stream: it does not move either connection
1344
+ // window (measured at 'session' on the running binary with
1345
+ // { initialWindowSize: 16384 }); connectionWindowSize does.
1346
+ effectiveLocalWindowSize: connectionWindowSize,
1309
1347
  effectiveRecvDataLength: 0,
1310
1348
  nextStreamID: 2,
1311
- localWindowSize: 65535,
1349
+ localWindowSize: Math.max(65535, connectionWindowSize),
1312
1350
  lastProcStreamID: 0,
1313
1351
  remoteWindowSize: 65535,
1314
1352
  outboundQueueSize: 0,
@@ -1324,10 +1362,19 @@ class Http2ServerSession extends EventEmitter {
1324
1362
  // reaches MaxListeners after eleven unanswered pings (measured: node warns for none). The
1325
1363
  // queue order is node's answer rule too (lib/client/Http2ClientSession.js, _pingQ).
1326
1364
  this._pingQ = [];
1365
+ // Streams granted a WINDOW_UPDATE in the current read batch; only these need
1366
+ // their queued flag cleared at _endBatch(), not every live stream.
1367
+ this._wuStreams = [];
1327
1368
  // Unbounded-work-per-peer guards (SECURITY §8B): node bounds these, h2lean must too.
1328
1369
  // maxOutstandingPings defaults to 10 (initializeOptions, internal/http2/util.js).
1329
1370
  this._maxPingQ = typeof opts.maxOutstandingPings === 'number'
1330
1371
  ? opts.maxOutstandingPings : DEFAULT_MAX_OUTSTANDING_PINGS;
1372
+ // maxSettings: node reads the option without creation-time validation and clamps a
1373
+ // finite number to at least 1; anything else keeps the 32-entry default. Measured on
1374
+ // a live node server: 0/1/1.5 refuse a two-entry SETTINGS frame, while NaN, Infinity
1375
+ // and a string fall back to 32 and still refuse the 33rd entry.
1376
+ this._maxSettings = typeof opts.maxSettings === 'number' && Number.isFinite(opts.maxSettings)
1377
+ ? Math.max(1, opts.maxSettings) : MAX_SETTINGS_ENTRIES;
1331
1378
  // maxSessionInvalidFrames: count the HTTP-messaging refusals (a bad request field
1332
1379
  // list, a trailer block without END_STREAM) instead of letting them be free; the
1333
1380
  // first limit+1 are refused per stream, the next closes the connection
@@ -1341,17 +1388,21 @@ class Http2ServerSession extends EventEmitter {
1341
1388
  this._rejectedStreams = 0;
1342
1389
  this._maxRejectedStreams = typeof opts.maxSessionRejectedStreams === 'number'
1343
1390
  ? opts.maxSessionRejectedStreams : DEFAULT_MAX_REJECTED_STREAMS;
1344
- // maxSessionMemory: charge each live stream its record and its retained
1345
- // header block, and refuse a new one with ENHANCE_YOUR_CALM when the charge
1346
- // would cross the budget (node_http2.cc CanAddStream / OnHeader). The charge
1347
- // leaves with the stream in _dropStream, so a connection that drains can open
1348
- // new streams again. node counts queued outbound bytes too; those are already
1349
- // bounded separately by _heldCost (MAX_SESSION_HOLD). The session's own
1350
- // scratch and staging buffers open the budget, as sizeof(Http2Session) does
1351
- // on node; _appendHdr adds the header assembly buffer when it exists.
1391
+ // maxSessionMemory: refuse a new stream with ENHANCE_YOUR_CALM when the
1392
+ // bytes this session actually holds cross the budget. Unlike node there is
1393
+ // no per-stream sizeof() charge: h2lean's accounting is the live byteLength
1394
+ // of its own buffers plus the bodies streams park without credit (the
1395
+ // _memUsed getter). A drained connection releases the parked bytes and can
1396
+ // open streams again.
1352
1397
  this._memLimit = typeof opts.maxSessionMemory === 'number'
1353
1398
  ? Math.max(1, opts.maxSessionMemory) * 1000000 : DEFAULT_MAX_SESSION_MEMORY;
1354
- this._memUsed = SESSION_MEM_CHARGE;
1399
+ // nghttp2 charges queued outbound bytes against the SAME session budget that
1400
+ // bounds stream records and headers (node_http2.cc DoWrite / CanAddStream), so
1401
+ // the parked-body ceiling is the caller's maxSessionMemory, not a separate
1402
+ // fixed number. Measured on v26.12.1: 100 x 139837-byte responses at m=1000
1403
+ // all go out on node, while the fixed 8 MiB ceiling refused 39 of them; with
1404
+ // this ceiling the counts agree at m=1/10/100/1000 and the DoS guard stays.
1405
+ this._holdLimit = this._memLimit;
1355
1406
  // Outbound padding: node's C++ switch only acts on 0/1/2; every other
1356
1407
  // number is an unpadded session (measured on a live node 26 server).
1357
1408
  this._padding = opts.paddingStrategy === f.PADDING_ALIGNED ? f.PADDING_ALIGNED
@@ -1453,10 +1504,10 @@ class Http2ServerSession extends EventEmitter {
1453
1504
  // already cut out of the queue wait in _esRequeue for the same reason.
1454
1505
  this._esMarkers = new Map();
1455
1506
  this._esRequeue = [];
1456
- // Connection-level send window: starts at the peer default (initialWindowSize), but
1457
- // can be overridden by the `connectionWindowSize` option (node's Http2Session option).
1458
- this._connSendWin = typeof opts.connectionWindowSize === 'number'
1459
- ? opts.connectionWindowSize : PEER_DEFAULTS.initialWindowSize;
1507
+ // Connection-level SEND window: the peer's 65535 until it grants more. The
1508
+ // connectionWindowSize option belongs to the RECEIVE side above -- applying it here
1509
+ // made remoteWindowSize echo our own choice instead of the peer's.
1510
+ this._connSendWin = PEER_DEFAULTS.initialWindowSize;
1460
1511
  this._prevInitialWin = PEER_DEFAULTS.initialWindowSize;
1461
1512
  this._connRecvUsed = 0; // consumed bytes owed back to the connection
1462
1513
  this._blocked = null; // streams waiting on credit
@@ -1660,6 +1711,14 @@ class Http2ServerSession extends EventEmitter {
1660
1711
  this.alpnProtocol = 'h2c';
1661
1712
  }
1662
1713
  this._sendSettings();
1714
+ // node's setupHandle raises the connection-level receive window at start with exactly
1715
+ // one WINDOW_UPDATE on stream 0, right after the initial SETTINGS and before 'connect'
1716
+ // (measured on v26.12.1: option 1048576 -> increment 983041). The default and any
1717
+ // option at or below it cannot shrink a live window, so node sends nothing then.
1718
+ if (this.state.effectiveLocalWindowSize > 65535) {
1719
+ this._windowUpdate(0, this.state.effectiveLocalWindowSize - 65535);
1720
+ this._flush();
1721
+ }
1663
1722
  // node's setupHandle announces the server `origins` option with one ORIGIN frame -- server
1664
1723
  // sessions only, and only when the option is an array -- right after the initial SETTINGS and
1665
1724
  // before 'connect'. A bad entry throws out of origin() synchronously, from this connect
@@ -2278,12 +2337,21 @@ class Http2ServerSession extends EventEmitter {
2278
2337
  // "sending a goaway frame has no other effect"), so the application's 'goaway' listener is
2279
2338
  // the peer's decision, never our own. Announcing our own here made a listener fire on a
2280
2339
  // shutdown it had no part in.
2281
- const tail = reason ? Buffer.byteLength(reason) : 0;
2282
- const body = Buffer.alloc(8 + tail);
2340
+ // node's validateBuffer admits Buffer and any TypedArray/DataView as opaqueData and
2341
+ // nghttp2 writes its bytes verbatim (measured v26.12.1). Keep the older string form
2342
+ // accepted here too -- callers on this stack already use it.
2343
+ let opaque;
2344
+ if (reason !== undefined && reason !== null) {
2345
+ opaque = ArrayBuffer.isView(reason)
2346
+ ? Buffer.from(reason.buffer, reason.byteOffset, reason.byteLength)
2347
+ : Buffer.from(String(reason), 'latin1');
2348
+ }
2349
+ const tail = opaque === undefined ? 0 : opaque.length;
2350
+ const body = Buffer.allocUnsafe(8 + tail);
2283
2351
  body.writeUInt32BE(lastStreamID >>> 0, 0);
2284
2352
  body.writeUInt32BE(code, 4);
2285
2353
  if (tail) {
2286
- body.write(reason, 8);
2354
+ opaque.copy(body, 8);
2287
2355
  }
2288
2356
  this._frame(GOAWAY, 0, 0, body, true);
2289
2357
  this._goawaySent = true;
@@ -2545,6 +2613,7 @@ class Http2ServerSession extends EventEmitter {
2545
2613
  return;
2546
2614
  }
2547
2615
  this.pendingSettingsAck = false;
2616
+ this._settingsAcked = true;
2548
2617
  // Process the oldest outstanding submit: node's settingsCallback fires the
2549
2618
  // callback with (null, localSettings, duration) where duration is a monotonic
2550
2619
  // clock reading in milliseconds, and emits 'localSettings' on EVERY ack --
@@ -2566,6 +2635,12 @@ class Http2ServerSession extends EventEmitter {
2566
2635
  return;
2567
2636
  }
2568
2637
  this._applySettings(buf, start, len);
2638
+ // A refused block produces no remoteSettings event and no SETTINGS ACK:
2639
+ // node's protocol error ends the session here (measured with maxSettings 1:
2640
+ // one server session, no stream, no remoteSettings, GOAWAY(11, 0)).
2641
+ if (!this._open) {
2642
+ return;
2643
+ }
2569
2644
  this.emit('remoteSettings', this.remoteSettings);
2570
2645
  this._frame(SETTINGS, F_ACK, 0, null);
2571
2646
  return;
@@ -2604,6 +2679,14 @@ class Http2ServerSession extends EventEmitter {
2604
2679
  const entry = this._pingQ.shift();
2605
2680
  if (entry !== undefined) {
2606
2681
  entry.cb(null, Number(process.hrtime.bigint() - entry.at) / 1e6, payload);
2682
+ } else {
2683
+ // An ACK with no PING of ours outstanding is a protocol error. Measured on
2684
+ // a live node server: ERR_HTTP2_ERROR "Protocol error" on the session, a
2685
+ // close and GOAWAY(error 2, last 0) with an empty debug field and no 'goaway'
2686
+ // event on the session. nghttp2 reports this protocol error with INTERNAL_ERROR
2687
+ // on the wire, not PROTOCOL_ERROR, and with node's own error shape rather
2688
+ // than the default ERR_HTTP2_SESSION_ERROR a fatal would otherwise report.
2689
+ this._fatal(INTERNAL_ERROR, 'Protocol error', 'ERR_HTTP2_ERROR', '');
2607
2690
  }
2608
2691
  return;
2609
2692
  }
@@ -2735,9 +2818,13 @@ class Http2ServerSession extends EventEmitter {
2735
2818
  }
2736
2819
  // CVE-2020-11080: the frame size limit does not cover SETTINGS (_allowFrame exempts
2737
2820
  // it, as RFC 9113 6.2 requires), so without an entry bound a peer can hand us any
2738
- // number of entries to parse. 32 is what node accepts; measured, see the constant.
2739
- if (len / 6 > MAX_SETTINGS_ENTRIES) {
2740
- this._fatal(ENHANCE_YOUR_CALM, 'SETTINGS: too many setting entries');
2821
+ // number of entries to parse. 32 is node's default; the maxSettings option moves the
2822
+ // bound per session, as measured on a live node server (see _maxSettings above).
2823
+ // node's own error is ERR_HTTP2_ERROR "Protocol error" with the entry-count reason
2824
+ // as GOAWAY debug data, not a session error named after the reason.
2825
+ if (len / 6 > this._maxSettings) {
2826
+ this._fatal(ENHANCE_YOUR_CALM, 'Protocol error', 'ERR_HTTP2_ERROR',
2827
+ 'SETTINGS: too many setting entries');
2741
2828
  return;
2742
2829
  }
2743
2830
  const seen = this.remoteSettings;
@@ -2874,6 +2961,9 @@ class Http2ServerSession extends EventEmitter {
2874
2961
  return;
2875
2962
  }
2876
2963
  this._hdrCont = 0; // one block, however many frames it takes
2964
+ // node hands the HEADERS frame flags to 'stream' as its third argument (5 for
2965
+ // a normal GET). Keep the flags of the opening frame, not the CONTINUATION's.
2966
+ this._hdrFlags = flags;
2877
2967
  const p = this._headersPrefix(buf, start, len, sid, flags, len);
2878
2968
  if (p < 0) {
2879
2969
  return;
@@ -2953,17 +3043,14 @@ class Http2ServerSession extends EventEmitter {
2953
3043
  cap *= 2;
2954
3044
  }
2955
3045
  this._hdr = Buffer.allocUnsafe(cap);
2956
- this._memUsed += cap;
2957
3046
  } else if (this._hdrLen + len > this._hdr.length) {
2958
- const old = this._hdr.length;
2959
- let cap = old * 2;
3047
+ let cap = this._hdr.length * 2;
2960
3048
  while (cap < this._hdrLen + len) {
2961
3049
  cap *= 2;
2962
3050
  }
2963
3051
  const bigger = Buffer.allocUnsafe(cap);
2964
3052
  f.copyInto(bigger, 0, this._hdr, 0, this._hdrLen);
2965
3053
  this._hdr = bigger;
2966
- this._memUsed += cap - old;
2967
3054
  }
2968
3055
  f.copyInto(this._hdr, this._hdrLen, buf, start, start + len);
2969
3056
  this._hdrLen += len;
@@ -3565,7 +3652,7 @@ class Http2ServerSession extends EventEmitter {
3565
3652
  // refusal clears itself: credit returns, _release drains, the charge drops below the bound.
3566
3653
  // What is bounded is the cost of accepting, not the total ever: an application that ignores
3567
3654
  // backpressure can still write into a stalled stream without limit.
3568
- if (this._heldCost() >= MAX_SESSION_HOLD) {
3655
+ if (this._heldCost() >= this._holdLimit) {
3569
3656
  this.sendRst(sid, REFUSED_STREAM);
3570
3657
  this._refused.push(sid);
3571
3658
  this._rejectedStreams++;
@@ -3603,12 +3690,12 @@ class Http2ServerSession extends EventEmitter {
3603
3690
 
3604
3691
  // maxSessionMemory: node refuses a stream it cannot account for with the same
3605
3692
  // code and the same rejected-stream escalation as a concurrency refusal
3606
- // (node_http2.cc:1073-1085). The charge is one stream record plus the header
3607
- // block the application may keep alive for the stream's lifetime. Charging
3608
- // here -- after the block is decoded, before the stream is created -- is the
3609
- // only place the peer is still refused without a handler holding its object.
3610
- const memCharge = STREAM_MEM_CHARGE + bytes;
3611
- if (this._memUsed + memCharge > this._memLimit) {
3693
+ // (node_http2.cc:1073-1085). h2lean checks the bytes it actually holds here
3694
+ // -- after the block is decoded, before the stream is created, the only
3695
+ // place the peer is still refused without a handler holding its object.
3696
+ // A flood of tiny header-only streams does not cross the cap: node charges
3697
+ // sizeof(Http2Stream) for each, h2lean has no such object to charge.
3698
+ if (this._memUsed > this._memLimit) {
3612
3699
  // node compares the PRE-increment count (rejected_stream_count_++ > max)
3613
3700
  // and submits no RST on the frame that trips it: max+1 refusals go out,
3614
3701
  // the next opens nothing and ends the session.
@@ -3688,19 +3775,21 @@ class Http2ServerSession extends EventEmitter {
3688
3775
  stream._reqPath = reqPath;
3689
3776
  stream._reqSensitive = sensitive;
3690
3777
  // node's argument order; the field list is the session's shared decode array
3691
- // or a cached one, so the raw list handed out is always a copy. In the compat
3692
- // path the copy is also the stable list the lazy request object builds from
3693
- // (the scratch's backing array is cleared in place by the next decode), so it
3694
- // travels with the stream even when no emit will carry it.
3695
- const raw = this._wantRaw ? fields.slice(0, fcount) : null;
3778
+ // or a cached one, so the raw list handed out is always a copy. Every plain
3779
+ // 'stream' delivery gets that copy as its fourth argument -- flat decoded pairs
3780
+ // including pseudo-headers, duplicates and wire order -- whether or not compat
3781
+ // is armed. In the compat path it is also the stable list the lazy request
3782
+ // object builds from (the scratch's backing array is cleared in place by the
3783
+ // next decode), so it travels with the stream even when no emit will carry it.
3784
+ // Sessions with neither listeners keep the old no-allocation path.
3785
+ const raw = this._wantRaw || this.listenerCount('stream') > 0
3786
+ ? fields.slice(0, fcount) : null;
3696
3787
  stream._reqFields = raw;
3697
3788
  if (headers !== undefined) {
3698
3789
  stream._requestHeaders = headers;
3699
3790
  }
3700
3791
  this._streams.set(sid, stream);
3701
3792
  this._liveStreams++;
3702
- stream._memCharge = memCharge;
3703
- this._memUsed += memCharge;
3704
3793
  if (promised !== undefined) {
3705
3794
  stream._expLen = +promised;
3706
3795
  }
@@ -3715,7 +3804,7 @@ class Http2ServerSession extends EventEmitter {
3715
3804
  // does, and emitting it into a listenerless session would drop the request
3716
3805
  // the compat callback was meant to receive.
3717
3806
  if (this.listenerCount('stream') > 0) {
3718
- this.emit('stream', stream, headers, end ? OPT_END_STREAM : OPT_NO_END_STREAM, raw);
3807
+ this.emit('stream', stream, headers, this._hdrFlags, raw);
3719
3808
  } else if (this._onStreamCompat !== null) {
3720
3809
  this._onStreamCompat(stream);
3721
3810
  }
@@ -3838,6 +3927,21 @@ class Http2ServerSession extends EventEmitter {
3838
3927
  this._fatal(FLOW_CONTROL_ERROR, 'connection flow control window exceeded');
3839
3928
  return undefined;
3840
3929
  }
3930
+ // The per-stream half of the same rule. node's nghttp2 counts the bytes RECEIVED
3931
+ // against the stream window as frames arrive, and consumption only grants credit
3932
+ // back through WINDOW_UPDATE (node sets NO_AUTO_WINDOW_UPDATE in its own C++).
3933
+ // A stream that overruns its window therefore kills the connection with an empty
3934
+ // GOAWAY(FLOW_CONTROL_ERROR) and ERR_HTTP2_ERROR "Protocol error" on both the
3935
+ // session and the stream, whether or not the application is reading -- measured on
3936
+ // a live node server with a flowing window of 18 (two 18-byte chunks delivered,
3937
+ // GOAWAY last stream 13 on the third) and a paused window of 36 (no data delivered,
3938
+ // GOAWAY on the third). The stream error is reported without an RST_STREAM: the
3939
+ // connection error's GOAWAY is the only frame on the wire.
3940
+ if (l > stream._state.localWindowSize) {
3941
+ this._fatal(FLOW_CONTROL_ERROR, 'Protocol error', 'ERR_HTTP2_ERROR', '');
3942
+ stream._tick(() => stream.emit('error', errorOf('ERR_HTTP2_ERROR', 'Protocol error')));
3943
+ return undefined;
3944
+ }
3841
3945
  // RFC 9113 8.2 makes content-length a promise, and the body may not run past it. Measured
3842
3946
  // on node (h2spec http2/8.1.2.6): the frame that crosses the line ends the CONNECTION --
3843
3947
  // GOAWAY(INTERNAL_ERROR) -- rather than the stream, because nghttp2 reads an overflow as a
@@ -3966,12 +4070,28 @@ class Http2ServerSession extends EventEmitter {
3966
4070
 
3967
4071
  // What this connection currently costs in answers it cannot send. Two terms because the flood
3968
4072
  // that needs bounding is many small stalled responses, and charging only their payloads would let
3969
- // 8 MiB of bound stand for 350 000 live stream records -- see MAX_SESSION_HOLD for the measurement.
4073
+ // 10 MB of bound stand for hundreds of thousands of live stream records -- see the charge comment
4074
+ // above for the measurement.
3970
4075
  _heldCost() {
3971
4076
  return this._heldBytes
3972
4077
  + (this._blocked === null ? 0 : this._blocked.size * STREAM_HOLD_CHARGE);
3973
4078
  }
3974
4079
 
4080
+ // The bytes this session actually holds, read on demand instead of maintained
4081
+ // as a counter: there is no calibration to keep in sync when one of the
4082
+ // buffers grows or is handed to the socket, and each term is the buffer's own
4083
+ // byteLength. Views of a socket read are not counted -- the session does not
4084
+ // own that memory (AGENTS.md §5) -- and a stage already queued belongs to the
4085
+ // socket queue, bounded separately by MAX_OUT_BATCH.
4086
+ get _memUsed() {
4087
+ return this._decoder.scratch.byteLength
4088
+ + this._fragHdr.byteLength
4089
+ + this._hdrPrefix.byteLength
4090
+ + (this._stage === null ? 0 : this._stage.byteLength)
4091
+ + (this._hdr === null ? 0 : this._hdr.byteLength)
4092
+ + this._heldBytes;
4093
+ }
4094
+
3975
4095
  // Only streams that actually stalled are worth revisiting. Scanning every
3976
4096
  // stream on each connection-level WINDOW_UPDATE looks harmless at low load
3977
4097
  // and is quadratic under a large response body (OPTIMIZATION.md item 19).
@@ -4125,7 +4245,17 @@ class Http2ServerSession extends EventEmitter {
4125
4245
  if (len < 8) {
4126
4246
  this._fatal(FRAME_SIZE_ERROR, 'GOAWAY payload too short'); return;
4127
4247
  }
4128
- this._goawayLastStreamID = buf.readUInt32BE(start);
4248
+ const lastStreamID = buf.readUInt32BE(start);
4249
+ // nghttp2 refuses an odd Last-Stream-ID on an inbound GOAWAY: measured on v26.12.1,
4250
+ // every odd id (1, 3, 5, 0x7fffffff) raises ERR_HTTP2_ERROR/"Protocol error" no matter
4251
+ // which streams the peer opened, while every even id -- even one above the highest
4252
+ // received -- is accepted. The check lives in the C layer, not in core.js's onGoawayData.
4253
+ if ((lastStreamID & 1) !== 0) {
4254
+ this._fatal(PROTOCOL_ERROR, 'Protocol error', 'ERR_HTTP2_ERROR',
4255
+ 'GOAWAY: invalid last_stream_id');
4256
+ return;
4257
+ }
4258
+ this._goawayLastStreamID = lastStreamID;
4129
4259
  this._goawayCode = buf.readUInt32BE(start + 4);
4130
4260
  // the debug data goes to the application, which may keep it: the same reason as
4131
4261
  // the PING payload above. allocUnsafe + copy instead of Buffer.from(subarray) for
@@ -4171,14 +4301,32 @@ class Http2ServerSession extends EventEmitter {
4171
4301
  _consume(stream, n) {
4172
4302
  stream._recvUsed -= n; // connection share, released below
4173
4303
  this._connRecvUsed += n;
4174
- // The peer's stream window only grows when we say so, and saying so once per
4175
- // quarter window keeps the frame count down instead of one update per chunk.
4304
+ // The peer's stream window only grows when we grant it. node's nghttp2 grants
4305
+ // consumed bytes in half-window steps and lets only ONE window update per stream
4306
+ // be queued at a time: the queued flag clears when the frame is sent, which here
4307
+ // is _endBatch()/_flush(). That is why a burst of DATA overruns the stream window
4308
+ // after the first grant rather than after every frame (measured on a live node
4309
+ // server: two 18-byte chunks with a window of 18, three with a window of 36).
4176
4310
  stream._unannounced += n;
4177
- if (stream._unannounced << 2 >= this.localSettings.initialWindowSize) {
4178
- const inc = stream._unannounced;
4179
- stream._unannounced = 0;
4180
- stream._state.localWindowSize += inc;
4181
- this._windowUpdate(stream.id, inc);
4311
+ if (!stream._wuQueued) {
4312
+ const owed = stream._streamInitialWindow - stream._state.localWindowSize;
4313
+ const inc = Math.min(stream._unannounced, owed);
4314
+ if (inc >= (stream._streamInitialWindow >> 1)) {
4315
+ stream._unannounced -= inc;
4316
+ stream._state.localWindowSize += inc;
4317
+ stream._wuQueued = true;
4318
+ // In a read batch _endBatch clears the flag once the batch is flushed.
4319
+ // Between batches _windowUpdate schedules its own flush and there is no
4320
+ // _endBatch coming, so it has to be cleared here or this stream could
4321
+ // never be granted credit again (a reader arriving on a timer stalls
4322
+ // the sender permanently).
4323
+ if (this._inBatch) {
4324
+ this._wuStreams.push(stream);
4325
+ } else {
4326
+ stream._wuQueued = false;
4327
+ }
4328
+ this._windowUpdate(stream.id, inc);
4329
+ }
4182
4330
  }
4183
4331
  // A reader that shows up between batches (a timer, an await) has to be able
4184
4332
  // to unblock the sender on its own: _endBatch() is not coming this turn.
@@ -4197,10 +4345,13 @@ class Http2ServerSession extends EventEmitter {
4197
4345
  // 640 KiB upload (tools/probe-conn-credit.js): node releases the connection window in steps of
4198
4346
  // 32768 octets -- half the 65535 it advertises -- and the same threshold here takes h2lean's
4199
4347
  // cadence from one frame per read batch to the same half-window steps, at the same throughput.
4200
- // A peer that keeps sending is therefore credited before its window can run out, so the
4201
- // anti-deadlock rule that this counter exists for still holds; below the threshold the bytes
4202
- // stay owed, and the next batch pays them.
4203
- if (this._connRecvUsed < this.localSettings.initialWindowSize >> 1) {
4348
+ // connectionWindowSize raises the connection's receive window, so the step has to follow the
4349
+ // effective window, not the per-stream SETTINGS value (measured with the option at 1048576:
4350
+ // node grants 524288 at a time after the start-of-session increase). A peer that keeps
4351
+ // sending is therefore credited before its window can run out, so the anti-deadlock rule that
4352
+ // this counter exists for still holds; below the threshold the bytes stay owed, and the next
4353
+ // batch pays them.
4354
+ if (this._connRecvUsed < this.state.effectiveLocalWindowSize >> 1) {
4204
4355
  return;
4205
4356
  }
4206
4357
  const inc = this._connRecvUsed;
@@ -4224,6 +4375,14 @@ class Http2ServerSession extends EventEmitter {
4224
4375
  _endBatch() {
4225
4376
  this._creditConnection();
4226
4377
  this._flush();
4378
+ // The batch's WINDOW_UPDATE frames are on the wire now: node clears a stream's
4379
+ // queued-update flag when the frame is sent, so the next consumption may grant
4380
+ // that stream more credit. Leftover consumed bytes stay in _unannounced until
4381
+ // the application takes more data -- nothing is granted to a reader that stopped.
4382
+ for (const stream of this._wuStreams) {
4383
+ stream._wuQueued = false;
4384
+ }
4385
+ this._wuStreams.length = 0;
4227
4386
  if (this._closing && this._liveStreams === 0) {
4228
4387
  // The same finish the stream teardown uses, not a raw socket.end(): the
4229
4388
  // flush above only HANDS the batch to the socket (_frozenLen covers it
@@ -4350,12 +4509,9 @@ class Http2ServerSession extends EventEmitter {
4350
4509
  return;
4351
4510
  }
4352
4511
  this._liveStreams--;
4353
- // the stream record and its retained header block no longer count against
4354
- // maxSessionMemory, so a drained connection can open streams again
4355
- if (stream._memCharge !== undefined) {
4356
- this._memUsed -= stream._memCharge;
4357
- stream._memCharge = undefined;
4358
- }
4512
+ // _memUsed is read from the buffers themselves: the parked bytes this
4513
+ // stream may have held leave the charge with the stream object, so a
4514
+ // drained connection can open streams again.
4359
4515
  // inbound bytes the application never got still owe the connection window
4360
4516
  this._abandon(stream);
4361
4517
  if (killed) {
@@ -4781,7 +4937,11 @@ class Http2ServerSession extends EventEmitter {
4781
4937
  // maxOutstandingPings: node caps the unanswered-ping queue (initializeOptions, util.js).
4782
4938
  // A full queue is not an error: nghttp2's submit fails, node's ping() answers false and
4783
4939
  // the callback is never registered (core.js: `if (duration !== false) this[kQueue].push`).
4940
+ // The refused submit still calls its callback SYNCHRONOUSLY with ERR_HTTP2_PING_CANCEL
4941
+ // ("HTTP2 ping cancelled", duration and pong undefined) before ping() returns false,
4942
+ // exactly as on the client half (measured on a live node server with cap 1 and 3).
4784
4943
  if (this._pingQ.length >= this._maxPingQ) {
4944
+ callback(pingCancelled());
4785
4945
  return false;
4786
4946
  }
4787
4947
  this._pingQ.push({ cb: callback, at: process.hrtime.bigint() });
@@ -4793,6 +4953,12 @@ class Http2ServerSession extends EventEmitter {
4793
4953
  }
4794
4954
 
4795
4955
  goaway(code = NO_ERROR, lastStreamID = this._maxInboundSid, reason) {
4956
+ // node_http2.cc Http2Session::Goaway: `if (lastStreamID <= 0) lastStreamID =
4957
+ // nghttp2_session_get_last_proc_stream_id(session)`. For a server that is the highest
4958
+ // stream id received from the peer, so an explicit 0 keeps an open request alive.
4959
+ if (lastStreamID <= 0) {
4960
+ lastStreamID = this._maxInboundSid;
4961
+ }
4796
4962
  this.sendGoaway(lastStreamID, code, reason);
4797
4963
  this._flush();
4798
4964
  return this;
@@ -4888,9 +5054,9 @@ class Http2ServerSession extends EventEmitter {
4888
5054
  }
4889
5055
 
4890
5056
  module.exports = { Http2ServerSession, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
4891
- ID_BY_SETTING, MAX_OUT_BATCH, MAX_SESSION_HOLD, STREAM_HOLD_CHARGE, BODY_MIN,
5057
+ ID_BY_SETTING, MAX_OUT_BATCH, STREAM_HOLD_CHARGE, BODY_MIN,
4892
5058
  STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
4893
- strictSingleValueFields, hashBlock, hashPieces, kBoundSession,
5059
+ strictSingleValueFields, validateConnectionWindowSize, hashBlock, hashPieces, kBoundSession,
4894
5060
  proxySocketHandler, extError, urlOrigin, checkAltSvc, buildOriginPayload,
4895
5061
  checkPing, invalidSession, pingCancelled, checkSettings, buildSubmission,
4896
5062
  submissionValues, accumulateCustom, customView, validateRemoteCustomSettings,