Code coverage report for lib/_http_outgoing.js

Statements: 96.48% (329 / 341)      Branches: 95.15% (196 / 206)      Functions: 92.59% (25 / 27)      Lines: 96.72% (324 / 335)      Ignored: none     

All files » lib/ » _http_outgoing.js
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    173 173 173 173 173   173 173 173   173 173 173 173 173 173 173   173               173 173 3058 135 135 135 135   3058   173 14       173 3871   3871 3871 3871   3871   3871 3871 3871 3871 3871 3871   3871 3871 3871   3871 3871   3871 3871 3871 3871 3871   173     173     173 8 8   8 2       6   8             173 41 35   6             173       26005 3824     2506   1318 1318 1318   3824   26005       173 26006 6 6     26006 2668 2664 2668     23338 23338         22536 22536 1316 1316 1316 1316 1316       1316 1316 1316       22536 802     21     781         173 781 781 781 781       173     3824                   3824 3337 3337 3337   3337 16857 16857 83 83   16774 16774     16857 4 9     16853           3824 3058                           3824 3824   2   2 2       3824 1 1 3823 3602       3602 1639   1963 1963       3824   1367   5 1362 730   632     233   399 398 398         1         3824 3824       3824     173     16862 5   16862   16862 222 222 206   16     16640 7 7   16633 2451 14182 2 14180 1 14179 1         173 8142 2 8140 2 8138     8138 1996   8138 8138 8138   8138 1336       173 2121 1     2120   1494 1494       173 15 1     14       14   14 7 7 3   14 7 7         173 1996       1996 1996   1995 1995 1995   1995 8131 8131   1995       173     2       173 8637 1 1   1     8636 27     8636           8636 1           8635   8622 8622 5949       1423 1423 1423     4526 1026   3500   4526 4523 4523   4526 4526 4526 4526     2673     8622 8622       173 1 1       173 4523 4523       173 2 2 2 2 2 8 8 8 8           8         173     173 3806     3806 2 2     3806 1     3805 7     3798 173 3780     3798 4   3798 2170 1431 216   1215   739   2170     3798 1   1     3798 2947   3798 3798   2969     3798 379     3419     3798 2947   3798       3798 3798 3050     3798       173 3792 3792                                             173 3847 3847   3847   3828 3828 751 751 751 751 771       751 751 751     3828   742 3086   9           173 3   2 2       173 2        
(function () { 'use strict';
 
const assert = require('assert').ok;
const Stream = require('stream');
const timers = require('timers');
const util = require('util');
const common = require('_http_common');
 
const CRLF = common.CRLF;
const chunkExpression = common.chunkExpression;
const debug = common.debug;
 
const connectionExpression = /^Connection$/i;
const transferEncodingExpression = /^Transfer-Encoding$/i;
const closeExpression = /close/i;
const contentLengthExpression = /^Content-Length$/i;
const dateExpression = /^Date$/i;
const expectExpression = /^Expect$/i;
const trailerExpression = /^Trailer$/i;
 
const automaticHeaders = {
  connection: true,
  'content-length': true,
  'transfer-encoding': true,
  date: true
};
 
 
var dateCache;
function utcDate() {
  if (!dateCache) {
    var d = new Date();
    dateCache = d.toUTCString();
    timers.enroll(utcDate, 1000 - d.getMilliseconds());
    timers._unrefActive(utcDate);
  }
  return dateCache;
}
utcDate._onTimeout = function() {
  dateCache = undefined;
};
 
 
function OutgoingMessage() {
  Stream.call(this);
 
  this.output = [];
  this.outputEncodings = [];
  this.outputCallbacks = [];
 
  this.writable = true;
 
  this._last = false;
  this.chunkedEncoding = false;
  this.shouldKeepAlive = true;
  this.useChunkedEncodingByDefault = true;
  this.sendDate = false;
  this._removedHeader = {};
 
  this._contentLength = null;
  this._hasBody = true;
  this._trailer = '';
 
  this.finished = false;
  this._headerSent = false;
 
  this.socket = null;
  this.connection = null;
  this._header = null;
  this._headers = null;
  this._headerNames = {};
}
util.inherits(OutgoingMessage, Stream);
 
 
exports.OutgoingMessage = OutgoingMessage;
 
 
OutgoingMessage.prototype.setTimeout = function(msecs, callback) {
  Eif (callback)
    this.on('timeout', callback);
 
  if (!this.socket) {
    this.once('socket', function(socket) {
      socket.setTimeout(msecs);
    });
  } else {
    this.socket.setTimeout(msecs);
  }
  return this;
};
 
 
// It's possible that the socket will be destroyed, and removed from
// any messages, before ever calling this.  In that case, just skip
// it, since something else is destroying this connection anyway.
OutgoingMessage.prototype.destroy = function(error) {
  if (this.socket)
    this.socket.destroy(error);
  else
    this.once('socket', function(socket) {
      socket.destroy(error);
    });
};
 
 
// This abstract either writing directly to the socket or buffering it.
OutgoingMessage.prototype._send = function(data, encoding, callback) {
  // This is a shameful hack to get the headers and first body chunk onto
  // the same packet. Future versions of Node are going to take care of
  // this at a lower level and in a more general way.
  if (!this._headerSent) {
    if (typeof data === 'string' &&
        encoding !== 'hex' &&
        encoding !== 'base64') {
      data = this._header + data;
    } else {
      this.output.unshift(this._header);
      this.outputEncodings.unshift('binary');
      this.outputCallbacks.unshift(null);
    }
    this._headerSent = true;
  }
  return this._writeRaw(data, encoding, callback);
};
 
 
OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) {
  if (typeof encoding === 'function') {
    callback = encoding;
    encoding = null;
  }
 
  if (data.length === 0) {
    if (typeof callback === 'function')
      process.nextTick(callback);
    return true;
  }
 
  var connection = this.connection;
  if (connection &&
      connection._httpMessage === this &&
      connection.writable &&
      !connection.destroyed) {
    // There might be pending data in the this.output buffer.
    var outputLength = this.output.length;
    if (outputLength > 0) {
      var output = this.output;
      var outputEncodings = this.outputEncodings;
      var outputCallbacks = this.outputCallbacks;
      for (var i = 0; i < outputLength; i++) {
        connection.write(output[i], outputEncodings[i],
                         outputCallbacks[i]);
      }
 
      this.output = [];
      this.outputEncodings = [];
      this.outputCallbacks = [];
    }
 
    // Directly write to socket.
    return connection.write(data, encoding, callback);
  } else if (connection && connection.destroyed) {
    // The socket was destroyed.  If we're still trying to write to it,
    // then we haven't gotten the 'close' event yet.
    return false;
  } else {
    // buffer, as long as we're not destroyed.
    return this._buffer(data, encoding, callback);
  }
};
 
 
OutgoingMessage.prototype._buffer = function(data, encoding, callback) {
  this.output.push(data);
  this.outputEncodings.push(encoding);
  this.outputCallbacks.push(callback);
  return false;
};
 
 
OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
  // firstLine in the case of request is: 'GET /index.html HTTP/1.1\r\n'
  // in the case of response it is: 'HTTP/1.1 200 OK\r\n'
  var state = {
    sentConnectionHeader: false,
    sentContentLengthHeader: false,
    sentTransferEncodingHeader: false,
    sentDateHeader: false,
    sentExpect: false,
    sentTrailer: false,
    messageHeader: firstLine
  };
 
  if (headers) {
    var keys = Object.keys(headers);
    var isArray = Array.isArray(headers);
    var field, value;
 
    for (var i = 0, l = keys.length; i < l; i++) {
      var key = keys[i];
      if (isArray) {
        field = headers[key][0];
        value = headers[key][1];
      } else {
        field = key;
        value = headers[key];
      }
 
      if (Array.isArray(value)) {
        for (var j = 0; j < value.length; j++) {
          storeHeader(this, state, field, value[j]);
        }
      } else {
        storeHeader(this, state, field, value);
      }
    }
  }
 
  // Date header
  if (this.sendDate === true && state.sentDateHeader === false) {
    state.messageHeader += 'Date: ' + utcDate() + CRLF;
  }
 
  // Force the connection to close when the response is a 204 No Content or
  // a 304 Not Modified and the user has set a "Transfer-Encoding: chunked"
  // header.
  //
  // RFC 2616 mandates that 204 and 304 responses MUST NOT have a body but
  // node.js used to send out a zero chunk anyway to accommodate clients
  // that don't have special handling for those responses.
  //
  // It was pointed out that this might confuse reverse proxies to the point
  // of creating security liabilities, so suppress the zero chunk and force
  // the connection to close.
  var statusCode = this.statusCode;
  if ((statusCode === 204 || statusCode === 304) &&
      this.chunkedEncoding === true) {
    debug(statusCode + ' response should not use chunked encoding,' +
          ' closing connection.');
    this.chunkedEncoding = false;
    this.shouldKeepAlive = false;
  }
 
  // keep-alive logic
  if (this._removedHeader.connection) {
    this._last = true;
    this.shouldKeepAlive = false;
  } else if (state.sentConnectionHeader === false) {
    var shouldSendKeepAlive = this.shouldKeepAlive &&
        (state.sentContentLengthHeader ||
         this.useChunkedEncodingByDefault ||
         this.agent);
    if (shouldSendKeepAlive) {
      state.messageHeader += 'Connection: keep-alive\r\n';
    } else {
      this._last = true;
      state.messageHeader += 'Connection: close\r\n';
    }
  }
 
  if (state.sentContentLengthHeader === false &&
      state.sentTransferEncodingHeader === false) {
    if (!this._hasBody) {
      // Make sure we don't end the 0\r\n\r\n at the end of the message.
      this.chunkedEncoding = false;
    } else if (!this.useChunkedEncodingByDefault) {
      this._last = true;
    } else {
      if (!state.sentTrailer &&
          !this._removedHeader['content-length'] &&
          typeof this._contentLength === 'number') {
        state.messageHeader += 'Content-Length: ' + this._contentLength +
                               '\r\n';
      } else if (!this._removedHeader['transfer-encoding']) {
        state.messageHeader += 'Transfer-Encoding: chunked\r\n';
        this.chunkedEncoding = true;
      } else {
        // We should only be able to get here if both Content-Length and
        // Transfer-Encoding are removed by the user.
        // See: test/parallel/test-http-remove-header-stays-removed.js
        debug('Both Content-Length and Transfer-Encoding are removed');
      }
    }
  }
 
  this._header = state.messageHeader + CRLF;
  this._headerSent = false;
 
  // wait until the first body chunk, or close(), is sent to flush,
  // UNLESS we're sending Expect: 100-continue.
  if (state.sentExpect) this._send('');
};
 
