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 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 | 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 372x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2260x 2260x 2260x 12x 12x 13908x 13908x 13908x 13908x 13908x 13908x 13908x 13908x 13908x 13908x 13908x 22x 22x 22x 22x 13908x 13908x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 13908x 12x 12x 12x 12x 12640x 12640x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12640x 12x 12x 12x 12x 12x 12x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 440x 439x 439x 440x 12x 12x 13081x 13081x 13081x 13081x 13081x 13081x 12x 12x 12x 12635x 12635x 12635x 12635x 12x 12x 12x 2x 2x 12x 12x 12x 2x 12x 12x 12x 11870x 12x 12x 12x 13510x 13510x 13510x 13510x 13510x 13x 13x 13497x 13497x 13510x 2x 2x 13510x 13495x 13495x 13495x 13495x 13495x 13497x 13497x 13497x 13510x 1313x 1313x 1313x 1x 1x 1x 2x 2x 2x 1313x 5x 5x 5x 5x 7x 7x 7x 5x 1313x 1x 1x 1312x 1312x 13510x 12184x 12184x 12184x 13496x 13496x 13510x 13493x 13493x 13493x 13510x 13510x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 13493x 13493x 13493x 13510x 13493x 13493x 13493x 13493x 13510x 12x 12x 12x 12x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 599x 12x 12x 599x 587x 587x 599x 599x 599x 12x 12x 599x 587x 587x 599x 599x 599x 599x 599x 13x 13x 599x 586x 586x 599x 599x 599x 12x 12x 599x 587x 587x 599x 12x 570x 570x 570x 570x 570x 570x 570x 570x 570x 12x 484x 484x 455x 458x 412x 412x 484x 40x 43x 3x 3x 452x 452x 452x 452x 452x 452x 452x 452x 453x 430x 430x 452x 452x 452x 452x 452x 452x 452x 452x 452x 452x 452x 452x 452x 484x 12x 12x 12x 12x 419x 419x 419x 12x 12x 12x 4x 4x 4x 6x 6x 12x 12x 12x 421x 421x 421x 1170x 1170x 12x 12x 12x 11x 11x 11x 11x 12x 12x 12x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 3x 3x 3x 3x 12x 12x 85x 85x 85x 85x 85x 85x 13x 13x 13x 13x 13x 13x 85x 12x 2260x 2260x 2260x 2260x 2260x 12x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 6x 6x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2249x 2249x 2249x 2249x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 2260x 12x 1x 1x 1x 12x 44330x 44330x 44330x 44330x 12x 54780x 54780x 54780x 54780x 54780x 8x 8x 8x 8x 8x 54780x 54780x 54780x 426x 426x 426x 54780x 12x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 12x 2231x 2231x 2231x 2231x 2231x 12x 2231x 2231x 1252x 1252x 1252x 2231x 2231x 12x 512x 512x 512x 512x 4x 4x 4x 512x 507x 508x 1x 1x 1x 1x 512x 12x 22x 22x 22x 22x 22x 22x 22x 12x 13x 13x 13x 13x 12x 3156x 3156x 3156x 3156x 3156x 3156x 3156x 3156x 3156x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 84x 84x 84x 84x 84x 50x 50x 84x 84x 42x 18x 18x 18x 18x 1x 1x 18x 9x 9x 18x 8x 8x 18x 18x 18x 18x 42x 42x 84x 12x 3178x 3178x 3178x 3178x 54x 54x 54x 3168x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 3124x 3175x 3178x 4x 4x 4x 4x 3178x 12x 14733x 14733x 14733x 14733x 14733x 4268x 2163x 2181x 2105x 2105x 4268x 14733x 12x 12634x 12634x 1x 1x 1x 1x 1x 1x 1x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 12634x 122x 119x 122x 3x 3x 12634x 2052x 2002x 2002x 2002x 12502x 10460x 10460x 10460x 10460x 10460x 10460x 12634x 12x 13073x 13073x 13072x 13072x 13072x 13072x 13073x 12x 12x 12x 12x 13919x 13919x 13919x 13919x 17x 17x 17x 17x 17x 13905x 13905x 13905x 13905x 13905x 13905x 13905x 2705x 2705x 9x 9x 9x 9x 9x 9x 2705x 13905x 13905x 13905x 13905x 13905x 13905x 13905x 13905x 13905x 13905x 13910x 1x 1x 1x 1x 1x 1x 1x 13905x 13910x 11287x 11287x 13898x 2618x 2618x 13905x 13905x 13905x 13905x 13905x 13905x 13905x 13905x 13905x 13919x 13883x 13883x 13697x 13883x 13883x 13883x 9x 9x 9x 9x 13883x 13883x 13883x 1x 1x 1x 1x 13883x 4x 4x 4x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x 13883x 13905x 13905x 13900x 13900x 13899x 13899x 13919x 12x 17097x 17097x 17097x 397x 17097x 17097x 17097x 12x 2302x 2302x 2302x 2302x 2302x 2302x 2302x 2302x 3x 3x 3x 2299x 2302x 38x 38x 38x 2302x 12x 44x 44x 41x 41x 41x 44x 12x 18x 18x 18x 18x 18x 18x 18x 18x 18x 12x 6780x 6780x 13295x 13295x 13295x 11x 11x 11x 11x 11x 13284x 13295x 13295x 13284x 13284x 6780x 6780x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x | // 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, Error, ObjectKeys, ObjectSetPrototypeOf, RegExpPrototypeExec, ReflectApply, Symbol, SymbolFor, } = primordials; const net = require('net'); const EE = require('events'); const assert = require('internal/assert'); const { parsers, freeParser, continueExpression, chunkExpression, kIncomingMessage, HTTPParser, isLenient, _checkInvalidHeaderChar: checkInvalidHeaderChar, prepareError, } = require('_http_common'); const { ConnectionsList } = internalBinding('http_parser'); const { kUniqueHeaders, parseUniqueHeadersOption, OutgoingMessage } = require('_http_outgoing'); const { kOutHeaders, kNeedDrain, } = require('internal/http'); const { defaultTriggerAsyncIdScope, getOrSetAsyncId } = require('internal/async_hooks'); const { IncomingMessage } = require('_http_incoming'); const { connResetException, codes } = require('internal/errors'); const { ERR_HTTP_REQUEST_TIMEOUT, ERR_HTTP_HEADERS_SENT, ERR_HTTP_INVALID_STATUS_CODE, ERR_HTTP_SOCKET_ENCODING, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_CHAR } = codes; const { validateInteger, validateBoolean } = require('internal/validators'); const Buffer = require('buffer').Buffer; const { DTRACE_HTTP_SERVER_REQUEST, DTRACE_HTTP_SERVER_RESPONSE } = require('internal/dtrace'); const { setInterval, clearInterval } = require('timers'); let debug = require('internal/util/debuglog').debuglog('http', (fn) => { debug = fn; }); const dc = require('diagnostics_channel'); const onRequestStartChannel = dc.channel('http.server.request.start'); const onResponseFinishChannel = dc.channel('http.server.response.finish'); const kServerResponse = Symbol('ServerResponse'); const kServerResponseStatistics = Symbol('ServerResponseStatistics'); const { hasObserver, startPerf, stopPerf, } = require('internal/perf/observe'); const STATUS_CODES = { 100: 'Continue', // RFC 7231 6.2.1 101: 'Switching Protocols', // RFC 7231 6.2.2 102: 'Processing', // RFC 2518 10.1 (obsoleted by RFC 4918) 103: 'Early Hints', // RFC 8297 2 200: 'OK', // RFC 7231 6.3.1 201: 'Created', // RFC 7231 6.3.2 202: 'Accepted', // RFC 7231 6.3.3 203: 'Non-Authoritative Information', // RFC 7231 6.3.4 204: 'No Content', // RFC 7231 6.3.5 205: 'Reset Content', // RFC 7231 6.3.6 206: 'Partial Content', // RFC 7233 4.1 207: 'Multi-Status', // RFC 4918 11.1 208: 'Already Reported', // RFC 5842 7.1 226: 'IM Used', // RFC 3229 10.4.1 300: 'Multiple Choices', // RFC 7231 6.4.1 301: 'Moved Permanently', // RFC 7231 6.4.2 302: 'Found', // RFC 7231 6.4.3 303: 'See Other', // RFC 7231 6.4.4 304: 'Not Modified', // RFC 7232 4.1 305: 'Use Proxy', // RFC 7231 6.4.5 307: 'Temporary Redirect', // RFC 7231 6.4.7 308: 'Permanent Redirect', // RFC 7238 3 400: 'Bad Request', // RFC 7231 6.5.1 401: 'Unauthorized', // RFC 7235 3.1 402: 'Payment Required', // RFC 7231 6.5.2 403: 'Forbidden', // RFC 7231 6.5.3 404: 'Not Found', // RFC 7231 6.5.4 405: 'Method Not Allowed', // RFC 7231 6.5.5 406: 'Not Acceptable', // RFC 7231 6.5.6 407: 'Proxy Authentication Required', // RFC 7235 3.2 408: 'Request Timeout', // RFC 7231 6.5.7 409: 'Conflict', // RFC 7231 6.5.8 410: 'Gone', // RFC 7231 6.5.9 411: 'Length Required', // RFC 7231 6.5.10 412: 'Precondition Failed', // RFC 7232 4.2 413: 'Payload Too Large', // RFC 7231 6.5.11 414: 'URI Too Long', // RFC 7231 6.5.12 415: 'Unsupported Media Type', // RFC 7231 6.5.13 416: 'Range Not Satisfiable', // RFC 7233 4.4 417: 'Expectation Failed', // RFC 7231 6.5.14 418: 'I\'m a Teapot', // RFC 7168 2.3.3 421: 'Misdirected Request', // RFC 7540 9.1.2 422: 'Unprocessable Entity', // RFC 4918 11.2 423: 'Locked', // RFC 4918 11.3 424: 'Failed Dependency', // RFC 4918 11.4 425: 'Too Early', // RFC 8470 5.2 426: 'Upgrade Required', // RFC 2817 and RFC 7231 6.5.15 428: 'Precondition Required', // RFC 6585 3 429: 'Too Many Requests', // RFC 6585 4 431: 'Request Header Fields Too Large', // RFC 6585 5 451: 'Unavailable For Legal Reasons', // RFC 7725 3 500: 'Internal Server Error', // RFC 7231 6.6.1 501: 'Not Implemented', // RFC 7231 6.6.2 502: 'Bad Gateway', // RFC 7231 6.6.3 503: 'Service Unavailable', // RFC 7231 6.6.4 504: 'Gateway Timeout', // RFC 7231 6.6.5 505: 'HTTP Version Not Supported', // RFC 7231 6.6.6 506: 'Variant Also Negotiates', // RFC 2295 8.1 507: 'Insufficient Storage', // RFC 4918 11.5 508: 'Loop Detected', // RFC 5842 7.2 509: 'Bandwidth Limit Exceeded', 510: 'Not Extended', // RFC 2774 7 511: 'Network Authentication Required' // RFC 6585 6 }; const kOnExecute = HTTPParser.kOnExecute | 0; const kOnTimeout = HTTPParser.kOnTimeout | 0; const kLenientAll = HTTPParser.kLenientAll | 0; const kLenientNone = HTTPParser.kLenientNone | 0; const kConnections = Symbol('http.server.connections'); const kConnectionsCheckingInterval = Symbol('http.server.connectionsCheckingInterval'); class HTTPServerAsyncResource { constructor(type, socket) { this.type = type; this.socket = socket; } } function ServerResponse(req) { OutgoingMessage.call(this); if (req.method === 'HEAD') this._hasBody = false; this.req = req; this.sendDate = true; this._sent100 = false; this._expect_continue = false; if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) { this.useChunkedEncodingByDefault = RegExpPrototypeExec(chunkExpression, req.headers.te) !== null; this.shouldKeepAlive = false; } if (hasObserver('http')) { startPerf(this, kServerResponseStatistics, { type: 'http', name: 'HttpRequest', detail: { req: { method: req.method, url: req.url, headers: req.headers, }, }, }); } } ObjectSetPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype); ObjectSetPrototypeOf(ServerResponse, OutgoingMessage); ServerResponse.prototype._finish = function _finish() { DTRACE_HTTP_SERVER_RESPONSE(this.socket); if (this[kServerResponseStatistics] && hasObserver('http')) { stopPerf(this, kServerResponseStatistics, { detail: { res: { statusCode: this.statusCode, statusMessage: this.statusMessage, headers: typeof this.getHeaders === 'function' ? this.getHeaders() : {}, }, }, }); } OutgoingMessage.prototype._finish.call(this); }; ServerResponse.prototype.statusCode = 200; ServerResponse.prototype.statusMessage = undefined; function onServerResponseClose() { // EventEmitter.emit makes a copy of the 'close' listeners array before // calling the listeners. detachSocket() unregisters onServerResponseClose // but if detachSocket() is called, directly or indirectly, by a 'close' // listener, onServerResponseClose is still in that copy of the listeners // array. That is, in the example below, b still gets called even though // it's been removed by a: // // var EventEmitter = require('events'); // var obj = new EventEmitter(); // obj.on('event', a); // obj.on('event', b); // function a() { obj.removeListener('event', b) } // function b() { throw "BAM!" } // obj.emit('event'); // throws // // Ergo, we need to deal with stale 'close' events and handle the case // where the ServerResponse object has already been deconstructed. // Fortunately, that requires only a single if check. :-) if (this._httpMessage) { emitCloseNT(this._httpMessage); } } ServerResponse.prototype.assignSocket = function assignSocket(socket) { assert(!socket._httpMessage); socket._httpMessage = this; socket.on('close', onServerResponseClose); this.socket = socket; this.emit('socket', socket); this._flush(); }; ServerResponse.prototype.detachSocket = function detachSocket(socket) { assert(socket._httpMessage === this); socket.removeListener('close', onServerResponseClose); socket._httpMessage = null; this.socket = null; }; ServerResponse.prototype.writeContinue = function writeContinue(cb) { this._writeRaw('HTTP/1.1 100 Continue\r\n\r\n', 'ascii', cb); this._sent100 = true; }; ServerResponse.prototype.writeProcessing = function writeProcessing(cb) { this._writeRaw('HTTP/1.1 102 Processing\r\n\r\n', 'ascii', cb); }; ServerResponse.prototype._implicitHeader = function _implicitHeader() { this.writeHead(this.statusCode); }; ServerResponse.prototype.writeHead = writeHead; function writeHead(statusCode, reason, obj) { const originalStatusCode = statusCode; statusCode |= 0; if (statusCode < 100 || statusCode > 999) { throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode); } if (typeof reason === 'string') { // writeHead(statusCode, reasonPhrase[, headers]) this.statusMessage = reason; } else { // writeHead(statusCode[, headers]) if (!this.statusMessage) this.statusMessage = STATUS_CODES[statusCode] || 'unknown'; obj = reason; } this.statusCode = statusCode; let headers; if (this[kOutHeaders]) { // Slow-case: when progressive API and header fields are passed. let k; if (ArrayIsArray(obj)) { if (obj.length % 2 !== 0) { throw new ERR_INVALID_ARG_VALUE('headers', obj); } for (let n = 0; n < obj.length; n += 2) { k = obj[n + 0]; if (k) this.setHeader(k, obj[n + 1]); } } else if (obj) { const keys = ObjectKeys(obj); // Retain for(;;) loop for performance reasons // Refs: https://github.com/nodejs/node/pull/30958 for (let i = 0; i < keys.length; i++) { k = keys[i]; if (k) this.setHeader(k, obj[k]); } } if (k === undefined && this._header) { throw new ERR_HTTP_HEADERS_SENT('render'); } // Only progressive api is used headers = this[kOutHeaders]; } else { // Only writeHead() called headers = obj; } if (checkInvalidHeaderChar(this.statusMessage)) throw new ERR_INVALID_CHAR('statusMessage'); const statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}\r\n`; if (statusCode === 204 || statusCode === 304 || (statusCode >= 100 && statusCode <= 199)) { // RFC 2616, 10.2.5: // The 204 response MUST NOT include a message-body, and thus is always // terminated by the first empty line after the header fields. // RFC 2616, 10.3.5: // The 304 response MUST NOT contain a message-body, and thus is always // terminated by the first empty line after the header fields. // RFC 2616, 10.1 Informational 1xx: // This class of status code indicates a provisional response, // consisting only of the Status-Line and optional headers, and is // terminated by an empty line. this._hasBody = false; } // Don't keep alive connections where the client expects 100 Continue // but we sent a final status; they may put extra bytes on the wire. if (this._expect_continue && !this._sent100) { this.shouldKeepAlive = false; } this._storeHeader(statusLine, headers); return this; } // Docs-only deprecated: DEP0063 ServerResponse.prototype.writeHeader = ServerResponse.prototype.writeHead; function storeHTTPOptions(options) { this[kIncomingMessage] = options.IncomingMessage || IncomingMessage; this[kServerResponse] = options.ServerResponse || ServerResponse; const maxHeaderSize = options.maxHeaderSize; if (maxHeaderSize !== undefined) validateInteger(maxHeaderSize, 'maxHeaderSize', 0); this.maxHeaderSize = maxHeaderSize; const insecureHTTPParser = options.insecureHTTPParser; if (insecureHTTPParser !== undefined) validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); this.insecureHTTPParser = insecureHTTPParser; if (options.noDelay === undefined) options.noDelay = true; const requestTimeout = options.requestTimeout; if (requestTimeout !== undefined) { validateInteger(requestTimeout, 'requestTimeout', 0); this.requestTimeout = requestTimeout; } else { this.requestTimeout = 300_000; // 5 minutes } const headersTimeout = options.headersTimeout; if (headersTimeout !== undefined) { validateInteger(headersTimeout, 'headersTimeout', 0); this.headersTimeout = headersTimeout; } else { this.headersTimeout = 60_000; // 60 seconds } if (this.requestTimeout > 0 && this.headersTimeout > 0 && this.headersTimeout >= this.requestTimeout) { throw new codes.ERR_OUT_OF_RANGE('headersTimeout', '>= requestTimeout', headersTimeout); } const keepAliveTimeout = options.keepAliveTimeout; if (keepAliveTimeout !== undefined) { validateInteger(keepAliveTimeout, 'keepAliveTimeout', 0); this.keepAliveTimeout = keepAliveTimeout; } else { this.keepAliveTimeout = 5_000; // 5 seconds; } const connectionsCheckingInterval = options.connectionsCheckingInterval; if (connectionsCheckingInterval !== undefined) { validateInteger(connectionsCheckingInterval, 'connectionsCheckingInterval', 0); this.connectionsCheckingInterval = connectionsCheckingInterval; } else { this.connectionsCheckingInterval = 30_000; // 30 seconds } } function setupConnectionsTracking(server) { // Start connection handling server[kConnections] = new ConnectionsList(); // This checker is started without checking whether any headersTimeout or requestTimeout is non zero // otherwise it would not be started if such timeouts are modified after createServer. server[kConnectionsCheckingInterval] = setInterval(checkConnections.bind(server), server.connectionsCheckingInterval).unref(); } function Server(options, requestListener) { if (!(this instanceof Server)) return new Server(options, requestListener); if (typeof options === 'function') { requestListener = options; options = {}; } else if (options == null || typeof options === 'object') { options = { ...options }; } else { throw new ERR_INVALID_ARG_TYPE('options', 'object', options); } storeHTTPOptions.call(this, options); net.Server.call( this, { allowHalfOpen: true, noDelay: options.noDelay, keepAlive: options.keepAlive, keepAliveInitialDelay: options.keepAliveInitialDelay }); if (requestListener) { this.on('request', requestListener); } // Similar option to this. Too lazy to write my own docs. // http://www.squid-cache.org/Doc/config/half_closed_clients/ // https://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F this.httpAllowHalfOpen = false; this.on('connection', connectionListener); this.timeout = 0; this.maxHeadersCount = null; this.maxRequestsPerSocket = 0; setupConnectionsTracking(this); this[kUniqueHeaders] = parseUniqueHeadersOption(options.uniqueHeaders); } ObjectSetPrototypeOf(Server.prototype, net.Server.prototype); ObjectSetPrototypeOf(Server, net.Server); Server.prototype.close = function() { this.closeIdleConnections(); clearInterval(this[kConnectionsCheckingInterval]); ReflectApply(net.Server.prototype.close, this, arguments); }; Server.prototype.closeAllConnections = function() { const connections = this[kConnections].all(); for (let i = 0, l = connections.length; i < l; i++) { connections[i].socket.destroy(); } }; Server.prototype.closeIdleConnections = function() { const connections = this[kConnections].idle(); for (let i = 0, l = connections.length; i < l; i++) { connections[i].socket.destroy(); } }; Server.prototype.setTimeout = function setTimeout(msecs, callback) { this.timeout = msecs; if (callback) this.on('timeout', callback); return this; }; Server.prototype[EE.captureRejectionSymbol] = function(err, event, ...args) { switch (event) { case 'request': { const { 1: res } = args; if (!res.headersSent && !res.writableEnded) { // Don't leak headers. const names = res.getHeaderNames(); for (let i = 0; i < names.length; i++) { res.removeHeader(names[i]); } res.statusCode = 500; res.end(STATUS_CODES[500]); } else { res.destroy(); } break; } default: net.Server.prototype[SymbolFor('nodejs.rejection')] .apply(this, arguments); } }; function checkConnections() { if (this.headersTimeout === 0 && this.requestTimeout === 0) { return; } const expired = this[kConnections].expired(this.headersTimeout, this.requestTimeout); for (let i = 0; i < expired.length; i++) { const socket = expired[i].socket; if (socket) { onRequestTimeout(socket); } } } function connectionListener(socket) { defaultTriggerAsyncIdScope( getOrSetAsyncId(socket), connectionListenerInternal, this, socket ); } function connectionListenerInternal(server, socket) { debug('SERVER new http connection'); // Ensure that the server property of the socket is correctly set. // See https://github.com/nodejs/node/issues/13435 socket.server = server; // If the user has added a listener to the server, // request, or response, then it's their responsibility. // otherwise, destroy on timeout by default if (server.timeout && typeof socket.setTimeout === 'function') socket.setTimeout(server.timeout); socket.on('timeout', socketOnTimeout); const parser = parsers.alloc(); const lenient = server.insecureHTTPParser === undefined ? isLenient() : server.insecureHTTPParser; // TODO(addaleax): This doesn't play well with the // `async_hooks.currentResource()` proposal, see // https://github.com/nodejs/node/pull/21313 parser.initialize( HTTPParser.REQUEST, new HTTPServerAsyncResource('HTTPINCOMINGMESSAGE', socket), server.maxHeaderSize || 0, lenient ? kLenientAll : kLenientNone, server[kConnections], ); parser.socket = socket; socket.parser = parser; // Propagate headers limit from server instance to parser if (typeof server.maxHeadersCount === 'number') { parser.maxHeaderPairs = server.maxHeadersCount << 1; } const state = { onData: null, onEnd: null, onClose: null, onDrain: null, outgoing: [], incoming: [], // `outgoingData` is an approximate amount of bytes queued through all // inactive responses. If more data than the high watermark is queued - we // need to pause TCP socket/HTTP parser, and wait until the data will be // sent to the client. outgoingData: 0, requestsCount: 0, keepAliveTimeoutSet: false }; state.onData = socketOnData.bind(undefined, server, socket, parser, state); state.onEnd = socketOnEnd.bind(undefined, server, socket, parser, state); state.onClose = socketOnClose.bind(undefined, socket, state); state.onDrain = socketOnDrain.bind(undefined, socket, state); socket.on('data', state.onData); socket.on('error', socketOnError); socket.on('end', state.onEnd); socket.on('close', state.onClose); socket.on('drain', state.onDrain); parser.onIncoming = parserOnIncoming.bind(undefined, server, socket, state); // We are consuming socket, so it won't get any actual data socket.on('resume', onSocketResume); socket.on('pause', onSocketPause); // Overrides to unconsume on `data`, `readable` listeners socket.on = generateSocketListenerWrapper('on'); socket.addListener = generateSocketListenerWrapper('addListener'); socket.prependListener = generateSocketListenerWrapper('prependListener'); socket.setEncoding = socketSetEncoding; // We only consume the socket if it has never been consumed before. if (socket._handle && socket._handle.isStreamBase && !socket._handle._consumed) { parser._consumed = true; socket._handle._consumed = true; parser.consume(socket._handle); } parser[kOnExecute] = onParserExecute.bind(undefined, server, socket, parser, state); parser[kOnTimeout] = onParserTimeout.bind(undefined, server, socket); socket._paused = false; } function socketSetEncoding() { throw new ERR_HTTP_SOCKET_ENCODING(); } function updateOutgoingData(socket, state, delta) { state.outgoingData += delta; socketOnDrain(socket, state); } function socketOnDrain(socket, state) { const needPause = state.outgoingData > socket.writableHighWaterMark; // If we previously paused, then start reading again. if (socket._paused && !needPause) { socket._paused = false; if (socket.parser) socket.parser.resume(); socket.resume(); } const msg = socket._httpMessage; if (msg && !msg.finished && msg[kNeedDrain]) { msg[kNeedDrain] = false; msg.emit('drain'); } } function socketOnTimeout() { const req = this.parser && this.parser.incoming; const reqTimeout = req && !req.complete && req.emit('timeout', this); const res = this._httpMessage; const resTimeout = res && res.emit('timeout', this); const serverTimeout = this.server.emit('timeout', this); if (!reqTimeout && !resTimeout && !serverTimeout) this.destroy(); } function socketOnClose(socket, state) { debug('server socket close'); freeParser(socket.parser, null, socket); abortIncoming(state.incoming); } function abortIncoming(incoming) { while (incoming.length) { const req = incoming.shift(); req.destroy(connResetException('aborted')); } // Abort socket._httpMessage ? } function socketOnEnd(server, socket, parser, state) { const ret = parser.finish(); if (ret instanceof Error) { debug('parse error'); // socketOnError has additional logic and will call socket.destroy(err). socketOnError.call(socket, ret); } else if (!server.httpAllowHalfOpen) { socket.end(); } else if (state.outgoing.length) { state.outgoing[state.outgoing.length - 1]._last = true; } else if (socket._httpMessage) { socket._httpMessage._last = true; } else { socket.end(); } } function socketOnData(server, socket, parser, state, d) { assert(!socket._paused); debug('SERVER socketOnData %d', d.length); const ret = parser.execute(d); onParserExecuteCommon(server, socket, parser, state, ret, d); } function onRequestTimeout(socket) { // socketOnError has additional logic and will call socket.destroy(err). socketOnError.call(socket, new ERR_HTTP_REQUEST_TIMEOUT()); } function onParserExecute(server, socket, parser, state, ret) { // When underlying `net.Socket` instance is consumed - no // `data` events are emitted, and thus `socket.setTimeout` fires the // callback even if the data is constantly flowing into the socket. // See, https://github.com/nodejs/node/commit/ec2822adaad76b126b5cccdeaa1addf2376c9aa6 socket._unrefTimer(); debug('SERVER socketOnParserExecute %d', ret); onParserExecuteCommon(server, socket, parser, state, ret, undefined); } function onParserTimeout(server, socket) { const serverTimeout = server.emit('timeout', socket); if (!serverTimeout) socket.destroy(); } const noop = () => {}; const badRequestResponse = Buffer.from( `HTTP/1.1 400 ${STATUS_CODES[400]}\r\n` + 'Connection: close\r\n\r\n', 'ascii' ); const requestTimeoutResponse = Buffer.from( `HTTP/1.1 408 ${STATUS_CODES[408]}\r\n` + 'Connection: close\r\n\r\n', 'ascii' ); const requestHeaderFieldsTooLargeResponse = Buffer.from( `HTTP/1.1 431 ${STATUS_CODES[431]}\r\n` + 'Connection: close\r\n\r\n', 'ascii' ); function socketOnError(e) { // Ignore further errors this.removeListener('error', socketOnError); if (this.listenerCount('error') === 0) { this.on('error', noop); } if (!this.server.emit('clientError', e, this)) { if (this.writable && this.bytesWritten === 0) { let response; switch (e.code) { case 'HPE_HEADER_OVERFLOW': response = requestHeaderFieldsTooLargeResponse; break; case 'ERR_HTTP_REQUEST_TIMEOUT': response = requestTimeoutResponse; break; default: response = badRequestResponse; break; } this.write(response); } this.destroy(e); } } function onParserExecuteCommon(server, socket, parser, state, ret, d) { resetSocketTimeout(server, socket, state); if (ret instanceof Error) { prepareError(ret, parser, d); debug('parse error', ret); socketOnError.call(socket, ret); } else if (parser.incoming && parser.incoming.upgrade) { // Upgrade or CONNECT const req = parser.incoming; debug('SERVER upgrade or connect', req.method); if (!d) d = parser.getCurrentBuffer(); socket.removeListener('data', state.onData); socket.removeListener('end', state.onEnd); socket.removeListener('close', state.onClose); socket.removeListener('drain', state.onDrain); socket.removeListener('error', socketOnError); socket.removeListener('timeout', socketOnTimeout); unconsume(parser, socket); parser.finish(); freeParser(parser, req, socket); parser = null; const eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; if (eventName === 'upgrade' || server.listenerCount(eventName) > 0) { debug('SERVER have listener for %s', eventName); const bodyHead = d.slice(ret, d.length); socket.readableFlowing = null; server.emit(eventName, req, socket, bodyHead); } else { // Got CONNECT method, but have no handler. socket.destroy(); } } else if (parser.incoming && parser.incoming.method === 'PRI') { debug('SERVER got PRI request'); socket.destroy(); } if (socket._paused && socket.parser) { // onIncoming paused the socket, we should pause the parser as well debug('pause parser'); socket.parser.pause(); } } function clearIncoming(req) { req = req || this; const parser = req.socket && req.socket.parser; // Reset the .incoming property so that the request object can be gc'ed. if (parser && parser.incoming === req) { if (req.readableEnded) { parser.incoming = null; } else { req.on('end', clearIncoming); } } } function resOnFinish(req, res, socket, state, server) { if (onResponseFinishChannel.hasSubscribers) { onResponseFinishChannel.publish({ request: req, response: res, socket, server }); } // Usually the first incoming element should be our request. it may // be that in the case abortIncoming() was called that the incoming // array will be empty. assert(state.incoming.length === 0 || state.incoming[0] === req); state.incoming.shift(); // If the user never called req.read(), and didn't pipe() or // .resume() or .on('data'), then we call req._dump() so that the // bytes will be pulled off the wire. if (!req._consuming && !req._readableState.resumeScheduled) req._dump(); res.detachSocket(socket); clearIncoming(req); process.nextTick(emitCloseNT, res); if (res._last) { if (typeof socket.destroySoon === 'function') { socket.destroySoon(); } else { socket.end(); } } else if (state.outgoing.length === 0) { if (server.keepAliveTimeout && typeof socket.setTimeout === 'function') { socket.setTimeout(server.keepAliveTimeout); state.keepAliveTimeoutSet = true; } } else { // Start sending the next message const m = state.outgoing.shift(); if (m) { m.assignSocket(socket); } } } function emitCloseNT(self) { if (!self._closed) { self.destroyed = true; self._closed = true; self.emit('close'); } } // The following callback is issued after the headers have been read on a // new message. In this callback we setup the response object and pass it // to the user. function parserOnIncoming(server, socket, state, req, keepAlive) { resetSocketTimeout(server, socket, state); if (req.upgrade) { req.upgrade = req.method === 'CONNECT' || server.listenerCount('upgrade') > 0; if (req.upgrade) return 2; } state.incoming.push(req); // If the writable end isn't consuming, then stop reading // so that we don't become overwhelmed by a flood of // pipelined requests that may never be resolved. if (!socket._paused) { const ws = socket._writableState; if (ws.needDrain || state.outgoingData >= socket.writableHighWaterMark) { socket._paused = true; // We also need to pause the parser, but don't do that until after // the call to execute, because we may still be processing the last // chunk. socket.pause(); } } const res = new server[kServerResponse](req); res._keepAliveTimeout = server.keepAliveTimeout; res._onPendingData = updateOutgoingData.bind(undefined, socket, state); res.shouldKeepAlive = keepAlive; res[kUniqueHeaders] = server[kUniqueHeaders]; DTRACE_HTTP_SERVER_REQUEST(req, socket); if (onRequestStartChannel.hasSubscribers) { onRequestStartChannel.publish({ request: req, response: res, socket, server }); } if (socket._httpMessage) { // There are already pending outgoing res, append. state.outgoing.push(res); } else { res.assignSocket(socket); } // When we're finished writing the response, check if this is the last // response, if so destroy the socket. res.on('finish', resOnFinish.bind(undefined, req, res, socket, state, server)); let handled = false; if (req.httpVersionMajor === 1 && req.httpVersionMinor === 1) { const isRequestsLimitSet = ( typeof server.maxRequestsPerSocket === 'number' && server.maxRequestsPerSocket > 0 ); if (isRequestsLimitSet) { state.requestsCount++; res.maxRequestsOnConnectionReached = ( server.maxRequestsPerSocket <= state.requestsCount); } if (isRequestsLimitSet && (server.maxRequestsPerSocket < state.requestsCount)) { handled = true; res.writeHead(503); res.end(); } else if (req.headers.expect !== undefined) { handled = true; if (RegExpPrototypeExec(continueExpression, req.headers.expect) !== null) { res._expect_continue = true; if (server.listenerCount('checkContinue') > 0) { server.emit('checkContinue', req, res); } else { res.writeContinue(); server.emit('request', req, res); } } else if (server.listenerCount('checkExpectation') > 0) { server.emit('checkExpectation', req, res); } else { res.writeHead(417); res.end(); } } } if (!handled) { server.emit('request', req, res); } return 0; // No special treatment. } function resetSocketTimeout(server, socket, state) { if (!state.keepAliveTimeoutSet) return; socket.setTimeout(server.timeout || 0); state.keepAliveTimeoutSet = false; } function onSocketResume() { // It may seem that the socket is resumed, but this is an enemy's trick to // deceive us! `resume` is emitted asynchronously, and may be called from // `incoming.readStart()`. Stop the socket again here, just to preserve the // state. // // We don't care about stream semantics for the consumed socket anyway. if (this._paused) { this.pause(); return; } if (this._handle && !this._handle.reading) { this._handle.reading = true; this._handle.readStart(); } } function onSocketPause() { if (this._handle && this._handle.reading) { this._handle.reading = false; this._handle.readStop(); } } function unconsume(parser, socket) { if (socket._handle) { if (parser._consumed) parser.unconsume(); parser._consumed = false; socket.removeListener('pause', onSocketPause); socket.removeListener('resume', onSocketResume); } } function generateSocketListenerWrapper(originalFnName) { return function socketListenerWrap(ev, fn) { const res = net.Socket.prototype[originalFnName].call(this, ev, fn); if (!this.parser) { this.on = net.Socket.prototype.on; this.addListener = net.Socket.prototype.addListener; this.prependListener = net.Socket.prototype.prependListener; return res; } if (ev === 'data' || ev === 'readable') unconsume(this.parser, this); return res; }; } module.exports = { STATUS_CODES, Server, ServerResponse, setupConnectionsTracking, storeHTTPOptions, _connectionListener: connectionListener, kServerResponse }; |