All files / lib _http_client.js

98.82% Statements 928/939
96.94% Branches 286/295
100% Functions 34/34
98.82% Lines 928/939

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 94011x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 390x 11x 11x 11x 11x 11x 11x 11x 11x 4140x 4140x 20x 20x 20x 20x 4120x 4140x 11x 11x 11x 2844x 2844x 2844x 11x 11x 4298x 4298x 4298x 4298x 82x 82x 4296x 4216x 45x 45x 4176x 4171x 4171x 4171x 4171x 4290x 4290x 39x 39x 4290x 4251x 4251x 4290x 4290x 4298x 4298x 5x 4289x 3891x 3861x 3861x 3891x 3891x 4284x 6x 6x 6x 6x 4284x 4284x 4298x 4298x 4298x 4298x 4284x 4290x 2218x 2218x 2218x 2218x 2929x 2935x 6x 6x 2923x 2923x 4298x 4298x 4298x 4298x 4298x 4298x 4298x 4298x 4298x 4298x 4298x 4298x 2902x 2902x 2929x 10x 10x 2902x 2902x 4298x 8x 8x 2894x 4298x 186x 1x 1x 185x 2929x 2708x 2708x 2893x 2893x 2893x 2928x 2893x 2893x 2893x 2928x 4298x 2x 2x 2x 2891x 2891x 4298x 4298x 2413x 2413x 2891x 2928x 4298x 4298x 4298x 4298x 4298x 2827x 2924x 64x 64x 2891x 2891x 2891x 2891x 2891x 2891x 2891x 2891x 2891x 2891x 2891x 2891x 2893x 2861x 2861x 2861x 2861x 2861x 60x 60x 2857x 2801x 2801x 2801x 2861x 2891x 2891x 2891x 2883x 258x 258x 258x 258x 1078x 1078x 1078x 257x 2882x 2883x 2868x 2868x 2868x 2868x 2868x 2868x 2868x 2868x 2868x 28x 28x 2868x 2868x 2827x 2827x 2868x 2868x 2882x 2883x 7x 7x 7x 2882x 2883x 5x     5x 5x 5x 5x 2928x 8x 8x 8x 2890x 2890x 2890x 2890x 2928x 10x 10x 10x 2890x 2890x 2892x 2860x 2928x 30x 30x 30x 30x 30x 26x 2x 26x 24x 24x 30x 30x 30x 30x 30x 30x 23x 23x 30x 1x 1x 30x       30x 4298x 11x 11x 11x 11x 2829x 2829x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2829x 1x 1x 1x 1x 11x 11x 11x 2865x     2865x 2865x 11x 11x 11x 54x 1x 1x 53x 53x 53x 11x 11x 11x 237x 136x 136x 101x 101x 101x 237x 50x 50x 101x 101x 237x 237x 237x 11x 11x 53x 53x 53x 11x 169x 169x 169x 164x 164x 164x 169x 11x 835x 835x 835x 835x 835x 835x 835x 835x 835x 835x 835x 835x 387x 387x 32x 32x 387x 387x 387x 68x 68x 835x 448x 23x 23x 23x 23x 23x 23x 448x 448x 448x 835x 835x 835x 835x 835x 835x 835x 835x 45x 45x 45x 835x 11x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 40x 11x 396x 396x 396x 396x 396x 396x 372x 372x 372x 372x 372x 396x 396x 396x 396x 396x 396x 11x 2982x 2982x 2982x 2982x 2982x 2982x 2982x 2982x 2982x 18x 18x 18x 18x 18x 18x 18x 18x 2975x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 83x 2x 2x 2x 2961x 2255x 2255x 2255x 2255x 2255x 2877x 2252x 2252x 2252x 2252x 2252x 2982x 11x 4563x 4563x 4563x 4563x 4563x 4563x 4563x 11x 11x 2393x 2393x 2393x 2393x 2393x 2393x 2393x 1x 1x 1x 1x 1x 2392x 2392x 2392x 2392x 2393x 2313x 2313x 2313x 2393x 5x 5x 5x 2308x 2386x 7x 7x 7x 7x 4x 4x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2301x 2393x 238x 238x 238x 238x 238x 2301x 2393x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2382x 1x 1x 1x 1x 1x 2301x 2301x 2301x 2301x 2301x 2301x 2301x 2301x 2301x 2301x 2301x 2393x 2393x 2298x 2298x 2379x 2293x 2375x 1x 1x 1x 2292x 2292x 2393x 11x 11x 1914x 1914x 1914x 1914x 1914x 1618x 1618x 1618x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 1914x 11x 2195x 2195x 2195x 2195x 2195x 2195x 2195x 2195x 2195x 2195x 2195x 2195x 280x 265x 265x 265x 7x 7x 265x 280x 2195x 1912x 1912x 1912x 1912x 1912x 1912x 1912x 2195x 11x 5x 5x 5x 5x 5x 5x 5x 11x 12x 12x 12x 12x 12x 12x 11x 1913x 1913x 1913x 1913x 1913x 1913x 1913x 11x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 6x 6x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2844x 2838x 2844x 2446x 2446x 2844x 2844x 11x 470x 470x 470x 470x 470x 470x 11x 2955x 2955x 496x 496x 2459x 2459x 2459x 2952x 1963x 2955x 496x 496x 496x 496x 2955x 11x 11x 2885x 2885x 2885x 11x 11x 2885x 2885x 41x 41x 41x 41x 3x 3x 41x 30x 30x 41x 41x 41x 41x 41x 24x 21x 24x 3x 3x 1x 1x 3x 3x 3x 3x 24x 38x 41x 2885x 2844x 2844x 2844x 2885x 11x 11x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x     4x 11x 11x 510x 1x 1x 509x 509x 509x 509x 509x 509x 13x 497x 496x 496x 509x 509x 11x 11x 509x 509x 397x 397x 397x 507x 112x 112x 509x 11x 11x 2x 11x 11x 11x 11x 2x 11x 11x 11x 12x 11x 11x 11x 11x 11x  
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
'use strict';
 
