Debian Codegraph @

lib/dispatcher/client-h1.js

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 'use strict'
2
3 /* global WebAssembly */
4
5 const assert = require('node:assert')
6 const util = require('../core/util.js')
7 const { channels } = require('../core/diagnostics.js')
8 const timers = require('../util/timers.js')
9 const {
10 RequestContentLengthMismatchError,
11 ResponseContentLengthMismatchError,
12 RequestAbortedError,
13 HeadersTimeoutError,
14 HeadersOverflowError,
15 SocketError,
16 InformationalError,
17 BodyTimeoutError,
18 HTTPParserError,
19 ResponseExceededMaxSizeError
20 } = require('../core/errors.js')
21 const {
22 kUrl,
23 kReset,
24 kClient,
25 kParser,
26 kBlocking,
27 kRunning,
28 kPending,
29 kSize,
30 kWriting,
31 kQueue,
32 kNoRef,
33 kKeepAliveDefaultTimeout,
34 kHostHeader,
35 kPendingIdx,
36 kRunningIdx,
37 kError,
38 kPipelining,
39 kSocket,
40 kKeepAliveTimeoutValue,
41 kMaxHeadersSize,
42 kKeepAliveMaxTimeout,
43 kKeepAliveTimeoutThreshold,
44 kHeadersTimeout,
45 kBodyTimeout,
46 kStrictContentLength,
47 kMaxRequests,
48 kCounter,
49 kMaxResponseSize,
50 kOnError,
51 kResume,
52 kHTTPContext,
53 kClosed
54 } = require('../core/symbols.js')
55
56 const constants = require('../llhttp/constants.js')
57 const EMPTY_BUF = Buffer.alloc(0)
58 const FastBuffer = Buffer[Symbol.species]
59 const removeAllListeners = util.removeAllListeners
60 const kIdleSocketValidation = Symbol('kIdleSocketValidation')
61 const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
62 const kSocketUsed = Symbol('kSocketUsed')
63
64 let extractBody
65
66 function lazyllhttp () {
67 const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined
68
69 let mod
70
71 // We disable wasm SIMD on ppc64 as it seems to be broken on Power 9 architectures.
72 let useWasmSIMD = process.arch !== 'ppc64'
73 // The Env Variable UNDICI_NO_WASM_SIMD allows explicitly overriding the default behavior
74 if (process.env.UNDICI_NO_WASM_SIMD === '1') {
75 useWasmSIMD = false
76 } else if (process.env.UNDICI_NO_WASM_SIMD === '0') {
77 useWasmSIMD = true
78 }
79
80 if (useWasmSIMD) {
81 try {
82 mod = new WebAssembly.Module(require('../llhttp/llhttp_simd-wasm.js'))
83 } catch {
84 }
85 }
86
87 if (!mod) {
88 // We could check if the error was caused by the simd option not
89 // being enabled, but the occurring of this other error
90 // * https://github.com/emscripten-core/emscripten/issues/11495
91 // got me to remove that check to avoid breaking Node 12.
92 mod = new WebAssembly.Module(llhttpWasmData || require('../llhttp/llhttp-wasm.js'))
93 }
94
95 return new WebAssembly.Instance(mod, {
96 env: {
97 /**
98 * @param {number} p
99 * @param {number} at
100 * @param {number} len
101 * @returns {number}
102 */
103 wasm_on_url: (p, at, len) => {
104 return 0
105 },
106 /**
107 * @param {number} p
108 * @param {number} at
109 * @param {number} len
110 * @returns {number}
111 */
112 wasm_on_status: (p, at, len) => {
113 assert(currentParser.ptr === p)
114 const start = at - currentBufferPtr + currentBufferRef.byteOffset
115 return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len))
116 },
117 /**
118 * @param {number} p
119 * @returns {number}
120 */
121 wasm_on_message_begin: (p) => {
122 assert(currentParser.ptr === p)
123 return currentParser.onMessageBegin()
124 },
125 /**
126 * @param {number} p
127 * @param {number} at
128 * @param {number} len
129 * @returns {number}
130 */
131 wasm_on_header_field: (p, at, len) => {
132 assert(currentParser.ptr === p)
133 const start = at - currentBufferPtr + currentBufferRef.byteOffset
134 return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len))
135 },
136 /**
137 * @param {number} p
138 * @param {number} at
139 * @param {number} len
140 * @returns {number}
141 */
142 wasm_on_header_value: (p, at, len) => {
143 assert(currentParser.ptr === p)
144 const start = at - currentBufferPtr + currentBufferRef.byteOffset
145 return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len))
146 },
147 /**
148 * @param {number} p
149 * @param {number} statusCode
150 * @param {0|1} upgrade
151 * @param {0|1} shouldKeepAlive
152 * @returns {number}
153 */
154 wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
155 assert(currentParser.ptr === p)
156 return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1)
157 },
158 /**
159 * @param {number} p
160 * @param {number} at
161 * @param {number} len
162 * @returns {number}
163 */
164 wasm_on_body: (p, at, len) => {
165 assert(currentParser.ptr === p)
166 const start = at - currentBufferPtr + currentBufferRef.byteOffset
167 return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len))
168 },
169 /**
170 * @param {number} p
171 * @returns {number}
172 */
173 wasm_on_message_complete: (p) => {
174 assert(currentParser.ptr === p)
175 return currentParser.onMessageComplete()
176 }
177
178 }
179 })
180 }
181
182 let llhttpInstance = null
183
184 /**
185 * @type {Parser|null}
186 */
187 let currentParser = null
188 let currentBufferRef = null
189 /**
190 * @type {number}
191 */
192 let currentBufferSize = 0
193 let currentBufferPtr = null
194 let currentBuffer = null
195
196 const USE_NATIVE_TIMER = 0
197 const USE_FAST_TIMER = 1
198
199 // Use fast timers for headers and body to take eventual event loop
200 // latency into account.
201 const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER
202 const TIMEOUT_BODY = 4 | USE_FAST_TIMER
203
204 // Use native timers to ignore event loop latency for keep-alive
205 // handling.
206 const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER
207
208 class Parser {
209 /**
210 * @param {import('./client.js')} client
211 * @param {import('net').Socket} socket
212 * @param {*} llhttp
213 */
214 constructor (client, socket, { exports }) {
215 this.llhttp = exports
216 this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
217 this.client = client
218 /**
219 * @type {import('net').Socket}
220 */
221 this.socket = socket
222 this.timeout = null
223 this.timeoutWeakRef = new WeakRef(this)
224 this.timeoutValue = null
225 this.timeoutType = null
226 this.statusCode = 0
227 this.statusText = ''
228 this.upgrade = false
229 this.headers = []
230 this.headersSize = 0
231 this.headersMaxSize = client[kMaxHeadersSize]
232 this.shouldKeepAlive = false
233 this.paused = false
234 this.resume = this.resume.bind(this)
235
236 this.bytesRead = 0
237
238 this.keepAlive = ''
239 this.contentLength = -1
240 this.connectionKeepAlive = false
241 this.maxResponseSize = client[kMaxResponseSize]
242 }
243
244 setTimeout (delay, type) {
245 // If the existing timer and the new timer are of different timer type
246 // (fast or native) or have different delay, we need to clear the existing
247 // timer and set a new one.
248 if (
249 delay !== this.timeoutValue ||
250 (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)
251 ) {
252 // If a timeout is already set, clear it with clearTimeout of the fast
253 // timer implementation, as it can clear fast and native timers.
254 if (this.timeout) {
255 timers.clearTimeout(this.timeout)
256 this.timeout = null
257 }
258
259 if (delay) {
260 if (type & USE_FAST_TIMER) {
261 this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef)
262 } else {
263 this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef)
264 this.timeout?.unref()
265 }
266 }
267
268 this.timeoutValue = delay
269 } else if (this.timeout) {
270 if (this.timeout.refresh) {
271 this.timeout.refresh()
272 }
273 }
274
275 this.timeoutType = type
276 }
277
278 resume () {
279 if (this.socket.destroyed || !this.paused) {
280 return
281 }
282
283 assert(this.ptr != null)
284 assert(currentParser === null)
285
286 this.llhttp.llhttp_resume(this.ptr)
287
288 assert(this.timeoutType === TIMEOUT_BODY)
289 if (this.timeout) {
290 if (this.timeout.refresh) {
291 this.timeout.refresh()
292 }
293 }
294
295 this.paused = false
296 this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
297 this.readMore()
298 }
299
300 readMore () {
301 while (!this.paused && this.ptr) {
302 const chunk = this.socket.read()
303 if (chunk === null) {
304 break
305 }
306 this.execute(chunk)
307 }
308 }
309
310 /**
311 * @param {Buffer} chunk
312 */
313 execute (chunk) {
314 assert(currentParser === null)
315 assert(this.ptr != null)
316 assert(!this.paused)
317
318 const { socket, llhttp } = this
319
320 // Allocate a new buffer if the current buffer is too small.
321 if (chunk.length > currentBufferSize) {
322 if (currentBufferPtr) {
323 llhttp.free(currentBufferPtr)
324 }
325 // Allocate a buffer that is a multiple of 4096 bytes.
326 currentBufferSize = Math.ceil(chunk.length / 4096) * 4096
327 currentBufferPtr = llhttp.malloc(currentBufferSize)
328 }
329
330 if (
331 currentBuffer === null ||
332 currentBuffer.buffer !== llhttp.memory.buffer ||
333 currentBuffer.byteOffset !== currentBufferPtr ||
334 currentBuffer.byteLength !== currentBufferSize
335 ) {
336 currentBuffer = new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize)
337 }
338
339 currentBuffer.set(chunk)
340
341 // Call `execute` on the wasm parser.
342 // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
343 // and finally the length of bytes to parse.
344 // The return value is an error code or `constants.ERROR.OK`.
345 try {
346 let ret
347
348 try {
349 currentBufferRef = chunk
350 currentParser = this
351 ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length)
352 } finally {
353 currentParser = null
354 currentBufferRef = null
355 }
356
357 if (ret !== constants.ERROR.OK) {
358 const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr)
359
360 if (ret === constants.ERROR.PAUSED_UPGRADE) {
361 this.onUpgrade(data)
362 } else if (ret === constants.ERROR.PAUSED) {
363 this.paused = true
364 socket.unshift(data)
365 } else {
366 throw this.createError(ret, data)
367 }
368 }
369 } catch (err) {
370 util.destroy(socket, err)
371 }
372 }
373
374 finish () {
375 assert(currentParser === null)
376 assert(this.ptr != null)
377
378 const { llhttp } = this
379
380 let ret
381
382 try {
383 currentParser = this
384 ret = llhttp.llhttp_finish(this.ptr)
385 } finally {
386 currentParser = null
387 }
388
389 if (ret === constants.ERROR.OK) {
390 return null
391 }
392
393 if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) {
394 this.paused = true
395 return null
396 }
397
398 return this.createError(ret, EMPTY_BUF)
399 }
400
401 createError (ret, data) {
402 const { llhttp, contentLength, bytesRead } = this
403
404 if (contentLength !== -1 && bytesRead !== contentLength) {
405 return new ResponseContentLengthMismatchError()
406 }
407
408 const ptr = llhttp.llhttp_get_error_reason(this.ptr)
409 let message = ''
410 if (ptr) {
411 const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
412 message =
413 'Response does not match the HTTP/1.1 protocol (' +
414 Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
415 ')'
416 }
417
418 return new HTTPParserError(message, constants.ERROR[ret], data)
419 }
420
421 destroy () {
422 assert(currentParser === null)
423 assert(this.ptr != null)
424
425 this.llhttp.llhttp_free(this.ptr)
426 this.ptr = null
427
428 this.timeout && timers.clearTimeout(this.timeout)
429 this.timeout = null
430 this.timeoutValue = null
431 this.timeoutType = null
432
433 this.paused = false
434 }
435
436 /**
437 * @param {Buffer} buf
438 * @returns {0}
439 */
440 onStatus (buf) {
441 this.statusText = buf.toString()
442 return 0
443 }
444
445 /**
446 * @returns {0|-1}
447 */
448 onMessageBegin () {
449 const { socket, client } = this
450
451 if (socket.destroyed) {
452 return -1
453 }
454
455 if (client[kRunning] === 0) {
456 util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
457 return -1
458 }
459
460 const request = client[kQueue][client[kRunningIdx]]
461 if (!request) {
462 return -1
463 }
464 request.onResponseStarted()
465
466 return 0
467 }
468
469 /**
470 * @param {Buffer} buf
471 * @returns {number}
472 */
473 onHeaderField (buf) {
474 const len = this.headers.length
475
476 if ((len & 1) === 0) {
477 this.headers.push(buf)
478 } else {
479 this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
480 }
481
482 this.trackHeader(buf.length)
483
484 return 0
485 }
486
487 /**
488 * @param {Buffer} buf
489 * @returns {number}
490 */
491 onHeaderValue (buf) {
492 let len = this.headers.length
493
494 if ((len & 1) === 1) {
495 this.headers.push(buf)
496 len += 1
497 } else {
498 this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
499 }
500
501 const key = this.headers[len - 2]
502 if (key.length === 10) {
503 const headerName = util.bufferToLowerCasedHeaderName(key)
504 if (headerName === 'keep-alive') {
505 this.keepAlive += buf.toString()
506 } else if (headerName === 'connection') {
507 this.connectionKeepAlive =
508 this.headers[len - 1].length === 10 &&
509 util.bufferToLowerCasedHeaderName(this.headers[len - 1]) === 'keep-alive'
510 }
511 } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
512 if (this.contentLength === -1) {
513 this.contentLength = 0
514 }
515 for (let i = 0; i < buf.length; i++) {
516 this.contentLength = (this.contentLength * 10) + (buf[i] - 0x30)
517 }
518 }
519
520 this.trackHeader(buf.length)
521
522 return 0
523 }
524
525 /**
526 * @param {number} len
527 */
528 trackHeader (len) {
529 this.headersSize += len
530 if (this.headersSize >= this.headersMaxSize) {
531 util.destroy(this.socket, new HeadersOverflowError())
532 }
533 }
534
535 /**
536 * @param {Buffer} head
537 */
538 onUpgrade (head) {
539 const { upgrade, client, socket, headers, statusCode } = this
540
541 assert(upgrade)
542 assert(client[kSocket] === socket)
543 assert(!socket.destroyed)
544 assert(!this.paused)
545 assert((headers.length & 1) === 0)
546
547 const request = client[kQueue][client[kRunningIdx]]
548 assert(request)
549 assert(request.upgrade || request.method === 'CONNECT')
550
551 this.statusCode = 0
552 this.statusText = ''
553 this.shouldKeepAlive = false
554
555 this.headers = []
556 this.headersSize = 0
557
558 socket.unshift(head)
559
560 socket[kParser].destroy()
561 socket[kParser] = null
562
563 socket[kClient] = null
564 socket[kError] = null
565
566 removeAllListeners(socket)
567
568 client[kSocket] = null
569 client[kHTTPContext] = null // TODO (fix): This is hacky...
570 client[kQueue][client[kRunningIdx]++] = null
571 client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
572
573 try {
574 request.onRequestUpgrade(statusCode, headers, socket)
575 } catch (err) {
576 util.destroy(socket, err)
577 }
578
579 client[kResume]()
580 }
581
582 /**
583 * @param {number} statusCode
584 * @param {boolean} upgrade
585 * @param {boolean} shouldKeepAlive
586 * @returns {number}
587 */
588 onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
589 const { client, socket, headers, statusText } = this
590
591 if (socket.destroyed) {
592 return -1
593 }
594
595 if (client[kRunning] === 0) {
596 util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
597 return -1
598 }
599
600 const request = client[kQueue][client[kRunningIdx]]
601
602 if (!request) {
603 return -1
604 }
605
606 assert(!this.upgrade)
607 assert(this.statusCode < 200)
608
609 if (statusCode === 100) {
610 util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
611 return -1
612 }
613
614 /* this can only happen if server is misbehaving */
615 if (upgrade && !request.upgrade) {
616 util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
617 return -1
618 }
619
620 assert(this.timeoutType === TIMEOUT_HEADERS)
621
622 this.statusCode = statusCode
623 this.shouldKeepAlive = (
624 shouldKeepAlive ||
625 // Override llhttp value which does not allow keepAlive for HEAD.
626 (request.method === 'HEAD' && !socket[kReset] && this.connectionKeepAlive)
627 )
628
629 if (this.statusCode >= 200) {
630 const bodyTimeout = request.bodyTimeout != null
631 ? request.bodyTimeout
632 : client[kBodyTimeout]
633 this.setTimeout(bodyTimeout, TIMEOUT_BODY)
634 } else if (this.timeout) {
635 if (this.timeout.refresh) {
636 this.timeout.refresh()
637 }
638 }
639
640 if (request.method === 'CONNECT') {
641 assert(client[kRunning] === 1)
642 this.upgrade = true
643 return 2
644 }
645
646 if (upgrade) {
647 assert(client[kRunning] === 1)
648 this.upgrade = true
649 return 2
650 }
651
652 assert((this.headers.length & 1) === 0)
653 this.headers = []
654 this.headersSize = 0
655
656 if (this.shouldKeepAlive && client[kPipelining]) {
657 const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
658
659 if (keepAliveTimeout != null) {
660 const timeout = Math.min(
661 keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
662 client[kKeepAliveMaxTimeout]
663 )
664 if (timeout <= 0) {
665 socket[kReset] = true
666 } else {
667 client[kKeepAliveTimeoutValue] = timeout
668 }
669 } else {
670 client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
671 }
672 } else {
673 // Stop more requests from being dispatched.
674 socket[kReset] = true
675 }
676
677 const pause = request.onResponseStart(statusCode, headers, this.resume, statusText) === false
678
679 if (request.aborted) {
680 return -1
681 }
682
683 if (request.method === 'HEAD') {
684 return 1
685 }
686
687 if (statusCode < 200) {
688 return 1
689 }
690
691 if (socket[kBlocking]) {
692 socket[kBlocking] = false
693 client[kResume]()
694 }
695
696 return pause ? constants.ERROR.PAUSED : 0
697 }
698
699 /**
700 * @param {Buffer} buf
701 * @returns {number}
702 */
703 onBody (buf) {
704 const { client, socket, statusCode, maxResponseSize } = this
705
706 if (socket.destroyed) {
707 return -1
708 }
709
710 const request = client[kQueue][client[kRunningIdx]]
711 assert(request)
712
713 assert(this.timeoutType === TIMEOUT_BODY)
714 if (this.timeout) {
715 if (this.timeout.refresh) {
716 this.timeout.refresh()
717 }
718 }
719
720 assert(statusCode >= 200)
721
722 if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
723 util.destroy(socket, new ResponseExceededMaxSizeError())
724 return -1
725 }
726
727 this.bytesRead += buf.length
728
729 if (request.onResponseData(buf) === false) {
730 return constants.ERROR.PAUSED
731 }
732
733 return 0
734 }
735
736 /**
737 * @returns {number}
738 */
739 onMessageComplete () {
740 const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
741
742 if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
743 return -1
744 }
745
746 if (upgrade) {
747 return 0
748 }
749
750 assert(statusCode >= 100)
751 assert((this.headers.length & 1) === 0)
752
753 const request = client[kQueue][client[kRunningIdx]]
754 assert(request)
755
756 this.statusCode = 0
757 this.statusText = ''
758 this.bytesRead = 0
759 this.contentLength = -1
760 this.keepAlive = ''
761 this.connectionKeepAlive = false
762
763 this.headers = []
764 this.headersSize = 0
765
766 if (statusCode < 200) {
767 return 0
768 }
769
770 if (request.method !== 'HEAD' && contentLength !== -1 && bytesRead !== contentLength) {
771 util.destroy(socket, new ResponseContentLengthMismatchError())
772 return -1
773 }
774
775 request.onResponseEnd(headers)
776
777 client[kQueue][client[kRunningIdx]++] = null
778 socket[kSocketUsed] = client[kPending] === 0
779
780 if (socket[kWriting]) {
781 assert(client[kRunning] === 0)
782 // Response completed before request.
783 util.destroy(socket, new InformationalError('reset'))
784 return constants.ERROR.PAUSED
785 } else if (!shouldKeepAlive) {
786 util.destroy(socket, new InformationalError('reset'))
787 return constants.ERROR.PAUSED
788 } else if (socket[kReset] && client[kRunning] === 0) {
789 // Destroy socket once all requests have completed.
790 // The request at the tail of the pipeline is the one
791 // that requested reset and no further requests should
792 // have been queued since then.
793 util.destroy(socket, new InformationalError('reset'))
794 return constants.ERROR.PAUSED
795 } else if (client[kPipelining] == null || client[kPipelining] === 1) {
796 // We must wait a full event loop cycle to reuse this socket to make sure
797 // that non-spec compliant servers are not closing the connection even if they
798 // said they won't.
799 setImmediate(client[kResume])
800 } else {
801 client[kResume]()
802 }
803
804 return 0
805 }
806 }
807
808 function onParserTimeout (parserWeakRef) {
809 const parser = parserWeakRef.deref()
810 if (!parser) {
811 return
812 }
813
814 const { socket, timeoutType, client, paused } = parser
815
816 if (timeoutType === TIMEOUT_HEADERS) {
817 if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
818 assert(!paused, 'cannot be paused while waiting for headers')
819 util.destroy(socket, new HeadersTimeoutError())
820 }
821 } else if (timeoutType === TIMEOUT_BODY) {
822 if (!paused) {
823 util.destroy(socket, new BodyTimeoutError())
824 }
825 } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
826 assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
827 util.destroy(socket, new InformationalError('socket idle timeout'))
828 }
829 }
830
831 /**
832 * @param {import ('./client.js')} client
833 * @param {import('net').Socket} socket
834 * @returns
835 */
836 function connectH1 (client, socket) {
837 client[kSocket] = socket
838
839 if (!llhttpInstance) {
840 llhttpInstance = lazyllhttp()
841 }
842
843 if (socket.errored) {
844 throw socket.errored
845 }
846
847 if (socket.destroyed) {
848 throw new SocketError('destroyed')
849 }
850
851 socket[kNoRef] = false
852 socket[kWriting] = false
853 socket[kReset] = false
854 socket[kBlocking] = false
855 socket[kIdleSocketValidation] = 0
856 socket[kIdleSocketValidationTimeout] = null
857 socket[kSocketUsed] = false
858 socket[kParser] = new Parser(client, socket, llhttpInstance)
859
860 util.addListener(socket, 'error', onHttpSocketError)
861 util.addListener(socket, 'readable', onHttpSocketReadable)
862 util.addListener(socket, 'end', onHttpSocketEnd)
863 util.addListener(socket, 'close', onHttpSocketClose)
864
865 socket[kClosed] = false
866 socket.on('close', onSocketClose)
867
868 return {
869 version: 'h1',
870 defaultPipelining: 1,
871 write (request) {
872 return writeH1(client, request)
873 },
874 resume () {
875 resumeH1(client)
876 },
877 /**
878 * @param {Error|undefined} err
879 * @param {() => void} callback
880 */
881 destroy (err, callback) {
882 if (socket[kClosed]) {
883 queueMicrotask(callback)
884 } else {
885 socket.on('close', callback)
886 socket.destroy(err)
887 }
888 },
889 /**
890 * @returns {boolean}
891 */
892 get destroyed () {
893 return socket.destroyed
894 },
895 /**
896 * @param {import('../core/request.js')} request
897 * @returns {boolean}
898 */
899 busy (request) {
900 if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
901 return true
902 }
903
904 if (request) {
905 if (client[kRunning] > 0 && !request.idempotent) {
906 // Non-idempotent request cannot be retried.
907 // Ensure that no other requests are inflight and
908 // could cause failure.
909 return true
910 }
911
912 if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
913 // Don't dispatch an upgrade until all preceding requests have completed.
914 // A misbehaving server might upgrade the connection before all pipelined
915 // request has completed.
916 return true
917 }
918
919 if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
920 (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
921 // Request with stream or iterator body can error while other requests
922 // are inflight and indirectly error those as well.
923 // Ensure this doesn't happen by waiting for inflight
924 // to complete before dispatching.
925
926 // Request with stream or iterator body cannot be retried.
927 // Ensure that no other requests are inflight and
928 // could cause failure.
929 return true
930 }
931 }
932
933 return false
934 }
935 }
936 }
937
938 function onHttpSocketError (err) {
939 assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
940
941 const parser = this[kParser]
942
943 // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
944 // to the user.
945 if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
946 const parserErr = parser.finish()
947 if (parserErr) {
948 this[kError] = parserErr
949 this[kClient][kOnError](parserErr)
950 }
951 return
952 }
953
954 this[kError] = err
955
956 this[kClient][kOnError](err)
957 }
958
959 function onHttpSocketReadable () {
960 this[kParser]?.readMore()
961 }
962
963 function onHttpSocketEnd () {
964 const parser = this[kParser]
965
966 if (parser.statusCode && !parser.shouldKeepAlive) {
967 const parserErr = parser.finish()
968 if (parserErr) {
969 util.destroy(this, parserErr)
970 }
971 return
972 }
973
974 util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
975 }
976
977 function onHttpSocketClose () {
978 const parser = this[kParser]
979
980 clearIdleSocketValidation(this)
981
982 if (parser) {
983 if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
984 this[kError] = parser.finish() || this[kError]
985 }
986
987 this[kParser].destroy()
988 this[kParser] = null
989 }
990
991 const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
992
993 const client = this[kClient]
994
995 client[kSocket] = null
996 client[kHTTPContext] = null // TODO (fix): This is hacky...
997
998 if (client.destroyed) {
999 assert(client[kPending] === 0)
1000
1001 // Fail entire queue.
1002 const requests = client[kQueue].splice(client[kRunningIdx])
1003 for (let i = 0; i < requests.length; i++) {
1004 const request = requests[i]
1005 util.errorRequest(client, request, err)
1006 }
1007 } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
1008 // Fail head of pipeline.
1009 const request = client[kQueue][client[kRunningIdx]]
1010 client[kQueue][client[kRunningIdx]++] = null
1011
1012 util.errorRequest(client, request, err)
1013 }
1014
1015 client[kPendingIdx] = client[kRunningIdx]
1016
1017 assert(client[kRunning] === 0)
1018
1019 client.emit('disconnect', client[kUrl], [client], err)
1020
1021 client[kResume]()
1022 }
1023
1024 function onSocketClose () {
1025 this[kClosed] = true
1026 }
1027
1028 function clearIdleSocketValidation (socket) {
1029 if (socket[kIdleSocketValidationTimeout]) {
1030 clearTimeout(socket[kIdleSocketValidationTimeout])
1031 socket[kIdleSocketValidationTimeout] = null
1032 }
1033
1034 socket[kIdleSocketValidation] = 0
1035 }
1036
1037 function scheduleIdleSocketValidation (client, socket) {
1038 socket[kIdleSocketValidation] = 1
1039 socket[kIdleSocketValidationTimeout] = setTimeout(() => {
1040 socket[kIdleSocketValidationTimeout] = null
1041 socket[kIdleSocketValidation] = 2
1042
1043 if (client[kSocket] === socket && !socket.destroyed) {
1044 client[kResume]()
1045 }
1046 }, 0)
1047 socket[kIdleSocketValidationTimeout].unref?.()
1048 }
1049
1050 /**
1051 * @param {import('./client.js')} client
1052 */
1053 function resumeH1 (client) {
1054 const socket = client[kSocket]
1055
1056 if (socket && !socket.destroyed) {
1057 if (client[kSize] === 0) {
1058 if (!socket[kNoRef] && socket.unref) {
1059 socket.unref()
1060 socket[kNoRef] = true
1061 }
1062 } else if (socket[kNoRef] && socket.ref) {
1063 socket.ref()
1064 socket[kNoRef] = false
1065 }
1066
1067 if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
1068 if (socket[kIdleSocketValidation] === 0) {
1069 scheduleIdleSocketValidation(client, socket)
1070 socket[kParser].readMore()
1071 if (socket.destroyed) {
1072 return
1073 }
1074 return
1075 }
1076
1077 if (socket[kIdleSocketValidation] === 1) {
1078 socket[kParser].readMore()
1079 if (socket.destroyed) {
1080 return
1081 }
1082 return
1083 }
1084 }
1085
1086 if (client[kRunning] === 0) {
1087 socket[kParser].readMore()
1088 if (socket.destroyed) {
1089 return
1090 }
1091 }
1092
1093 if (client[kSize] === 0) {
1094 if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
1095 socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
1096 }
1097 } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
1098 if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
1099 const request = client[kQueue][client[kRunningIdx]]
1100 const headersTimeout = request.headersTimeout != null
1101 ? request.headersTimeout
1102 : client[kHeadersTimeout]
1103 socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
1104 }
1105 }
1106 }
1107 }
1108
1109 // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
1110 function shouldSendContentLength (method) {
1111 return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
1112 }
1113
1114 /**
1115 * @param {import('./client.js')} client
1116 * @param {import('../core/request.js')} request
1117 * @returns
1118 */
1119 function writeH1 (client, request) {
1120 const { method, path, host, upgrade, blocking, reset } = request
1121
1122 let { body, headers, contentLength } = request
1123
1124 // https://tools.ietf.org/html/rfc7231#section-4.3.1
1125 // https://tools.ietf.org/html/rfc7231#section-4.3.2
1126 // https://tools.ietf.org/html/rfc7231#section-4.3.5
1127
1128 // Sending a payload body on a request that does not
1129 // expect it can cause undefined behavior on some
1130 // servers and corrupt connection state. Do not
1131 // re-use the connection for further requests.
1132
1133 const expectsPayload = (
1134 method === 'PUT' ||
1135 method === 'POST' ||
1136 method === 'PATCH' ||
1137 method === 'QUERY' ||
1138 method === 'PROPFIND' ||
1139 method === 'PROPPATCH'
1140 )
1141
1142 if (util.isFormDataLike(body)) {
1143 if (!extractBody) {
1144 extractBody = require('../web/fetch/body.js').extractBody
1145 }
1146
1147 const [bodyStream, contentType] = extractBody(body)
1148 if (request.contentType == null) {
1149 headers.push('content-type', contentType)
1150 }
1151 body = bodyStream.stream
1152 contentLength = bodyStream.length
1153 } else if (util.isBlobLike(body) && request.contentType == null && body.type) {
1154 headers.push('content-type', body.type)
1155 }
1156
1157 if (body && typeof body.read === 'function') {
1158 // Try to read EOF in order to get length.
1159 body.read(0)
1160 }
1161
1162 const bodyLength = util.bodyLength(body)
1163
1164 contentLength = bodyLength ?? contentLength
1165
1166 if (contentLength === null) {
1167 contentLength = request.contentLength
1168 }
1169
1170 if (contentLength === 0 && !expectsPayload) {
1171 // https://tools.ietf.org/html/rfc7230#section-3.3.2
1172 // A user agent SHOULD NOT send a Content-Length header field when
1173 // the request message does not contain a payload body and the method
1174 // semantics do not anticipate such a body.
1175
1176 contentLength = null
1177 }
1178
1179 // https://github.com/nodejs/undici/issues/2046
1180 // A user agent may send a Content-Length header with 0 value, this should be allowed.
1181 if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
1182 if (client[kStrictContentLength]) {
1183 util.errorRequest(client, request, new RequestContentLengthMismatchError())
1184 return false
1185 }
1186
1187 process.emitWarning(new RequestContentLengthMismatchError())
1188 }
1189
1190 const socket = client[kSocket]
1191 clearIdleSocketValidation(socket)
1192
1193 /**
1194 * @param {Error} [err]
1195 * @returns {void}
1196 */
1197 const abort = (err) => {
1198 if (request.aborted || request.completed) {
1199 return
1200 }
1201
1202 util.errorRequest(client, request, err || new RequestAbortedError())
1203
1204 util.destroy(body)
1205 util.destroy(socket, new InformationalError('aborted'))
1206 }
1207
1208 try {
1209 request.onRequestStart(abort, null)
1210 } catch (err) {
1211 util.errorRequest(client, request, err)
1212 }
1213
1214 if (request.aborted) {
1215 return false
1216 }
1217
1218 if (method === 'HEAD') {
1219 // https://github.com/mcollina/undici/issues/258
1220 // Close after a HEAD request to interop with misbehaving servers
1221 // that may send a body in the response.
1222
1223 socket[kReset] = true
1224 }
1225
1226 if (upgrade || method === 'CONNECT') {
1227 // On CONNECT or upgrade, block pipeline from dispatching further
1228 // requests on this connection.
1229
1230 socket[kReset] = true
1231 }
1232
1233 if (reset != null) {
1234 socket[kReset] = reset
1235 }
1236
1237 if (client[kMaxRequests] && ++socket[kCounter] >= client[kMaxRequests]) {
1238 socket[kReset] = true
1239 }
1240
1241 if (blocking) {
1242 socket[kBlocking] = true
1243 }
1244
1245 if (socket.setTypeOfService) {
1246 socket.setTypeOfService(request.typeOfService)
1247 }
1248
1249 let header = `${method} ${path} HTTP/1.1\r\n`
1250
1251 if (typeof host === 'string') {
1252 header += `host: ${host}\r\n`
1253 } else {
1254 header += client[kHostHeader]
1255 }
1256
1257 if (upgrade) {
1258 header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
1259 } else if (client[kPipelining] && !socket[kReset]) {
1260 header += 'connection: keep-alive\r\n'
1261 } else {
1262 header += 'connection: close\r\n'
1263 }
1264
1265 if (Array.isArray(headers)) {
1266 for (let n = 0; n < headers.length; n += 2) {
1267 const key = headers[n + 0]
1268 const val = headers[n + 1]
1269
1270 if (Array.isArray(val)) {
1271 for (let i = 0; i < val.length; i++) {
1272 header += `${key}: ${val[i]}\r\n`
1273 }
1274 } else {
1275 header += `${key}: ${val}\r\n`
1276 }
1277 }
1278 }
1279
1280 if (channels.sendHeaders.hasSubscribers) {
1281 channels.sendHeaders.publish({ request, headers: header, socket })
1282 }
1283
1284 if (!body || bodyLength === 0) {
1285 writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload)
1286 } else if (util.isBuffer(body)) {
1287 writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload)
1288 } else if (util.isBlobLike(body)) {
1289 if (typeof body.stream === 'function') {
1290 writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload)
1291 } else {
1292 writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload)
1293 }
1294 } else if (util.isStream(body)) {
1295 writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload)
1296 } else if (util.isIterable(body)) {
1297 writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload)
1298 } else {
1299 assert(false)
1300 }
1301
1302 return true
1303 }
1304
1305 /**
1306 * @param {AbortCallback} abort
1307 * @param {import('stream').Stream} body
1308 * @param {import('./client.js')} client
1309 * @param {import('../core/request.js')} request
1310 * @param {import('net').Socket} socket
1311 * @param {number} contentLength
1312 * @param {string} header
1313 * @param {boolean} expectsPayload
1314 */
1315 function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1316 assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
1317
1318 let finished = false
1319
1320 const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
1321
1322 /**
1323 * @param {Buffer} chunk
1324 * @returns {void}
1325 */
1326 const onData = function (chunk) {
1327 if (finished) {
1328 return
1329 }
1330
1331 try {
1332 if (!writer.write(chunk) && this.pause) {
1333 this.pause()
1334 }
1335 } catch (err) {
1336 util.destroy(this, err)
1337 }
1338 }
1339
1340 /**
1341 * @returns {void}
1342 */
1343 const onDrain = function () {
1344 if (finished) {
1345 return
1346 }
1347
1348 if (body.resume) {
1349 body.resume()
1350 }
1351 }
1352
1353 /**
1354 * @returns {void}
1355 */
1356 const onClose = function () {
1357 // 'close' might be emitted *before* 'error' for
1358 // broken streams. Wait a tick to avoid this case.
1359 queueMicrotask(() => {
1360 // It's only safe to remove 'error' listener after
1361 // 'close'.
1362 body.removeListener('error', onFinished)
1363 })
1364
1365 if (!finished) {
1366 const err = new RequestAbortedError()
1367 queueMicrotask(() => onFinished(err))
1368 }
1369 }
1370
1371 /**
1372 * @param {Error} [err]
1373 * @returns
1374 */
1375 const onFinished = function (err) {
1376 if (finished) {
1377 return
1378 }
1379
1380 finished = true
1381
1382 assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
1383
1384 socket
1385 .off('drain', onDrain)
1386 .off('error', onFinished)
1387
1388 body
1389 .removeListener('data', onData)
1390 .removeListener('end', onFinished)
1391 .removeListener('close', onClose)
1392
1393 if (!err) {
1394 try {
1395 writer.end()
1396 } catch (er) {
1397 err = er
1398 }
1399 }
1400
1401 writer.destroy(err)
1402
1403 if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
1404 util.destroy(body, err)
1405 } else {
1406 util.destroy(body)
1407 }
1408 }
1409
1410 body
1411 .on('data', onData)
1412 .on('end', onFinished)
1413 .on('error', onFinished)
1414 .on('close', onClose)
1415
1416 if (body.resume) {
1417 body.resume()
1418 }
1419
1420 socket
1421 .on('drain', onDrain)
1422 .on('error', onFinished)
1423
1424 if (body.errorEmitted ?? body.errored) {
1425 setImmediate(onFinished, body.errored)
1426 } else if (body.endEmitted ?? body.readableEnded) {
1427 setImmediate(onFinished, null)
1428 }
1429
1430 if (body.closeEmitted ?? body.closed) {
1431 setImmediate(onClose)
1432 }
1433 }
1434
1435 /**
1436 * @typedef AbortCallback
1437 * @type {Function}
1438 * @param {Error} [err]
1439 * @returns {void}
1440 */
1441
1442 /**
1443 * @param {AbortCallback} abort
1444 * @param {Uint8Array|null} body
1445 * @param {import('./client.js')} client
1446 * @param {import('../core/request.js')} request
1447 * @param {import('net').Socket} socket
1448 * @param {number} contentLength
1449 * @param {string} header
1450 * @param {boolean} expectsPayload
1451 * @returns {void}
1452 */
1453 function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1454 try {
1455 if (!body) {
1456 if (contentLength === 0) {
1457 socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
1458 } else {
1459 assert(contentLength === null, 'no body must not have content length')
1460 socket.write(`${header}\r\n`, 'latin1')
1461 }
1462 } else if (util.isBuffer(body)) {
1463 assert(contentLength === body.byteLength, 'buffer body must have content length')
1464
1465 socket.cork()
1466 socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1467 socket.write(body)
1468 socket.uncork()
1469 request.onBodySent(body)
1470
1471 if (!expectsPayload && request.reset !== false) {
1472 socket[kReset] = true
1473 }
1474 }
1475 request.onRequestSent()
1476
1477 client[kResume]()
1478 } catch (err) {
1479 abort(err)
1480 }
1481 }
1482
1483 /**
1484 * @param {AbortCallback} abort
1485 * @param {Blob} body
1486 * @param {import('./client.js')} client
1487 * @param {import('../core/request.js')} request
1488 * @param {import('net').Socket} socket
1489 * @param {number} contentLength
1490 * @param {string} header
1491 * @param {boolean} expectsPayload
1492 * @returns {Promise<void>}
1493 */
1494 async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1495 try {
1496 if (contentLength != null && contentLength !== body.size) {
1497 throw new RequestContentLengthMismatchError()
1498 }
1499
1500 const buffer = Buffer.from(await body.arrayBuffer())
1501
1502 socket.cork()
1503 socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1504 socket.write(buffer)
1505 socket.uncork()
1506
1507 request.onBodySent(buffer)
1508 request.onRequestSent()
1509
1510 if (!expectsPayload && request.reset !== false) {
1511 socket[kReset] = true
1512 }
1513
1514 client[kResume]()
1515 } catch (err) {
1516 abort(err)
1517 }
1518 }
1519
1520 /**
1521 * @param {AbortCallback} abort
1522 * @param {Iterable} body
1523 * @param {import('./client.js')} client
1524 * @param {import('../core/request.js')} request
1525 * @param {import('net').Socket} socket
1526 * @param {number} contentLength
1527 * @param {string} header
1528 * @param {boolean} expectsPayload
1529 * @returns {Promise<void>}
1530 */
1531 async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1532 assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
1533
1534 let callback = null
1535 function onDrain () {
1536 if (callback) {
1537 const cb = callback
1538 callback = null
1539 cb()
1540 }
1541 }
1542
1543 const waitForDrain = () => new Promise((resolve, reject) => {
1544 assert(callback === null)
1545
1546 if (socket[kError]) {
1547 reject(socket[kError])
1548 } else {
1549 callback = resolve
1550 }
1551 })
1552
1553 socket
1554 .on('close', onDrain)
1555 .on('drain', onDrain)
1556
1557 const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
1558 try {
1559 // It's up to the user to somehow abort the async iterable.
1560 for await (const chunk of body) {
1561 if (socket[kError]) {
1562 throw socket[kError]
1563 }
1564
1565 if (!writer.write(chunk)) {
1566 await waitForDrain()
1567 }
1568 }
1569
1570 writer.end()
1571 } catch (err) {
1572 writer.destroy(err)
1573 } finally {
1574 socket
1575 .off('close', onDrain)
1576 .off('drain', onDrain)
1577 }
1578 }
1579
1580 class AsyncWriter {
1581 /**
1582 *
1583 * @param {object} arg
1584 * @param {AbortCallback} arg.abort
1585 * @param {import('net').Socket} arg.socket
1586 * @param {import('../core/request.js')} arg.request
1587 * @param {number} arg.contentLength
1588 * @param {import('./client.js')} arg.client
1589 * @param {boolean} arg.expectsPayload
1590 * @param {string} arg.header
1591 */
1592 constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) {
1593 this.socket = socket
1594 this.request = request
1595 this.contentLength = contentLength
1596 this.client = client
1597 this.bytesWritten = 0
1598 this.expectsPayload = expectsPayload
1599 this.header = header
1600 this.abort = abort
1601
1602 socket[kWriting] = true
1603 }
1604
1605 /**
1606 * @param {string|Uint8Array} chunk
1607 * @returns
1608 */
1609 write (chunk) {
1610 const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
1611
1612 if (socket[kError]) {
1613 throw socket[kError]
1614 }
1615
1616 if (socket.destroyed) {
1617 return false
1618 }
1619
1620 const len = chunk instanceof Uint8Array ? chunk.byteLength : Buffer.byteLength(chunk)
1621 if (!len) {
1622 return true
1623 }
1624
1625 // We should defer writing chunks.
1626 if (contentLength !== null && bytesWritten + len > contentLength) {
1627 if (client[kStrictContentLength]) {
1628 throw new RequestContentLengthMismatchError()
1629 }
1630
1631 process.emitWarning(new RequestContentLengthMismatchError())
1632 }
1633
1634 socket.cork()
1635
1636 if (bytesWritten === 0) {
1637 if (!expectsPayload && request.reset !== false) {
1638 socket[kReset] = true
1639 }
1640
1641 if (contentLength === null) {
1642 socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
1643 } else {
1644 socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1645 }
1646 }
1647
1648 if (contentLength === null) {
1649 socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
1650 }
1651
1652 this.bytesWritten += len
1653
1654 const ret = socket.write(chunk)
1655
1656 socket.uncork()
1657
1658 request.onBodySent(chunk)
1659
1660 if (!ret) {
1661 if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
1662 if (socket[kParser].timeout.refresh) {
1663 socket[kParser].timeout.refresh()
1664 }
1665 }
1666 }
1667
1668 return ret
1669 }
1670
1671 /**
1672 * @returns {void}
1673 */
1674 end () {
1675 const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
1676 request.onRequestSent()
1677
1678 socket[kWriting] = false
1679
1680 if (socket[kError]) {
1681 throw socket[kError]
1682 }
1683
1684 if (socket.destroyed) {
1685 return
1686 }
1687
1688 if (bytesWritten === 0) {
1689 if (expectsPayload) {
1690 // https://tools.ietf.org/html/rfc7230#section-3.3.2
1691 // A user agent SHOULD send a Content-Length in a request message when
1692 // no Transfer-Encoding is sent and the request method defines a meaning
1693 // for an enclosed payload body.
1694
1695 socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
1696 } else {
1697 socket.write(`${header}\r\n`, 'latin1')
1698 }
1699 } else if (contentLength === null) {
1700 socket.write('\r\n0\r\n\r\n', 'latin1')
1701 }
1702
1703 if (contentLength !== null && bytesWritten !== contentLength) {
1704 if (client[kStrictContentLength]) {
1705 throw new RequestContentLengthMismatchError()
1706 } else {
1707 process.emitWarning(new RequestContentLengthMismatchError())
1708 }
1709 }
1710
1711 if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
1712 if (socket[kParser].timeout.refresh) {
1713 socket[kParser].timeout.refresh()
1714 }
1715 }
1716
1717 client[kResume]()
1718 }
1719
1720 /**
1721 * @param {Error} [err]
1722 * @returns {void}
1723 */
1724 destroy (err) {
1725 const { socket, client, abort } = this
1726
1727 socket[kWriting] = false
1728
1729 if (err) {
1730 assert(client[kRunning] <= 1, 'pipeline should only contain this request')
1731 abort(err)
1732 }
1733 }
1734 }
1735
1736 module.exports = connectH1