lib: turn on strict mode
[platform/upstream/nodejs.git] / lib / _http_outgoing.js
index 7248e5a..cef135c 100644 (file)
 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 // USE OR OTHER DEALINGS IN THE SOFTWARE.
 
+'use strict';
+
 var assert = require('assert').ok;
 var Stream = require('stream');
+var timers = require('timers');
 var util = require('util');
 
 var common = require('_http_common');
 
 var CRLF = common.CRLF;
 var chunkExpression = common.chunkExpression;
-var continueExpression = common.continueExpression;
 var debug = common.debug;
 
 
@@ -38,18 +40,27 @@ var contentLengthExpression = /Content-Length/i;
 var dateExpression = /Date/i;
 var expectExpression = /Expect/i;
 
+var automaticHeaders = {
+  connection: true,
+  'content-length': true,
+  'transfer-encoding': true,
+  date: true
+};
+
 
 var dateCache;
 function utcDate() {
   if (!dateCache) {
     var d = new Date();
     dateCache = d.toUTCString();
-    setTimeout(function() {
-      dateCache = undefined;
-    }, 1000 - d.getMilliseconds());
+    timers.enroll(utcDate, 1000 - d.getMilliseconds());
+    timers._unrefActive(utcDate);
   }
   return dateCache;
 }