const {
  ArrayIsArray,
  Boolean,
  Error,
  FunctionPrototypeCall,
  NumberIsFinite,
  ObjectAssign,
  ObjectKeys,
  ObjectSetPrototypeOf,
  ReflectApply,
  RegExpPrototypeExec,
  String,
  StringPrototypeCharCodeAt,
  StringPrototypeIncludes,
  StringPrototypeIndexOf,
  StringPrototypeToUpperCase,
  Symbol,
  TypedArrayPrototypeSlice,
} = primordials;
 
const net = require('net');
const assert = require('internal/assert');
const {
  kEmptyObject,
  once,
} = require('internal/util');
const {
  _checkIsHttpToken: checkIsHttpToken,
  freeParser,
  parsers,
  HTTPParser,
  isLenient,
  prepareError,
} = require('_http_common');
const {
  kUniqueHeaders,
  parseUniqueHeadersOption,
  OutgoingMessage
} = require('_http_outgoing');
const Agent = require('_http_agent');
const { Buffer } = require('buffer');
const { defaultTriggerAsyncIdScope } = require('internal/async_hooks');
const { URL, urlToHttpOptions, searchParamsSymbol } = require('internal/url');
const { kOutHeaders, kNeedDrain } = require('internal/http');
const { connResetException, codes } = require('internal/errors');
const {
  ERR_HTTP_HEADERS_SENT,
  ERR_INVALID_ARG_TYPE,
  ERR_INVALID_HTTP_TOKEN,
  ERR_INVALID_PROTOCOL,
  ERR_UNESCAPED_CHARACTERS
} = codes;
const {
  validateInteger,
} = require('internal/validators');
const { getTimerDuration } = require('internal/timers');
const {
  hasObserver,
  startPerf,
  stopPerf,
} = require('internal/perf/observe');
 
const kClientRequestStatistics = Symbol('ClientRequestStatistics');
 
const dc = require('diagnostics_channel');
const onClientRequestStartChannel = dc.channel('http.client.request.start');
const onClientResponseFinishChannel = dc.channel('http.client.response.finish');
 
const { addAbortSignal, finished } = require('stream');
 
let debug = require('internal/util/debuglog').debuglog('http', (fn) => {
  debug = fn;
});
 
const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/;
const kError = Symbol('kError');
 
