1 // Copyright Joyent, Inc. and other Node contributors.
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:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
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.
22 var assert = require('assert').ok;
23 var Stream = require('stream');
24 var timers = require('timers');
25 var util = require('util');
27 var common = require('_http_common');
29 var CRLF = common.CRLF;
30 var chunkExpression = common.chunkExpression;
31 var debug = common.debug;
34 var connectionExpression = /Connection/i;
35 var transferEncodingExpression = /Transfer-Encoding/i;
36 var closeExpression = /close/i;
37 var contentLengthExpression = /Content-Length/i;
38 var dateExpression = /Date/i;
39 var expectExpression = /Expect/i;
46 dateCache = d.toUTCString();
47 timers.enroll(utcDate, 1000 - d.getMilliseconds());
48 timers._unrefActive(utcDate);
52 utcDate._onTimeout = function() {
53 dateCache = undefined;
57 function OutgoingMessage() {
61 this.outputEncodings = [];
62 this.outputCallbacks = [];
67 this.chunkedEncoding = false;
68 this.shouldKeepAlive = true;
69 this.useChunkedEncodingByDefault = true;
70 this.sendDate = false;
75 this.finished = false;
76 this._hangupClose = false;
79 this.connection = null;
81 util.inherits(OutgoingMessage, Stream);
84 exports.OutgoingMessage = OutgoingMessage;
87 OutgoingMessage.prototype.setTimeout = function(msecs, callback) {
89 this.on('timeout', callback);
91 this.once('socket', function(socket) {
92 socket.setTimeout(msecs);
95 this.socket.setTimeout(msecs);
99 // It's possible that the socket will be destroyed, and removed from
100 // any messages, before ever calling this. In that case, just skip
101 // it, since something else is destroying this connection anyway.
102 OutgoingMessage.prototype.destroy = function(error) {
104 this.socket.destroy(error);
106 this.once('socket', function(socket) {
107 socket.destroy(error);
112 // This abstract either writing directly to the socket or buffering it.
113 OutgoingMessage.prototype._send = function(data, encoding, callback) {
114 // This is a shameful hack to get the headers and first body chunk onto
115 // the same packet. Future versions of Node are going to take care of
116 // this at a lower level and in a more general way.
117 if (!this._headerSent) {
118 if (util.isString(data) &&
119 encoding !== 'hex' &&
120 encoding !== 'base64') {
121 data = this._header + data;
123 this.output.unshift(this._header);
124 this.outputEncodings.unshift('binary');
125 this.outputCallbacks.unshift(null);
127 this._headerSent = true;
129 return this._writeRaw(data, encoding, callback);
133 OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) {
134 if (util.isFunction(encoding)) {
139 if (data.length === 0) {
140 if (util.isFunction(callback))
141 process.nextTick(callback);
145 if (this.connection &&
146 this.connection._httpMessage === this &&
147 this.connection.writable &&
148 !this.connection.destroyed) {
149 // There might be pending data in the this.output buffer.
150 while (this.output.length) {
151 if (!this.connection.writable) {
152 this._buffer(data, encoding, callback);
155 var c = this.output.shift();
156 var e = this.outputEncodings.shift();
157 var cb = this.outputCallbacks.shift();
158 this.connection.write(c, e, cb);
161 // Directly write to socket.
162 return this.connection.write(data, encoding, callback);
163 } else if (this.connection && this.connection.destroyed) {
164 // The socket was destroyed. If we're still trying to write to it,
165 // then we haven't gotten the 'close' event yet.
168 // buffer, as long as we're not destroyed.
169 this._buffer(data, encoding, callback);
175 OutgoingMessage.prototype._buffer = function(data, encoding, callback) {
176 this.output.push(data);
177 this.outputEncodings.push(encoding);
178 this.outputCallbacks.push(callback);
183 OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
184 // firstLine in the case of request is: 'GET /index.html HTTP/1.1\r\n'
185 // in the case of response it is: 'HTTP/1.1 200 OK\r\n'
187 sentConnectionHeader: false,
188 sentContentLengthHeader: false,
189 sentTransferEncodingHeader: false,
190 sentDateHeader: false,
192 messageHeader: firstLine
198 var keys = Object.keys(headers);
199 var isArray = util.isArray(headers);
202 for (var i = 0, l = keys.length; i < l; i++) {
205 field = headers[key][0];
206 value = headers[key][1];
209 value = headers[key];
212 if (util.isArray(value)) {
213 for (var j = 0; j < value.length; j++) {
214 storeHeader(this, state, field, value[j]);
217 storeHeader(this, state, field, value);
223 if (this.sendDate == true && state.sentDateHeader == false) {
224 state.messageHeader += 'Date: ' + utcDate() + CRLF;
227 // Force the connection to close when the response is a 204 No Content or
228 // a 304 Not Modified and the user has set a "Transfer-Encoding: chunked"
231 // RFC 2616 mandates that 204 and 304 responses MUST NOT have a body but
232 // node.js used to send out a zero chunk anyway to accommodate clients
233 // that don't have special handling for those responses.
235 // It was pointed out that this might confuse reverse proxies to the point
236 // of creating security liabilities, so suppress the zero chunk and force
237 // the connection to close.
238 var statusCode = this.statusCode;
239 if ((statusCode == 204 || statusCode === 304) &&
240 this.chunkedEncoding === true) {
241 debug(statusCode + ' response should not use chunked encoding,' +
242 ' closing connection.');
243 this.chunkedEncoding = false;
244 this.shouldKeepAlive = false;
248 if (state.sentConnectionHeader === false) {
249 var shouldSendKeepAlive = this.shouldKeepAlive &&
250 (state.sentContentLengthHeader ||
251 this.useChunkedEncodingByDefault ||
253 if (shouldSendKeepAlive) {
254 state.messageHeader += 'Connection: keep-alive\r\n';
257 state.messageHeader += 'Connection: close\r\n';
261 if (state.sentContentLengthHeader == false &&
262 state.sentTransferEncodingHeader == false) {
264 if (this.useChunkedEncodingByDefault) {
265 state.messageHeader += 'Transfer-Encoding: chunked\r\n';
266 this.chunkedEncoding = true;
271 // Make sure we don't end the 0\r\n\r\n at the end of the message.
272 this.chunkedEncoding = false;
276 this._header = state.messageHeader + CRLF;
277 this._headerSent = false;
279 // wait until the first body chunk, or close(), is sent to flush,
280 // UNLESS we're sending Expect: 100-continue.
281 if (state.sentExpect) this._send('');
284 function storeHeader(self, state, field, value) {
285 // Protect against response splitting. The if statement is there to
286 // minimize the performance impact in the common case.
287 if (/[\r\n]/.test(value))
288 value = value.replace(/[\r\n]+[ \t]*/g, '');
290 state.messageHeader += field + ': ' + value + CRLF;
292 if (connectionExpression.test(field)) {
293 state.sentConnectionHeader = true;
294 if (closeExpression.test(value)) {
297 self.shouldKeepAlive = true;
300 } else if (transferEncodingExpression.test(field)) {
301 state.sentTransferEncodingHeader = true;
302 if (chunkExpression.test(value)) self.chunkedEncoding = true;
304 } else if (contentLengthExpression.test(field)) {
305 state.sentContentLengthHeader = true;
306 } else if (dateExpression.test(field)) {
307 state.sentDateHeader = true;
308 } else if (expectExpression.test(field)) {
309 state.sentExpect = true;
314 OutgoingMessage.prototype.setHeader = function(name, value) {
315 if (arguments.length < 2) {
316 throw new Error('`name` and `value` are required for setHeader().');
320 throw new Error('Can\'t set headers after they are sent.');
323 var key = name.toLowerCase();
324 this._headers = this._headers || {};
325 this._headerNames = this._headerNames || {};
326 this._headers[key] = value;
327 this._headerNames[key] = name;
331 OutgoingMessage.prototype.getHeader = function(name) {
332 if (arguments.length < 1) {
333 throw new Error('`name` is required for getHeader().');
336 if (!this._headers) return;
338 var key = name.toLowerCase();
339 return this._headers[key];
343 OutgoingMessage.prototype.removeHeader = function(name) {
344 if (arguments.length < 1) {
345 throw new Error('`name` is required for removeHeader().');
349 throw new Error('Can\'t remove headers after they are sent.');
352 if (!this._headers) return;
354 var key = name.toLowerCase();
355 delete this._headers[key];
356 delete this._headerNames[key];
360 OutgoingMessage.prototype._renderHeaders = function() {
362 throw new Error('Can\'t render headers after they are sent to the client.');
365 if (!this._headers) return {};
368 var keys = Object.keys(this._headers);
369 for (var i = 0, l = keys.length; i < l; i++) {
371 headers[this._headerNames[key]] = this._headers[key];
377 Object.defineProperty(OutgoingMessage.prototype, 'headersSent', {
380 get: function() { return !!this._header; }
384 OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
386 this._implicitHeader();
389 if (!this._hasBody) {
390 debug('This type of response MUST NOT have a body. ' +
391 'Ignoring write() calls.');
395 if (!util.isString(chunk) && !util.isBuffer(chunk)) {
396 throw new TypeError('first argument must be a string or Buffer');
400 // If we get an empty string or buffer, then just do nothing, and
401 // signal the user to keep writing.
402 if (chunk.length === 0) return true;
405 if (this.chunkedEncoding) {
406 if (util.isString(chunk) &&
407 encoding !== 'hex' &&
408 encoding !== 'base64' &&
409 encoding !== 'binary') {
410 len = Buffer.byteLength(chunk, encoding);
411 chunk = len.toString(16) + CRLF + chunk + CRLF;
412 ret = this._send(chunk, encoding, callback);
414 // buffer, or a non-toString-friendly encoding
415 if (util.isString(chunk))
416 len = Buffer.byteLength(chunk, encoding);
421 this.connection.cork();
422 this._send(len.toString(16), 'binary', null);
423 this._send(crlf_buf, null, null);
424 this._send(chunk, encoding, null);
425 ret = this._send(crlf_buf, null, callback);
427 this.connection.uncork();
430 ret = this._send(chunk, encoding, callback);
433 debug('write ret = ' + ret);
438 OutgoingMessage.prototype.addTrailers = function(headers) {
440 var keys = Object.keys(headers);
441 var isArray = util.isArray(headers);
443 for (var i = 0, l = keys.length; i < l; i++) {
446 field = headers[key][0];
447 value = headers[key][1];
450 value = headers[key];
453 this._trailer += field + ': ' + value + CRLF;
458 var crlf_buf = new Buffer('\r\n');
461 OutgoingMessage.prototype.end = function(data, encoding, callback) {
462 if (util.isFunction(data)) {
465 } else if (util.isFunction(encoding)) {
470 if (data && !util.isString(data) && !util.isBuffer(data)) {
471 throw new TypeError('first argument must be a string or Buffer');
483 if (util.isFunction(callback))
484 this.once('finish', callback);
488 this._implicitHeader();
491 if (data && !this._hasBody) {
492 debug('This type of response MUST NOT have a body. ' +
493 'Ignoring data passed to end().');
497 if (this.connection && data)
498 this.connection.cork();
502 // Normal body write.
503 ret = this.write(data, encoding);
506 if (this.chunkedEncoding) {
507 ret = this._send('0\r\n' + this._trailer + '\r\n', 'binary', finish);
509 // Force a flush, HACK.
510 ret = this._send('', 'binary', finish);
513 if (this.connection && data)
514 this.connection.uncork();
516 this.finished = true;
518 // There is the first message on the outgoing queue, and we've sent
519 // everything to the socket.
520 debug('outgoing message end.');
521 if (this.output.length === 0 && this.connection._httpMessage === this) {
529 OutgoingMessage.prototype._finish = function() {
530 assert(this.connection);
531 this.emit('prefinish');
535 // This logic is probably a bit confusing. Let me explain a bit:
537 // In both HTTP servers and clients it is possible to queue up several
538 // outgoing messages. This is easiest to imagine in the case of a client.
539 // Take the following situation:
541 // req1 = client.request('GET', '/');
542 // req2 = client.request('POST', '/');
544 // When the user does
546 // req2.write('hello world\n');
548 // it's possible that the first request has not been completely flushed to
549 // the socket yet. Thus the outgoing messages need to be prepared to queue
550 // up data internally before sending it on further to the socket's queue.
552 // This function, outgoingFlush(), is called by both the Server and Client
553 // to attempt to flush any pending messages out to the socket.
554 OutgoingMessage.prototype._flush = function() {
555 if (this.socket && this.socket.writable) {
557 while (this.output.length) {
558 var data = this.output.shift();
559 var encoding = this.outputEncodings.shift();
560 var cb = this.outputCallbacks.shift();
561 ret = this.socket.write(data, encoding, cb);
565 // This is a queue to the server or client to bring in the next this.
568 // This is necessary to prevent https from breaking