• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23
24const {
25  ArrayIsArray,
26  Error,
27  ObjectKeys,
28  ObjectSetPrototypeOf,
29  Symbol,
30  SymbolFor,
31} = primordials;
32
33const net = require('net');
34const EE = require('events');
35const assert = require('internal/assert');
36const {
37  parsers,
38  freeParser,
39  debug,
40  CRLF,
41  continueExpression,
42  chunkExpression,
43  kIncomingMessage,
44  kRequestTimeout,
45  HTTPParser,
46  isLenient,
47  _checkInvalidHeaderChar: checkInvalidHeaderChar,
48  prepareError,
49} = require('_http_common');
50const { OutgoingMessage } = require('_http_outgoing');
51const {
52  kOutHeaders,
53  kNeedDrain,
54  emitStatistics
55} = require('internal/http');
56const {
57  defaultTriggerAsyncIdScope,
58  getOrSetAsyncId
59} = require('internal/async_hooks');
60const { IncomingMessage } = require('_http_incoming');
61const {
62  ERR_HTTP_REQUEST_TIMEOUT,
63  ERR_HTTP_HEADERS_SENT,
64  ERR_HTTP_INVALID_STATUS_CODE,
65  ERR_INVALID_ARG_TYPE,
66  ERR_INVALID_ARG_VALUE,
67  ERR_INVALID_CHAR
68} = require('internal/errors').codes;
69const {
70  validateInteger,
71  validateBoolean
72} = require('internal/validators');
73const Buffer = require('buffer').Buffer;
74const {
75  DTRACE_HTTP_SERVER_REQUEST,
76  DTRACE_HTTP_SERVER_RESPONSE
77} = require('internal/dtrace');
78const { observerCounts, constants } = internalBinding('performance');
79const { setTimeout, clearTimeout } = require('timers');
80const { NODE_PERFORMANCE_ENTRY_TYPE_HTTP } = constants;
81
82const dc = require('diagnostics_channel');
83const onRequestStartChannel = dc.channel('http.server.request.start');
84const onResponseFinishChannel = dc.channel('http.server.response.finish');
85
86const kServerResponse = Symbol('ServerResponse');
87const kServerResponseStatistics = Symbol('ServerResponseStatistics');
88
89const STATUS_CODES = {
90  100: 'Continue',                   // RFC 7231 6.2.1
91  101: 'Switching Protocols',        // RFC 7231 6.2.2
92  102: 'Processing',                 // RFC 2518 10.1 (obsoleted by RFC 4918)
93  103: 'Early Hints',                // RFC 8297 2
94  200: 'OK',                         // RFC 7231 6.3.1
95  201: 'Created',                    // RFC 7231 6.3.2
96  202: 'Accepted',                   // RFC 7231 6.3.3
97  203: 'Non-Authoritative Information', // RFC 7231 6.3.4
98  204: 'No Content',                 // RFC 7231 6.3.5
99  205: 'Reset Content',              // RFC 7231 6.3.6
100  206: 'Partial Content',            // RFC 7233 4.1
101  207: 'Multi-Status',               // RFC 4918 11.1
102  208: 'Already Reported',           // RFC 5842 7.1
103  226: 'IM Used',                    // RFC 3229 10.4.1
104  300: 'Multiple Choices',           // RFC 7231 6.4.1
105  301: 'Moved Permanently',          // RFC 7231 6.4.2
106  302: 'Found',                      // RFC 7231 6.4.3
107  303: 'See Other',                  // RFC 7231 6.4.4
108  304: 'Not Modified',               // RFC 7232 4.1
109  305: 'Use Proxy',                  // RFC 7231 6.4.5
110  307: 'Temporary Redirect',         // RFC 7231 6.4.7
111  308: 'Permanent Redirect',         // RFC 7238 3
112  400: 'Bad Request',                // RFC 7231 6.5.1
113  401: 'Unauthorized',               // RFC 7235 3.1
114  402: 'Payment Required',           // RFC 7231 6.5.2
115  403: 'Forbidden',                  // RFC 7231 6.5.3
116  404: 'Not Found',                  // RFC 7231 6.5.4
117  405: 'Method Not Allowed',         // RFC 7231 6.5.5
118  406: 'Not Acceptable',             // RFC 7231 6.5.6
119  407: 'Proxy Authentication Required', // RFC 7235 3.2
120  408: 'Request Timeout',            // RFC 7231 6.5.7
121  409: 'Conflict',                   // RFC 7231 6.5.8
122  410: 'Gone',                       // RFC 7231 6.5.9
123  411: 'Length Required',            // RFC 7231 6.5.10
124  412: 'Precondition Failed',        // RFC 7232 4.2
125  413: 'Payload Too Large',          // RFC 7231 6.5.11
126  414: 'URI Too Long',               // RFC 7231 6.5.12
127  415: 'Unsupported Media Type',     // RFC 7231 6.5.13
128  416: 'Range Not Satisfiable',      // RFC 7233 4.4
129  417: 'Expectation Failed',         // RFC 7231 6.5.14
130  418: 'I\'m a Teapot',              // RFC 7168 2.3.3
131  421: 'Misdirected Request',        // RFC 7540 9.1.2
132  422: 'Unprocessable Entity',       // RFC 4918 11.2
133  423: 'Locked',                     // RFC 4918 11.3
134  424: 'Failed Dependency',          // RFC 4918 11.4
135  425: 'Too Early',                  // RFC 8470 5.2
136  426: 'Upgrade Required',           // RFC 2817 and RFC 7231 6.5.15
137  428: 'Precondition Required',      // RFC 6585 3
138  429: 'Too Many Requests',          // RFC 6585 4
139  431: 'Request Header Fields Too Large', // RFC 6585 5
140  451: 'Unavailable For Legal Reasons', // RFC 7725 3
141  500: 'Internal Server Error',      // RFC 7231 6.6.1
142  501: 'Not Implemented',            // RFC 7231 6.6.2
143  502: 'Bad Gateway',                // RFC 7231 6.6.3
144  503: 'Service Unavailable',        // RFC 7231 6.6.4
145  504: 'Gateway Timeout',            // RFC 7231 6.6.5
146  505: 'HTTP Version Not Supported', // RFC 7231 6.6.6
147  506: 'Variant Also Negotiates',    // RFC 2295 8.1
148  507: 'Insufficient Storage',       // RFC 4918 11.5
149  508: 'Loop Detected',              // RFC 5842 7.2
150  509: 'Bandwidth Limit Exceeded',
151  510: 'Not Extended',               // RFC 2774 7
152  511: 'Network Authentication Required' // RFC 6585 6
153};
154
155const kOnMessageBegin = HTTPParser.kOnMessageBegin | 0;
156const kOnExecute = HTTPParser.kOnExecute | 0;
157const kOnTimeout = HTTPParser.kOnTimeout | 0;
158
159class HTTPServerAsyncResource {
160  constructor(type, socket) {
161    this.type = type;
162    this.socket = socket;
163  }
164}
165
166function ServerResponse(req) {
167  OutgoingMessage.call(this);
168
169  if (req.method === 'HEAD') this._hasBody = false;
170
171  this.sendDate = true;
172  this._sent100 = false;
173  this._expect_continue = false;
174
175  if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {
176    this.useChunkedEncodingByDefault = chunkExpression.test(req.headers.te);
177    this.shouldKeepAlive = false;
178  }
179
180  const httpObserverCount = observerCounts[NODE_PERFORMANCE_ENTRY_TYPE_HTTP];
181  if (httpObserverCount > 0) {
182    this[kServerResponseStatistics] = {
183      startTime: process.hrtime()
184    };
185  }
186}
187ObjectSetPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype);
188ObjectSetPrototypeOf(ServerResponse, OutgoingMessage);
189
190ServerResponse.prototype._finish = function _finish() {
191  DTRACE_HTTP_SERVER_RESPONSE(this.socket);
192  if (this[kServerResponseStatistics] !== undefined) {
193    emitStatistics(this[kServerResponseStatistics]);
194  }
195  OutgoingMessage.prototype._finish.call(this);
196};
197
198
199ServerResponse.prototype.statusCode = 200;
200ServerResponse.prototype.statusMessage = undefined;
201
202function onServerResponseClose() {
203  // EventEmitter.emit makes a copy of the 'close' listeners array before
204  // calling the listeners. detachSocket() unregisters onServerResponseClose
205  // but if detachSocket() is called, directly or indirectly, by a 'close'
206  // listener, onServerResponseClose is still in that copy of the listeners
207  // array. That is, in the example below, b still gets called even though
208  // it's been removed by a:
209  //
210  //   var EventEmitter = require('events');
211  //   var obj = new EventEmitter();
212  //   obj.on('event', a);
213  //   obj.on('event', b);
214  //   function a() { obj.removeListener('event', b) }
215  //   function b() { throw "BAM!" }
216  //   obj.emit('event');  // throws
217  //
218  // Ergo, we need to deal with stale 'close' events and handle the case
219  // where the ServerResponse object has already been deconstructed.
220  // Fortunately, that requires only a single if check. :-)
221  if (this._httpMessage) this._httpMessage.emit('close');
222}
223
224ServerResponse.prototype.assignSocket = function assignSocket(socket) {
225  assert(!socket._httpMessage);
226  socket._httpMessage = this;
227  socket.on('close', onServerResponseClose);
228  this.socket = socket;
229  this.emit('socket', socket);
230  this._flush();
231};
232
233ServerResponse.prototype.detachSocket = function detachSocket(socket) {
234  assert(socket._httpMessage === this);
235  socket.removeListener('close', onServerResponseClose);
236  socket._httpMessage = null;
237  this.socket = null;
238};
239
240ServerResponse.prototype.writeContinue = function writeContinue(cb) {
241  this._writeRaw(`HTTP/1.1 100 Continue${CRLF}${CRLF}`, 'ascii', cb);
242  this._sent100 = true;
243};
244
245ServerResponse.prototype.writeProcessing = function writeProcessing(cb) {
246  this._writeRaw(`HTTP/1.1 102 Processing${CRLF}${CRLF}`, 'ascii', cb);
247};
248
249ServerResponse.prototype._implicitHeader = function _implicitHeader() {
250  this.writeHead(this.statusCode);
251};
252
253ServerResponse.prototype.writeHead = writeHead;
254function writeHead(statusCode, reason, obj) {
255  const originalStatusCode = statusCode;
256
257  statusCode |= 0;
258  if (statusCode < 100 || statusCode > 999) {
259    throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
260  }
261
262
263  if (typeof reason === 'string') {
264    // writeHead(statusCode, reasonPhrase[, headers])
265    this.statusMessage = reason;
266  } else {
267    // writeHead(statusCode[, headers])
268    if (!this.statusMessage)
269      this.statusMessage = STATUS_CODES[statusCode] || 'unknown';
270    obj = reason;
271  }
272  this.statusCode = statusCode;
273
274  let headers;
275  if (this[kOutHeaders]) {
276    // Slow-case: when progressive API and header fields are passed.
277    let k;
278    if (ArrayIsArray(obj)) {
279      if (obj.length % 2 !== 0) {
280        throw new ERR_INVALID_ARG_VALUE('headers', obj);
281      }
282
283      for (let n = 0; n < obj.length; n += 2) {
284        k = obj[n + 0];
285        if (k) this.setHeader(k, obj[n + 1]);
286      }
287    } else if (obj) {
288      const keys = ObjectKeys(obj);
289      // Retain for(;;) loop for performance reasons
290      // Refs: https://github.com/nodejs/node/pull/30958
291      for (let i = 0; i < keys.length; i++) {
292        k = keys[i];
293        if (k) this.setHeader(k, obj[k]);
294      }
295    }
296    if (k === undefined && this._header) {
297      throw new ERR_HTTP_HEADERS_SENT('render');
298    }
299    // Only progressive api is used
300    headers = this[kOutHeaders];
301  } else {
302    // Only writeHead() called
303    headers = obj;
304  }
305
306  if (checkInvalidHeaderChar(this.statusMessage))
307    throw new ERR_INVALID_CHAR('statusMessage');
308
309  const statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}${CRLF}`;
310
311  if (statusCode === 204 || statusCode === 304 ||
312      (statusCode >= 100 && statusCode <= 199)) {
313    // RFC 2616, 10.2.5:
314    // The 204 response MUST NOT include a message-body, and thus is always
315    // terminated by the first empty line after the header fields.
316    // RFC 2616, 10.3.5:
317    // The 304 response MUST NOT contain a message-body, and thus is always
318    // terminated by the first empty line after the header fields.
319    // RFC 2616, 10.1 Informational 1xx:
320    // This class of status code indicates a provisional response,
321    // consisting only of the Status-Line and optional headers, and is
322    // terminated by an empty line.
323    this._hasBody = false;
324  }
325
326  // Don't keep alive connections where the client expects 100 Continue
327  // but we sent a final status; they may put extra bytes on the wire.
328  if (this._expect_continue && !this._sent100) {
329    this.shouldKeepAlive = false;
330  }
331
332  this._storeHeader(statusLine, headers);
333
334  return this;
335}
336
337// Docs-only deprecated: DEP0063
338ServerResponse.prototype.writeHeader = ServerResponse.prototype.writeHead;
339
340function storeHTTPOptions(options) {
341  this[kIncomingMessage] = options.IncomingMessage || IncomingMessage;
342  this[kServerResponse] = options.ServerResponse || ServerResponse;
343
344  const maxHeaderSize = options.maxHeaderSize;
345  if (maxHeaderSize !== undefined)
346    validateInteger(maxHeaderSize, 'maxHeaderSize', 0);
347  this.maxHeaderSize = maxHeaderSize;
348
349  const insecureHTTPParser = options.insecureHTTPParser;
350  if (insecureHTTPParser !== undefined)
351    validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser');
352  this.insecureHTTPParser = insecureHTTPParser;
353}
354
355function Server(options, requestListener) {
356  if (!(this instanceof Server)) return new Server(options, requestListener);
357
358  if (typeof options === 'function') {
359    requestListener = options;
360    options = {};
361  } else if (options == null || typeof options === 'object') {
362    options = { ...options };
363  } else {
364    throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
365  }
366
367  storeHTTPOptions.call(this, options);
368  net.Server.call(this, { allowHalfOpen: true });
369
370  if (requestListener) {
371    this.on('request', requestListener);
372  }
373
374  // Similar option to this. Too lazy to write my own docs.
375  // http://www.squid-cache.org/Doc/config/half_closed_clients/
376  // https://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F
377  this.httpAllowHalfOpen = false;
378
379  this.on('connection', connectionListener);
380
381  this.timeout = 0;
382  this.keepAliveTimeout = 5000;
383  this.maxHeadersCount = null;
384  this.headersTimeout = 60 * 1000; // 60 seconds
385  this.requestTimeout = 0;
386}
387ObjectSetPrototypeOf(Server.prototype, net.Server.prototype);
388ObjectSetPrototypeOf(Server, net.Server);
389
390
391Server.prototype.setTimeout = function setTimeout(msecs, callback) {
392  this.timeout = msecs;
393  if (callback)
394    this.on('timeout', callback);
395  return this;
396};
397
398Server.prototype[EE.captureRejectionSymbol] = function(err, event, ...args) {
399  switch (event) {
400    case 'request':
401      const { 1: res } = args;
402      if (!res.headersSent && !res.writableEnded) {
403        // Don't leak headers.
404        const names = res.getHeaderNames();
405        for (let i = 0; i < names.length; i++) {
406          res.removeHeader(names[i]);
407        }
408        res.statusCode = 500;
409        res.end(STATUS_CODES[500]);
410      } else {
411        res.destroy();
412      }
413      break;
414    default:
415      net.Server.prototype[SymbolFor('nodejs.rejection')]
416        .apply(this, arguments);
417  }
418};
419
420function connectionListener(socket) {
421  defaultTriggerAsyncIdScope(
422    getOrSetAsyncId(socket), connectionListenerInternal, this, socket
423  );
424}
425
426function connectionListenerInternal(server, socket) {
427  debug('SERVER new http connection');
428
429  // Ensure that the server property of the socket is correctly set.
430  // See https://github.com/nodejs/node/issues/13435
431  socket.server = server;
432
433  // If the user has added a listener to the server,
434  // request, or response, then it's their responsibility.
435  // otherwise, destroy on timeout by default
436  if (server.timeout && typeof socket.setTimeout === 'function')
437    socket.setTimeout(server.timeout);
438  socket.on('timeout', socketOnTimeout);
439
440  const parser = parsers.alloc();
441
442  // TODO(addaleax): This doesn't play well with the
443  // `async_hooks.currentResource()` proposal, see
444  // https://github.com/nodejs/node/pull/21313
445  parser.initialize(
446    HTTPParser.REQUEST,
447    new HTTPServerAsyncResource('HTTPINCOMINGMESSAGE', socket),
448    server.maxHeaderSize || 0,
449    server.insecureHTTPParser === undefined ?
450      isLenient() : server.insecureHTTPParser,
451    server.headersTimeout || 0,
452  );
453  parser.socket = socket;
454  socket.parser = parser;
455
456  // Propagate headers limit from server instance to parser
457  if (typeof server.maxHeadersCount === 'number') {
458    parser.maxHeaderPairs = server.maxHeadersCount << 1;
459  }
460
461  const state = {
462    onData: null,
463    onEnd: null,
464    onClose: null,
465    onDrain: null,
466    outgoing: [],
467    incoming: [],
468    // `outgoingData` is an approximate amount of bytes queued through all
469    // inactive responses. If more data than the high watermark is queued - we
470    // need to pause TCP socket/HTTP parser, and wait until the data will be
471    // sent to the client.
472    outgoingData: 0,
473    keepAliveTimeoutSet: false
474  };
475  state.onData = socketOnData.bind(undefined, server, socket, parser, state);
476  state.onEnd = socketOnEnd.bind(undefined, server, socket, parser, state);
477  state.onClose = socketOnClose.bind(undefined, socket, state);
478  state.onDrain = socketOnDrain.bind(undefined, socket, state);
479  socket.on('data', state.onData);
480  socket.on('error', socketOnError);
481  socket.on('end', state.onEnd);
482  socket.on('close', state.onClose);
483  socket.on('drain', state.onDrain);
484  parser.onIncoming = parserOnIncoming.bind(undefined, server, socket, state);
485
486  // We are consuming socket, so it won't get any actual data
487  socket.on('resume', onSocketResume);
488  socket.on('pause', onSocketPause);
489
490  // Overrides to unconsume on `data`, `readable` listeners
491  socket.on = generateSocketListenerWrapper('on');
492  socket.addListener = generateSocketListenerWrapper('addListener');
493  socket.prependListener = generateSocketListenerWrapper('prependListener');
494
495  // We only consume the socket if it has never been consumed before.
496  if (socket._handle && socket._handle.isStreamBase &&
497      !socket._handle._consumed) {
498    parser._consumed = true;
499    socket._handle._consumed = true;
500    parser.consume(socket._handle);
501  }
502  parser[kOnExecute] =
503    onParserExecute.bind(undefined, server, socket, parser, state);
504
505  parser[kOnTimeout] =
506    onParserTimeout.bind(undefined, server, socket);
507
508  // When receiving new requests on the same socket (pipelining or keep alive)
509  // make sure the requestTimeout is active.
510  parser[kOnMessageBegin] =
511    setRequestTimeout.bind(undefined, server, socket);
512
513  // This protects from DOS attack where an attacker establish the connection
514  // without sending any data on applications where server.timeout is left to
515  // the default value of zero.
516  setRequestTimeout(server, socket);
517
518  socket._paused = false;
519}
520
521function updateOutgoingData(socket, state, delta) {
522  state.outgoingData += delta;
523  socketOnDrain(socket, state);
524}
525
526function socketOnDrain(socket, state) {
527  const needPause = state.outgoingData > socket.writableHighWaterMark;
528
529  // If we previously paused, then start reading again.
530  if (socket._paused && !needPause) {
531    socket._paused = false;
532    if (socket.parser)
533      socket.parser.resume();
534    socket.resume();
535  }
536
537  const msg = socket._httpMessage;
538  if (msg && !msg.finished && msg[kNeedDrain]) {
539    msg[kNeedDrain] = false;
540    msg.emit('drain');
541  }
542}
543
544function socketOnTimeout() {
545  const req = this.parser && this.parser.incoming;
546  const reqTimeout = req && !req.complete && req.emit('timeout', this);
547  const res = this._httpMessage;
548  const resTimeout = res && res.emit('timeout', this);
549  const serverTimeout = this.server.emit('timeout', this);
550
551  if (!reqTimeout && !resTimeout && !serverTimeout)
552    this.destroy();
553}
554
555function socketOnClose(socket, state) {
556  debug('server socket close');
557  // Mark this parser as reusable
558  if (socket.parser) {
559    freeParser(socket.parser, null, socket);
560  }
561
562  abortIncoming(state.incoming);
563}
564
565function abortIncoming(incoming) {
566  while (incoming.length) {
567    const req = incoming.shift();
568    req.aborted = true;
569    req.emit('aborted');
570    req.emit('close');
571  }
572  // Abort socket._httpMessage ?
573}
574
575function socketOnEnd(server, socket, parser, state) {
576  const ret = parser.finish();
577
578  if (ret instanceof Error) {
579    debug('parse error');
580    socketOnError.call(socket, ret);
581    return;
582  }
583
584  if (!server.httpAllowHalfOpen) {
585    abortIncoming(state.incoming);
586    if (socket.writable) socket.end();
587  } else if (state.outgoing.length) {
588    state.outgoing[state.outgoing.length - 1]._last = true;
589  } else if (socket._httpMessage) {
590    socket._httpMessage._last = true;
591  } else if (socket.writable) {
592    socket.end();
593  }
594}
595
596function socketOnData(server, socket, parser, state, d) {
597  assert(!socket._paused);
598  debug('SERVER socketOnData %d', d.length);
599
600  const ret = parser.execute(d);
601  onParserExecuteCommon(server, socket, parser, state, ret, d);
602}
603
604function onRequestTimeout(socket) {
605  socket[kRequestTimeout] = undefined;
606  socketOnError.call(socket, new ERR_HTTP_REQUEST_TIMEOUT());
607}
608
609function onParserExecute(server, socket, parser, state, ret) {
610  // When underlying `net.Socket` instance is consumed - no
611  // `data` events are emitted, and thus `socket.setTimeout` fires the
612  // callback even if the data is constantly flowing into the socket.
613  // See, https://github.com/nodejs/node/commit/ec2822adaad76b126b5cccdeaa1addf2376c9aa6
614  socket._unrefTimer();
615  debug('SERVER socketOnParserExecute %d', ret);
616  onParserExecuteCommon(server, socket, parser, state, ret, undefined);
617}
618
619function onParserTimeout(server, socket) {
620  const serverTimeout = server.emit('timeout', socket);
621
622  if (!serverTimeout)
623    socket.destroy();
624}
625
626const noop = () => {};
627const badRequestResponse = Buffer.from(
628  `HTTP/1.1 400 ${STATUS_CODES[400]}${CRLF}` +
629  `Connection: close${CRLF}${CRLF}`, 'ascii'
630);
631const requestTimeoutResponse = Buffer.from(
632  `HTTP/1.1 408 ${STATUS_CODES[408]}${CRLF}` +
633  `Connection: close${CRLF}${CRLF}`, 'ascii'
634);
635const requestHeaderFieldsTooLargeResponse = Buffer.from(
636  `HTTP/1.1 431 ${STATUS_CODES[431]}${CRLF}` +
637  `Connection: close${CRLF}${CRLF}`, 'ascii'
638);
639function socketOnError(e) {
640  // Ignore further errors
641  this.removeListener('error', socketOnError);
642  this.on('error', noop);
643
644  if (!this.server.emit('clientError', e, this)) {
645    if (this.writable && this.bytesWritten === 0) {
646      let response;
647
648      switch (e.code) {
649        case 'HPE_HEADER_OVERFLOW':
650          response = requestHeaderFieldsTooLargeResponse;
651          break;
652        case 'ERR_HTTP_REQUEST_TIMEOUT':
653          response = requestTimeoutResponse;
654          break;
655        default:
656          response = badRequestResponse;
657          break;
658      }
659
660      this.write(response);
661    }
662    this.destroy(e);
663  }
664}
665
666function onParserExecuteCommon(server, socket, parser, state, ret, d) {
667  resetSocketTimeout(server, socket, state);
668
669  if (ret instanceof Error) {
670    prepareError(ret, parser, d);
671    ret.rawPacket = d || parser.getCurrentBuffer();
672    debug('parse error', ret);
673    socketOnError.call(socket, ret);
674  } else if (parser.incoming && parser.incoming.upgrade) {
675    // Upgrade or CONNECT
676    const req = parser.incoming;
677    debug('SERVER upgrade or connect', req.method);
678
679    if (!d)
680      d = parser.getCurrentBuffer();
681
682    socket.removeListener('data', state.onData);
683    socket.removeListener('end', state.onEnd);
684    socket.removeListener('close', state.onClose);
685    socket.removeListener('drain', state.onDrain);
686    socket.removeListener('error', socketOnError);
687    socket.removeListener('timeout', socketOnTimeout);
688    unconsume(parser, socket);
689    parser.finish();
690    freeParser(parser, req, socket);
691    parser = null;
692
693    const eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade';
694    if (eventName === 'upgrade' || server.listenerCount(eventName) > 0) {
695      debug('SERVER have listener for %s', eventName);
696      const bodyHead = d.slice(ret, d.length);
697
698      socket.readableFlowing = null;
699
700      // Clear the requestTimeout after upgrading the connection.
701      clearRequestTimeout(req);
702
703      server.emit(eventName, req, socket, bodyHead);
704    } else {
705      // Got CONNECT method, but have no handler.
706      socket.destroy();
707    }
708  } else {
709    // When receiving new requests on the same socket (pipelining or keep alive)
710    // make sure the requestTimeout is active.
711    parser[kOnMessageBegin] =
712      setRequestTimeout.bind(undefined, server, socket);
713  }
714
715  if (socket._paused && socket.parser) {
716    // onIncoming paused the socket, we should pause the parser as well
717    debug('pause parser');
718    socket.parser.pause();
719  }
720}
721
722function clearIncoming(req) {
723  req = req || this;
724  const parser = req.socket && req.socket.parser;
725  // Reset the .incoming property so that the request object can be gc'ed.
726  if (parser && parser.incoming === req) {
727    if (req.readableEnded) {
728      parser.incoming = null;
729      req.emit('close');
730    } else {
731      req.on('end', clearIncoming);
732    }
733  } else {
734    req.emit('close');
735  }
736}
737
738function setRequestTimeout(server, socket) {
739  // Set the request timeout handler.
740  if (
741    !socket[kRequestTimeout] &&
742    server.requestTimeout && server.requestTimeout > 0
743  ) {
744    debug('requestTimeout timer set');
745    socket[kRequestTimeout] =
746      setTimeout(onRequestTimeout, server.requestTimeout, socket).unref();
747  }
748}
749
750function clearRequestTimeout(req) {
751  if (!req) {
752    req = this;
753  }
754
755  if (!req[kRequestTimeout]) {
756    return;
757  }
758
759  debug('requestTimeout timer cleared');
760  clearTimeout(req[kRequestTimeout]);
761  req[kRequestTimeout] = undefined;
762}
763
764function resOnFinish(req, res, socket, state, server) {
765  if (onResponseFinishChannel.hasSubscribers) {
766    onResponseFinishChannel.publish({
767      request: req,
768      response: res,
769      socket,
770      server
771    });
772  }
773
774  // Usually the first incoming element should be our request.  it may
775  // be that in the case abortIncoming() was called that the incoming
776  // array will be empty.
777  assert(state.incoming.length === 0 || state.incoming[0] === req);
778
779  state.incoming.shift();
780
781  // If the user never called req.read(), and didn't pipe() or
782  // .resume() or .on('data'), then we call req._dump() so that the
783  // bytes will be pulled off the wire.
784  if (!req._consuming && !req._readableState.resumeScheduled)
785    req._dump();
786
787  // Make sure the requestTimeout is cleared before finishing.
788  // This might occur if the application has sent a response
789  // without consuming the request body, which would have already
790  // cleared the timer.
791  // clearRequestTimeout can be executed even if the timer is not active,
792  // so this is safe.
793  clearRequestTimeout(req);
794
795  res.detachSocket(socket);
796  clearIncoming(req);
797  process.nextTick(emitCloseNT, res);
798
799  if (res._last) {
800    if (typeof socket.destroySoon === 'function') {
801      socket.destroySoon();
802    } else {
803      socket.end();
804    }
805  } else if (state.outgoing.length === 0) {
806    if (server.keepAliveTimeout && typeof socket.setTimeout === 'function') {
807      socket.setTimeout(server.keepAliveTimeout);
808      state.keepAliveTimeoutSet = true;
809    }
810  } else {
811    // Start sending the next message
812    const m = state.outgoing.shift();
813    if (m) {
814      m.assignSocket(socket);
815    }
816  }
817}
818
819function emitCloseNT(self) {
820  self.emit('close');
821}
822
823// The following callback is issued after the headers have been read on a
824// new message. In this callback we setup the response object and pass it
825// to the user.
826function parserOnIncoming(server, socket, state, req, keepAlive) {
827  resetSocketTimeout(server, socket, state);
828
829  if (req.upgrade) {
830    req.upgrade = req.method === 'CONNECT' ||
831                  server.listenerCount('upgrade') > 0;
832    if (req.upgrade)
833      return 2;
834  }
835
836  state.incoming.push(req);
837
838  // If the writable end isn't consuming, then stop reading
839  // so that we don't become overwhelmed by a flood of
840  // pipelined requests that may never be resolved.
841  if (!socket._paused) {
842    const ws = socket._writableState;
843    if (ws.needDrain || state.outgoingData >= socket.writableHighWaterMark) {
844      socket._paused = true;
845      // We also need to pause the parser, but don't do that until after
846      // the call to execute, because we may still be processing the last
847      // chunk.
848      socket.pause();
849    }
850  }
851
852  const res = new server[kServerResponse](req);
853  res._keepAliveTimeout = server.keepAliveTimeout;
854  res._onPendingData = updateOutgoingData.bind(undefined, socket, state);
855
856  res.shouldKeepAlive = keepAlive;
857  DTRACE_HTTP_SERVER_REQUEST(req, socket);
858
859  if (onRequestStartChannel.hasSubscribers) {
860    onRequestStartChannel.publish({
861      request: req,
862      response: res,
863      socket,
864      server
865    });
866  }
867
868  if (socket._httpMessage) {
869    // There are already pending outgoing res, append.
870    state.outgoing.push(res);
871  } else {
872    res.assignSocket(socket);
873  }
874
875  // When we're finished writing the response, check if this is the last
876  // response, if so destroy the socket.
877  res.on('finish',
878         resOnFinish.bind(undefined, req, res, socket, state, server));
879
880  if (req.headers.expect !== undefined &&
881      (req.httpVersionMajor === 1 && req.httpVersionMinor === 1)) {
882    if (continueExpression.test(req.headers.expect)) {
883      res._expect_continue = true;
884
885      if (server.listenerCount('checkContinue') > 0) {
886        server.emit('checkContinue', req, res);
887      } else {
888        res.writeContinue();
889        server.emit('request', req, res);
890      }
891    } else if (server.listenerCount('checkExpectation') > 0) {
892      server.emit('checkExpectation', req, res);
893    } else {
894      res.writeHead(417);
895      res.end();
896    }
897  } else {
898    req.on('end', clearRequestTimeout);
899
900    server.emit('request', req, res);
901  }
902  return 0;  // No special treatment.
903}
904
905function resetSocketTimeout(server, socket, state) {
906  if (!state.keepAliveTimeoutSet)
907    return;
908
909  socket.setTimeout(server.timeout || 0);
910  state.keepAliveTimeoutSet = false;
911}
912
913function onSocketResume() {
914  // It may seem that the socket is resumed, but this is an enemy's trick to
915  // deceive us! `resume` is emitted asynchronously, and may be called from
916  // `incoming.readStart()`. Stop the socket again here, just to preserve the
917  // state.
918  //
919  // We don't care about stream semantics for the consumed socket anyway.
920  if (this._paused) {
921    this.pause();
922    return;
923  }
924
925  if (this._handle && !this._handle.reading) {
926    this._handle.reading = true;
927    this._handle.readStart();
928  }
929}
930
931function onSocketPause() {
932  if (this._handle && this._handle.reading) {
933    this._handle.reading = false;
934    this._handle.readStop();
935  }
936}
937
938function unconsume(parser, socket) {
939  if (socket._handle) {
940    if (parser._consumed)
941      parser.unconsume();
942    parser._consumed = false;
943    socket.removeListener('pause', onSocketPause);
944    socket.removeListener('resume', onSocketResume);
945  }
946}
947
948function generateSocketListenerWrapper(originalFnName) {
949  return function socketListenerWrap(ev, fn) {
950    const res = net.Socket.prototype[originalFnName].call(this, ev, fn);
951    if (!this.parser) {
952      this.on = net.Socket.prototype.on;
953      this.addListener = net.Socket.prototype.addListener;
954      this.prependListener = net.Socket.prototype.prependListener;
955      return res;
956    }
957
958    if (ev === 'data' || ev === 'readable')
959      unconsume(this.parser, this);
960
961    return res;
962  };
963}
964
965module.exports = {
966  STATUS_CODES,
967  Server,
968  ServerResponse,
969  storeHTTPOptions,
970  _connectionListener: connectionListener,
971  kServerResponse
972};
973