const kLenientAll = HTTPParser.kLenientAll | 0;
const kLenientNone = HTTPParser.kLenientNone | 0;
 
function validateHost(host, name) {
  if (host !== null && host !== undefined && typeof host !== 'string') {
    throw new ERR_INVALID_ARG_TYPE(`options.${name}`,
                                   ['string', 'undefined', 'null'],
                                   host);
  }
  return host;
}
 
class HTTPClientAsyncResource {
  constructor(type, req) {
    this.type = type;
    this.req = req;
  }
}
 
function ClientRequest(input, options, cb) {
  FunctionPrototypeCall(OutgoingMessage, this);
 
  if (typeof input === 'string') {
    const urlStr = input;
    input = urlToHttpOptions(new URL(urlStr));
  } else if (input && input[searchParamsSymbol] &&
             input[searchParamsSymbol][searchParamsSymbol]) {
    // url.URL instance
    input = urlToHttpOptions(input);
  } else {
    cb = options;
    options = input;
    input = null;
  }
 
  if (typeof options === 'function') {
    cb = options;
    options = input || kEmptyObject;
  } else {
    options = ObjectAssign(input || {}, options);
  }
 
  let agent = options.agent;
  const defaultAgent = options._defaultAgent || Agent.globalAgent;
  if (agent === false) {
    agent = new defaultAgent.constructor();
  } else if (agent === null || agent === undefined) {
    if (typeof options.createConnection !== 'function') {
      agent = defaultAgent;
    }
    // Explicitly pass through this statement as agent will not be used
    // when createConnection is provided.
  } else if (typeof agent.addRequest !== 'function') {
    throw new ERR_INVALID_ARG_TYPE('options.agent',
                                   ['Agent-like Object', 'undefined', 'false'],
                                   agent);
  }
  this.agent = agent;
 
  const protocol = options.protocol || defaultAgent.protocol;
  let expectedProtocol = defaultAgent.protocol;
  if (this.agent && this.agent.protocol)
    expectedProtocol = this.agent.protocol;
 
  if (options.path) {
    const path = String(options.path);
    if (RegExpPrototypeExec(INVALID_PATH_REGEX, path) !== null)
      throw new ERR_UNESCAPED_CHARACTERS('Request path');
  }
 
  if (protocol !== expectedProtocol) {
    throw new ERR_INVALID_PROTOCOL(protocol, expectedProtocol);
  }
 
  const defaultPort = options.defaultPort ||
                    (this.agent && this.agent.defaultPort);
 
  const port = options.port = options.port || defaultPort || 80;
  const host = options.host = validateHost(options.hostname, 'hostname') ||
                            validateHost(options.host, 'host') || 'localhost';
 
  const setHost = (options.setHost === undefined || Boolean(options.setHost));
 
  this.socketPath = options.socketPath;
 
  if (options.timeout !== undefined)
    this.timeout = getTimerDuration(options.timeout, 'timeout');
 
  const signal = options.signal;
  if (signal) {
    addAbortSignal(signal, this);
  }
  let method = options.method;
  const methodIsString = (typeof method === 'string');
  if (method !== null && method !== undefined && !methodIsString) {
    throw new ERR_INVALID_ARG_TYPE('options.method', 'string', method);
  }
 
  if (methodIsString && method) {
    if (!checkIsHttpToken(method)) {
      throw new ERR_INVALID_HTTP_TOKEN('Method', method);
    }
    method = this.method = StringPrototypeToUpperCase(method);
  } else {
    method = this.method = 'GET';
  }
 
  const maxHeaderSize = options.maxHeaderSize;
  if (maxHeaderSize !== undefined)
    validateInteger(maxHeaderSize, 'maxHeaderSize', 0);
  this.maxHeaderSize = maxHeaderSize;
 
  const insecureHTTPParser = options.insecureHTTPParser;
  if (insecureHTTPParser !== undefined &&
      typeof insecureHTTPParser !== 'boolean') {
    throw new ERR_INVALID_ARG_TYPE(
      'options.insecureHTTPParser', 'boolean', insecureHTTPParser);
  }
  this.insecureHTTPParser = insecureHTTPParser;
 
  this.path = options.path || '/';
  if (cb) {
    this.once('response', cb);
  }
 
  if (method === 'GET' ||
      method === 'HEAD' ||
      method === 'DELETE' ||
      method === 'OPTIONS' ||
      method === 'TRACE' ||
      method === 'CONNECT') {
    this.useChunkedEncodingByDefault = false;
  } else {
    this.useChunkedEncodingByDefault = true;
  }
 
  this._ended = false;
  this.res = null;
  this.aborted = false;
  this.timeoutCb = null;
  this.upgradeOrConnect = false;
  this.parser = null;
  this.maxHeadersCount = null;
  this.reusedSocket = false;
  this.host = host;
  this.protocol = protocol;
 
  if (this.agent) {
    // If there is an agent we should default to Connection:keep-alive,
    // but only if the Agent will actually reuse the connection!
    // If it's not a keepAlive agent, and the maxSockets==Infinity, then
    // there's never a case where this socket will actually be reused
    if (!this.agent.keepAlive && !NumberIsFinite(this.agent.maxSockets)) {
      this._last = true;
      this.shouldKeepAlive = false;
    } else {
      this._last = false;
      this.shouldKeepAlive = true;
    }
  }
 
  const headersArray = ArrayIsArray(options.headers);
  if (!headersArray) {
    if (options.headers) {
      const keys = ObjectKeys(options.headers);
      // Retain for(;;) loop for performance reasons
      // Refs: https://github.com/nodejs/node/pull/30958
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        this.setHeader(key, options.headers[key]);
      }
    }
 
    if (host && !this.getHeader('host') && setHost) {
      let hostHeader = host;
 
      // For the Host header, ensure that IPv6 addresses are enclosed
      // in square brackets, as defined by URI formatting
      // https://tools.ietf.org/html/rfc3986#section-3.2.2
      const posColon = StringPrototypeIndexOf(hostHeader, ':');
      if (posColon !== -1 &&
          StringPrototypeIncludes(hostHeader, ':', posColon + 1) &&
          StringPrototypeCharCodeAt(hostHeader, 0) !== 91/* '[' */) {
        hostHeader = `[${hostHeader}]`;
      }
 
      if (port && +port !== defaultPort) {
        hostHeader += ':' + port;
      }
      this.setHeader('Host', hostHeader);
    }
 
    if (options.auth && !this.getHeader('Authorization')) {
      this.setHeader('Authorization', 'Basic ' +
                     Buffer.from(options.auth).toString('base64'));
    }
 
    if (this.getHeader('expect')) {
      if (this._header) {
        throw new ERR_HTTP_HEADERS_SENT('render');
      }
 
      this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n',
                        this[kOutHeaders]);
    }
  } else {
    this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n',
                      options.headers);
  }
 
  this[kUniqueHeaders] = parseUniqueHeadersOption(options.uniqueHeaders);
 
  let optsWithoutSignal = options;
  if (optsWithoutSignal.signal) {
    optsWithoutSignal = ObjectAssign({}, options);
    delete optsWithoutSignal.signal;
  }
 
  // initiate connection
  if (this.agent) {
    this.agent.addRequest(this, optsWithoutSignal);
  } else {
    // No agent, default to Connection:close.
    this._last = true;
    this.shouldKeepAlive = false;
    if (typeof optsWithoutSignal.createConnection === 'function') {
      const oncreate = once((err, socket) => {
        if (err) {
          process.nextTick(() => this.emit('error', err));
        } else {
          this.onSocket(socket);
        }
      });
 
      try {
        const newSocket = optsWithoutSignal.createConnection(optsWithoutSignal,
                                                             oncreate);
        if (newSocket) {
          oncreate(null, newSocket);
        }
      } catch (err) {
        oncreate(err);
      }
    } else {
      debug('CLIENT use net.createConnection', optsWithoutSignal);
      this.onSocket(net.createConnection(optsWithoutSignal));
    }
  }
}
ObjectSetPrototypeOf(ClientRequest.prototype, OutgoingMessage.prototype);
ObjectSetPrototypeOf(ClientRequest, OutgoingMessage);
 
