Debian Codegraph @

lib/dispatcher/client-h2.js

raw
1 'use strict'
2
3 const assert = require('node:assert')
4 const { pipeline } = require('node:stream')
5 const util = require('../core/util.js')
6 const {
7 RequestContentLengthMismatchError,
8 RequestAbortedError,
9 SocketError,
10 InformationalError,
11 InvalidArgumentError,
12 HeadersTimeoutError,
13 BodyTimeoutError
14 } = require('../core/errors.js')
15 const {
16 kUrl,
17 kReset,
18 kClient,
19 kRunning,
20 kPending,
21 kQueue,
22 kPendingIdx,
23 kRunningIdx,
24 kError,
25 kSocket,
26 kStrictContentLength,
27 kOnError,
28 kMaxConcurrentStreams,
29 kPingInterval,
30 kHTTP2Session,
31 kHTTP2InitialWindowSize,
32 kHTTP2ConnectionWindowSize,
33 kHostAuthority,
34 kResume,
35 kSize,
36 kHTTPContext,
37 kClosed,
38 kKeepAliveDefaultTimeout,
39 kHeadersTimeout,
40 kBodyTimeout,
41 kEnableConnectProtocol,
42 kRemoteSettings,
43 kHTTP2Stream,
44 kHTTP2SessionState
45 } = require('../core/symbols.js')
46 const { channels } = require('../core/diagnostics.js')
47
48 const kOpenStreams = Symbol('open streams')
49 const kRequestStreamId = Symbol('request stream id')
50 const kRequestStream = Symbol('request stream')
51 const kRequestStreamCleanup = Symbol('request stream cleanup')
52 const kRequestStreamState = Symbol('request stream state')
53 const kReceivedGoAway = Symbol('received goaway')
54
55 let extractBody
56
57 /** @type {import('http2')} */
58 let http2
59 try {
60 http2 = require('node:http2')
61 } catch {
62 // @ts-ignore
63 http2 = { constants: {} }
64 }
65
66 const {
67 constants: {
68 HTTP2_HEADER_AUTHORITY,
69 HTTP2_HEADER_METHOD,
70 HTTP2_HEADER_PATH,
71 HTTP2_HEADER_SCHEME,
72 HTTP2_HEADER_CONTENT_LENGTH,
73 HTTP2_HEADER_EXPECT,
74 HTTP2_HEADER_STATUS,
75 HTTP2_HEADER_PROTOCOL,
76 NGHTTP2_NO_ERROR,
77 NGHTTP2_REFUSED_STREAM
78 }
79 } = http2
80
81 function getGoAwayError (session, errorCode) {
82 return session[kError] ||
83 (errorCode === NGHTTP2_NO_ERROR
84 ? new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`)
85 : new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(session[kSocket])))
86 }
87
88 function resetHttp2Session (session, err) {
89 const client = session[kClient]
90 const socket = session[kSocket]
91
92 if (client[kHTTP2Session] === session) {
93 client[kSocket] = null
94 client[kHTTPContext] = null
95 client[kHTTP2Session] = null
96 }
97
98 if (socket != null && socket[kError] == null) {
99 socket[kError] = err
100 }
101
102 if (!session.closed && !session.destroyed) {
103 try {
104 session.destroy(err)
105 } catch {}
106 }
107
108 util.destroy(socket, err)
109 }
110
111 function getGoAwayPendingIdx (client, lastStreamID) {
112 const maxAcceptedStreamID = Number.isInteger(lastStreamID) ? lastStreamID : Number.MAX_SAFE_INTEGER
113
114 for (let i = client[kRunningIdx]; i < client[kPendingIdx]; i++) {
115 const request = client[kQueue][i]
116
117 if (request == null) {
118 continue
119 }
120
121 if (typeof request[kRequestStreamId] !== 'number' || request[kRequestStreamId] > maxAcceptedStreamID) {
122 return i
123 }
124 }
125
126 return client[kPendingIdx]
127 }
128
129 function detachRequestFromStream (request) {
130 request[kRequestStreamId] = null
131 request[kRequestStream] = null
132 request[kRequestStreamCleanup] = null
133 }
134
135 function bindRequestToStream (request, stream, cleanup) {
136 const previousCleanup = request[kRequestStreamCleanup]
137 const previousStream = request[kRequestStream]
138 detachRequestFromStream(request)
139 previousCleanup?.(previousStream)
140 request[kRequestStreamId] = stream.id
141 request[kRequestStream] = stream
142 request[kRequestStreamCleanup] = cleanup
143 }
144
145 function clearRequestStream (request) {
146 const cleanup = request[kRequestStreamCleanup]
147 const stream = request[kRequestStream]
148 detachRequestFromStream(request)
149 cleanup?.(stream)
150 }
151
152 function requeueUnsentRequest (client, request) {
153 client[kQueue].splice(client[kPendingIdx] + 1, 0, request)
154 }
155
156 function completeRequest (client, request, resetPendingIdx = false) {
157 const index = client[kQueue].indexOf(request, client[kRunningIdx])
158
159 if (index === -1 || index >= client[kPendingIdx]) {
160 return
161 }
162
163 client[kQueue].splice(index, 1)
164 client[kPendingIdx]--
165
166 if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
167 client[kPendingIdx] = client[kRunningIdx]
168 }
169 }
170
171 function canRetryRequestAfterGoAway (request) {
172 const { body } = request
173
174 return body == null || util.isBuffer(body) || util.isBlobLike(body)
175 }
176
177 function closeRequestStream (request, code = NGHTTP2_REFUSED_STREAM) {
178 const stream = request[kRequestStream]
179
180 clearRequestStream(request)
181
182 if (stream != null && !stream.destroyed && !stream.closed) {
183 try {
184 stream.close(code)
185 } catch {}
186 }
187 }
188
189 function connectH2 (client, socket) {
190 client[kSocket] = socket
191
192 const http2InitialWindowSize = client[kHTTP2InitialWindowSize]
193 const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize]
194
195 const session = http2.connect(client[kUrl], {
196 createConnection: () => socket,
197 peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
198 settings: {
199 // TODO(metcoder95): add support for PUSH
200 enablePush: false,
201 ...(http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null)
202 }
203 })
204
205 client[kSocket] = socket
206 session[kOpenStreams] = 0
207 session[kClient] = client
208 session[kSocket] = socket
209 session[kHTTP2SessionState] = {
210 idleTimeout: null,
211 ping: {
212 interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref()
213 }
214 }
215 session[kReceivedGoAway] = false
216 // We set it to true by default in a best-effort; however once connected to an H2 server
217 // we will check if extended CONNECT protocol is supported or not
218 // and set this value accordingly.
219 session[kEnableConnectProtocol] = false
220 // States whether or not we have received the remote settings from the server
221 session[kRemoteSettings] = false
222
223 // Apply connection-level flow control once connected (if supported).
224 if (http2ConnectionWindowSize) {
225 util.addListener(session, 'connect', applyConnectionWindowSize.bind(session, http2ConnectionWindowSize))
226 }
227
228 util.addListener(session, 'error', onHttp2SessionError)
229 util.addListener(session, 'frameError', onHttp2FrameError)
230 util.addListener(session, 'end', onHttp2SessionEnd)
231 util.addListener(session, 'goaway', onHttp2SessionGoAway)
232 util.addListener(session, 'close', onHttp2SessionClose)
233 util.addListener(session, 'remoteSettings', onHttp2RemoteSettings)
234 // TODO (@metcoder95): implement SETTINGS support
235 // util.addListener(session, 'localSettings', onHttp2RemoteSettings)
236
237 session.unref()
238
239 client[kHTTP2Session] = session
240 socket[kHTTP2Session] = session
241
242 util.addListener(socket, 'error', onHttp2SocketError)
243 util.addListener(socket, 'end', onHttp2SocketEnd)
244 util.addListener(socket, 'close', onHttp2SocketClose)
245
246 socket[kClosed] = false
247 socket.on('close', onSocketClose)
248
249 return {
250 version: 'h2',
251 defaultPipelining: Infinity,
252 /**
253 * @param {import('../core/request.js')} request
254 * @returns {boolean}
255 */
256 write (request) {
257 return writeH2(client, request)
258 },
259 /**
260 * @returns {void}
261 */
262 resume () {
263 resumeH2(client)
264 },
265 /**
266 * @param {Error | null} err
267 * @param {() => void} callback
268 */
269 destroy (err, callback) {
270 if (socket[kClosed]) {
271 queueMicrotask(callback)
272 } else {
273 socket.destroy(err).on('close', callback)
274 }
275 },
276 /**
277 * @type {boolean}
278 */
279 get destroyed () {
280 return socket.destroyed
281 },
282 /**
283 * @param {import('../core/request.js')} request
284 * @returns {boolean}
285 */
286 busy (request) {
287 if (session[kRemoteSettings] === false && client[kRunning] > 0) {
288 return true
289 }
290
291 if (client[kRunning] >= client[kMaxConcurrentStreams]) {
292 return true
293 }
294
295 if (request != null) {
296 if (client[kRunning] > 0) {
297 // We are already processing requests
298
299 // Unlike HTTP/1.1 pipelining, HTTP/2 multiplexes requests on
300 // independent streams, so non-idempotent requests can be dispatched
301 // concurrently. Retry eligibility is handled by stream/session error
302 // handling instead of by serializing all non-idempotent requests.
303 // Don't dispatch an upgrade until all preceding requests have completed.
304 // Possibly, we do not have remote settings confirmed yet.
305 if ((request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false) return true
306 // Request with stream or iterator body can error while other requests
307 // are inflight and indirectly error those as well.
308 // Ensure this doesn't happen by waiting for inflight
309 // to complete before dispatching.
310
311 // Request with stream or iterator body cannot be retried.
312 // Ensure that no other requests are inflight and
313 // could cause failure.
314 if (util.bodyLength(request.body) !== 0 &&
315 (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) return true
316 } else {
317 return (request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false
318 }
319 }
320
321 return false
322 }
323 }
324 }
325
326 function resumeH2 (client) {
327 const socket = client[kSocket]
328 const session = client[kHTTP2Session]
329
330 if (socket?.destroyed === false) {
331 if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
332 socket.unref()
333 session.unref()
334 } else {
335 socket.ref()
336 session.ref()
337 }
338
339 if (client[kSize] === 0 && session[kOpenStreams] === 0) {
340 setHttp2IdleTimeout(session)
341 } else {
342 clearHttp2IdleTimeout(session)
343 }
344 }
345 }
346
347 function clearHttp2IdleTimeout (session) {
348 const state = session[kHTTP2SessionState]
349
350 if (state?.idleTimeout != null) {
351 clearTimeout(state.idleTimeout)
352 state.idleTimeout = null
353 }
354 }
355
356 function setHttp2IdleTimeout (session) {
357 const client = session[kClient]
358
359 if (client[kHTTP2Session] !== session || session.closed || session.destroyed) {
360 return
361 }
362
363 if (session[kOpenStreams] !== 0 || client[kSize] !== 0) {
364 clearHttp2IdleTimeout(session)
365 return
366 }
367
368 const state = session[kHTTP2SessionState]
369 if (state.idleTimeout == null) {
370 state.idleTimeout = setTimeout(onHttp2SessionIdleTimeout, client[kKeepAliveDefaultTimeout], session).unref()
371 }
372 }
373
374 function onHttp2SessionIdleTimeout (session) {
375 const client = session[kClient]
376 const socket = session[kSocket]
377 const state = session[kHTTP2SessionState]
378
379 state.idleTimeout = null
380
381 if (client[kHTTP2Session] !== session || session[kOpenStreams] !== 0 || client[kSize] !== 0 || session.closed || session.destroyed) {
382 return
383 }
384
385 const err = new InformationalError('socket idle timeout')
386 socket[kError] = err
387 util.destroy(socket, err)
388 }
389
390 function applyConnectionWindowSize (connectionWindowSize) {
391 try {
392 if (typeof this.setLocalWindowSize === 'function') {
393 this.setLocalWindowSize(connectionWindowSize)
394 }
395 } catch {
396 // Best-effort only.
397 }
398 }
399
400 function onHttp2RemoteSettings (settings) {
401 // Fallbacks are a safe bet, remote setting will always override
402 this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams]
403 /**
404 * From RFC-8441
405 * A sender MUST NOT send a SETTINGS_ENABLE_CONNECT_PROTOCOL parameter
406 * with the value of 0 after previously sending a value of 1.
407 */
408 // Note: Cannot be tested in Node, it does not supports disabling the extended CONNECT protocol once enabled
409 if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) {
410 const err = new InformationalError('HTTP/2: Server disabled extended CONNECT protocol against RFC-8441')
411 this[kSocket][kError] = err
412 this[kClient][kOnError](err)
413 return
414 }
415
416 this[kEnableConnectProtocol] = settings.enableConnectProtocol ?? this[kEnableConnectProtocol]
417 this[kRemoteSettings] = true
418 this[kClient][kResume]()
419 }
420
421 function onHttp2SendPing (session) {
422 const state = session[kHTTP2SessionState]
423 if ((session.closed || session.destroyed) && state.ping.interval != null) {
424 clearInterval(state.ping.interval)
425 state.ping.interval = null
426 return
427 }
428
429 // If no ping sent, do nothing
430 session.ping(onPing.bind(session))
431
432 function onPing (err, duration) {
433 const client = this[kClient]
434 const socket = this[kSocket]
435
436 if (err != null) {
437 const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`)
438 socket[kError] = error
439 client[kOnError](error)
440 } else {
441 client.emit('ping', duration)
442 }
443 }
444 }
445
446 function onHttp2SessionError (err) {
447 assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
448
449 this[kSocket][kError] = err
450 this[kClient][kOnError](err)
451 }
452
453 function onHttp2FrameError (type, code, id) {
454 if (id === 0) {
455 const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
456 this[kSocket][kError] = err
457 this[kClient][kOnError](err)
458 }
459 }
460
461 function onHttp2SessionEnd () {
462 const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket]))
463 this.destroy(err)
464 util.destroy(this[kSocket], err)
465 }
466
467 /**
468 * This is the root cause of #3011
469 * We need to handle GOAWAY frames properly, and trigger the session close
470 * along with the socket right away
471 *
472 * @this {import('http2').ClientHttp2Session}
473 * @param {number} errorCode
474 * @param {number} lastStreamID
475 */
476 function onHttp2SessionGoAway (errorCode, lastStreamID) {
477 if (this[kReceivedGoAway]) {
478 return
479 }
480
481 this[kReceivedGoAway] = true
482
483 const err = getGoAwayError(this, errorCode)
484 const client = this[kClient]
485 const previousPendingIdx = client[kPendingIdx]
486 const pendingIdx = getGoAwayPendingIdx(client, lastStreamID)
487 const retriableRequests = []
488
489 for (let i = pendingIdx; i < previousPendingIdx; i++) {
490 const request = client[kQueue][i]
491
492 if (request != null) {
493 closeRequestStream(request)
494
495 if (canRetryRequestAfterGoAway(request)) {
496 retriableRequests.push(request)
497 } else {
498 util.errorRequest(client, request, err)
499 }
500 }
501 }
502
503 if (pendingIdx !== previousPendingIdx) {
504 const remainingPendingRequests = client[kQueue].slice(previousPendingIdx)
505 client[kQueue].length = pendingIdx
506 client[kQueue].push(...retriableRequests, ...remainingPendingRequests)
507 }
508
509 if (client[kHTTP2Session] === this) {
510 client[kSocket] = null
511 client[kHTTPContext] = null
512 client[kHTTP2Session] = null
513 }
514
515 clearHttp2IdleTimeout(this)
516
517 if (!this.closed && !this.destroyed) {
518 this.close()
519 }
520
521 client[kPendingIdx] = pendingIdx
522
523 client.emit('disconnect', client[kUrl], [client], err)
524
525 client[kResume]()
526 }
527
528 function onHttp2SessionClose () {
529 const { [kClient]: client, [kHTTP2SessionState]: state, [kSocket]: socket } = this
530
531 const err = socket[kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))
532
533 if (client[kHTTP2Session] === this) {
534 client[kSocket] = null
535 client[kHTTPContext] = null
536 client[kHTTP2Session] = null
537 }
538
539 clearHttp2IdleTimeout(this)
540
541 if (state.ping.interval != null) {
542 clearInterval(state.ping.interval)
543 state.ping.interval = null
544 }
545
546 if (client.destroyed) {
547 assert(client[kPending] === 0)
548
549 // Fail entire queue.
550 const requests = client[kQueue].splice(client[kRunningIdx])
551 for (let i = 0; i < requests.length; i++) {
552 const request = requests[i]
553 if (request != null) {
554 util.errorRequest(client, request, err)
555 }
556 }
557 }
558 }
559
560 function onHttp2SocketClose () {
561 const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
562
563 const session = this[kHTTP2Session]
564 const client = session[kClient]
565
566 if (client[kSocket] !== this) {
567 // Ignore stale socket closes from a detached GOAWAY session and from any
568 // session that has already been replaced. If the session was detached
569 // without a GOAWAY and there is no replacement yet, we still need the
570 // close event to flush the client state.
571 if (session[kReceivedGoAway] || (client[kHTTP2Session] != null && client[kHTTP2Session] !== session)) {
572 return
573 }
574 }
575
576 client[kSocket] = null
577 client[kHTTPContext] = null
578 if (client[kHTTP2Session] === session) {
579 client[kHTTP2Session] = null
580 }
581
582 session.destroy(err)
583
584 client[kPendingIdx] = client[kRunningIdx]
585
586 assert(client[kRunning] === 0)
587
588 client.emit('disconnect', client[kUrl], [client], err)
589
590 client[kResume]()
591 }
592
593 function onHttp2SocketError (err) {
594 assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
595
596 this[kError] = err
597
598 this[kClient][kOnError](err)
599 }
600
601 function onHttp2SocketEnd () {
602 util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
603 }
604
605 function onSocketClose () {
606 this[kClosed] = true
607 }
608
609 function noop () {}
610
611 function closeStreamSession (stream) {
612 const session = stream[kHTTP2Session]
613
614 stream[kHTTP2Session] = null
615 session[kOpenStreams] -= 1
616 if (session[kOpenStreams] === 0) {
617 session.unref()
618 setHttp2IdleTimeout(session)
619 }
620 }
621
622 function onUpgradeStreamClose () {
623 this.off('error', noop)
624
625 const state = this[kRequestStreamState]
626 this[kRequestStreamState] = null
627
628 failUpgradeStream(state, new InformationalError('HTTP/2: stream closed before response headers'))
629 closeStreamSession(this)
630 }
631
632 function onRequestStreamClose () {
633 const state = this[kRequestStreamState]
634
635 if (state) {
636 // Release the stream first so request references are cleared,
637 // then complete the response with trailers if available.
638 releaseRequestStream(this)
639
640 if (state.pendingEnd && !state.request.aborted && !state.request.completed) {
641 state.request.onResponseEnd(state.trailers || {})
642 state.finalizeRequest()
643 }
644 }
645
646 this.off('data', onData)
647 this.off('error', noop)
648 closeStreamSession(this)
649 this[kRequestStreamState] = null
650 }
651
652 // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
653 function shouldSendContentLength (method) {
654 return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
655 }
656
657 function buildRequestHeaders (reqHeaders) {
658 const headers = {}
659
660 for (let n = 0; n < reqHeaders.length; n += 2) {
661 const key = reqHeaders[n + 0]
662 const val = reqHeaders[n + 1]
663 const current = headers[key]
664
665 if (key === 'cookie') {
666 if (current != null) {
667 headers[key] = Array.isArray(current) ? (current.push(val), current) : [current, val]
668 } else {
669 headers[key] = val
670 }
671
672 continue
673 }
674
675 if (typeof val === 'string') {
676 headers[key] = current ? `${current}, ${val}` : val
677 continue
678 }
679
680 for (let i = 0; i < val.length; i++) {
681 headers[key] = headers[key] ? `${headers[key]}, ${val[i]}` : val[i]
682 }
683 }
684
685 return headers
686 }
687
688 function removeUpgradeStreamListeners (stream) {
689 stream.off('response', onUpgradeResponse)
690 stream.off('error', onUpgradeStreamError)
691 stream.off('end', onUpgradeStreamEnd)
692 stream.off('timeout', onUpgradeStreamTimeout)
693 stream.off('error', noop)
694 }
695
696 function releaseUpgradeStream (stream) {
697 if (stream == null) {
698 return
699 }
700
701 const state = stream[kRequestStreamState]
702 if (state == null) {
703 return
704 }
705
706 const { request } = state
707
708 if (request[kRequestStream] === stream) {
709 detachRequestFromStream(request)
710 }
711
712 removeUpgradeStreamListeners(stream)
713
714 if (!stream.destroyed && !stream.closed) {
715 stream.once('error', noop)
716 }
717 }
718
719 function failUpgradeStream (state, err) {
720 if (state == null) {
721 return
722 }
723
724 const { request } = state
725 if (state.responseReceived || request.aborted || request.completed) {
726 return
727 }
728
729 releaseUpgradeStream(state.stream)
730 state.abort(err, true)
731 }
732
733 function onUpgradeStreamError () {
734 const state = this[kRequestStreamState]
735
736 if (typeof this.rstCode === 'number' && this.rstCode !== 0) {
737 failUpgradeStream(state, new InformationalError(`HTTP/2: "stream error" received - code ${this.rstCode}`))
738 } else {
739 failUpgradeStream(state, new InformationalError('HTTP/2: stream errored before response headers'))
740 }
741 }
742
743 function onUpgradeStreamEnd () {
744 failUpgradeStream(this[kRequestStreamState], new InformationalError('HTTP/2: stream half-closed (remote)'))
745 }
746
747 function onUpgradeStreamTimeout () {
748 const state = this[kRequestStreamState]
749 failUpgradeStream(state, new InformationalError(`HTTP/2: "stream timeout after ${state.headersTimeout}"`))
750 }
751
752 function onUpgradeResponse (headers, _flags) {
753 const stream = this
754 const state = stream[kRequestStreamState]
755 const { request } = state
756
757 state.responseReceived = true
758
759 const statusCode = headers[HTTP2_HEADER_STATUS]
760 delete headers[HTTP2_HEADER_STATUS]
761
762 request.onRequestUpgrade(statusCode, headers, stream)
763
764 if (request.aborted || request.completed) {
765 return
766 }
767
768 removeUpgradeStreamListeners(stream)
769 detachRequestFromStream(request)
770 state.finalizeRequest()
771 }
772
773 function setupUpgradeStream (stream, state) {
774 const { request, headersTimeout, session } = state
775
776 stream[kHTTP2Stream] = true
777 stream[kHTTP2Session] = session
778 stream[kRequestStreamState] = state
779 state.stream = stream
780
781 bindRequestToStream(request, stream, releaseUpgradeStream)
782 stream.once('response', onUpgradeResponse)
783 stream.on('error', onUpgradeStreamError)
784 stream.once('end', onUpgradeStreamEnd)
785 stream.on('timeout', onUpgradeStreamTimeout)
786 stream.once('close', onUpgradeStreamClose)
787
788 clearHttp2IdleTimeout(session)
789 ++session[kOpenStreams]
790 stream.setTimeout(headersTimeout)
791 }
792
793 function writeH2 (client, request) {
794 const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout]
795 const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout]
796 const session = client[kHTTP2Session]
797 const { method, path, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request
798 let { body } = request
799
800 if (upgrade != null && upgrade !== 'websocket') {
801 util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`))
802 return false
803 }
804
805 const headers = buildRequestHeaders(reqHeaders)
806
807 /** @type {import('node:http2').ClientHttp2Stream} */
808 let stream = null
809
810 headers[HTTP2_HEADER_AUTHORITY] = host || client[kHostAuthority]
811 headers[HTTP2_HEADER_METHOD] = method
812
813 let requestFinalized = false
814 const finalizeRequest = (resetPendingIdx = false) => {
815 if (requestFinalized) {
816 return
817 }
818
819 requestFinalized = true
820 completeRequest(client, request, resetPendingIdx)
821
822 client[kResume]()
823 }
824
825 const abort = (err, resetPendingIdx = false) => {
826 if (request.aborted || request.completed) {
827 return
828 }
829
830 err = err || new RequestAbortedError()
831
832 util.errorRequest(client, request, err)
833
834 if (stream != null) {
835 clearRequestStream(request)
836
837 // On Abort, we close the stream to send RST_STREAM frame
838 stream.close()
839
840 // We move the running index to the next request
841 client[kOnError](err)
842 finalizeRequest(resetPendingIdx)
843 }
844
845 // We do not destroy the socket as we can continue using the session
846 // the stream gets destroyed and the session remains to create new streams
847 util.destroy(body, err)
848 }
849
850 const requestStream = (headers, options) => {
851 try {
852 return session.request(headers, options)
853 } catch (err) {
854 if (err?.code === 'ERR_HTTP2_INVALID_SESSION') {
855 const wrappedErr = new SocketError(err.message, util.getSocketInfo(session[kSocket]))
856 wrappedErr.cause = err
857 session[kError] = wrappedErr
858 resetHttp2Session(session, wrappedErr)
859 requeueUnsentRequest(client, request)
860
861 return null
862 }
863
864 const wrappedErr = new InformationalError(err.message, { cause: err })
865 session[kError] = wrappedErr
866 session[kSocket][kError] = wrappedErr
867
868 session.destroy(wrappedErr)
869 util.destroy(session[kSocket], wrappedErr)
870 abort(wrappedErr)
871
872 return null
873 }
874 }
875
876 try {
877 // We are already connected, streams are pending.
878 // We can call on connect, and wait for abort
879 request.onRequestStart(abort, null)
880 } catch (err) {
881 util.errorRequest(client, request, err)
882 }
883
884 if (request.aborted) {
885 return false
886 }
887
888 if (upgrade || method === 'CONNECT') {
889 session.ref()
890
891 const upgradeState = {
892 abort,
893 finalizeRequest,
894 request,
895 headersTimeout,
896 bodyTimeout,
897 responseReceived: false,
898 session,
899 stream: null
900 }
901
902 if (upgrade === 'websocket') {
903 // We cannot upgrade to websocket if extended CONNECT protocol is not supported
904 if (session[kEnableConnectProtocol] === false) {
905 util.errorRequest(client, request, new InformationalError('HTTP/2: Extended CONNECT protocol not supported by server'))
906 session.unref()
907 return false
908 }
909
910 // We force the method to CONNECT
911 // as per RFC-8441
912 // https://datatracker.ietf.org/doc/html/rfc8441#section-4
913 headers[HTTP2_HEADER_METHOD] = 'CONNECT'
914 headers[HTTP2_HEADER_PROTOCOL] = 'websocket'
915 // :path and :scheme headers must be omitted when sending CONNECT but set if extended-CONNECT
916 headers[HTTP2_HEADER_PATH] = path
917
918 if (protocol === 'ws:' || protocol === 'wss:') {
919 headers[HTTP2_HEADER_SCHEME] = protocol === 'ws:' ? 'http' : 'https'
920 } else {
921 headers[HTTP2_HEADER_SCHEME] = protocol === 'http:' ? 'http' : 'https'
922 }
923
924 stream = requestStream(headers, { endStream: false, signal })
925 if (stream == null) {
926 session.unref()
927 return false
928 }
929 setupUpgradeStream(stream, upgradeState)
930 return true
931 }
932
933 // TODO: consolidate once we support CONNECT properly
934 // NOTE: We are already connected, streams are pending, first request
935 // will create a new stream. We trigger a request to create the stream and wait until
936 // `ready` event is triggered
937 // We disabled endStream to allow the user to write to the stream
938 stream = requestStream(headers, { endStream: false, signal })
939 if (stream == null) {
940 session.unref()
941 return false
942 }
943 setupUpgradeStream(stream, upgradeState)
944
945 return true
946 }
947
948 // https://tools.ietf.org/html/rfc7540#section-8.3
949 // :path and :scheme headers must be omitted when sending CONNECT
950 headers[HTTP2_HEADER_PATH] = path
951 headers[HTTP2_HEADER_SCHEME] = protocol === 'http:' ? 'http' : 'https'
952
953 // https://tools.ietf.org/html/rfc7231#section-4.3.1
954 // https://tools.ietf.org/html/rfc7231#section-4.3.2
955 // https://tools.ietf.org/html/rfc7231#section-4.3.5
956
957 // Sending a payload body on a request that does not
958 // expect it can cause undefined behavior on some
959 // servers and corrupt connection state. Do not
960 // re-use the connection for further requests.
961
962 const expectsPayload = (
963 method === 'PUT' ||
964 method === 'POST' ||
965 method === 'PATCH' ||
966 method === 'QUERY' ||
967 method === 'PROPFIND' ||
968 method === 'PROPPATCH'
969 )
970
971 if (body && typeof body.read === 'function') {
972 // Try to read EOF in order to get length.
973 body.read(0)
974 }
975
976 let contentLength = util.bodyLength(body)
977
978 if (util.isFormDataLike(body)) {
979 extractBody ??= require('../web/fetch/body.js').extractBody
980
981 const [bodyStream, contentType] = extractBody(body)
982 headers['content-type'] = contentType
983
984 body = bodyStream.stream
985 contentLength = bodyStream.length
986 }
987
988 if (contentLength == null) {
989 contentLength = request.contentLength
990 }
991
992 if (contentLength === 0 && !expectsPayload) {
993 // https://tools.ietf.org/html/rfc7230#section-3.3.2
994 // A user agent SHOULD NOT send a Content-Length header field when
995 // the request message does not contain a payload body and the method
996 // semantics do not anticipate such a body.
997 // And for methods that don't expect a payload, omit Content-Length.
998 contentLength = null
999 }
1000
1001 // https://github.com/nodejs/undici/issues/2046
1002 // A user agent may send a Content-Length header with 0 value, this should be allowed.
1003 if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
1004 if (client[kStrictContentLength]) {
1005 util.errorRequest(client, request, new RequestContentLengthMismatchError())
1006 return false
1007 }
1008
1009 process.emitWarning(new RequestContentLengthMismatchError())
1010 }
1011
1012 if (contentLength != null) {
1013 assert(body || contentLength === 0, 'no body must not have content length')
1014 headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
1015 }
1016
1017 session.ref()
1018
1019 if (channels.sendHeaders.hasSubscribers) {
1020 let header = ''
1021 for (const key in headers) {
1022 header += `${key}: ${headers[key]}\r\n`
1023 }
1024 channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] })
1025 }
1026
1027 // TODO(metcoder95): add support for sending trailers
1028 const shouldEndStream = body === null || contentLength === 0
1029 const state = {
1030 abort,
1031 body,
1032 client,
1033 contentLength,
1034 expectsPayload,
1035 finalizeRequest,
1036 request,
1037 headersTimeout,
1038 bodyTimeout,
1039 responseReceived: false,
1040 session,
1041 stream: null
1042 }
1043
1044 if (expectContinue) {
1045 headers[HTTP2_HEADER_EXPECT] = '100-continue'
1046 }
1047
1048 stream = requestStream(headers, { endStream: shouldEndStream, signal })
1049 if (stream == null) {
1050 return false
1051 }
1052 stream[kHTTP2Stream] = true
1053 stream[kRequestStreamState] = state
1054 state.stream = stream
1055
1056 // Increment counter as we have new streams open
1057 clearHttp2IdleTimeout(session)
1058 ++session[kOpenStreams]
1059 stream.setTimeout(headersTimeout)
1060
1061 stream[kHTTP2Session] = session
1062 stream.once('close', onRequestStreamClose)
1063
1064 bindRequestToStream(request, stream, releaseRequestStream)
1065 if (expectContinue) {
1066 stream.once('continue', writeBodyH2)
1067 }
1068 stream.once('response', onResponse)
1069 stream.once('end', onEnd)
1070 stream.once('error', onError)
1071 stream.once('frameError', onFrameError)
1072 stream.on('aborted', onAborted)
1073 stream.on('timeout', onTimeout)
1074 stream.once('trailers', onTrailers)
1075
1076 if (!expectContinue) {
1077 writeBodyH2.call(stream)
1078 }
1079
1080 return true
1081 }
1082
1083 function removeRequestStreamListeners (stream) {
1084 stream.off('error', noop)
1085 stream.off('continue', writeBodyH2)
1086 stream.off('response', onResponse)
1087 stream.off('end', onEnd)
1088 stream.off('error', onError)
1089 stream.off('frameError', onFrameError)
1090 stream.off('aborted', onAborted)
1091 stream.off('timeout', onTimeout)
1092 stream.off('trailers', onTrailers)
1093 stream.off('data', onData)
1094 }
1095
1096 function releaseRequestStream (stream) {
1097 if (stream == null) {
1098 return
1099 }
1100
1101 const state = stream[kRequestStreamState]
1102 if (state == null) {
1103 return
1104 }
1105
1106 const { request } = state
1107
1108 if (request[kRequestStream] === stream) {
1109 detachRequestFromStream(request)
1110 }
1111
1112 removeRequestStreamListeners(stream)
1113
1114 if (!stream.destroyed && !stream.closed) {
1115 stream.once('error', noop)
1116 }
1117 }
1118
1119 function onData (chunk) {
1120 const stream = this
1121 const { request } = stream[kRequestStreamState]
1122
1123 if (request.aborted || request.completed) {
1124 return
1125 }
1126
1127 if (request.onResponseData(chunk) === false) {
1128 stream.pause()
1129 }
1130 }
1131
1132 function onResponse (headers) {
1133 const stream = this
1134 const state = stream[kRequestStreamState]
1135 const { request } = state
1136
1137 stream.off('response', onResponse)
1138
1139 const statusCode = headers[HTTP2_HEADER_STATUS]
1140 delete headers[HTTP2_HEADER_STATUS]
1141 request.onResponseStarted()
1142 state.responseReceived = true
1143 stream.setTimeout(state.bodyTimeout)
1144
1145 // Due to the stream nature, it is possible we face a race condition
1146 // where the stream has been assigned, but the request has been aborted
1147 // the request remains in-flight and headers hasn't been received yet
1148 // for those scenarios, best effort is to destroy the stream immediately
1149 // as there's no value to keep it open.
1150 if (request.aborted) {
1151 releaseRequestStream(stream)
1152 return
1153 }
1154
1155 if (request.onResponseStart(Number(statusCode), headers, stream.resume.bind(stream), '') === false) {
1156 stream.pause()
1157 }
1158
1159 stream.on('data', onData)
1160 }
1161
1162 function onEnd () {
1163 const stream = this
1164 const state = stream[kRequestStreamState]
1165 const { request } = state
1166
1167 stream.off('end', onEnd)
1168
1169 // If we received a response, this is a normal completion.
1170 // Defer actual completion to onRequestStreamClose so that
1171 // onTrailers (which may fire after 'end' on Windows) can
1172 // store trailers first.
1173 if (state.responseReceived) {
1174 if (!request.aborted && !request.completed) {
1175 state.pendingEnd = true
1176 }
1177 } else {
1178 // Stream ended without receiving a response - this is an error
1179 // (e.g., server destroyed the stream before sending headers)
1180 state.abort(new InformationalError('HTTP/2: stream half-closed (remote)'), true)
1181 }
1182 }
1183
1184 function onError (err) {
1185 const stream = this
1186 const state = stream[kRequestStreamState]
1187
1188 stream.off('error', onError)
1189 state.abort(err)
1190 }
1191
1192 function onFrameError (type, code) {
1193 const stream = this
1194 const state = stream[kRequestStreamState]
1195
1196 stream.off('frameError', onFrameError)
1197 state.abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`))
1198 }
1199
1200 function onAborted () {
1201 this.off('data', onData)
1202 }
1203
1204 function onTimeout () {
1205 const stream = this
1206 const state = stream[kRequestStreamState]
1207
1208 // Remove self so timeout doesn't fire again after we handle it
1209 stream.off('timeout', onTimeout)
1210
1211 const err = state.responseReceived
1212 ? new BodyTimeoutError(`HTTP/2: "stream timeout after ${state.bodyTimeout}"`)
1213 : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${state.headersTimeout}"`)
1214 state.abort(err)
1215 }
1216
1217 function onTrailers (trailers) {
1218 const stream = this
1219 const state = stream[kRequestStreamState]
1220 const { request } = state
1221
1222 stream.off('trailers', onTrailers)
1223 stream.off('data', onData)
1224
1225 if (request.aborted || request.completed) {
1226 return
1227 }
1228
1229 // Store trailers for onRequestStreamClose to use when completing
1230 state.trailers = trailers
1231 }
1232
1233 function writeBodyH2 () {
1234 const stream = this
1235 const state = stream[kRequestStreamState]
1236 const { abort, body, client, contentLength, expectsPayload, request } = state
1237
1238 if (!body || contentLength === 0) {
1239 writeBuffer(
1240 abort,
1241 stream,
1242 null,
1243 client,
1244 request,
1245 client[kSocket],
1246 contentLength,
1247 expectsPayload
1248 )
1249 } else if (util.isBuffer(body)) {
1250 writeBuffer(
1251 abort,
1252 stream,
1253 body,
1254 client,
1255 request,
1256 client[kSocket],
1257 contentLength,
1258 expectsPayload
1259 )
1260 } else if (util.isBlobLike(body)) {
1261 if (typeof body.stream === 'function') {
1262 writeIterable(
1263 abort,
1264 stream,
1265 body.stream(),
1266 client,
1267 request,
1268 client[kSocket],
1269 contentLength,
1270 expectsPayload
1271 )
1272 } else {
1273 writeBlob(
1274 abort,
1275 stream,
1276 body,
1277 client,
1278 request,
1279 client[kSocket],
1280 contentLength,
1281 expectsPayload
1282 )
1283 }
1284 } else if (util.isStream(body)) {
1285 writeStream(
1286 abort,
1287 client[kSocket],
1288 expectsPayload,
1289 stream,
1290 body,
1291 client,
1292 request,
1293 contentLength
1294 )
1295 } else if (util.isIterable(body)) {
1296 writeIterable(
1297 abort,
1298 stream,
1299 body,
1300 client,
1301 request,
1302 client[kSocket],
1303 contentLength,
1304 expectsPayload
1305 )
1306 } else {
1307 assert(false)
1308 }
1309 }
1310
1311 function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
1312 try {
1313 if (body != null && util.isBuffer(body)) {
1314 assert(contentLength === body.byteLength, 'buffer body must have content length')
1315 h2stream.cork()
1316 h2stream.write(body)
1317 h2stream.uncork()
1318 h2stream.end()
1319
1320 request.onBodySent(body)
1321 }
1322
1323 if (!expectsPayload) {
1324 socket[kReset] = true
1325 }
1326
1327 request.onRequestSent()
1328 client[kResume]()
1329 } catch (error) {
1330 abort(error)
1331 }
1332 }
1333
1334 function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
1335 assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
1336
1337 // For HTTP/2, is enough to pipe the stream
1338 const pipe = pipeline(
1339 body,
1340 h2stream,
1341 (err) => {
1342 if (err) {
1343 util.destroy(pipe, err)
1344 abort(err)
1345 } else {
1346 util.removeAllListeners(pipe)
1347 request.onRequestSent()
1348
1349 if (!expectsPayload) {
1350 socket[kReset] = true
1351 }
1352
1353 client[kResume]()
1354 }
1355 }
1356 )
1357
1358 util.addListener(pipe, 'data', onPipeData)
1359
1360 function onPipeData (chunk) {
1361 request.onBodySent(chunk)
1362 }
1363 }
1364
1365 async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
1366 try {
1367 if (contentLength != null && contentLength !== body.size) {
1368 throw new RequestContentLengthMismatchError()
1369 }
1370
1371 const buffer = Buffer.from(await body.arrayBuffer())
1372
1373 h2stream.cork()
1374 h2stream.write(buffer)
1375 h2stream.uncork()
1376 h2stream.end()
1377
1378 request.onBodySent(buffer)
1379 request.onRequestSent()
1380
1381 if (!expectsPayload) {
1382 socket[kReset] = true
1383 }
1384
1385 client[kResume]()
1386 } catch (err) {
1387 abort(err)
1388 }
1389 }
1390
1391 async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
1392 assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
1393
1394 let callback = null
1395 function onDrain () {
1396 if (callback) {
1397 const cb = callback
1398 callback = null
1399 cb()
1400 }
1401 }
1402
1403 const waitForDrain = () => new Promise((resolve, reject) => {
1404 assert(callback === null)
1405
1406 if (socket[kError]) {
1407 reject(socket[kError])
1408 } else {
1409 callback = resolve
1410 }
1411 })
1412
1413 h2stream
1414 .on('close', onDrain)
1415 .on('drain', onDrain)
1416
1417 try {
1418 // It's up to the user to somehow abort the async iterable.
1419 for await (const chunk of body) {
1420 if (socket[kError]) {
1421 throw socket[kError]
1422 }
1423
1424 const res = h2stream.write(chunk)
1425 request.onBodySent(chunk)
1426 if (!res) {
1427 await waitForDrain()
1428 }
1429 }
1430
1431 h2stream.end()
1432
1433 request.onRequestSent()
1434
1435 if (!expectsPayload) {
1436 socket[kReset] = true
1437 }
1438
1439 client[kResume]()
1440 } catch (err) {
1441 abort(err)
1442 } finally {
1443 h2stream
1444 .off('close', onDrain)
1445 .off('drain', onDrain)
1446 }
1447 }
1448
1449 module.exports = connectH2