+utcDate._onTimeout = function() {
+  dateCache = undefined;
+};
 
 
 function OutgoingMessage() {
@@ -57,6 +68,7 @@ function OutgoingMessage() {
 
   this.output = [];
   this.outputEncodings = [];
+  this.outputCallbacks = [];
 
   this.writable = true;
 
@@ -65,15 +77,20 @@ function OutgoingMessage() {
   this.shouldKeepAlive = true;
   this.useChunkedEncodingByDefault = true;
   this.sendDate = false;
+  this._removedHeader = {};
 
   this._hasBody = true;
   this._trailer = '';
 
   this.finished = false;
   this._hangupClose = false;
+  this._headerSent = false;
 
   this.socket = null;
   this.connection = null;
+  this._header = null;
+  this._headers = null;
+  this._headerNames = {};
 }
 util.inherits(OutgoingMessage, Stream);
 
@@ -107,25 +124,35 @@ OutgoingMessage.prototype.destroy = function(error) {
 
 
 // This abstract either writing directly to the socket or buffering it.
-OutgoingMessage.prototype._send = function(data, encoding) {
+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') {
+    if (util.isString(data) &&
+        encoding !== 'hex' &&
+        encoding !== 'base64') {
       data = this._header + data;
     } else {
       this.output.unshift(this._header);
-      this.outputEncodings.unshift('ascii');
+      this.outputEncodings.unshift('binary');
+      this.outputCallbacks.unshift(null);
     }
     this._headerSent = true;
   }
-  return this._writeRaw(data, encoding);
+  return this._writeRaw(data, encoding, callback);
 };
 
 
-OutgoingMessage.prototype._writeRaw = function(data, encoding) {
+OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) {
+  if (util.isFunction(encoding)) {
+    callback = encoding;
+    encoding = null;
+  }
+
   if (data.length === 0) {
+    if (util.isFunction(callback))
+      process.nextTick(callback);
     return true;
   }
 
@@ -136,51 +163,33 @@ OutgoingMessage.prototype._writeRaw = function(data, encoding) {
     // There might be pending data in the this.output buffer.
     while (this.output.length) {
       if (!this.connection.writable) {
-        this._buffer(data, encoding);
+        this._buffer(data, encoding, callback);
         return false;
       }
       var c = this.output.shift();
       var e = this.outputEncodings.shift();
-      this.connection.write(c, e);
+      var cb = this.outputCallbacks.shift();
+      this.connection.write(c, e, cb);
     }
 
     // Directly write to socket.
-    return this.connection.write(data, encoding);
+    return this.connection.write(data, encoding, callback);
   } else if (this.connection && this.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.
-    this._buffer(data, encoding);
+    this._buffer(data, encoding, callback);
     return false;
   }
 };
 
 
-OutgoingMessage.prototype._buffer = function(data, encoding) {
-  if (data.length === 0) return;
-
-  var length = this.output.length;
-
-  if (length === 0 || typeof data != 'string') {
-    this.output.push(data);
-    this.outputEncodings.push(encoding);
-    return false;
-  }
-
-  var lastEncoding = this.outputEncodings[length - 1];
-  var lastData = this.output[length - 1];
-
-  if ((encoding && lastEncoding === encoding) ||
-      (!encoding && data.constructor === lastData.constructor)) {
-    this.output[length - 1] = lastData + data;
-    return false;
-  }
-
+OutgoingMessage.prototype._buffer = function(data, encoding, callback) {
   this.output.push(data);
   this.outputEncodings.push(encoding);
-
+  this.outputCallbacks.push(callback);
   return false;
 };
 
@@ -198,11 +207,10 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
   };
 
   var field, value;
-  var self = this;
 
   if (headers) {
     var keys = Object.keys(headers);
-    var isArray = (Array.isArray(headers));
+    var isArray = util.isArray(headers);
     var field, value;
 
     for (var i = 0, l = keys.length; i < l; i++) {
@@ -215,7 +223,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
         value = headers[key];
       }
 
-      if (Array.isArray(value)) {
+      if (util.isArray(value)) {
         for (var j = 0; j < value.length; j++) {
           storeHeader(this, state, field, value[j]);
         }
@@ -226,7 +234,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
   }
 
   // Date header
-  if (this.sendDate == true && state.sentDateHeader == false) {
+  if (this.sendDate === true && state.sentDateHeader === false) {
     state.messageHeader += 'Date: ' + utcDate() + CRLF;
   }
 
@@ -242,7 +250,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
   // of creating security liabilities, so suppress the zero chunk and force
   // the connection to close.
   var statusCode = this.statusCode;
-  if ((statusCode == 204 || statusCode === 304) &&
+  if ((statusCode === 204 || statusCode === 304) &&
       this.chunkedEncoding === true) {
     debug(statusCode + ' response should not use chunked encoding,' +
           ' closing connection.');
@@ -251,7 +259,10 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
   }
 
   // keep-alive logic
-  if (state.sentConnectionHeader === false) {
+  if (this._removedHeader.connection) {
+    this._last = true;
+    this.shouldKeepAlive = false;
+  } else if (state.sentConnectionHeader === false) {
     var shouldSendKeepAlive = this.shouldKeepAlive &&
         (state.sentContentLengthHeader ||
          this.useChunkedEncodingByDefault ||
@@ -264,9 +275,9 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
     }
   }
 
-  if (state.sentContentLengthHeader == false &&
-      state.sentTransferEncodingHeader == false) {
-    if (this._hasBody) {
+  if (state.sentContentLengthHeader === false &&
+      state.sentTransferEncodingHeader === false) {
+    if (this._hasBody && !this._removedHeader['transfer-encoding']) {
       if (this.useChunkedEncodingByDefault) {
         state.messageHeader += 'Transfer-Encoding: chunked\r\n';
         this.chunkedEncoding = true;
@@ -318,19 +329,22 @@ function storeHeader(self, state, field, value) {
 
 
 OutgoingMessage.prototype.setHeader = function(name, value) {
-  if (arguments.length < 2) {
-    throw new Error('`name` and `value` are required for setHeader().');
-  }
-
-  if (this._header) {
+  if (typeof name !== 'string')
+    throw new TypeError('"name" should be a string');
+  if (value === undefined)
+    throw new Error('"name" and "value" are required for setHeader().');
+  if (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 = this._headers || {};
-  this._headerNames = this._headerNames || {};
   this._headers[key] = value;
   this._headerNames[key] = name;
+
+  if (automaticHeaders[key])
+    this._removedHeader[key] = false;
 };
 
 
@@ -355,11 +369,17 @@ OutgoingMessage.prototype.removeHeader = function(name) {
     throw new Error('Can\'t remove headers after they are sent.');
   }
 
-  if (!this._headers) return;
-
   var key = name.toLowerCase();
-  delete this._headers[key];
-  delete this._headerNames[key];
+
+  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];
+  }
 };
 
 
@@ -372,6 +392,7 @@ OutgoingMessage.prototype._renderHeaders = function() {
 
   var headers = {};
   var keys = Object.keys(this._headers);
+
   for (var i = 0, l = keys.length; i < l; i++) {
     var key = keys[i];
     headers[this._headerNames[key]] = this._headers[key];
@@ -387,7 +408,19 @@ Object.defineProperty(OutgoingMessage.prototype, 'headersSent', {
 });
 
 
-OutgoingMessage.prototype.write = function(chunk, encoding) {
+OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
+  var self = this;
+
+  if (this.finished) {
+    var err = new Error('write after end');
+    process.nextTick(function() {
+      self.emit('error', err);
+      if (callback) callback(err);
+    });
+
+    return true;
+  }
+
   if (!this._header) {
     this._implicitHeader();
   }
@@ -398,36 +431,46 @@ OutgoingMessage.prototype.write = function(chunk, encoding) {
     return true;
   }
 
-  if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) {
+  if (!util.isString(chunk) && !util.isBuffer(chunk)) {
     throw new TypeError('first argument must be a string or Buffer');
   }
 
-  if (chunk.length === 0) return false;
+
+  // 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' &&
+    if (util.isString(chunk) &&
         encoding !== 'hex' &&
         encoding !== 'base64' &&
         encoding !== 'binary') {
       len = Buffer.byteLength(chunk, encoding);
       chunk = len.toString(16) + CRLF + chunk + CRLF;
-      ret = this._send(chunk, encoding);
+      ret = this._send(chunk, encoding, callback);
     } else {
       // buffer, or a non-toString-friendly encoding
-      len = chunk.length;
+      if (util.isString(chunk))
+        len = Buffer.byteLength(chunk, encoding);
+      else
+        len = chunk.length;
 
-      if (this.connection)
+      if (this.connection && !this.connection.corked) {
         this.connection.cork();
-      this._send(len.toString(16));
-      this._send(crlf_buf);
-      this._send(chunk);
-      ret = this._send(crlf_buf);
-      if (this.connection)
-        this.connection.uncork();
+        var conn = this.connection;
+        process.nextTick(function connectionCork() {
+          if (conn)
+            conn.uncork();
+        });
+      }
+      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);
+    ret = this._send(chunk, encoding, callback);
   }
 
   debug('write ret = ' + ret);
@@ -438,7 +481,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding) {
 OutgoingMessage.prototype.addTrailers = function(headers) {
   this._trailer = '';
   var keys = Object.keys(headers);
-  var isArray = (Array.isArray(headers));
+  var isArray = util.isArray(headers);
   var field, value;
   for (var i = 0, l = keys.length; i < l; i++) {
     var key = keys[i];
@@ -455,18 +498,35 @@ OutgoingMessage.prototype.addTrailers = function(headers) {
 };
 
 
-var zero_chunk_buf = new Buffer('\r\n0\r\n');
 var crlf_buf = new Buffer('\r\n');
 
 
-OutgoingMessage.prototype.end = function(data, encoding) {
-  if (data && typeof data !== 'string' && !Buffer.isBuffer(data)) {
+OutgoingMessage.prototype.end = function(data, encoding, callback) {
+  if (util.isFunction(data)) {
+    callback = data;
+    data = null;
+  } else if (util.isFunction(encoding)) {
+    callback = encoding;
+    encoding = null;
+  }
+
+  if (data && !util.isString(data) && !util.isBuffer(data)) {
     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 (util.isFunction(callback))
+    this.once('finish', callback);
+
+
   if (!this._header) {
     this._implicitHeader();
   }
@@ -474,7 +534,7 @@ OutgoingMessage.prototype.end = function(data, encoding) {
   if (data && !this._hasBody) {
     debug('This type of response MUST NOT have a body. ' +
           'Ignoring data passed to end().');
-    data = false;
+    data = null;
   }
 
   if (this.connection && data)
@@ -486,11 +546,11 @@ OutgoingMessage.prototype.end = function(data, encoding) {
     ret = this.write(data, encoding);
   }
 
-  if (this.chunkedEncoding) {
-    ret = this._send('0\r\n' + this._trailer + '\r\n'); // Last chunk.
+  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('');
+    ret = this._send('', 'binary', finish);
   }
 
   if (this.connection && data)
@@ -509,68 +569,56 @@ OutgoingMessage.prototype.end = function(data, encoding) {
 };
 
 
-var ServerResponse, ClientRequest;
-
 OutgoingMessage.prototype._finish = function() {
   assert(this.connection);
-
-  if (!ServerResponse)
-    ServerResponse = require('_http_server').ServerResponse;
-
-  if (!ClientRequest)
-    ClientRequest = require('_http_client').ClientRequest;
-
-  if (this instanceof ServerResponse) {
-    DTRACE_HTTP_SERVER_RESPONSE(this.connection);
-    COUNTER_HTTP_SERVER_RESPONSE();
-  } else {
-    assert(this instanceof ClientRequest);
-    DTRACE_HTTP_CLIENT_REQUEST(this, this.connection);
-    COUNTER_HTTP_CLIENT_REQUEST();
-  }
-  this.emit('finish');
+  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() {
-  // 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.
-
-  if (!this.socket) return;
-
-  var ret;
-  while (this.output.length) {
-
-    if (!this.socket.writable) return; // XXX Necessary?
-
-    var data = this.output.shift();
-    var encoding = this.outputEncodings.shift();
+  if (this.socket && this.socket.writable) {
+    var ret;
+    while (this.output.length) {
+      var data = this.output.shift();
+      var encoding = this.outputEncodings.shift();
+      var cb = this.outputCallbacks.shift();
+      ret = this.socket.write(data, encoding, cb);
+    }
 
-    ret = this.socket.write(data, encoding);
+    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');
+    }
   }
+};
 
-  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.flush = function() {
+  if (!this._header) {
+    // Force-flush the headers.
+    this._implicitHeader();
+    this._send('');
   }
 };