ClientRequest.prototype._finish = function _finish() {
  FunctionPrototypeCall(OutgoingMessage.prototype._finish, this);
  if (hasObserver('http')) {
    startPerf(this, kClientRequestStatistics, {
      type: 'http',
      name: 'HttpClient',
      detail: {
        req: {
          method: this.method,
          url: `${this.protocol}//${this.host}${this.path}`,
          headers: typeof this.getHeaders === 'function' ? this.getHeaders() : {},
        },
      },
    });
  }
  if (onClientRequestStartChannel.hasSubscribers) {
    onClientRequestStartChannel.publish({
      request: this,
    });
  }
};
 
ClientRequest.prototype._implicitHeader = function _implicitHeader() {
  if (this._header) {
    throw new ERR_HTTP_HEADERS_SENT('render');
  }
  this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n',
                    this[kOutHeaders]);
};
 
ClientRequest.prototype.abort = function abort() {
  if (this.aborted) {
    return;
  }
  this.aborted = true;
  process.nextTick(emitAbortNT, this);
  this.destroy();
};
 
ClientRequest.prototype.destroy = function destroy(err) {
  if (this.destroyed) {
    return this;
  }
  this.destroyed = true;
 
  // If we're aborting, we don't care about any more response data.
  if (this.res) {
    this.res._dump();
  }
 
  this[kError] = err;
  this.socket?.destroy(err);
 
  return this;
};
 