function storeHeader(self, state, field, value) {
  // Protect against response splitting. The if statement is there to
  // minimize the performance impact in the common case.
  if (/[\r\n]/.test(value))
    value = value.replace(/[\r\n]+[ \t]*/g, '');
 
  state.messageHeader += field + ': ' + value + CRLF;
 
  if (connectionExpression.test(field)) {
    state.sentConnectionHeader = true;
    if (closeExpression.test(value)) {
      self._last = true;
    } else {
      self.shouldKeepAlive = true;
    }
 
  } else if (transferEncodingExpression.test(field)) {
    state.sentTransferEncodingHeader = true;
    Eif (chunkExpression.test(value)) self.chunkedEncoding = true;
 
  } else if (contentLengthExpression.test(field)) {
    state.sentContentLengthHeader = true;
  } else if (dateExpression.test(field)) {
    state.sentDateHeader = true;
  } else if (expectExpression.test(field)) {
    state.sentExpect = true;
  } else if (trailerExpression.test(field)) {
    state.sentTrailer = true;
  }
}
 
 
OutgoingMessage.prototype.setHeader = function(name, value) {
  if (typeof name !== 'string')
    throw new TypeError('`name` should be a string in setHeader(name, value).');
  if (value === undefined)
    throw new Error('`value` required in setHeader("' + name + '", value).');
  Iif (this._header)
    throw new Error('Can\'t set headers after they are sent.');
 
  if (this._headers === null)
    this._headers = {};
 
  var key = name.toLowerCase();
  this._headers[key] = value;
  this._headerNames[key] = name;
 
  if (automaticHeaders[key])
    this._removedHeader[key] = false;
};
 
 
OutgoingMessage.prototype.getHeader = function(name) {
  if (arguments.length < 1) {
    throw new Error('`name` is required for getHeader(name).');
  }
 
  if (!this._headers) return;
 
  var key = name.toLowerCase();
  return this._headers[key];
};
 
 
OutgoingMessage.prototype.removeHeader = function(name) {
  if (arguments.length < 1) {
    throw new Error('`name` is required for removeHeader(name).');
  }
 
  Iif (this._header) {
    throw new Error('Can\'t remove headers after they are sent.');
  }
 
  var key = name.toLowerCase();
 
  if (key === 'date')
    this.sendDate = false;
  else if (automaticHeaders[key])
    this._removedHeader[key] = true;
 
  if (this._headers) {
    delete this._headers[key];
    delete this._headerNames[key];
  }
};
 
 
OutgoingMessage.prototype._renderHeaders = function() {
  Iif (this._header) {
    throw new Error('Can\'t render headers after they are sent to the client.');
  }
 
  var headersMap = this._headers;
  if (!headersMap) return {};
 
  var headers = {};
  var keys = Object.keys(headersMap);
  var headerNames = this._headerNames;
 
  for (var i = 0, l = keys.length; i < l; i++) {
    var key = keys[i];
    headers[headerNames[key]] = headersMap[key];
  }
  return headers;
};
 
 
Object.defineProperty(OutgoingMessage.prototype, 'headersSent', {
  configurable: true,
  enumerable: true,
  get: function() { return !!this._header; }
});
 
 
OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
  if (this.finished) {
    var err = new Error('write after end');
    process.nextTick(writeAfterEndNT, this, err, callback);
 
    return true;
  }
 
  if (!this._header) {
    this._implicitHeader();
  }
 
  Iif (!this._hasBody) {
    debug('This type of response MUST NOT have a body. ' +
          'Ignoring write() calls.');
    return true;
  }
 
  if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
    throw new TypeError('first argument must be a string or Buffer');
  }
 
 
  // If we get an empty string or buffer, then just do nothing, and
  // signal the user to keep writing.
  if (chunk.length === 0) return true;
 
  var len, ret;
  if (this.chunkedEncoding) {
    if (typeof chunk === 'string' &&
        encoding !== 'hex' &&
        encoding !== 'base64' &&
        encoding !== 'binary') {
      len = Buffer.byteLength(chunk, encoding);
      chunk = len.toString(16) + CRLF + chunk + CRLF;
      ret = this._send(chunk, encoding, callback);
    } else {
      // buffer, or a non-toString-friendly encoding
      if (typeof chunk === 'string')
        len = Buffer.byteLength(chunk, encoding);
      else
        len = chunk.length;
 
      if (this.connection && !this.connection.corked) {
        this.connection.cork();
        process.nextTick(connectionCorkNT, this.connection);
      }
      this._send(len.toString(16), 'binary', null);
      this._send(crlf_buf, null, null);
      this._send(chunk, encoding, null);
      ret = this._send(crlf_buf, null, callback);
    }
  } else {
    ret = this._send(chunk, encoding, callback);
  }
 
  debug('write ret = ' + ret);
  return ret;
};
 
 
function writeAfterEndNT(self, err, callback) {
  self.emit('error', err);
  Iif (callback) callback(err);
}
 
 
function connectionCorkNT(conn) {
  Eif (conn)
    conn.uncork();
}
 
 
OutgoingMessage.prototype.addTrailers = function(headers) {
  this._trailer = '';
  var keys = Object.keys(headers);
  var isArray = Array.isArray(headers);
  var field, value;
  for (var i = 0, l = keys.length; i < l; i++) {
    var key = keys[i];
    Eif (isArray) {
      field = headers[key][0];
      value = headers[key][1];
    } else {
      field = key;
      value = headers[key];
    }
 
    this._trailer += field + ': ' + value + CRLF;
  }
};
 
 
const crlf_buf = new Buffer('\r\n');
 
 
OutgoingMessage.prototype.end = function(data, encoding, callback) {
  Iif (typeof data === 'function') {
    callback = data;
    data = null;
  } else if (typeof encoding === 'function') {
    callback = encoding;
    encoding = null;
  }
 
  if (data && typeof data !== 'string' && !(data instanceof Buffer)) {
    throw new TypeError('first argument must be a string or Buffer');
  }
 
  if (this.finished) {
    return false;
  }
 
  var self = this;
  function finish() {
    self.emit('finish');
  }
 
  if (typeof callback === 'function')
    this.once('finish', callback);
 
  if (!this._header) {
    if (data) {
      if (typeof data === 'string')
        this._contentLength = Buffer.byteLength(data, encoding);
      else
        this._contentLength = data.length;
    } else {
      this._contentLength = 0;
    }
    this._implicitHeader();
  }
 
  if (data && !this._hasBody) {
    debug('This type of response MUST NOT have a body. ' +
          'Ignoring data passed to end().');
    data = null;
  }
 
  if (this.connection && data)
    this.connection.cork();
 
  var ret;
  if (data) {
    // Normal body write.
    ret = this.write(data, encoding);
  }
 
  if (this._hasBody && this.chunkedEncoding) {
    ret = this._send('0\r\n' + this._trailer + '\r\n', 'binary', finish);
  } else {
    // Force a flush, HACK.
    ret = this._send('', 'binary', finish);
  }
 
  if (this.connection && data)
    this.connection.uncork();
 
  this.finished = true;
 
  // There is the first message on the outgoing queue, and we've sent
  // everything to the socket.
  debug('outgoing message end.');
  if (this.output.length === 0 && this.connection._httpMessage === this) {
    this._finish();
  }
 
  return ret;
};
 
 
OutgoingMessage.prototype._finish = function() {
  assert(this.connection);
  this.emit('prefinish');
};
 
 
// This logic is probably a bit confusing. Let me explain a bit:
//
// In both HTTP servers and clients it is possible to queue up several
// outgoing messages. This is easiest to imagine in the case of a client.
// Take the following situation:
//
//    req1 = client.request('GET', '/');
//    req2 = client.request('POST', '/');
//
// When the user does
//
//   req2.write('hello world\n');
//
// it's possible that the first request has not been completely flushed to
// the socket yet. Thus the outgoing messages need to be prepared to queue
// up data internally before sending it on further to the socket's queue.
//
// This function, outgoingFlush(), is called by both the Server and Client
// to attempt to flush any pending messages out to the socket.
OutgoingMessage.prototype._flush = function() {
  var socket = this.socket;
  var outputLength, ret;
 
  if (socket && socket.writable) {
    // There might be remaining data in this.output; write it out
    outputLength = this.output.length;
    if (outputLength > 0) {
      var output = this.output;
      var outputEncodings = this.outputEncodings;
      var outputCallbacks = this.outputCallbacks;
      for (var i = 0; i < outputLength; i++) {
        ret = socket.write(output[i], outputEncodings[i],
                           outputCallbacks[i]);
      }
 
      this.output = [];
      this.outputEncodings = [];
      this.outputCallbacks = [];
    }
 
    if (this.finished) {
      // This is a queue to the server or client to bring in the next this.
      this._finish();
    } else if (ret) {
      // This is necessary to prevent https from breaking
      this.emit('drain');
    }
  }
};
 
 
OutgoingMessage.prototype.flushHeaders = function() {
  if (!this._header) {
    // Force-flush the headers.
    this._implicitHeader();
    this._send('');
  }
};
 
OutgoingMessage.prototype.flush = util.deprecate(function() {
  this.flushHeaders();
}, 'flush is deprecated. Use flushHeaders instead.');
 
}());