Merge remote-tracking branch 'ry/v0.10'
[platform/upstream/nodejs.git] / lib / _http_outgoing.js
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 var assert = require('assert').ok;
23 var Stream = require('stream');
24 var timers = require('timers');
25 var util = require('util');
26
27 var common = require('_http_common');
28
29 var CRLF = common.CRLF;
30 var chunkExpression = common.chunkExpression;
31 var debug = common.debug;
32
33
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;
40
41
42 var dateCache;
43 function utcDate() {
44   if (!dateCache) {
45     var d = new Date();
46     dateCache = d.toUTCString();
47     timers.enroll(utcDate, 1000 - d.getMilliseconds());
48     timers._unrefActive(utcDate);
49   }
50   return dateCache;
51 }
52 utcDate._onTimeout = function() {
53   dateCache = undefined;
54 };
55
56
57 function OutgoingMessage() {
58   Stream.call(this);
59
60   this.output = [];
61   this.outputEncodings = [];
62   this.outputCallbacks = [];
63
64   this.writable = true;
65
66   this._last = false;
67   this.chunkedEncoding = false;
68   this.shouldKeepAlive = true;
69   this.useChunkedEncodingByDefault = true;
70   this.sendDate = false;
71
72   this._hasBody = true;
73   this._trailer = '';
74
75   this.finished = false;
76   this._hangupClose = false;
77
78   this.socket = null;
79   this.connection = null;
80 }
81 util.inherits(OutgoingMessage, Stream);
82
83
84 exports.OutgoingMessage = OutgoingMessage;
85
86
87 OutgoingMessage.prototype.setTimeout = function(msecs, callback) {
88   if (callback)
89     this.on('timeout', callback);
90   if (!this.socket) {
91     this.once('socket', function(socket) {
92       socket.setTimeout(msecs);
93     });
94   } else
95     this.socket.setTimeout(msecs);
96 };
97
98
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) {
103   if (this.socket)
104     this.socket.destroy(error);
105   else
106     this.once('socket', function(socket) {
107       socket.destroy(error);
108     });
109 };
110
111
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;
122     } else {
123       this.output.unshift(this._header);
124       this.outputEncodings.unshift('binary');
125       this.outputCallbacks.unshift(null);
126     }
127     this._headerSent = true;
128   }
129   return this._writeRaw(data, encoding, callback);
130 };
131
132
133 OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) {
134   if (util.isFunction(encoding)) {
135     callback = encoding;
136     encoding = null;
137   }
138
139   if (data.length === 0) {
140     if (util.isFunction(callback))
141       process.nextTick(callback);
142     return true;
143   }
144
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);
153         return false;
154       }
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);
159     }
160
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.
166     return false;
167   } else {
168     // buffer, as long as we're not destroyed.
169     this._buffer(data, encoding, callback);
170     return false;
171   }
172 };
173
174
175 OutgoingMessage.prototype._buffer = function(data, encoding, callback) {
176   this.output.push(data);
177   this.outputEncodings.push(encoding);
178   this.outputCallbacks.push(callback);
179   return false;
180 };
181
182
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'
186   var state = {
187     sentConnectionHeader: false,
188     sentContentLengthHeader: false,
189     sentTransferEncodingHeader: false,
190     sentDateHeader: false,
191     sentExpect: false,
192     messageHeader: firstLine
193   };
194
195   var field, value;
196
197   if (headers) {
198     var keys = Object.keys(headers);
199     var isArray = util.isArray(headers);
200     var field, value;
201
202     for (var i = 0, l = keys.length; i < l; i++) {
203       var key = keys[i];
204       if (isArray) {
205         field = headers[key][0];
206         value = headers[key][1];
207       } else {
208         field = key;
209         value = headers[key];
210       }
211
212       if (util.isArray(value)) {
213         for (var j = 0; j < value.length; j++) {
214           storeHeader(this, state, field, value[j]);
215         }
216       } else {
217         storeHeader(this, state, field, value);
218       }
219     }
220   }
221
222   // Date header
223   if (this.sendDate == true && state.sentDateHeader == false) {
224     state.messageHeader += 'Date: ' + utcDate() + CRLF;
225   }
226
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"
229   // header.
230   //
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.
234   //
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;
245   }
246
247   // keep-alive logic
248   if (state.sentConnectionHeader === false) {
249     var shouldSendKeepAlive = this.shouldKeepAlive &&
250         (state.sentContentLengthHeader ||
251          this.useChunkedEncodingByDefault ||
252          this.agent);
253     if (shouldSendKeepAlive) {
254       state.messageHeader += 'Connection: keep-alive\r\n';
255     } else {
256       this._last = true;
257       state.messageHeader += 'Connection: close\r\n';
258     }
259   }
260
261   if (state.sentContentLengthHeader == false &&
262       state.sentTransferEncodingHeader == false) {
263     if (this._hasBody) {
264       if (this.useChunkedEncodingByDefault) {
265         state.messageHeader += 'Transfer-Encoding: chunked\r\n';
266         this.chunkedEncoding = true;
267       } else {
268         this._last = true;
269       }
270     } else {
271       // Make sure we don't end the 0\r\n\r\n at the end of the message.
272       this.chunkedEncoding = false;
273     }
274   }
275
276   this._header = state.messageHeader + CRLF;
277   this._headerSent = false;
278
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('');
282 };
283
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, '');
289
290   state.messageHeader += field + ': ' + value + CRLF;
291
292   if (connectionExpression.test(field)) {
293     state.sentConnectionHeader = true;
294     if (closeExpression.test(value)) {
295       self._last = true;
296     } else {
297       self.shouldKeepAlive = true;
298     }
299
300   } else if (transferEncodingExpression.test(field)) {
301     state.sentTransferEncodingHeader = true;
302     if (chunkExpression.test(value)) self.chunkedEncoding = true;
303
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;
310   }
311 }
312
313
314 OutgoingMessage.prototype.setHeader = function(name, value) {
315   if (arguments.length < 2) {
316     throw new Error('`name` and `value` are required for setHeader().');
317   }
318
319   if (this._header) {
320     throw new Error('Can\'t set headers after they are sent.');
321   }
322
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;
328 };
329
330
331 OutgoingMessage.prototype.getHeader = function(name) {
332   if (arguments.length < 1) {
333     throw new Error('`name` is required for getHeader().');
334   }
335
336   if (!this._headers) return;
337
338   var key = name.toLowerCase();
339   return this._headers[key];
340 };
341
342
343 OutgoingMessage.prototype.removeHeader = function(name) {
344   if (arguments.length < 1) {
345     throw new Error('`name` is required for removeHeader().');
346   }
347
348   if (this._header) {
349     throw new Error('Can\'t remove headers after they are sent.');
350   }
351
352   if (!this._headers) return;
353
354   var key = name.toLowerCase();
355   delete this._headers[key];
356   delete this._headerNames[key];
357 };
358
359
360 OutgoingMessage.prototype._renderHeaders = function() {
361   if (this._header) {
362     throw new Error('Can\'t render headers after they are sent to the client.');
363   }
364
365   if (!this._headers) return {};
366
367   var headers = {};
368   var keys = Object.keys(this._headers);
369   for (var i = 0, l = keys.length; i < l; i++) {
370     var key = keys[i];
371     headers[this._headerNames[key]] = this._headers[key];
372   }
373   return headers;
374 };
375
376
377 Object.defineProperty(OutgoingMessage.prototype, 'headersSent', {
378   configurable: true,
379   enumerable: true,
380   get: function() { return !!this._header; }
381 });
382
383
384 OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
385   if (!this._header) {
386     this._implicitHeader();
387   }
388
389   if (!this._hasBody) {
390     debug('This type of response MUST NOT have a body. ' +
391           'Ignoring write() calls.');
392     return true;
393   }
394
395   if (!util.isString(chunk) && !util.isBuffer(chunk)) {
396     throw new TypeError('first argument must be a string or Buffer');
397   }
398
399
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;
403
404   var len, ret;
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);
413     } else {
414       // buffer, or a non-toString-friendly encoding
415       if (util.isString(chunk))
416         len = Buffer.byteLength(chunk, encoding);
417       else
418         len = chunk.length;
419
420       if (this.connection)
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);
426       if (this.connection)
427         this.connection.uncork();
428     }
429   } else {
430     ret = this._send(chunk, encoding, callback);
431   }
432
433   debug('write ret = ' + ret);
434   return ret;
435 };
436
437
438 OutgoingMessage.prototype.addTrailers = function(headers) {
439   this._trailer = '';
440   var keys = Object.keys(headers);
441   var isArray = util.isArray(headers);
442   var field, value;
443   for (var i = 0, l = keys.length; i < l; i++) {
444     var key = keys[i];
445     if (isArray) {
446       field = headers[key][0];
447       value = headers[key][1];
448     } else {
449       field = key;
450       value = headers[key];
451     }
452
453     this._trailer += field + ': ' + value + CRLF;
454   }
455 };
456
457
458 var crlf_buf = new Buffer('\r\n');
459
460
461 OutgoingMessage.prototype.end = function(data, encoding, callback) {
462   if (util.isFunction(data)) {
463     callback = data;
464     data = null;
465   } else if (util.isFunction(encoding)) {
466     callback = encoding;
467     encoding = null;
468   }
469
470   if (data && !util.isString(data) && !util.isBuffer(data)) {
471     throw new TypeError('first argument must be a string or Buffer');
472   }
473
474   if (this.finished) {
475     return false;
476   }
477
478   var self = this;
479   function finish() {
480     self.emit('finish');
481   }
482
483   if (util.isFunction(callback))
484     this.once('finish', callback);
485
486
487   if (!this._header) {
488     this._implicitHeader();
489   }
490
491   if (data && !this._hasBody) {
492     debug('This type of response MUST NOT have a body. ' +
493           'Ignoring data passed to end().');
494     data = null;
495   }
496
497   if (this.connection && data)
498     this.connection.cork();
499
500   var ret;
501   if (data) {
502     // Normal body write.
503     ret = this.write(data, encoding);
504   }
505
506   if (this.chunkedEncoding) {
507     ret = this._send('0\r\n' + this._trailer + '\r\n', 'binary', finish);
508   } else {
509     // Force a flush, HACK.
510     ret = this._send('', 'binary', finish);
511   }
512
513   if (this.connection && data)
514     this.connection.uncork();
515
516   this.finished = true;
517
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) {
522     this._finish();
523   }
524
525   return ret;
526 };
527
528
529 OutgoingMessage.prototype._finish = function() {
530   assert(this.connection);
531   this.emit('prefinish');
532 };
533
534
535 // This logic is probably a bit confusing. Let me explain a bit:
536 //
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:
540 //
541 //    req1 = client.request('GET', '/');
542 //    req2 = client.request('POST', '/');
543 //
544 // When the user does
545 //
546 //   req2.write('hello world\n');
547 //
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.
551 //
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) {
556     var ret;
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);
562     }
563
564     if (this.finished) {
565       // This is a queue to the server or client to bring in the next this.
566       this._finish();
567     } else if (ret) {
568       // This is necessary to prevent https from breaking
569       this.emit('drain');
570     }
571   }
572 };