function emitAbortNT(req) {
  req.emit('abort');
}
 
function ondrain() {
  const msg = this._httpMessage;
  if (msg && !msg.finished && msg[kNeedDrain]) {
    msg[kNeedDrain] = false;
    msg.emit('drain');
  }
}
 
function socketCloseListener() {
  const socket = this;
  const req = socket._httpMessage;
  debug('HTTP socket close');
 
  // NOTE: It's important to get parser here, because it could be freed by
  // the `socketOnData`.
  const parser = socket.parser;
  const res = req.res;
 
  req.destroyed = true;
  if (res) {
    // Socket closed before we emitted 'end' below.
    if (!res.complete) {
      res.destroy(connResetException('aborted'));
    }
    req._closed = true;
    req.emit('close');
    if (!res.aborted && res.readable) {
      res.push(null);
    }
  } else {
    if (!req.socket._hadError) {
      // This socket error fired before we started to
      // receive a response. The error needs to
      // fire on the request.
      req.socket._hadError = true;
      req.emit('error', connResetException('socket hang up'));
    }
    req._closed = true;
    req.emit('close');
  }
 
  // Too bad.  That output wasn't getting written.
  // This is pretty terrible that it doesn't raise an error.
  // Fixed better in v0.10
  if (req.outputData)
    req.outputData.length = 0;
 
  if (parser) {
    parser.finish();
    freeParser(parser, req, socket);
  }
}
 
function socketErrorListener(err) {
  const socket = this;
  const req = socket._httpMessage;
  debug('SOCKET ERROR:', err.message, err.stack);
 
  if (req) {
    // For Safety. Some additional errors might fire later on
    // and we need to make sure we don't double-fire the error event.
    req.socket._hadError = true;
    req.emit('error', err);
  }
 
  const parser = socket.parser;
  if (parser) {
    parser.finish();
    freeParser(parser, req, socket);
  }
 
  // Ensure that no further data will come out of the socket
  socket.removeListener('data', socketOnData);
  socket.removeListener('end', socketOnEnd);
  socket.destroy();
}
 
function socketOnEnd() {
  const socket = this;
  const req = this._httpMessage;
  const parser = this.parser;
 
  if (!req.res && !req.socket._hadError) {
    // If we don't have a response then we know that the socket
    // ended prematurely and we need to emit an error on the request.
    req.socket._hadError = true;
    req.emit('error', connResetException('socket hang up'));
  }
  if (parser) {
    parser.finish();
    freeParser(parser, req, socket);
  }
  socket.destroy();
}
 
function socketOnData(d) {
  const socket = this;
  const req = this._httpMessage;
  const parser = this.parser;
 
  assert(parser && parser.socket === socket);
 
  const ret = parser.execute(d);
  if (ret instanceof Error) {
    prepareError(ret, parser, d);
    debug('parse error', ret);
    freeParser(parser, req, socket);
    socket.removeListener('data', socketOnData);
    socket.removeListener('end', socketOnEnd);
    socket.destroy();
    req.socket._hadError = true;
    req.emit('error', ret);
  } else if (parser.incoming && parser.incoming.upgrade) {
    // Upgrade (if status code 101) or CONNECT
    const bytesParsed = ret;
    const res = parser.incoming;
    req.res = res;
 
    socket.removeListener('data', socketOnData);
    socket.removeListener('end', socketOnEnd);
    socket.removeListener('drain', ondrain);
 
    if (req.timeoutCb) socket.removeListener('timeout', req.timeoutCb);
    socket.removeListener('timeout', responseOnTimeout);
 
    parser.finish();
    freeParser(parser, req, socket);
 
    const bodyHead = TypedArrayPrototypeSlice(d, bytesParsed, d.length);
 
    const eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade';
    if (req.listenerCount(eventName) > 0) {
      req.upgradeOrConnect = true;
 
      // detach the socket
      socket.emit('agentRemove');
      socket.removeListener('close', socketCloseListener);
      socket.removeListener('error', socketErrorListener);
 
      socket._httpMessage = null;
      socket.readableFlowing = null;
 
      req.emit(eventName, res, socket, bodyHead);
      req.destroyed = true;
      req._closed = true;
      req.emit('close');
    } else {
      // Requested Upgrade or used CONNECT method, but have no handler.
      socket.destroy();
    }
  } else if (parser.incoming && parser.incoming.complete &&
             // When the status code is informational (100, 102-199),
             // the server will send a final response after this client
             // sends a request body, so we must not free the parser.
             // 101 (Switching Protocols) and all other status codes
             // should be processed normally.
             !statusIsInformational(parser.incoming.statusCode)) {
    socket.removeListener('data', socketOnData);
    socket.removeListener('end', socketOnEnd);
    socket.removeListener('drain', ondrain);
    freeParser(parser, req, socket);
  }
}
 
function statusIsInformational(status) {
  // 100 (Continue)    RFC7231 Section 6.2.1
  // 102 (Processing)  RFC2518
  // 103 (Early Hints) RFC8297
  // 104-199 (Unassigned)
  return (status < 200 && status >= 100 && status !== 101);
}
 
// client
function parserOnIncomingClient(res, shouldKeepAlive) {
  const socket = this.socket;
  const req = socket._httpMessage;
 
  debug('AGENT incoming response!');
 
  if (req.res) {
    // We already have a response object, this means the server
    // sent a double response.
    socket.destroy();
    return 0;  // No special treatment.
  }
  req.res = res;
 
  // Skip body and treat as Upgrade.
  if (res.upgrade)
    return 2;
 
  // Responses to CONNECT request is handled as Upgrade.
  const method = req.method;
  if (method === 'CONNECT') {
    res.upgrade = true;
    return 2;  // Skip body and treat as Upgrade.
  }
 
  if (statusIsInformational(res.statusCode)) {
    // Restart the parser, as this is a 1xx informational message.
    req.res = null; // Clear res so that we don't hit double-responses.
    // Maintain compatibility by sending 100-specific events
    if (res.statusCode === 100) {
      req.emit('continue');
    }
    // Send information events to all 1xx responses except 101 Upgrade.
    req.emit('information', {
      statusCode: res.statusCode,
      statusMessage: res.statusMessage,
      httpVersion: res.httpVersion,
      httpVersionMajor: res.httpVersionMajor,
      httpVersionMinor: res.httpVersionMinor,
      headers: res.headers,
      rawHeaders: res.rawHeaders
    });
 
    return 1;  // Skip body but don't treat as Upgrade.
  }
 
  if (req.shouldKeepAlive && !shouldKeepAlive && !req.upgradeOrConnect) {
    // Server MUST respond with Connection:keep-alive for us to enable it.
    // If we've been upgraded (via WebSockets) we also shouldn't try to
    // keep the connection open.
    req.shouldKeepAlive = false;
  }
 
  if (req[kClientRequestStatistics] && hasObserver('http')) {
    stopPerf(req, kClientRequestStatistics, {
      detail: {
        res: {
          statusCode: res.statusCode,
          statusMessage: res.statusMessage,
          headers: res.headers,
        },
      },
    });
  }
  if (onClientResponseFinishChannel.hasSubscribers) {
    onClientResponseFinishChannel.publish({
      request: req,
      response: res,
    });
  }
  req.res = res;
  res.req = req;
 
  // Add our listener first, so that we guarantee socket cleanup
  res.on('end', responseOnEnd);
  req.on('prefinish', requestOnPrefinish);
  socket.on('timeout', responseOnTimeout);
 
  // If the user did not listen for the 'response' event, then they
  // can't possibly read the data, so we ._dump() it into the void
  // so that the socket doesn't hang there in a paused state.
  if (req.aborted || !req.emit('response', res))
    res._dump();
 
  if (method === 'HEAD')
    return 1;  // Skip body but don't treat as Upgrade.
 
  if (res.statusCode === 304) {
    res.complete = true;
    return 1; // Skip body as there won't be any
  }
 
  return 0;  // No special treatment.
}
 
// client
function responseKeepAlive(req) {
  const socket = req.socket;
 
  debug('AGENT socket keep-alive');
  if (req.timeoutCb) {
    socket.setTimeout(0, req.timeoutCb);
    req.timeoutCb = null;
  }
  socket.removeListener('close', socketCloseListener);
  socket.removeListener('error', socketErrorListener);
  socket.removeListener('data', socketOnData);
  socket.removeListener('end', socketOnEnd);
 
  // TODO(ronag): Between here and emitFreeNT the socket
  // has no 'error' handler.
 
  // There are cases where _handle === null. Avoid those. Passing undefined to
  // nextTick() will call getDefaultTriggerAsyncId() to retrieve the id.
  const asyncId = socket._handle ? socket._handle.getAsyncId() : undefined;
  // Mark this socket as available, AFTER user-added end
  // handlers have a chance to run.
  defaultTriggerAsyncIdScope(asyncId, process.nextTick, emitFreeNT, req);
 
  req.destroyed = true;
  if (req.res) {
    // Detach socket from IncomingMessage to avoid destroying the freed
    // socket in IncomingMessage.destroy().
    req.res.socket = null;
  }
}
 
function responseOnEnd() {
  const req = this.req;
  const socket = req.socket;
 
  if (socket) {
    if (req.timeoutCb) socket.removeListener('timeout', emitRequestTimeout);
    socket.removeListener('timeout', responseOnTimeout);
  }
 
  req._ended = true;
 
  if (!req.shouldKeepAlive) {
    if (socket.writable) {
      debug('AGENT socket.destroySoon()');
      if (typeof socket.destroySoon === 'function')
        socket.destroySoon();
      else
        socket.end();
    }
    assert(!socket.writable);
  } else if (req.finished && !this.aborted) {
    // We can assume `req.finished` means all data has been written since:
    // - `'responseOnEnd'` means we have been assigned a socket.
    // - when we have a socket we write directly to it without buffering.
    // - `req.finished` means `end()` has been called and no further data.
    //   can be written
    responseKeepAlive(req);
  }
}
 
function responseOnTimeout() {
  const req = this._httpMessage;
  if (!req) return;
  const res = req.res;
  if (!res) return;
  res.emit('timeout');
}
 
function requestOnPrefinish() {
  const req = this;
 
  if (req.shouldKeepAlive && req._ended)
    responseKeepAlive(req);
}
 
function emitFreeNT(req) {
  req._closed = true;
  req.emit('close');
  if (req.socket) {
    req.socket.emit('free');
  }
}
 
function tickOnSocket(req, socket) {
  const parser = parsers.alloc();
  req.socket = socket;
  const lenient = req.insecureHTTPParser === undefined ?
    isLenient() : req.insecureHTTPParser;
  parser.initialize(HTTPParser.RESPONSE,
                    new HTTPClientAsyncResource('HTTPINCOMINGMESSAGE', req),
                    req.maxHeaderSize || 0,
                    lenient ? kLenientAll : kLenientNone);
  parser.socket = socket;
  parser.outgoing = req;
  req.parser = parser;
 
  socket.parser = parser;
  socket._httpMessage = req;
 
  // Propagate headers limit from request object to parser
  if (typeof req.maxHeadersCount === 'number') {
    parser.maxHeaderPairs = req.maxHeadersCount << 1;
  }
 
  parser.onIncoming = parserOnIncomingClient;
  socket.on('error', socketErrorListener);
  socket.on('data', socketOnData);
  socket.on('end', socketOnEnd);
  socket.on('close', socketCloseListener);
  socket.on('drain', ondrain);
 
  if (
    req.timeout !== undefined ||
    (req.agent && req.agent.options && req.agent.options.timeout)
  ) {
    listenSocketTimeout(req);
  }
  req.emit('socket', socket);
}
 
function emitRequestTimeout() {
  const req = this._httpMessage;
  if (req) {
    req.emit('timeout');
  }
}
 
function listenSocketTimeout(req) {
  if (req.timeoutCb) {
    return;
  }
  // Set timeoutCb so it will get cleaned up on request end.
  req.timeoutCb = emitRequestTimeout;
  // Delegate socket timeout event.
  if (req.socket) {
    req.socket.once('timeout', emitRequestTimeout);
  } else {
    req.on('socket', (socket) => {
      socket.once('timeout', emitRequestTimeout);
    });
  }
}
 
ClientRequest.prototype.onSocket = function onSocket(socket, err) {
  // TODO(ronag): Between here and onSocketNT the socket
  // has no 'error' handler.
  process.nextTick(onSocketNT, this, socket, err);
};
 
function onSocketNT(req, socket, err) {
  if (req.destroyed || err) {
    req.destroyed = true;
 
    function _destroy(req, err) {
      if (!req.aborted && !err) {
        err = connResetException('socket hang up');
      }
      if (err) {
        req.emit('error', err);
      }
      req._closed = true;
      req.emit('close');
    }
 
    if (socket) {
      if (!err && req.agent && !socket.destroyed) {
        socket.emit('free');
      } else {
        finished(socket.destroy(err || req[kError]), (er) => {
          if (er?.code === 'ERR_STREAM_PREMATURE_CLOSE') {
            er = null;
          }
          _destroy(req, er || err);
        });
        return;
      }
    }
 
    _destroy(req, err || req[kError]);
  } else {
    tickOnSocket(req, socket);
    req._flush();
  }
}
 
ClientRequest.prototype._deferToConnect = _deferToConnect;
function _deferToConnect(method, arguments_) {
  // This function is for calls that need to happen once the socket is
  // assigned to this request and writable. It's an important promisy
  // thing for all the socket calls that happen either now
  // (when a socket is assigned) or in the future (when a socket gets
  // assigned out of the pool and is eventually writable).
 
  const callSocketMethod = () => {
    if (method)
      ReflectApply(this.socket[method], this.socket, arguments_);
  };
 
  const onSocket = () => {
    if (this.socket.writable) {
      callSocketMethod();
    } else {
      this.socket.once('connect', callSocketMethod);
    }
  };
 
  if (!this.socket) {
    this.once('socket', onSocket);
  } else {
    onSocket();
  }
}
 
ClientRequest.prototype.setTimeout = function setTimeout(msecs, callback) {
  if (this._ended) {
    return this;
  }
 
  listenSocketTimeout(this);
  msecs = getTimerDuration(msecs, 'msecs');
  if (callback) this.once('timeout', callback);
 
  if (this.socket) {
    setSocketTimeout(this.socket, msecs);
  } else {
    this.once('socket', (sock) => setSocketTimeout(sock, msecs));
  }
 
  return this;
};
 
function setSocketTimeout(sock, msecs) {
  if (sock.connecting) {
    sock.once('connect', function() {
      sock.setTimeout(msecs);
    });
  } else {
    sock.setTimeout(msecs);
  }
}
 
ClientRequest.prototype.setNoDelay = function setNoDelay(noDelay) {
  this._deferToConnect('setNoDelay', [noDelay]);
};
 
ClientRequest.prototype.setSocketKeepAlive =
    function setSocketKeepAlive(enable, initialDelay) {
      this._deferToConnect('setKeepAlive', [enable, initialDelay]);
    };
 
ClientRequest.prototype.clearTimeout = function clearTimeout(cb) {
  this.setTimeout(0, cb);
};
 
module.exports = {
  ClientRequest
};